Skip to content

Spot it. Save it. Free, local-first Chrome extension for images, videos and prompts. Explore 2,000+ curated cases and connect your library to AI Agents via MCP. 提示词导演

Release 1.27.1: capture originals and installation fixes

wchao68915baf76c48c5b
diff --git a/.github/workflows/release-safety.yml b/.github/workflows/release-safety.yml
index 2b4d654..7c27f12 100644
--- a/.github/workflows/release-safety.yml
+++ b/.github/workflows/release-safety.yml
@@ -97,7 +97,8 @@ jobs:
name: Packaged Chromium shard ${{ matrix.shard }}
needs: [plan, package]
if: needs.plan.outputs.browser == 'true'
- runs-on: ubuntu-latest
+ # Keep the OS compatible with the pinned Playwright 1.58 browser build.
+ runs-on: ubuntu-24.04
strategy:
fail-fast: false
max-parallel: 4
@@ -126,7 +127,7 @@ jobs:
name: Linux packaged upgrade
needs: [plan, package]
if: needs.plan.outputs.upgrade == 'true'
- runs-on: ubuntu-latest
+ runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v6
with:
diff --git a/.github/workflows/video-component.yml b/.github/workflows/video-component.yml
index fc84234..1b2e9ff 100644
--- a/.github/workflows/video-component.yml
+++ b/.github/workflows/video-component.yml
@@ -125,9 +125,15 @@ jobs:
$env:PROMPTDIRECTOR_VIDEO_REQUIRE_TOOLS = '1'
node --test connector/test/video-source-install.test.mjs connector/test/video-registration.test.mjs
if ($LASTEXITCODE -ne 0) { throw 'Source installation contracts failed' }
- $sourceRoot = Join-Path $env:RUNNER_TEMP 'PromptDirector video source'
+ $sourceRoot = Join-Path $env:RUNNER_TEMP 'PromptDirector 视频 source'
$componentRoot = Join-Path $env:LOCALAPPDATA 'PromptDirector/VideoComponent-Source'
Expand-Archive -LiteralPath dist/video-component/PromptDirector-Video-Source.zip -DestinationPath $sourceRoot
+ # Exercise native commands from a constrained session. This does not
+ # claim to reproduce an enterprise WDAC/AppLocker policy.
+ $ExecutionContext.SessionState.LanguageMode = 'ConstrainedLanguage'
+ if ($ExecutionContext.SessionState.LanguageMode -ne 'ConstrainedLanguage') { throw 'ConstrainedLanguage was not enabled' }
+ node --test connector/test/video-registration.test.mjs
+ if ($LASTEXITCODE -ne 0) { throw 'Constrained-session registry contracts failed' }
try {
node "$sourceRoot/connector/register-video.mjs" install
if ($LASTEXITCODE -ne 0) { throw 'Source installation failed' }
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6f4703f..9a5d8aa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,15 @@
了解每个版本带来的功能变化与使用改善。下载请前往 [GitHub Releases](https://github.com/wchao6891/PromptDirector/releases/latest)。
+## 1.27.1
+
+- 修复首次手选追加覆盖已有采集内容的问题,保留正文、提示词、图片和截图;同一图片合并可用来源。
+- 通用采集与站点适配器统一优先保存原图,改善 X 图片尺寸;原图不可用时明确提示保存了较小图片。
+- 修复案例管理栏滚动后菜单无法正常展开的问题。
+- 整理通用设置,固定版本与更新操作;离线或网络失败时仅在主动检查后给出简短提示。
+- 修复 Windows 视频组件在受限 PowerShell 环境中的注册问题,刷新后重新检测安装状态;新增“让 Agent 安装”入口。
+- 免费视频组件源码包更新至 0.1.1,已有正常工作的 0.1.0 组件仍可使用。
+
## 1.27.0
- 采集侧栏与外部 Agent 共用可接续的预览、选择、补采和保存流程,保留原文、原词与人工编辑,显示真实任务进度及部分成功结果。
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 22b1849..1bef5a5 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -81,7 +81,7 @@
<p align="center"><img src="https://wchao6891.github.io/PromptDirector-Curated/guide-assets/v127-maintenance.jpg" alt="设置 → 任务与维护:文字标签补全、资料索引自动补全、案例排重" width="860"></p>
-**备份、同步和 Agent,都在设置里。** 在「设置 → 界面与资料库」这一页可以整库备份与恢复、跨设备同步,也能复制 Agent 连接指令交给 Codex、Claude Code 或 WorkBuddy;资料库名称和视频采集也在这里。
+**备份、同步和 Agent,都在设置里。** 在「设置 → 通用」这一页可以整库备份与恢复、跨设备同步,也能复制 Agent 连接指令交给 Codex、Claude Code 或 WorkBuddy;资料库名称和视频采集也在这里。
<p align="center"><img src="https://wchao6891.github.io/PromptDirector-Curated/guide-assets/v127-settings-video.jpg" alt="设置 → 界面与资料库页:资料库名称、分享保存位置、采集权限与视频采集;Agent 连接、备份与同步在本页下方" width="760"></p>
diff --git a/connector/register-video.mjs b/connector/register-video.mjs
index 3e6abf7..3ca8134 100644
--- a/connector/register-video.mjs
+++ b/connector/register-video.mjs
@@ -1,6 +1,6 @@
-import { readFile, writeFile, mkdir, cp, rm, lstat, rename, chmod, access, realpath } from 'node:fs/promises';
+import { readFile, writeFile, mkdir, cp, rm, lstat, rename, chmod, access, realpath, mkdtemp } from 'node:fs/promises';
import { join, dirname, resolve, win32 } from 'node:path';
-import { homedir } from 'node:os';
+import { homedir, tmpdir } from 'node:os';
import { randomUUID } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { execFile } from 'node:child_process';
@@ -88,77 +88,91 @@ export async function registerVideoViews(registration, registry) {
}
}
-// Values are data, never interpolated as PowerShell. Conditional restoration is
-// performed in the same native operation as the read, preserving later writers.
-export function windowsVideoRegistry(plan, { keyName = 'Software\\Google\\Chrome\\NativeMessagingHosts\\com.promptdirector.video' } = {}) {
- if (!process.env.SystemRoot) throw new Error('Windows system directory is unavailable.');
- const script = `$ErrorActionPreference='Stop'
-$name=$env:PROMPTDIRECTOR_VIDEO_REGISTRY_KEY
-if ($env:PROMPTDIRECTOR_VIDEO_REGISTRY_OPERATION -eq 'snapshot') {
- $snapshots=@()
- foreach ($view in @([Microsoft.Win32.RegistryView]::Registry32,[Microsoft.Win32.RegistryView]::Registry64)) {
- $base=[Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::CurrentUser,$view)
- try {
- $key=$base.OpenSubKey($name)
- if ($null -eq $key) { $snapshots += @{exists=$false} }
- else {
- try {
- $hasValue=$key.GetValueNames() -contains ''
- $value=$null; $kind=$null
- if ($hasValue) {
- $value=$key.GetValue('',$null,[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
- $kind=$key.GetValueKind('').ToString()
- }
- $snapshots += @{exists=$true; hasValue=$hasValue; value=$value; kind=$kind}
- } finally { $key.Dispose() }
- }
- } finally { $base.Dispose() }
- }
- ConvertTo-Json -InputObject @($snapshots) -Compress -Depth 5
-} else {
- $view=[Enum]::Parse([Microsoft.Win32.RegistryView],$env:PROMPTDIRECTOR_VIDEO_REGISTRY_VIEW)
- $base=[Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::CurrentUser,$view)
- try {
- if ($env:PROMPTDIRECTOR_VIDEO_REGISTRY_OPERATION -eq 'write') {
- $key=$base.CreateSubKey($name)
- try {
- $key.SetValue('',$env:PROMPTDIRECTOR_VIDEO_MANIFEST,[Microsoft.Win32.RegistryValueKind]::String)
- if ($key.GetValue('') -cne $env:PROMPTDIRECTOR_VIDEO_MANIFEST) { throw 'Video registration readback mismatch' }
- } finally { $key.Dispose() }
- } elseif ($env:PROMPTDIRECTOR_VIDEO_REGISTRY_OPERATION -eq 'restore') {
- $key=$base.OpenSubKey($name,$true)
- if ($null -ne $key) {
- $deleteEmpty=$false
- try {
- if ($key.GetValue('') -ceq $env:PROMPTDIRECTOR_VIDEO_MANIFEST) {
- $previous=ConvertFrom-Json $env:PROMPTDIRECTOR_VIDEO_PREVIOUS
- if ($previous.exists -and $previous.hasValue) {
- $kind=[Enum]::Parse([Microsoft.Win32.RegistryValueKind],$previous.kind)
- $key.SetValue('',$previous.value,$kind)
- } else {
- $key.DeleteValue('',$false)
- $deleteEmpty=(!$previous.exists -and $key.ValueCount -eq 0 -and $key.SubKeyCount -eq 0)
- }
- }
- } finally { $key.Dispose() }
- if ($deleteEmpty) { $base.DeleteSubKey($name) }
- }
- } else { throw 'Invalid video registry operation' }
- } finally { $base.Dispose() }
-}`;
- const run = async (operation, view, previous) => {
- const { stdout } = await promisify(execFile)(win32.join(process.env.SystemRoot, 'System32/WindowsPowerShell/v1.0/powershell.exe'),
- ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')],
- { windowsHide: true, timeout: 30_000, env: { ...process.env, PROMPTDIRECTOR_VIDEO_MANIFEST: plan.registration,
- PROMPTDIRECTOR_VIDEO_REGISTRY_KEY: keyName,
- PROMPTDIRECTOR_VIDEO_REGISTRY_OPERATION: operation, PROMPTDIRECTOR_VIDEO_REGISTRY_VIEW: view || '',
- PROMPTDIRECTOR_VIDEO_PREVIOUS: JSON.stringify(previous || {}) } });
- return stdout;
+// reg.exe exports UTF-16, independent of the console code page. Preserve the
+// default entry verbatim so rollback also restores its original registry type.
+function readRegistryExport(bytes, key) {
+ if (bytes[0] !== 0xff || bytes[1] !== 0xfe) throw new Error('Invalid Unicode registry snapshot.');
+ const lines = bytes.toString('utf16le').slice(1).replace(/\\\r?\n[ \t]*/gu, '').split(/\r?\n/u);
+ const heading = `[${key}]`;
+ const start = lines.findIndex(line => line.toLowerCase() === heading.toLowerCase());
+ if (start < 0) throw new Error('Registry snapshot key mismatch.');
+ let entry, otherValues = false, subkeys = false;
+ for (const line of lines.slice(start + 1)) {
+ if (line.startsWith('[')) { subkeys = true; break; }
+ if (line.startsWith('@=')) entry = line;
+ else if (line.trim() && !line.startsWith(';')) otherValues = true;
+ }
+ let value, kind;
+ if (entry?.startsWith('@="')) {
+ if (!/^@="(?:[^"\\]|\\["\\])*"$/u.test(entry)) throw new Error('Invalid registry string snapshot.');
+ value = entry.slice(3, -1).replace(/\\(["\\])/gu, '$1'); kind = 'String';
+ }
+ return { exists: true, hasValue: entry !== undefined, entry, value, kind, otherValues, subkeys };
+}
+
+export function windowsVideoRegistry(plan, { keyName = 'Software\\Google\\Chrome\\NativeMessagingHosts\\com.promptdirector.video',
+ env = process.env, exec = promisify(execFile) } = {}) {
+ if (!env.SystemRoot) throw new Error('Windows system directory is unavailable.');
+ const executable = win32.join(env.SystemRoot, 'System32', 'reg.exe');
+ const key = `HKEY_CURRENT_USER\\${keyName}`;
+ const run = (view, args) => {
+ if (!['Registry32', 'Registry64'].includes(view)) throw new Error('Invalid registry view.');
+ return exec(executable, [...args, view === 'Registry32' ? '/reg:32' : '/reg:64'],
+ { windowsHide: true, timeout: 30_000, encoding: 'buffer', env });
+ };
+ // Exit code 1 can mean missing OR access denied. Enumerate the nearest
+ // readable ancestor before treating a failed query as an absent key.
+ const exists = async (view, path = key) => {
+ try { await run(view, ['query', path]); return true; }
+ catch (error) {
+ if (error.code !== 1 || !path.includes('\\')) throw error;
+ const parent = path.slice(0, path.lastIndexOf('\\'));
+ if (!await exists(view, parent)) return false;
+ const { stdout } = await run(view, ['query', parent]);
+ const children = stdout.toString('utf8').split(/\r?\n/u).map(line => line.trim().toLowerCase());
+ if (children.includes(path.toLowerCase())) throw error;
+ return false;
+ }
+ };
+ const withFile = async action => {
+ const directory = await mkdtemp(join(tmpdir(), 'pd-video-reg-'));
+ try { return await action(join(directory, 'snapshot.reg')); }
+ finally { await rm(directory, { recursive: true, force: true }); }
};
+ const snapshot = async view => {
+ if (!await exists(view)) return { exists: false };
+ return withFile(async file => {
+ await run(view, ['export', key, file, '/y']);
+ return readRegistryExport(await readFile(file), key);
+ });
+ };
+ const owns = (current, registration) => current.kind === 'String' && current.value === registration;
return {
- snapshot: async () => JSON.parse(await run('snapshot')),
- write: view => run('write', view),
- restoreIfCurrent: (view, _registration, previous) => run('restore', view, previous)
+ snapshot: async () => [await snapshot('Registry32'), await snapshot('Registry64')],
+ async write(view, registration = plan.registration) {
+ await run(view, ['add', key, '/ve', '/t', 'REG_SZ', '/d', registration, '/f']);
+ if (!owns(await snapshot(view), registration)) throw new Error('Video registration readback mismatch');
+ },
+ async restoreIfCurrent(view, registration = plan.registration, previous) {
+ const current = await snapshot(view);
+ if (!owns(current, registration)) return;
+ if (previous.exists && previous.hasValue) {
+ await withFile(async file => {
+ await writeFile(file, Buffer.from(`\ufeffWindows Registry Editor Version 5.00\r\n\r\n[${key}]\r\n${previous.entry}\r\n`, 'utf16le'));
+ await run(view, ['import', file]);
+ });
+ if ((await snapshot(view)).entry !== previous.entry) throw new Error('Video registration rollback readback mismatch');
+ } else {
+ // Never recursively remove a key containing somebody else's data.
+ await run(view, ['delete', key, '/ve', '/f']);
+ const remaining = await snapshot(view);
+ if (remaining.hasValue) throw new Error('Video registration removal readback mismatch');
+ if (!previous.exists && remaining.exists && !remaining.otherValues && !remaining.subkeys) {
+ await run(view, ['delete', key, '/f']);
+ if (await exists(view)) throw new Error('Video registry key removal readback mismatch');
+ }
+ }
+ }
};
}
async function windowsRegistration(plan, remove = false) {
diff --git a/connector/test/video-registration.test.mjs b/connector/test/video-registration.test.mjs
index 38b1774..7336200 100644
--- a/connector/test/video-registration.test.mjs
+++ b/connector/test/video-registration.test.mjs
@@ -1,5 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
+import { readFile, writeFile } from 'node:fs/promises';
+import { win32 } from 'node:path';
import { randomUUID } from 'node:crypto';
import { registerVideoViews, windowsVideoRegistry } from '../register-video.mjs';
@@ -81,6 +83,105 @@ test('Windows uses the real registry to restore a failed second view without clo
}
}
} finally {
- for (const registry of [old, next, external]) for (const view of views) await registry.restoreIfCurrent(view, '', { exists: false });
+ for (const registry of [old, next, external]) for (const view of views) await registry.restoreIfCurrent(view, undefined, { exists: false });
}
});
+
+// Emulate only the reg.exe boundary; run the production snapshot, Unicode
+// parsing, readback, ownership checks and rollback on every development OS.
+function regFixture(initial = [{ exists: false }, { exists: false }]) {
+ const state = structuredClone(initial), calls = [];
+ const keyName = 'Software\\PromptDirectorSourceTests\\fixture';
+ const key = `HKEY_CURRENT_USER\\${keyName}`;
+ const missing = () => Object.assign(new Error('localized registry error'), { code: 1 });
+ let fail;
+ const exec = async (file, args, options) => {
+ calls.push({ file, args, options });
+ assert.equal(file, 'C:\\Windows\\System32\\reg.exe');
+ assert.equal(options.shell, undefined);
+ const index = args.at(-1) === '/reg:32' ? 0 : 1;
+ const current = state[index];
+ if (fail?.(args, index)) throw missing();
+ const [operation, target] = args;
+ if (operation === 'query') {
+ if (target === key && !current.exists) throw missing();
+ return { stdout: Buffer.from(`${target}\r\n${target !== key && current.exists ? key : ''}\r\n`) };
+ }
+ if (operation === 'export') {
+ if (!current.exists) throw missing();
+ await writeFile(args[2], Buffer.from(`\ufeffWindows Registry Editor Version 5.00\r\n\r\n[${key}]\r\n${current.entry || ''}\r\n${current.otherValues ? '"Other"="keep"\r\n' : ''}${current.subkeys ? `\r\n[${key}\\Child]\r\n` : ''}`, 'utf16le'));
+ } else if (operation === 'add') {
+ current.exists = true;
+ current.entry = '@=' + JSON.stringify(args[args.indexOf('/d') + 1]);
+ } else if (operation === 'import') {
+ current.entry = (await readFile(target, 'utf16le')).split('\r\n').find(line => line.startsWith('@='));
+ } else if (operation === 'delete') {
+ if (args.includes('/ve')) delete current.entry;
+ else state[index] = { exists: false };
+ } else assert.fail(`Unexpected command ${operation}`);
+ return { stdout: Buffer.alloc(0) };
+ };
+ const registration = 'C:\\Users\\中文 A & B%20!\\视频组件\\com.promptdirector.video.json';
+ const registry = windowsVideoRegistry({ registration }, { keyName, env: { SystemRoot: 'C:\\Windows', PATH: '' }, exec });
+ return { state, calls, registry, registration, setFailure: callback => { fail = callback; } };
+}
+
+test('reg.exe first install, reinstall and uninstall preserve Unicode and shell characters in both views without PowerShell', async () => {
+ const f = regFixture();
+ await registerVideoViews(f.registration, f.registry);
+ await registerVideoViews(f.registration, f.registry);
+ for (const snapshot of await f.registry.snapshot()) assert.equal(snapshot.value, f.registration);
+ for (const view of views) await f.registry.restoreIfCurrent(view, f.registration, { exists: false });
+ assert.deepEqual(await f.registry.snapshot(), [{ exists: false }, { exists: false }]);
+ const writes = f.calls.filter(call => call.args[0] === 'add');
+ assert.equal(writes.length, 4);
+ for (const call of writes) assert.equal(call.args[call.args.indexOf('/d') + 1], f.registration);
+});
+
+for (const entry of ['@="旧组件\\\\manifest.json"', '@=hex(2):25,00,54,00,45,00,4d,00,50,00,25,00,00,00', '@=dword:0000002a', '@=hex:00,ff,1a', undefined]) {
+ test(`reg.exe restores the original default value and type after second-view readback failure: ${entry}`, async () => {
+ const initial = [{ exists: true, entry, otherValues: true, subkeys: true }, { exists: false }];
+ const f = regFixture(initial);
+ const before = await f.registry.snapshot();
+ let failed = false;
+ f.setFailure((args, index) => {
+ if (index === 1 && args[0] === 'export' && !failed) { failed = true; return true; }
+ return false;
+ });
+ await assert.rejects(registerVideoViews(f.registration, f.registry), /localized/u);
+ assert.deepEqual(await f.registry.snapshot(), before);
+ });
+}
+
+test('snapshot access errors abort before any writes, rather than being treated as an absent key', async () => {
+ const f = regFixture([{ exists: true, entry: '@="keep"' }, { exists: false }]);
+ f.setFailure(args => args[0] === 'query' && args[1].endsWith('\\fixture'));
+ await assert.rejects(registerVideoViews(f.registration, f.registry), /localized/u);
+ assert.equal(f.calls.filter(call => call.args[0] === 'add').length, 0);
+});
+
+test('uninstall preserves another installation and unrelated values/subkeys at the owned registration key', async () => {
+ const f = regFixture([{ exists: true, entry: '@="another-component.json"' }, { exists: true, otherValues: true, subkeys: true }]);
+ await f.registry.write('Registry64');
+ for (const view of views) await f.registry.restoreIfCurrent(view, f.registration, { exists: false });
+ const actual = await f.registry.snapshot();
+ assert.equal(actual[0].value, 'another-component.json');
+ assert.equal(actual[1].exists, true);
+ assert.equal(actual[1].hasValue, false);
+ assert.equal(actual[1].otherValues, true);
+ assert.equal(actual[1].subkeys, true);
+});
+
+test('real Windows Unicode paths survive install, reinstall, removal and readback in both registry views', { skip: process.platform !== 'win32' }, async () => {
+ const keyName = `Software\\PromptDirectorSourceTests\\${randomUUID()}`;
+ const registration = win32.join(process.env.TEMP, '视频 source & %20!', 'manifest.json');
+ const registry = windowsVideoRegistry({ registration }, { keyName });
+ try {
+ await registerVideoViews(registration, registry);
+ await registerVideoViews(registration, registry);
+ for (const item of await registry.snapshot()) assert.equal(item.value, registration);
+ } finally {
+ for (const view of views) await registry.restoreIfCurrent(view, registration, { exists: false });
+ }
+ for (const item of await registry.snapshot()) assert.equal(item.hasValue || false, false);
+});
diff --git a/connector/test/video-service.test.mjs b/connector/test/video-service.test.mjs
index c60e68e..0682865 100644
--- a/connector/test/video-service.test.mjs
+++ b/connector/test/video-service.test.mjs
@@ -123,7 +123,8 @@ for (const reason of ['timeout', 'space']) test(`native ${reason} abort keeps it
} });
try {
await assert.rejects(service.request('download', { url: 'https://www.bilibili.com/video/BVtest/',
- streams: { videoUrl: 'https://a.bilivideo.com/video' }, maxBytes: 10, budget: { maxDurationMs: 5 } }),
+ streams: { videoUrl: 'https://a.bilivideo.com/video' }, maxBytes: 10,
+ ...(reason === 'timeout' ? { budget: { maxDurationMs: 5 } } : {}) }),
{ code: reason === 'space' ? 'video_staging_exceeded' : 'video_timeout' });
} finally { await service.close(); }
});
diff --git a/connector/test/video-source-install.test.mjs b/connector/test/video-source-install.test.mjs
index d835b25..1a3bbac 100644
--- a/connector/test/video-source-install.test.mjs
+++ b/connector/test/video-source-install.test.mjs
@@ -19,13 +19,13 @@ async function fixture(t) {
const base = await mkdtemp(join(tmpdir(), 'pd-video-source-'));
t.after(() => rm(base, { recursive: true, force: true }));
await packageVideoSource(base);
- const directory = join(base, 'source with space');
+ const directory = join(base, '视频 source with space');
const files = await readZipBlob(new Blob([await readFile(join(base, VIDEO_SOURCE_ASSET))]));
for (const [name, data] of files) {
await mkdir(dirname(join(directory, name)), { recursive: true });
await writeFile(join(directory, name), Buffer.from(await data.arrayBuffer()));
}
- const plan = await videoSourcePlan({ directory, root: join(base, 'installed with space'), nativeDirectory: join(base, 'chrome'), platform: process.platform === 'win32' ? 'win32' : 'darwin' });
+ const plan = await videoSourcePlan({ directory, root: join(base, '视频 installed with space'), nativeDirectory: join(base, 'chrome'), platform: process.platform === 'win32' ? 'win32' : 'darwin' });
return { base, directory, files, plan };
}
async function fixtureTools(directory) {
@@ -202,3 +202,23 @@ test('the installed source host can invoke actual local dependencies without a b
assert.equal(await readFile(join(plan.root, 'LICENSE'), 'utf8'), await readFile(new URL('../../LICENSE', import.meta.url), 'utf8'));
} finally { await uninstallVideoSource(plan, { register: async () => {} }); }
});
+
+test('a registry failure during Windows reinstallation restores the previous runtime and leaves external tools untouched', async t => {
+ const { plan, base } = await fixture(t);
+ const tools = await fixtureTools(join(base, 'external tools'));
+ if (!tools.ytDlp || !tools.ffmpeg || !tools.ffprobe) {
+ assert.notEqual(process.env.PROMPTDIRECTOR_VIDEO_REQUIRE_TOOLS, '1'); return t.skip('Windows integration requires video tools');
+ }
+ // On macOS this exercises file replacement only, never the real registry.
+ plan.platform = 'win32';
+ await installVideoSource(plan, { env: toolEnv(tools), register: async () => {} });
+ const marker = join(plan.root, 'previous-runtime.txt');
+ await writeFile(marker, 'previous installation');
+ const previousManifest = await readFile(plan.registration, 'utf8');
+ await assert.rejects(installVideoSource(plan, { env: toolEnv(tools), register: async () => { throw new Error('Registry write denied'); } }), /Registry write denied/u);
+ assert.equal(await readFile(marker, 'utf8'), 'previous installation');
+ assert.equal(await readFile(plan.registration, 'utf8'), previousManifest);
+ assert.equal((await stat(tools.ffmpeg)).isFile(), true);
+ assert.deepEqual((await readdir(base)).filter(name => name.includes('.install-') || name.includes('.previous-')), []);
+ await uninstallVideoSource(plan, { register: async () => {} });
+});
diff --git a/docs/CAPTURE_SUPPORT.md b/docs/CAPTURE_SUPPORT.md
index ea8715a..77bcfbb 100644
--- a/docs/CAPTURE_SUPPORT.md
+++ b/docs/CAPTURE_SUPPORT.md
@@ -2,6 +2,10 @@
在想保存的作品、帖子或文章中打开扩展,点击网页采集,检查正文和媒体后保存。选区、选图、剪贴板和截图可以继续补充当前草稿。普通采集、手动补选和保存不调用 AI。
+已有一个选中案例时,“选取内容”从第一次起就追加到该案例,保留已有正文、提示词和选择;截图也作为新增图片保存。再次选中同一张图会合并可用来源,优先采用原图,不重复添加图片;撤销可退回补选前。未选定案例或已选中多个案例时,手选内容独立加入预览,保留原候选及选择。
+
+通用采集与站点适配器共用原图优先规则:页面明确提供的原图先于展示图,X 照片使用原图地址。原图公开下载失败时,在已获准范围内尝试网页会话;仍失败才使用可用预览,并在保存回执说明降级。网站没有提供可访问原图时,不会把预览图称为原图;手动截图保留所选画面的像素。
+
点击采集页顶部的助手图标,可以直接问“这个怎么采集?”“怎么保存到项目?”,或说明要采集的内容。询问用法不会强制扫描或保存;明确要求采集后,正文、媒体、项目选择和保存按钮直接出现在对话内。可以点击保存,也可以明确说“保存到某项目”;未指定新项目时沿用当前人工选择。保存结果可直接打开案例,重复内容也会应用明确指定的项目。
助手沿用 AI 服务中已配置的创作规划模型,输入框显示模型,模型按钮说明可能的 API 费用;打开助手不会调用模型。回复支持流式显示和 Markdown。附件按钮可补入本机图片、视频或文档,刷新保留已准备的附件与选择,保存沿普通采集的原件入库流程。普通扫描失败时,助手可读取网页实际正文和媒体链接补漏;支持图像输入的模型还可读取当前可见网页截图或预览中的图片原件。截图和封面不代表取得了视频原件,当前采集对话不直接理解视频内容。
@@ -64,7 +68,7 @@
## 视频与保存结果
- 默认下载并保存完整视频文件。网页播放地址、封面和分段资源不会作为原件保存成功;解析或下载失败会保留待重试项及具体原因。
-- 在“设置 → 界面与资料库 → 视频采集”打开“仅保存在线播放”,可主动跳过原件下载以节省空间;此设置默认关闭,既有案例与原件不变。独立在线播放保留原作品地址与单独播放地址;分段 HLS 沿用随扩展打包的播放器。
+- 在“设置 → 通用 → 视频采集”打开“仅保存在线播放”,可主动跳过原件下载以节省空间;此设置默认关闭,既有案例与原件不变。独立在线播放保留原作品地址与单独播放地址;分段 HLS 沿用随扩展打包的播放器。
- 本机视频组件复用连接器的本机通信注册,不依赖 Agent 连接开关。解析使用本机 yt-dlp,分离音视频使用 FFmpeg 合并,不调用付费解析网站;所选网站的登录、地区与访问限制仍适用。
- 在线视频仍依赖来源可用性。登录失效、链接过期、限流或禁止播放时会显示问题,可回到原作品重新采集;不会用封面或网页嵌套冒充视频播放。
- 案例正文或部分媒体已保存时,未完成的采集项保留供重试,并显示失败原因;全部完成后清空采集预览。已保存的补充文字与图片从草稿中清除,重试补存到同一案例。
diff --git a/docs/RELEASE_VERIFICATION.md b/docs/RELEASE_VERIFICATION.md
index 8a77fe2..ea7197f 100644
--- a/docs/RELEASE_VERIFICATION.md
+++ b/docs/RELEASE_VERIFICATION.md
@@ -21,6 +21,8 @@ Each browser receipt includes its complete planned scenario list, every result,
Only a full successful run uploads `promptdirector-tested-packages-<commit>` with `ci-validation.json`; partial checks never produce a full-release artifact. Download that exact artifact for publication and compare its recorded source tree with the merged commit. Publish the existing ZIP/checksum files after readback verification; do not rebuild them. The store ZIP remains a separate channel.
+Linux browser shards and the Linux upgrade job use Ubuntu 24.04, supported by the pinned Playwright 1.58.0 browser runtime. Keep that runner label aligned with `.github/actions/setup-browser/action.yml` when changing the test runtime.
+
## Triggers and local checks
Protected PRs run the gate. Merging the same source does not start a second identical main-branch run; explicit full verification remains available through `workflow_dispatch`. The existing branch-protection check names are unchanged. Keep branch protection enabled for main.
diff --git a/docs/VIDEO_COMPONENT.md b/docs/VIDEO_COMPONENT.md
index 80a00b9..dca5daf 100644
--- a/docs/VIDEO_COMPONENT.md
+++ b/docs/VIDEO_COMPONENT.md
@@ -2,11 +2,11 @@
## 免费源码安装 / Free source installation
-能直接保存的视频无需安装组件。需要本机处理时,在采集侧栏下载 `PromptDirector-Video-Source.zip`,完整解压,按包内 `INSTALL.zh.md` / `INSTALL.en.md` 安装免费的 Node.js、yt-dlp、FFmpeg/FFprobe,然后双击 `Install-macOS.command` 或 `Install-Windows.cmd`。成功后返回插件,原采集自动继续;若检查已暂停,点“继续”。关闭侧栏后重新打开仍可接续;取消的保存不会因安装完成自动提交。
+能直接保存的视频无需安装组件。需要本机处理时,点击现有组件提示中的“让 Agent 安装”,把复制的任务交给有本机执行权限的 Agent;它会按[执行指南](../tools/video-component/INSTALL-AGENT.md)检查现有工具、补齐缺少的免费依赖、安装并验证。完成后插件自动检测并接续待保存的视频;已经暂停时点击“继续”。也可把已解压组件包交给 Agent,说“按包内 INSTALL-AGENT.md 帮我安装并验证视频组件”。
-不需要付费账号、开发者证书、Agent 配对、填写路径或手写 manifest。安装脚本只自动查找已安装依赖和包内可选 `tools/` 文件夹,不下载依赖、不代替用户接受协议、不改变系统保护。工具缺失或被系统拦截时给出具体来源,保留待保存内容。完整步骤及官方来源见[中文安装说明](../tools/video-component/INSTALL.zh.md)和 [English installation guide](../tools/video-component/INSTALL.en.md)。
+不使用 Agent 时,保留原安装包下载和手动安装入口。具体步骤及官方依赖来源见[中文安装说明](../tools/video-component/INSTALL.zh.md)和 [English installation guide](../tools/video-component/INSTALL.en.md)。不需要付费账号、开发者证书、Agent 配对、填写路径或手写 manifest。基础安装脚本复用已有依赖和可选 `tools/` 文件夹,不联网下载或调整系统保护;Agent 在用户委托范围内完成缺少的工具安装。浏览器授权或系统权限确实需要人工操作时再提示。
-Directly available originals need no component. When prompted, download and fully extract `PromptDirector-Video-Source.zip`, install the free dependencies listed in its guide, then double-click the platform's Install script. Return to the extension to resume the pending capture, or select Continue if checks paused. No paid account, developer certificate, Agent pairing or manual path editing is required. The installer does not download dependencies, accept agreements or weaken system protection.
+Directly available originals need no component. Select **Install with Agent** in the component prompt and paste the copied request into a local Agent. Following the [execution guide](../tools/video-component/INSTALL-AGENT.md), it reuses existing tools, supplies missing free dependencies, installs the component and verifies it. The extension detects readiness and resumes the pending capture; select Continue if checks paused. Manual download and installation remain available. No paid account, developer certificate, Python installation or Agent pairing is required. The base installer itself does not download dependencies or change system protection.
macOS and Windows are supported subject to the chosen dependencies' OS/architecture requirements. The source package does not imply that every old OS, managed device or Smart App Control configuration permits those dependencies. Follow [Apple's security guidance](https://support.apple.com/en-us/102445) and [Microsoft's Smart App Control documentation](https://learn.microsoft.com/en-us/windows/apps/develop/smart-app-control/overview); do not disable protection or remove security markers. The online-only preference remains off unless the user explicitly enables it.
diff --git a/extension/appearance-controls.js b/extension/appearance-controls.js
index 8aedcd5..819fdcf 100644
--- a/extension/appearance-controls.js
+++ b/extension/appearance-controls.js
@@ -1,26 +1,22 @@
// Presentation adapter: preference values and persistence remain owned by the caller.
-export function bindAppearanceControls({ dark, system, motion, getPreferences, save, onError, systemDark }) {
+export function bindAppearanceControls({ theme, motion, getPreferences, save, onError }) {
let saving = false;
function sync() {
const preferences = getPreferences();
- system.checked = preferences.theme === 'system';
- dark.checked = system.checked ? systemDark.matches : preferences.theme === 'dark';
+ theme.value = preferences.theme;
motion.checked = preferences.motion === 'reduced';
- dark.disabled = saving || system.checked;
- system.disabled = motion.disabled = saving;
+ theme.disabled = motion.disabled = saving;
}
async function commit(change) {
if (saving) return;
saving = true;
- dark.disabled = system.disabled = motion.disabled = true;
+ theme.disabled = motion.disabled = true;
try { await save(change); }
catch (error) { onError(error); }
finally { saving = false; sync(); }
}
- dark.addEventListener('change', () => commit({ theme: dark.checked ? 'dark' : 'light' }));
- system.addEventListener('change', () => commit({ theme: system.checked ? 'system' : systemDark.matches ? 'dark' : 'light' }));
+ theme.addEventListener('change', () => commit({ theme: theme.value }));
motion.addEventListener('change', () => commit({ motion: motion.checked ? 'reduced' : 'system' }));
- systemDark.addEventListener('change', sync);
sync();
return { sync };
}
diff --git a/extension/background.js b/extension/background.js
index c1459cc..a2becdb 100644
--- a/extension/background.js
+++ b/extension/background.js
@@ -1423,20 +1423,11 @@ async function handleMessage(message, interaction = {}) {
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 }) };
+ 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': {
- let state = await videoComponentSetup.get();
- if (['downloading', 'review', 'installing'].includes(state.phase)) state = await videoComponentSetup.check();
- else if (['idle', 'ready'].includes(state.phase)) {
- try {
- const result = await nativeVideoStatus();
- state = { phase: result.updateRequired ? 'update' : result.available ? 'ready' : 'idle' };
- }
- catch { state = { phase: 'idle' }; }
- }
- return { ok: true, state };
+ return { ok: true, state: await videoComponentSetup.refresh() };
}
case 'UPDATE_LAYOUT_PREFERENCES':
return enqueue(async () => {
@@ -2646,12 +2637,13 @@ async function commitPageCapture(batchValue, metadata = {}, progress = createCap
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: media.url, sourceTitle: media.filename || media.sourceTitle || media.alt || candidate.title,
+ 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
});
diff --git a/extension/capture-additions.js b/extension/capture-additions.js
index e760da8..1a08c57 100644
--- a/extension/capture-additions.js
+++ b/extension/capture-additions.js
@@ -18,19 +18,25 @@ export function appendCaptureCandidate(candidate, addition, selection, { include
remapped.set(item.id, block.id);
}
for (const item of addition.media || []) {
- const existing = media.find(m => m.id === item.id || item.localAssetId && m.localAssetId === item.localAssetId
+ const identities = new Set([item.url, ...(item.variants || []).map(v => v.url)].filter(Boolean).map(pageCaptureMediaIdentity).filter(Boolean));
+ const existing = media.find(m => m.kind === (item.kind || "image") && (item.localAssetId && m.localAssetId === item.localAssetId
+ || item.localTransferId && m.localTransferId === item.localTransferId
|| item.contentHash && m.contentHash === item.contentHash
- || item.url && m.url && pageCaptureMediaIdentity(item.url) === pageCaptureMediaIdentity(m.url));
+ || !item.localAssetId && !m.localAssetId && !item.localTransferId && !m.localTransferId && [m.url, ...(m.variants || []).map(v => v.url)]
+ .some(url => url && identities.has(pageCaptureMediaIdentity(url)))));
if (existing) {
remapped.set(item.id, existing.id);
- // Explicitly adding a selected reply includes its already discovered
- // attachments as well. Ordinary draft merges keep earlier choices.
+ const index = media.indexOf(existing);
+ media[index] = { ...existing,
+ variants: [...(existing.variants || []), existing, ...(item.variants || []), item],
+ originalPrompt: existing.originalPrompt || item.originalPrompt || '',
+ originalWorkUrl: existing.originalWorkUrl || item.originalWorkUrl || '',
+ posterUrl: existing.posterUrl || item.posterUrl || '' };
+ // A manual pick includes its already discovered attachments.
+ // Ordinary draft merges keep earlier exclusions.
if (includeExistingMedia) {
mediaIds.add(existing.id);
- const index = media.indexOf(existing);
- media[index] = { ...existing, placement: 'inline',
- originalWorkUrl: existing.originalWorkUrl || item.originalWorkUrl || '',
- posterUrl: existing.posterUrl || item.posterUrl || '' };
+ media[index].placement = 'inline';
}
continue;
}
diff --git a/extension/collector.js b/extension/collector.js
index dcb7de8..22248ab 100644
--- a/extension/collector.js
+++ b/extension/collector.js
@@ -119,7 +119,7 @@ const captureAssistantView = installCaptureAssistant({ getBatch: () => pageCaptu
preserveBatch: () => Boolean(pageCaptureBatch && captureSaveTask?.input?.type === 'COMMIT_PAGE_CAPTURE'),
switchBatch: batch => {
pageCaptureAppendBase = null; pageCaptureDetailsBase = null; genericGroupingBase = null;
- pageCaptureMediaView = null; pageCaptureEditHistory = []; pageCaptureDraftIds = new Set(); manuallyPickedBatchId = '';
+ pageCaptureMediaView = null; pageCaptureEditHistory = []; pageCaptureDraftIds = new Set();
pageCaptureBatch = batch ? normalizePageCaptureBatch(batch) : null; render();
},
applyBatch: batch => { pageCaptureBatch = batch ? normalizePageCaptureBatch(batch) : null; render(); } });
@@ -139,7 +139,6 @@ let feedbackTimer = 0;
let pageCaptureRequestId = "";
let pageCaptureListRequested = false;
let pageCaptureEditing = null;
-let manuallyPickedBatchId = "";
let pageCaptureSupplementRequest = null;
let pageCaptureCancelling = false;
let pageCapturePreviewRequest = 0;
@@ -512,18 +511,15 @@ async function extractPageSelection(button) {
const batch = normalizePageCaptureBatch({ ...response.batch, status: "preview" });
const candidate = batch.candidates[0];
if (!candidate?.contentText && !candidate?.media.length) return showFeedback(batch.error || "这个区域没有可保存内容", true);
- const previousCandidate = previous?.candidates.find(item => item.id === previous.selections[0]?.candidateId);
- if (previousCandidate && (manuallyPickedBatchId === previous.id || response.supplement === "comments")) {
- appendToPageCapture(candidate);
+ if (previous) {
+ appendToPageCapture(candidate, { includeExistingMedia: true });
if (batch.error) pageCaptureBatch = normalizePageCaptureBatch({ ...pageCaptureBatch, error: batch.error });
if (batch.selectionTemplate) pageCaptureBatch = normalizePageCaptureBatch({ ...pageCaptureBatch, selectionTemplate: batch.selectionTemplate });
render();
return;
}
- if (previous) pageCaptureEditHistory.push({ batch: structuredClone(previous) });
pageCaptureBatch = normalizePageCaptureBatch({ ...batch, selections: [{ candidateId: candidate.id,
selectedTextBlockIds: candidate.textBlocks.map(item => item.id), selectedMediaIds: pageCaptureDefaultMediaIds(candidate), mediaDecision: "pending" }] });
- manuallyPickedBatchId = pageCaptureBatch.id;
pageCaptureDraftIds = new Set();
syncDraftIntoPageCapture();
render();
@@ -1042,12 +1038,27 @@ function textNode(tagName, value) {
return node;
}
-function appendToPageCapture(addition) {
+function appendToPageCapture(addition, options = {}) {
capturePreviewEditVersion++;
const selection = pageCaptureBatch?.selections[0];
- if (!selection || pageCaptureBatch.selections.length !== 1) return;
+ if (!pageCaptureBatch) return;
+ if (!selection || pageCaptureBatch.selections.length !== 1) {
+ const addedBatch = normalizePageCaptureBatch({ candidates: [{ ...addition,
+ canonicalUrl: addition.canonicalUrl || pageCaptureBatch.sourceUrl, id: `added:${crypto.randomUUID()}` }] });
+ const added = addedBatch.candidates[0];
+ if (!added) return;
+ pageCaptureEditHistory.push({ batch: structuredClone(pageCaptureBatch), genericBase: genericGroupingBase });
+ genericGroupingBase = null;
+ pageCaptureBatch = normalizePageCaptureBatch({ ...pageCaptureBatch,
+ captureMode: selection ? "list" : pageCaptureBatch.captureMode,
+ candidates: [...pageCaptureBatch.candidates, added],
+ selections: [...pageCaptureBatch.selections, { candidateId: added.id,
+ selectedTextBlockIds: added.textBlocks.map(block => block.id),
+ selectedMediaIds: pageCaptureDefaultMediaIds(added), mediaDecision: "confirmed" }] });
+ return;
+ }
const candidate = pageCaptureBatch.candidates.find(c => c.id === selection.candidateId);
- const result = appendCaptureCandidate(candidate, addition, selection);
+ const result = appendCaptureCandidate(candidate, addition, selection, options);
pageCaptureEditHistory.push({ candidateId: candidate.id, candidate: structuredClone(candidate), selection: structuredClone(selection), genericBase: genericGroupingBase });
genericGroupingBase = null;
pageCaptureBatch = normalizePageCaptureBatch({ ...pageCaptureBatch,
@@ -1072,7 +1083,7 @@ function confirmPageCaptureCandidate(candidate) {
selectedMediaIds: pageCaptureDefaultMediaIds(candidate), mediaDecision: "confirmed" }] }))[0];
pageCaptureBatch = pageCaptureAppendBase;
pageCaptureAppendBase = null;
- appendToPageCapture(selected);
+ appendToPageCapture(selected, { includeExistingMedia: true });
render();
return;
}
diff --git a/extension/i18n.js b/extension/i18n.js
index 2d76271..4b8c5ec 100644
--- a/extension/i18n.js
+++ b/extension/i18n.js
@@ -46,6 +46,10 @@ const EN = Object.freeze({
"打开安装包": "Open installer",
"重新下载": "Download again",
"安装视频组件": "Install video component",
+ "让 Agent 安装": "Install with Agent",
+ "手动安装": "Install manually",
+ "已复制,粘贴给本机 Agent,安装后自动继续": "Copied. Paste into a local Agent; saving resumes after installation.",
+ "无法复制安装指令,请重试": "Could not copy the installation request. Try again.",
"未开启组件连接权限,待保存内容已保留": "Component permissions were not enabled. Your capture is preserved.",
"视频组件安装未开始": "Video component setup did not start.",
@@ -658,7 +662,7 @@ const EN = Object.freeze({
"未识别到可靠的多个案例边界,请保留整篇文章或手动选择内容": "No reliable boundaries between multiple cases were found. Keep the full article or select content manually.",
"复制连接指令": "Copy connection request",
"Agent 连接": "Agent connection",
- "复制连接指令发给你的 Agent,由它完成安装和配对。需要浏览器授权时点击启用;断开后停止接收新请求,已提交任务继续处理。": "Copy the connection request to your Agent to install and pair. Enable when browser permission is needed. Disconnect stops new requests; submitted tasks continue.",
+ "复制连接指令,交给 Agent 完成安装与配对。": "Copy the connection request to your Agent to install and pair.",
"案例库:按需;仅在你要求查询或参考时使用,点击关闭": "Library: on demand. Used only when you ask to search or reference it. Click to turn off.",
"案例库:关闭,点击开启": "Library: off. Click to enable.",
"当前模型未声明工具能力,可通过选择案例手动查询;点击关闭案例库": "Tool support is not declared for this model. Search manually using Select cases. Click to disable the library.",
@@ -1938,7 +1942,6 @@ const EN = Object.freeze({
"选中全部可分析": "Select all analyzable",
"清空已选": "Clear selection",
"移入回收站": "Move to recycle bin",
- "界面与资料库": "Interface and library",
"任务与维护": "Tasks and maintenance",
"AI 服务": "AI services",
"AI 配置": "AI configuration",
@@ -1999,7 +2002,6 @@ const EN = Object.freeze({
"当前还有未保存草稿,请先保存或丢弃": "Save or discard the current draft first",
"备份与同步": "Backup and sync",
"备份、恢复或跨设备同步": "Back up, restore, or sync across devices",
- "界面与资料库设置": "Interface and library settings",
"关闭数据与同步": "Close data and sync",
"尚未连接同步文件夹": "No sync folder connected",
"同一台电脑可选择普通本地文件夹;跨设备请选择已登录的 iCloud Drive、Dropbox 或 OneDrive 文件夹。两端选择同一个父文件夹并使用相同密码。插件会在其中创建 PromptDirector-Sync,请勿手动修改。": "For profiles on the same computer, choose a normal local folder. For multiple devices, choose a signed-in iCloud Drive, Dropbox, or OneDrive folder. Select the same parent folder and use the same password on both sides. PromptDirector creates PromptDirector-Sync inside it; do not edit that folder manually.",
@@ -2145,6 +2147,8 @@ const EN = Object.freeze({
"已保存到我的案例库": "Saved to my archive",
"正在保存": "Saving",
"浏览器未允许复制,请选中文本后复制": "Clipboard access was not granted. Select the text and copy it manually.",
+ "暂时无法检查更新,请稍后重试": "Could not check for updates. Try again later.",
+ "当前未联网,联网后再检查更新": "You’re offline. Reconnect to check for updates.",
"检查更新": "Check for updates",
"状态不可用": "Status unavailable",
"本地开发版 · 手动替换代码": "Local development build · Replace files manually",
@@ -3964,6 +3968,7 @@ export function translateUiMessage(value) {
[/^(.+):视频本地副本未保存,已保留来源链接((.+))$/u, "$1: Local video copy not saved; source link kept ($2)"],
[/^(.+):来源封面未保存((.+))$/u, "$1: Source cover not saved ($2)"],
[/^(.+):原图不可用,已保存页面可见画面$/u, "$1: Original image unavailable; saved the visible page render instead"],
+ [/^(.+):原图不可用,已保存网站提供的较小图片$/u, "$1: Original image unavailable; saved a smaller image from the site"],
[/^保存成功,但状态提示更新失败:(.+)$/u, "Saved, but the status indicator could not be updated: $1"],
[/^已保存 (\d+) 项,跳过 (\d+) 项重复内容$/u, "Saved $1 items and skipped $2 duplicates"],
[/^已保存 (\d+) 项$/u, "Saved $1 items"],
diff --git a/extension/library-layout.css b/extension/library-layout.css
index 93c3172..1502fa6 100644
--- a/extension/library-layout.css
+++ b/extension/library-layout.css
@@ -114,7 +114,6 @@
.modular-library .topbar #share-count { font-size: 10px; }
.modular-library .topbar #share-cancel { padding-inline: 5px; }
.modular-library .topbar .selection-mode .gallery-heading-copy { display: none; }
- .modular-library .topbar .selection-menu-panel { position: fixed; top: var(--library-topbar-height); left: 8px; right: 8px; width: auto; }
}
.modular-library .gallery-shell { grid-column: 3; grid-row: 1; }
diff --git a/extension/library.css b/extension/library.css
index ea21eca..be7db32 100644
--- a/extension/library.css
+++ b/extension/library.css
@@ -343,7 +343,9 @@ details:not([open]) > .selection-menu-panel { display: none; }
.project-menu { position: relative; }
.project-menu > summary { display: grid; width: 30px; min-height: 30px; place-items: center; color: var(--muted); cursor: pointer; list-style: none; }
.project-menu > summary::-webkit-details-marker { display: none; }
-.project-menu-panel { position: absolute; z-index: 12; top: calc(100% + 5px); right: 0; display: grid; width: min(228px, calc(100vw - 32px)); min-width: 0; max-width: calc(100vw - 32px); gap: 6px; border: 1px solid var(--line); border-radius: var(--ui-container-radius); padding: var(--ui-space-1); background: var(--card); box-shadow: var(--shadow); }
+.project-menu-panel { z-index: 12; display: grid; width: min(228px, calc(100vw - 32px)); min-width: 0; max-width: calc(100vw - 32px); gap: 6px; border: 1px solid var(--line); border-radius: var(--ui-container-radius); padding: var(--ui-space-1); background: var(--card); box-shadow: var(--shadow); }
+/* Top-layer menus use the shared viewport positioning; inline menus anchor locally. */
+.project-menu-panel:not(.ui-popover-menu) { position: absolute; top: calc(100% + 5px); right: 0; }
.project-menu-panel button { width: 100%; min-width: 0; max-width: 100%; min-height: var(--ui-control-height); border-radius: var(--ui-control-radius); padding: 7px 12px; font-size: var(--ui-button-size); line-height: 1.35; overflow-wrap: anywhere; white-space: normal; }
.project-menu-panel .project-menu-primary { color: var(--accent-contrast); border-color: var(--accent); background: var(--accent); }
.project-menu-panel:not(.ui-action-menu) .quiet-danger { border-color: color-mix(in srgb, var(--danger) 18%, var(--line)); background: color-mix(in srgb, var(--danger) 5%, var(--card)); }
@@ -825,7 +827,7 @@ details:not([open]) > .selection-menu-panel { display: none; }
.ai-advanced-settings-body { display: grid; gap: 14px; padding-top: 14px; }
.analysis-kind-tabs button { min-height: 32px; color: var(--muted); background: transparent; }
.analysis-kind-tabs button[aria-selected="true"] { color: var(--ink); background: var(--selection); box-shadow: inset 0 -1px var(--selection-indicator); }
-.settings-shell { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr); min-height: 0; overflow: hidden; }
+.settings-shell { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr) auto; min-height: 0; overflow: hidden; }
.settings-tabs { display: flex; gap: 8px; margin-bottom: 4px; border-bottom: 1px solid var(--line); padding-bottom: 10px; }
.settings-tabs button { min-height: 32px; color: var(--muted); background: transparent; }
.settings-tabs button[aria-selected="true"] { color: var(--ink); background: var(--selection); box-shadow: inset 0 -1px var(--selection-indicator); }
@@ -853,7 +855,9 @@ details:not([open]) > .selection-menu-panel { display: none; }
.share-location-controls { display: flex; align-items: center; min-width: 0; gap: var(--ui-space-1); }
.share-location-controls input { flex: 1; min-width: 0; }
.share-location-controls button { flex: none; }
-.capture-permission-list { display: flex; flex-wrap: wrap; gap: 8px 32px; }
+.capture-permission-list, .video-capture-controls { display: flex; align-items: center; flex-wrap: wrap; gap: 8px 32px; }
+.video-capture-controls > .setting-row { grid-template-columns: max-content auto; flex: none; }
+.video-capture-controls > .capture-permission-row { min-width: 0; max-width: 100%; }
.capture-permission-row { display: flex; align-items: center; gap: 12px; min-height: 36px; }
.agent-connection-row { flex-wrap: wrap; }
.agent-connection-actions { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
@@ -881,6 +885,25 @@ details:not([open]) > .selection-menu-panel { display: none; }
.settings-about .about-trigger { background: transparent; border-color: transparent; color: var(--muted); font-size: 11px; }
.settings-about .is-available { color: var(--accent-ink); }
.settings-about .is-error { color: var(--danger); }
+.settings-shell > .settings-about { margin-top: 0; }
+.settings-version, .settings-update-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }
+.settings-version { flex: 0 0 auto; }
+.settings-update-actions { min-width: 0; }
+.settings-about #check-extension-update { display: inline-flex; align-items: center; gap: 6px; }
+.settings-about #check-extension-update[hidden] { display: none; }
+.settings-about #update-feedback { flex-basis: 100%; margin: 0; }
+.settings-about #update-feedback:empty { display: none; }
+#settings-general-panel .setting-section { padding-block: 14px; }
+#settings-general-panel .setting-section:first-child { padding-top: 8px; }
+#settings-general-panel .appearance-grid { gap: 16px; align-items: start; }
+#settings-general-panel :is(.appearance-grid > label, .appearance-field) { font-size: 12px; }
+#settings-general-panel :is(.setting-row > label, .appearance-grid > label > span, .appearance-field > span) { color: var(--ink); }
+#settings-general-panel :is(.capture-permission-row span, .setting-section-heading small, .sync-settings summary small) { font-size: 12px; }
+#settings-general-panel .capture-permission-row > strong { flex: 0 0 108px; }
+#settings-general-panel .video-component-setup > span { flex: 0 1 auto; }
+.settings-diagnostics { padding-top: 8px; }
+.settings-diagnostics > label { justify-content: flex-start; color: var(--ink); font-size: 13px; }
+#agent-connection-help { margin-top: 6px; font-size: 12px; }
.settings-tasks-panel { gap: 12px; }
.analysis-settings-form { display: grid; gap: 14px; }
.analysis-settings-form label { display: grid; gap: 6px; color: var(--muted); font-size: 11px; font-weight: 700; }
@@ -1005,7 +1028,7 @@ details:not([open]) > .selection-menu-panel { display: none; }
.selection-selected-actions { max-width: 100%; flex-wrap: wrap; }
.selection-compact-action, .selection-menu > summary { min-height: 36px; padding: 5px 8px; }
.selection-menu { position: static; }
- .selection-menu-panel { position: absolute; top: 100%; right: 0; bottom: auto; left: auto; width: min(430px, 100%); max-height: calc(100dvh - var(--library-topbar-height) - var(--library-management-height)); overflow: auto; }
+ .selection-menu-panel { width: min(430px, 100%); max-height: calc(100dvh - var(--library-topbar-height) - var(--library-management-height)); overflow: auto; }
.selection-project-actions { grid-template-columns: 1fr; }
.workspace, .workspace.filters-collapsed { display: block; }
.filter-sidebar { position: fixed; z-index: 35; top: 0; left: 0; width: min(310px, 88vw); height: 100vh; padding-top: 20px; box-shadow: var(--shadow); transform: translateX(-105%); opacity: 0; }
@@ -1360,7 +1383,6 @@ details:not([open]) > .selection-menu-panel { display: none; }
.import-summary span:nth-child(3) { border-left: 0; border-top: 1px solid var(--line); }
.import-summary span:nth-child(4) { border-top: 1px solid var(--line); }
.import-options { grid-template-columns: 1fr; align-items: stretch; }
- .capture-permission-list { grid-template-columns: 1fr; }
.data-safety-actions.import-actions { position: sticky; bottom: 0; flex-wrap: wrap; background: var(--card); }
.import-actions #import-cancel { margin-right: 0; }
}
diff --git a/extension/library.html b/extension/library.html
index 105f158..25f99a0 100644
--- a/extension/library.html
+++ b/extension/library.html
@@ -352,7 +352,7 @@
<header class="data-safety-header ui-dialog-header"><div class="ui-dialog-heading"><h2 data-i18n="设置">设置</h2></div><button id="settings-close" class="icon-button" type="button" aria-label="关闭设置" data-i18n-aria-label="关闭设置" title="关闭设置" data-i18n-title="关闭设置"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-x"></use></svg></button></header>
<div class="data-safety-body settings-shell">
<nav class="settings-tabs" aria-label="设置视图" data-i18n-aria-label="设置视图">
- <button type="button" data-settings-tab="general" aria-selected="true" data-i18n="界面与资料库">界面与资料库</button>
+ <button type="button" data-settings-tab="general" aria-selected="true" data-i18n="通用">通用</button>
<button type="button" data-settings-tab="ai" aria-selected="false" data-i18n="AI 配置">AI 配置</button>
<button type="button" data-settings-tab="rules" aria-selected="false" data-i18n="分析与创作规则">分析与创作规则</button>
<button type="button" data-settings-tab="shortcuts" aria-selected="false" data-i18n="键盘快捷键">键盘快捷键</button>
@@ -387,9 +387,8 @@
<section id="settings-general-panel" class="settings-panel compact-general" data-settings-panel="general">
<section class="setting-section appearance-grid">
<label><span data-i18n="界面语言">界面语言</span><select id="ui-locale"><option value="system" data-i18n="跟随浏览器">跟随浏览器</option><option value="zh-CN" data-i18n="中文">中文</option><option value="en">English</option></select></label>
- <div class="appearance-field"><span data-i18n="主题">主题</span><div class="appearance-switches"><label><input id="ui-theme" class="ui-switch" type="checkbox" role="switch"><span data-i18n="深色">深色</span></label><label><input id="ui-theme-system" class="ui-switch" type="checkbox" role="switch"><span data-i18n="跟随系统">跟随系统</span></label></div></div>
+ <label><span data-i18n="主题">主题</span><select id="ui-theme"><option value="system" data-i18n="跟随系统">跟随系统</option><option value="light" data-i18n="浅色">浅色</option><option value="dark" data-i18n="深色">深色</option></select></label>
<div class="appearance-field"><span data-i18n="动态效果">动态效果</span><div class="appearance-switches"><label><input id="ui-motion" class="ui-switch" type="checkbox" role="switch"><span data-i18n="减少动态效果">减少动态效果</span></label></div></div>
- <div class="appearance-field"><label for="ui-diagnostics" data-i18n="开发诊断">开发诊断</label><input id="ui-diagnostics" class="ui-switch" type="checkbox" role="switch"></div>
</section>
<section class="setting-section">
<div class="setting-section-heading"><h3 data-i18n="资料库">资料库</h3></div>
@@ -407,13 +406,15 @@
</section>
<section class="setting-section">
<div class="setting-section-heading"><h3 data-i18n="视频采集">视频采集</h3></div>
- <div class="setting-row"><label for="video-online-only" data-i18n="仅保存在线播放">仅保存在线播放</label><input id="video-online-only" class="ui-switch" type="checkbox" role="switch"></div>
- <div class="capture-permission-row"><strong data-i18n="本机视频解析">本机视频解析</strong><span id="video-component-status" role="status" data-i18n="未检查">未检查</span><button id="connect-video-component" class="button-secondary" type="button" data-i18n="安装视频组件">安装视频组件</button></div>
+ <div class="video-capture-controls">
+ <div class="setting-row"><label for="video-online-only" data-i18n="仅保存在线播放">仅保存在线播放</label><input id="video-online-only" class="ui-switch" type="checkbox" role="switch"></div>
+ <div class="capture-permission-row"><strong data-i18n="本机视频解析">本机视频解析</strong><span id="video-component-status" role="status" data-i18n="未检查">未检查</span><button id="connect-video-component" class="button-secondary" type="button" data-i18n="安装视频组件">安装视频组件</button></div>
+ </div>
<p id="video-capture-settings-feedback" class="data-safety-feedback ui-task-feedback" role="status" aria-live="polite"></p>
</section>
<section class="setting-section">
<div class="capture-permission-row agent-connection-row"><strong data-i18n="Agent 连接">Agent 连接</strong><span id="agent-connection-status" role="status" data-i18n="未连接">未连接</span><div class="agent-connection-actions"><button id="copy-agent-connection" class="button-secondary" type="button" data-i18n="复制连接指令">复制连接指令</button><button id="toggle-agent-connection" class="button-secondary" type="button" data-i18n="启用">启用</button></div></div>
- <p id="agent-connection-help" class="data-safety-feedback ui-task-feedback" hidden data-i18n="复制连接指令发给你的 Agent,由它完成安装和配对。需要浏览器授权时点击启用;断开后停止接收新请求,已提交任务继续处理。">复制连接指令发给你的 Agent,由它完成安装和配对。需要浏览器授权时点击启用;断开后停止接收新请求,已提交任务继续处理。</p>
+ <p id="agent-connection-help" class="setting-help" hidden data-i18n="复制连接指令,交给 Agent 完成安装与配对。">复制连接指令,交给 Agent 完成安装与配对。</p>
<p id="agent-connection-feedback" class="data-safety-feedback ui-task-feedback" role="status" aria-live="polite"></p>
</section>
<section id="data-safety-dialog" class="setting-section settings-data-safety">
@@ -435,15 +436,6 @@
</div>
</details>
</section>
- <footer class="settings-about">
- <input id="local-extension-package" type="file" accept=".zip,application/zip" hidden />
- <strong id="about-version">PromptDirector</strong>
- <span id="update-status" role="status"></span>
- <button id="check-extension-update" class="icon-button compact-icon" type="button" aria-label="检查更新" data-i18n-aria-label="检查更新" title="检查更新" data-i18n-title="检查更新"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-refresh-cw"></use></svg></button>
- <button id="apply-extension-update" type="button" hidden></button>
- <button id="open-about" class="about-trigger" type="button" data-i18n="关于">关于</button>
- <p id="update-feedback" class="data-safety-feedback ui-task-feedback" role="status" aria-live="polite"></p>
- </footer>
</section>
<section id="settings-dedupe-panel" class="settings-panel settings-dedupe-panel" data-settings-panel="dedupe" aria-label="案例排重" data-i18n-aria-label="案例排重" hidden>
<div class="settings-subview-heading"><button id="dedupe-back" class="icon-button" type="button" aria-label="返回任务与维护" title="返回任务与维护" data-i18n-aria-label="返回任务与维护" data-i18n-title="返回任务与维护"><svg class="ui-icon" aria-hidden="true"><use href="assets/ui-icons.svg#icon-arrow-left"></use></svg></button><h3 data-i18n="案例排重">案例排重</h3></div>
@@ -478,6 +470,7 @@
</div>
<div class="batch-card"><div class="task-heading"><div class="task-copy"><h3 data-i18n="案例排重">案例排重</h3><p data-i18n="查找图片或视频原件完全相同的案例。">查找图片或视频原件完全相同的案例。</p></div><button id="inspect-duplicates" class="button-secondary" type="button" data-i18n="查看重复案例">查看重复案例</button></div></div>
<div id="legacy-candidates" class="batch-card"></div>
+ <section class="settings-diagnostics"><label class="appearance-switches" for="ui-diagnostics"><span data-i18n="开发诊断">开发诊断</span><input id="ui-diagnostics" class="ui-switch" type="checkbox" role="switch"></label><p id="diagnostic-settings-feedback" class="ui-task-feedback" role="status"></p></section>
</section>
<section id="settings-ai-panel" class="settings-panel settings-ai-panel" data-settings-panel="ai" hidden>
<section class="ai-routing-card">
@@ -566,6 +559,15 @@
</form>
</section>
+ <footer class="settings-about">
+ <input id="local-extension-package" type="file" accept=".zip,application/zip" hidden />
+ <div class="settings-version"><strong id="about-version">PromptDirector</strong><span id="update-status" role="status"></span><button id="open-about" class="about-trigger" type="button" data-i18n="关于">关于</button></div>
+ <div class="settings-update-actions">
+ <button id="check-extension-update" class="button-secondary" type="button" aria-label="检查更新" data-i18n-aria-label="检查更新" title="检查更新" data-i18n-title="检查更新"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-refresh-cw"></use></svg><span data-i18n="检查更新">检查更新</span></button>
+ <button id="apply-extension-update" type="button" hidden></button>
+ </div>
+ <p id="update-feedback" class="data-safety-feedback ui-task-feedback" role="status" aria-live="polite"></p>
+ </footer>
</div>
</dialog>
diff --git a/extension/library.js b/extension/library.js
index 287f203..a347d74 100644
--- a/extension/library.js
+++ b/extension/library.js
@@ -882,14 +882,13 @@ elements.uiLocale.value = uiPreferences.locale;
bindDiagnosticControls({
controls: [elements.copyAnalysisDiagnostics], toggle: document.querySelector('#ui-diagnostics'), preferences: uiPreferences,
save: async change => (uiPreferences = await updateUiPreferences(change)),
- onError: error => transientFeedback.show(elements.librarySettingsFeedback, translateUiMessage(error.message), { error: true })
+ onError: error => transientFeedback.show(document.querySelector('#diagnostic-settings-feedback'), translateUiMessage(error.message), { error: true })
});
bindAppearanceControls({
- dark: elements.uiTheme, system: document.querySelector('#ui-theme-system'), motion: elements.uiMotion,
+ theme: elements.uiTheme, motion: elements.uiMotion,
getPreferences: () => uiPreferences,
save: async change => { uiPreferences = await updateUiPreferences(change); },
onError: error => transientFeedback.show(elements.librarySettingsFeedback, translateUiMessage(error.message), { error: true }),
- systemDark: matchMedia('(prefers-color-scheme: dark)')
});
mountSelectionIndicator(document.querySelector('.gallery-view-switch'), { selector: '[data-gallery-view]', attribute: 'aria-pressed' });
mountSelectionIndicator(document.querySelector('#settings-dialog .settings-tabs'), { selector: '[data-settings-tab]', attribute: 'aria-selected', underline: true });
@@ -901,6 +900,7 @@ void refreshExtensionUpdateStatus().then(async () => {
localUpgradeFeedback = result.message;
localUpgradeCleanupRequired = result.cleanupRequired;
renderExtensionUpdateStatus(extensionUpdateStatus);
+ if (localUpgradeFeedback) showUpdateFeedback(localUpgradeFeedback);
} catch (error) { showUpdateFeedback(error.message, true); }
});
try {
@@ -4361,8 +4361,9 @@ async function refreshExtensionUpdateStatus() {
const response = await chrome.runtime.sendMessage({ type: "GET_EXTENSION_UPDATE_STATUS" });
if (!response?.ok || !response.status) throw new Error(response?.status?.lastError || response?.message || "无法读取更新状态");
renderExtensionUpdateStatus(response.status);
- } catch (error) {
- if (!extensionUpdateStatus) renderExtensionUpdateStatus(null, error?.message || "无法读取更新状态");
+ } catch {
+ // Passive status reads never replay a previous network error.
+ if (!extensionUpdateStatus) renderExtensionUpdateStatus(null);
}
}
@@ -4375,8 +4376,8 @@ async function checkExtensionUpdate() {
if (response?.status) renderExtensionUpdateStatus(response.status);
if (!response?.ok) throw new Error(response?.status?.lastError || response?.message || "检查更新失败");
showUpdateFeedback(updateCheckFeedback(response.status));
- } catch (error) {
- showUpdateFeedback(error?.message || "检查更新失败", true);
+ } catch {
+ showUpdateFeedback(navigator.onLine ? "暂时无法检查更新,请稍后重试" : "当前未联网,联网后再检查更新");
} finally {
elements.checkExtensionUpdate.disabled = false;
elements.checkExtensionUpdate.removeAttribute("aria-busy");
@@ -4392,6 +4393,7 @@ async function applyExtensionUpdate() {
localUpgradeCleanupRequired = false;
localUpgradeFeedback = t("已清理升级临时文件");
renderExtensionUpdateStatus(extensionUpdateStatus);
+ showUpdateFeedback(localUpgradeFeedback);
}
} catch (error) { showUpdateFeedback(error.message, true); }
finally { elements.applyExtensionUpdate.disabled = false; }
@@ -4423,7 +4425,7 @@ async function applyExtensionUpdate() {
}
}
-function renderExtensionUpdateStatus(nextStatus, fallbackError = "") {
+function renderExtensionUpdateStatus(nextStatus) {
if (nextStatus) extensionUpdateStatus = { ...(extensionUpdateStatus ?? {}), ...nextStatus };
const status = extensionUpdateStatus;
elements.aboutVersion.textContent = `PromptDirector ${status?.currentVersion || chrome.runtime.getManifest().version}`;
@@ -4437,7 +4439,7 @@ function renderExtensionUpdateStatus(nextStatus, fallbackError = "") {
elements.settingsUpdateBadge.hidden = !hasUpdate;
elements.openSettings.setAttribute("aria-label", t(hasUpdate ? "设置,有可用更新" : "设置"));
elements.openSettings.title = t(hasUpdate ? "设置,有可用更新" : "设置");
- showUpdateFeedback(status?.lastError || fallbackError || localUpgradeFeedback, Boolean(status?.lastError || fallbackError));
+ // Status notifications update controls only; feedback belongs to the action that requested it.
}
async function showExtensionAbout() {
diff --git a/extension/manifest.json b/extension/manifest.json
index c0a96aa..16877d6 100644
--- a/extension/manifest.json
+++ b/extension/manifest.json
@@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "__MSG_extensionName__",
- "version": "1.27.0",
+ "version": "1.27.1",
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq2m8W9ACXJTkJqPAd36sPrtzonmHhOYU34uS7c+D7DXX6ggWNMwB4xZapGFJ4ScBQJv71PeG9KfsEnhcXFZ9RoX/X3wY+57evL19hf6woNX1xxhKOe1rtx5QmzWCEYIr99TzW50k/N9U6tS9Ri+2DHKYA85ssXTC8B2yRQ5zUXhsAWZe/HDU18UFuvUKXYt3ZdIUi31c2vIlgFFBfsyKbIUMny9LlxL/smb4vJzU/+A3LwJDjjvOtS/lmQ2vHoQGjHJItO18bYI6h67fIEvmWk+HJKtO08Ca+5RLS8TYhI+K7l7S0RyDVNujyVWtvhAULot1H0BvteYL87fKu3SNywIDAQAB",
"homepage_url": "https://github.com/wchao6891/PromptDirector",
"default_locale": "zh_CN",
diff --git a/extension/page-capture-site-adapters.js b/extension/page-capture-site-adapters.js
index 81a8fce..e420e6b 100644
--- a/extension/page-capture-site-adapters.js
+++ b/extension/page-capture-site-adapters.js
@@ -247,7 +247,8 @@ export function collectPageCaptureSitePayload(options = {}) {
const images = rawImages.slice(0, maxMedia).map((image) => ({
id: Number(image?.id) || 0,
uuid: clean(image?.uuid),
- originalImageUrl: clean(image?.originalImageUrl || image?.previewUrl),
+ originalImageUrl: clean(image?.originalImageUrl),
+ previewUrl: clean(image?.previewUrl),
imageUrl: clean(image?.imageUrl || image?.watermarkImageUrl),
width: Number(image?.width) || 0,
height: Number(image?.height) || 0,
@@ -1054,8 +1055,8 @@ function normalizeKreaPayload(value, canonicalUrlValue) {
canonicalUrl,
title: jsonLd.name,
prompt: value?.prompt,
- imageUrl: jsonLd.contentUrl || jsonLd.url || jsonLd.thumbnailUrl,
- imagePreviewUrl: value?.imagePreviewUrl,
+ imageUrl: jsonLd.contentUrl || jsonLd.url,
+ imagePreviewUrl: value?.imagePreviewUrl || jsonLd.thumbnailUrl,
styleReferences: value?.styleReferences,
publishedAt: jsonLd.datePublished,
width: jsonLd.width,
@@ -1070,15 +1071,17 @@ function normalizeKreaItem(value) {
if (!(canonicalHost === "krea.ai" || canonicalHost.endsWith(".krea.ai"))) return null;
const itemId = clean(value?.itemId) || kreaItemId(canonicalUrl) || kreaItemId(value?.imageUrl);
if (!itemId) return null;
- const url = safeTrustedMediaUrl("krea", value?.imageUrl);
+ const originalUrl = safeTrustedMediaUrl("krea", value?.imageUrl);
const width = positiveInteger(value?.width);
const height = positiveInteger(value?.height);
const prompt = cleanMultiline(value?.prompt);
const previewUrl = safeTrustedMediaUrl("krea", value?.imagePreviewUrl);
+ const url = originalUrl || previewUrl;
+ const sourceKind = originalUrl ? "site-original" : "current";
const media = url ? [{
id: `krea:${itemId}:1`, kind: "image", url, width, height, originalPrompt: prompt,
- sourceKind: "site-original", captureMethod: "source",
- variants: [{ url, sourceKind: "site-original", width, height },
+ sourceKind, captureMethod: "source",
+ variants: [{ url, sourceKind, width, height },
...(previewUrl && previewUrl !== url ? [{ url: previewUrl, sourceKind: "current" }] : [])]
}] : [];
for (const [index, reference] of (Array.isArray(value?.styleReferences) ? value.styleReferences : []).entries()) {
@@ -1191,12 +1194,12 @@ function normalizeHiggsfieldWork(value, briefValue) {
const imageValues = Array.isArray(value?.image) ? [...value.image] : value?.image ? [value.image] : [];
const types = Array.isArray(value?.["@type"]) ? value["@type"] : [value?.["@type"]];
const videoValues = [...(Array.isArray(value?.video) ? value.video : value?.video ? [value.video] : []), ...(types.includes("VideoObject") ? [value] : [])];
- if (types.includes("ImageObject")) imageValues.push(value);
+ if (types.includes("ImageObject") && (value.contentUrl || safeHttpUrl(value.url) !== canonicalUrl)) imageValues.push(value);
const contentText = cleanMultiline(briefValue) || cleanMultiline(value?.description);
const isArticle = Boolean(cleanMultiline(briefValue) || types.some((type) => ["Article", "BlogPosting"].includes(type)));
const media = [];
const seen = new Set();
- const addMedia = (item, kind) => {
+ const addMedia = (item, kind, sourceKind = "site-original") => {
const playbackUrl = safeTrustedMediaUrl("higgsfield", typeof item === "string" ? item : item?.contentUrl || item?.url);
const url = kind === "video" && safeTrustedMediaUrl("higgsfield", item?.originalSrc) || playbackUrl;
if (!url || seen.has(url)) return;
@@ -1207,8 +1210,8 @@ function normalizeHiggsfieldWork(value, briefValue) {
id: `higgsfield:${stableTextHash(itemId)}:${stableTextHash(url)}`, kind, url, width, height,
...(kind === "video" ? { posterUrl: safeTrustedMediaUrl("higgsfield", item?.thumbnailUrl),
...(/\.m3u8(?:[?#]|$)/iu.test(playbackUrl) ? { streamUrl: playbackUrl } : {}) } : {}),
- sourceKind: "site-original", captureMethod: "source",
- variants: [{ url, sourceKind: "site-original", width, height },
+ sourceKind, captureMethod: "source",
+ variants: [{ url, sourceKind, width, height },
...(playbackUrl && playbackUrl !== url ? [{ url: playbackUrl, sourceKind: "video-element" }] : [])]
});
};
@@ -1217,7 +1220,7 @@ function normalizeHiggsfieldWork(value, briefValue) {
for (const item of imageValues) {
if (isArticle || !posters.has(typeof item === "string" ? item : item?.contentUrl || item?.url)) addMedia(item, "image");
}
- if (!media.length && value?.thumbnailUrl) addMedia(value.thumbnailUrl, "image");
+ if (!media.length && value?.thumbnailUrl) addMedia(value.thumbnailUrl, "image", "current");
if (isArticle) {
const cover = media.find((item) => item.kind === "image");
if (cover) cover.isCover = true;
@@ -1364,15 +1367,17 @@ function normalizeLiblibPayload(value, canonicalUrlValue) {
const handle = clean(value?.author?.uuid);
const images = Array.isArray(data.images) ? data.images : [];
const media = images.flatMap((image, index) => {
- const originalUrl = safeTrustedMediaUrl("liblibai", image?.originalImageUrl || image?.previewUrl);
+ const originalUrl = safeTrustedMediaUrl("liblibai", image?.originalImageUrl);
const displayUrl = safeTrustedMediaUrl("liblibai", image?.imageUrl || image?.watermarkImageUrl);
- const url = originalUrl || displayUrl;
+ const previewUrl = safeTrustedMediaUrl("liblibai", image?.previewUrl);
+ const url = originalUrl || displayUrl || previewUrl;
if (!url) return [];
const width = positiveInteger(image?.width);
const height = positiveInteger(image?.height);
const variants = [
originalUrl ? { url: originalUrl, sourceKind: "site-original", width, height } : null,
- displayUrl && displayUrl !== originalUrl ? { url: displayUrl, sourceKind: "current", width, height } : null
+ displayUrl && displayUrl !== originalUrl ? { url: displayUrl, sourceKind: "current" } : null,
+ previewUrl && previewUrl !== originalUrl && previewUrl !== displayUrl ? { url: previewUrl, sourceKind: "current" } : null
].filter(Boolean);
return [{
id: `liblibai:${itemId}:${clean(image?.uuid || image?.id) || index + 1}`,
diff --git a/extension/page-capture.js b/extension/page-capture.js
index 347c44d..0f51a95 100644
--- a/extension/page-capture.js
+++ b/extension/page-capture.js
@@ -613,16 +613,7 @@ export function pageCapturePermissionOrigins(candidates = []) {
}
export function pageCaptureMediaFetchCandidates(value = {}) {
- const seen = new Set();
- return [
- ...(Array.isArray(value.variants) ? value.variants.map((variant) => variant?.url) : []),
- value.url
- ].flatMap((candidate) => {
- const url = safeUrl(candidate);
- if (!url || seen.has(url)) return [];
- seen.add(url);
- return [url];
- });
+ return normalizeMediaVariants(value).map((variant) => variant.url);
}
export async function resolvePageCaptureImage(mediaValue = {}, options = {}) {
@@ -630,25 +621,34 @@ export async function resolvePageCaptureImage(mediaValue = {}, options = {}) {
throw new Error("网页媒体解析器缺少下载能力");
}
const failures = [];
- for (const url of pageCaptureMediaFetchCandidates(mediaValue)) {
- try {
- const downloaded = await options.fetchMedia(url);
- const blob = downloaded?.blob instanceof Blob ? downloaded.blob : downloaded;
- return { blob, metadata: downloaded?.metadata || null, sourceUrl: url, captureMethod: "source", usedPixelFallback: false, failures };
- } catch (error) {
- options.signal?.throwIfAborted();
- failures.push({ url, message: String(error?.message || error) });
- }
- }
- if (options.sessionMediaAllowed !== false && typeof options.fetchSessionMedia === "function") {
- for (const url of pageCaptureMediaFetchCandidates(mediaValue)) {
+ const variants = normalizeMediaVariants(mediaValue);
+ const urls = variants.map(variant => variant.url);
+ const originals = variants.filter(variant => variant.sourceKind === "site-original").map(variant => variant.url);
+ // Try originals through the allowed page session before accepting preview renditions.
+ const groups = originals.length ? [originals, urls.filter(url => !originals.includes(url))] : [urls];
+ for (const group of groups) {
+ for (const url of group) {
try {
- const downloaded = await options.fetchSessionMedia(url);
+ const downloaded = await options.fetchMedia(url);
const blob = downloaded?.blob instanceof Blob ? downloaded.blob : downloaded;
- return { blob, metadata: downloaded?.metadata || null, sourceUrl: url, captureMethod: "page-session", usedPixelFallback: false, failures };
+ return { blob, metadata: downloaded?.metadata || null, sourceUrl: url, captureMethod: "source", usedPixelFallback: false,
+ usedReducedImage: originals.length > 0 && !originals.includes(url), failures };
} catch (error) {
options.signal?.throwIfAborted();
- failures.push({ url, method: "page-session", message: String(error?.message || error) });
+ failures.push({ url, message: String(error?.message || error) });
+ }
+ }
+ if (options.sessionMediaAllowed !== false && typeof options.fetchSessionMedia === "function") {
+ for (const url of group) {
+ try {
+ const downloaded = await options.fetchSessionMedia(url);
+ const blob = downloaded?.blob instanceof Blob ? downloaded.blob : downloaded;
+ return { blob, metadata: downloaded?.metadata || null, sourceUrl: url, captureMethod: "page-session", usedPixelFallback: false,
+ usedReducedImage: originals.length > 0 && !originals.includes(url), failures };
+ } catch (error) {
+ options.signal?.throwIfAborted();
+ failures.push({ url, method: "page-session", message: String(error?.message || error) });
+ }
}
}
}
@@ -2387,8 +2387,8 @@ export async function collectPageCaptureSnapshot(options = {}) {
url: sourceUrl,
posterUrl: "",
alt: cleanText(element.alt),
- width: Number(element.naturalWidth || element.width) || 0,
- height: Number(element.naturalHeight || element.height) || 0,
+ width: variants[0]?.declaredWidth || (sourceUrl === safeHttpUrl(element.currentSrc || element.src) ? Number(element.naturalWidth) || 0 : 0),
+ height: sourceUrl === safeHttpUrl(element.currentSrc || element.src) ? Number(element.naturalHeight) || 0 : 0,
captureMethod: "source",
sourceKind: variants[0]?.sourceKind || "source",
variants
@@ -2717,7 +2717,8 @@ export async function collectPageCaptureSnapshot(options = {}) {
const fallbackRect = kind === "image" && !deferredReveal && rect.width >= 48 && rect.height >= 48 && rect.bottom >= 0 && rect.top <= (Number(window.innerHeight) || 720)
? { rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height }, viewportWidth: Number(window.innerWidth) || document.documentElement.clientWidth, viewportHeight: Number(window.innerHeight) || document.documentElement.clientHeight }
: null;
- const responsiveCandidate = Boolean(imageSource?.declaredWidth || imageSource?.density > 1);
+ const responsiveCandidate = Boolean(imageSource?.declaredWidth || imageSource?.density > 1
+ || kind === "image" && url !== safeHttpUrl(element.currentSrc || element.src));
media.push({
id: `${kind}:${elementIndex}:${hashText(cleanText(element.alt || element.getAttribute?.("aria-label")))}`,
kind,
@@ -2863,8 +2864,8 @@ export async function collectPageCaptureSnapshot(options = {}) {
}
}
const seen = new Set();
- return candidates.filter((candidate) => candidate.url && !seen.has(candidate.url) && seen.add(candidate.url))
- .sort((left, right) => imageVariantScore(right) - imageVariantScore(left));
+ return candidates.sort((left, right) => imageVariantScore(right) - imageVariantScore(left))
+ .filter((candidate) => candidate.url && !seen.has(candidate.url) && seen.add(candidate.url));
}
function urlWidthHint(value) {
@@ -2904,16 +2905,17 @@ export async function collectPageCaptureSnapshot(options = {}) {
function imageVariantScore(value) {
const sourcePriority = {
- "site-original": 600,
- "picture-srcset": 500,
- structured: 550,
- "deferred-srcset": 450,
- "deferred-src": 400,
- "img-srcset": 350,
- current: 200,
- source: 100
+ "site-original": 1000000,
+ "picture-srcset": 500000,
+ structured: 550000,
+ "deferred-srcset": 450000,
+ "deferred-src": 400000,
+ "img-srcset": 350000,
+ "css-background": 250000,
+ current: 200000,
+ source: 100000
}[value?.sourceKind] || 0;
- return sourcePriority + Math.min(100000, Number(value?.declaredWidth || 0)) + Math.min(100, Number(value?.density || 0) * 10);
+ return sourcePriority + Math.min(99999, Number(value?.width || value?.declaredWidth || 0)) + Math.min(99, Number(value?.density || 0) * 10);
}
function isSupportedVideoFrame(element) {
@@ -3136,6 +3138,7 @@ function uniqueMedia(values) {
for (const value of Array.isArray(values) ? values : []) {
const variants = normalizeMediaVariants(value);
const url = variants[0]?.url || safeUrl(value?.url);
+ const changedImageSource = (!value?.kind || value.kind === "image") && url !== safeUrl(value?.url);
const posterUrl = safeUrl(value?.posterUrl);
const dataUrl = safeImageDataUrl(value?.dataUrl);
const previewDataUrl = safeImageDataUrl(value?.previewDataUrl);
@@ -3177,10 +3180,10 @@ function uniqueMedia(values) {
sourceTitle: cleanCaptureImageDescription(value.sourceTitle),
sourceAuthor: clean(value.sourceAuthor),
originalWorkUrl: safeUrl(value.originalWorkUrl),
- width: positiveInteger(variants[0]?.width || value.width, 0),
- height: positiveInteger(variants[0]?.height || value.height, 0),
+ width: positiveInteger(variants[0]?.width || (changedImageSource ? 0 : value.width), 0),
+ height: positiveInteger(variants[0]?.height || (changedImageSource ? 0 : value.height), 0),
sourceKind: variants[0]?.sourceKind || normalizeMediaSourceKind(value.sourceKind),
- declaredWidth: positiveInteger(variants[0]?.declaredWidth || value.declaredWidth, 0),
+ declaredWidth: positiveInteger(variants[0]?.declaredWidth || (changedImageSource ? 0 : value.declaredWidth), 0),
density: positiveNumber(variants[0]?.density || value.density, 0),
captureMethod: ["source", "css-background", "page-session", "pixel-fallback"].includes(value.captureMethod) ? value.captureMethod : "source"
};
@@ -3188,7 +3191,7 @@ function uniqueMedia(values) {
const existingIndex = indexById.get(id) ?? (identity ? indexByIdentity.get(identity) : undefined);
if (existingIndex !== undefined) {
const existing = items[existingIndex];
- const mergedVariants = normalizeMediaVariants({ variants: [...existing.variants, ...item.variants] });
+ const mergedVariants = normalizeMediaVariants({ ...existing, variants: [...existing.variants, ...item.variants] });
items[existingIndex] = {
...existing,
url: mergedVariants[0]?.url || existing.url,
@@ -3240,6 +3243,24 @@ function normalizeFallbackRect(value) {
};
}
+function xOriginalImageUrl(value) {
+ try {
+ const url = new URL(value);
+ if (url.protocol !== "https:" || url.hostname !== "pbs.twimg.com" || url.username || url.password
+ || !/^\/media\/[A-Za-z0-9_-]+(?:\.(?:jpe?g|png|webp))?(?::[A-Za-z0-9_]+)?$/u.test(url.pathname)) return "";
+ // X serves original post photos through name=orig (or the legacy .jpg:orig form).
+ if (/:[A-Za-z0-9_]+$/u.test(url.pathname)) {
+ url.pathname = url.pathname.replace(/:[A-Za-z0-9_]+$/u, ":orig");
+ url.searchParams.delete("name");
+ } else {
+ url.searchParams.set("name", "orig");
+ }
+ return url.href;
+ } catch {
+ return "";
+ }
+}
+
function normalizeMediaVariants(value = {}) {
const seen = new Set();
const variants = [...(Array.isArray(value.variants) ? value.variants : []), {
@@ -3251,7 +3272,7 @@ function normalizeMediaVariants(value = {}) {
density: value.density
}].flatMap((variant, index) => {
const url = safeUrl(variant?.url);
- if (!url || seen.has(url)) return [];
+ if (!url) return [];
seen.add(url);
return [{
url,
@@ -3263,7 +3284,30 @@ function normalizeMediaVariants(value = {}) {
order: index
}];
});
- return variants.sort((left, right) => mediaVariantScore(right) - mediaVariantScore(left) || left.order - right.order)
+ if ((!value.kind || value.kind === "image") && !value.localAssetId && !value.localTransferId) {
+ for (const variant of [...variants]) {
+ const original = xOriginalImageUrl(variant.url);
+ if (!original) continue;
+ if (original === variant.url) variant.sourceKind = "site-original";
+ else {
+ if (variant.sourceKind === "site-original") variant.sourceKind = "current";
+ if (!seen.has(original)) {
+ seen.add(original);
+ variants.push({ url: original, sourceKind: "site-original", width: 0, height: 0,
+ declaredWidth: 0, density: 0, order: variants.length });
+ }
+ }
+ }
+ }
+ const specificUrls = new Set(variants.filter(variant => variant.sourceKind !== "source").map(variant => variant.url));
+ const uniqueUrls = new Set();
+ return variants.filter(variant => variant.sourceKind !== "source" || !specificUrls.has(variant.url))
+ .sort((left, right) => mediaVariantScore(right) - mediaVariantScore(left) || left.order - right.order)
+ .filter(variant => {
+ if (uniqueUrls.has(variant.url)) return false;
+ uniqueUrls.add(variant.url);
+ return true;
+ })
.map(({ order, ...variant }) => variant);
}
@@ -3276,7 +3320,7 @@ function normalizeMediaSourceKind(value) {
function mediaVariantScore(value) {
const sourcePriority = {
- "site-original": 600000,
+ "site-original": 1000000,
structured: 550000,
"picture-srcset": 500000,
"deferred-srcset": 450000,
diff --git a/extension/share-preview.js b/extension/share-preview.js
index 44e4f1b..e723602 100644
--- a/extension/share-preview.js
+++ b/extension/share-preview.js
@@ -86,7 +86,7 @@ export function renderSharePreviewHtml(
</header>
<aside class="import-guide">
- <p><strong data-zh="这是可离线浏览的只读分享包。" data-en="This is a read-only package that works offline.">${locale === "en" ? "This is a read-only package that works offline." : "这是可离线浏览的只读分享包。"}</strong> <span data-zh="要整理、编辑或继续创作,请原样保留 ZIP,并在 PromptDirector 中打开“设置 → 界面与资料库 → 导入分享包”。" data-en="To organize, edit, or continue creating, keep the ZIP intact and open Settings → Interface & Library → Import shared package in PromptDirector.">${locale === "en" ? "To organize, edit, or continue creating, keep the ZIP intact and open Settings → Interface & Library → Import shared package in PromptDirector." : "要整理、编辑或继续创作,请原样保留 ZIP,并在 PromptDirector 中打开“设置 → 界面与资料库 → 导入分享包”。"}</span></p>
+ <p><strong data-zh="这是可离线浏览的只读分享包。" data-en="This is a read-only package that works offline.">${locale === "en" ? "This is a read-only package that works offline." : "这是可离线浏览的只读分享包。"}</strong> <span data-zh="要整理、编辑或继续创作,请原样保留 ZIP,并在 PromptDirector 中打开“添加 → 导入本机资料”。" data-en="To organize, edit, or continue creating, keep the ZIP intact and open Add → Import local materials in PromptDirector.">${locale === "en" ? "To organize, edit, or continue creating, keep the ZIP intact and open Add → Import local materials in PromptDirector." : "要整理、编辑或继续创作,请原样保留 ZIP,并在 PromptDirector 中打开“添加 → 导入本机资料”。"}</span></p>
<div class="product-actions">${installAction}${sourceAction}</div>
</aside>
diff --git a/extension/video-component-config.js b/extension/video-component-config.js
index f4900a6..35d5df1 100644
--- a/extension/video-component-config.js
+++ b/extension/video-component-config.js
@@ -1,7 +1,7 @@
// Stable asset names are shared by the installers and the in-context setup UI.
export const VIDEO_PROTOCOL_VERSION = 1;
export const VIDEO_COMPONENT = Object.freeze({
- host: 'com.promptdirector.video', version: '0.1.0', tag: 'video-v0.1.0',
+ host: 'com.promptdirector.video', version: '0.1.1', minimumVersion: '0.1.0', tag: 'video-v0.1.1',
sourceAsset: 'PromptDirector-Video-Source.zip',
assets: { mac: 'PromptDirector-Video-macOS.pkg', win: 'PromptDirector-Video-Windows.exe' }
});
@@ -9,9 +9,20 @@ export const VIDEO_COMPONENT = Object.freeze({
export function videoComponentDownload(platform, homepage) {
if (!Object.hasOwn(VIDEO_COMPONENT.assets, platform)) throw new Error('视频组件目前支持 Windows 和 macOS');
const asset = VIDEO_COMPONENT.sourceAsset;
+ return `${videoComponentRepository(homepage)}/releases/download/${VIDEO_COMPONENT.tag}/${asset}`;
+}
+
+function videoComponentRepository(homepage) {
const repository = new URL(homepage);
if (repository.protocol !== 'https:' || repository.hostname !== 'github.com') throw new Error('视频组件下载地址不可用');
- return `${repository.href.replace(/\/$/u, '')}/releases/download/${VIDEO_COMPONENT.tag}/${asset}`;
+ return repository.href.replace(/\/$/u, '');
+}
+
+export function videoComponentInstallRequest(locale, homepage) {
+ const guide = `${videoComponentRepository(homepage)}/blob/main/tools/video-component/INSTALL-AGENT.md`;
+ return locale === 'en'
+ ? `Install the PromptDirector video component on my computer. Follow the official guide: ${guide}\nReuse an extracted package I provided, or obtain the latest official video-component source release. Detect my OS and existing tools, install only missing free dependencies from official or officially recommended sources, then install and verify the component. Do not require Python or change system security settings. Ask me only for unavoidable system authorization. Verify Chrome's connection and save and reopen the video I am trying to capture when browser access is available; clearly report any unverified step.`
+ : `帮我在本机安装 PromptDirector 视频组件。请按官方指南完成:${guide}\n优先使用我提供的已解压组件包,否则取得官方最新视频组件源码包;自动识别系统、复用现有工具,仅从官方或官方推荐来源补齐缺少的免费依赖,再完成安装和验证。不要要求安装 Python,不修改系统安全设置,只在确实需要我操作的系统授权处停下。有浏览器操作权限时,验证 Chrome 连接并保存、重开我正在采集的视频;未验证的环节如实说明。`;
}
export function videoComponentRequired(message) {
@@ -20,7 +31,7 @@ export function videoComponentRequired(message) {
export function videoComponentCurrent(version) {
if (!/^\d+\.\d+\.\d+$/u.test(version || '')) return false;
- const current = version.split('.').map(Number), minimum = VIDEO_COMPONENT.version.split('.').map(Number);
+ const current = version.split('.').map(Number), minimum = VIDEO_COMPONENT.minimumVersion.split('.').map(Number);
for (let index = 0; index < minimum.length; index++) if (current[index] !== minimum[index]) return current[index] > minimum[index];
return true;
}
diff --git a/extension/video-component-setup.js b/extension/video-component-setup.js
index ee1ae49..cdc8a61 100644
--- a/extension/video-component-setup.js
+++ b/extension/video-component-setup.js
@@ -7,7 +7,7 @@ export const VIDEO_SETUP_ALARM = 'video-component-setup';
// alarm survives worker suspension; the memory timer keeps an open view responsive.
export function createVideoComponentSetup({ storage, inspect, platform, homepage, downloads, resume,
alarms, fetchImpl = fetch, notify = () => {}, now = Date.now, schedule = setTimeout, cancel = clearTimeout }) {
- let timer, starting, checking = false;
+ let timer, starting, refreshing, checking = false;
const publish = async state => { await storage.set({ [VIDEO_SETUP_KEY]: state }); await notify(state); return state; };
const get = async () => (await storage.get(VIDEO_SETUP_KEY))[VIDEO_SETUP_KEY] || { phase: 'idle' };
const stop = async () => { if (timer) cancel(timer); timer = null; await alarms.clear(VIDEO_SETUP_ALARM); };
@@ -57,7 +57,26 @@ export function createVideoComponentSetup({ storage, inspect, platform, homepage
}
return {
get, check, restore: check,
- async start({ restart = false } = {}) {
+ async refresh() {
+ if (refreshing) return refreshing;
+ refreshing = (async () => {
+ const state = await get();
+ if (['downloading', 'review', 'installing'].includes(state.phase)) return check();
+ // A visible page refresh probes once, even after a failed download or
+ // manual installation. It never restarts downloads or expired tasks.
+ let result;
+ try { result = await inspect(); } catch { result = {}; }
+ const current = await get();
+ if (JSON.stringify(current) !== JSON.stringify(state)) return current;
+ if (result.available || result.updateRequired) {
+ return publish({ phase: result.updateRequired ? 'update' : 'ready', versions: result.versions });
+ }
+ if (['idle', 'ready', 'update'].includes(state.phase)) return publish({ phase: 'idle' });
+ return state;
+ })();
+ try { return await refreshing; } finally { refreshing = null; }
+ },
+ async start({ restart = false, viaAgent = false } = {}) {
if (starting) return starting;
starting = (async () => {
await stop();
@@ -66,8 +85,15 @@ export function createVideoComponentSetup({ storage, inspect, platform, homepage
try {
if ((await inspect()).available) { await publish({ phase: 'ready' }); await resume(); return get(); }
} catch { /* Offer the complete installer. */ }
- if (!restart && ['downloading', 'review', 'installing'].includes(current.phase)) { await arm(); return get(); }
+ if (!restart && ['downloading', 'review', 'installing'].includes(current.phase)) {
+ if (viaAgent) await publish({ ...current, viaAgent: true });
+ await arm(); return get();
+ }
const url = videoComponentDownload((await platform()).os, homepage);
+ if (viaAgent) {
+ await publish({ phase: 'installing', viaAgent: true, startedAt: now() });
+ await arm(); return get();
+ }
const response = await fetchImpl(url, { method: 'HEAD', signal: AbortSignal.timeout(30_000) });
if (!response.ok) throw new Error(response.status === 404 ? '视频组件安装包尚未发布,待保存内容已保留' : '暂时无法下载安装包,请稍后重试');
const downloadId = await downloads.download({ url, saveAs: false });
@@ -80,11 +106,7 @@ export function createVideoComponentSetup({ storage, inspect, platform, homepage
async continue() {
await stop();
const state = await get();
- await publish({ ...state, phase: state.downloadId ? 'installing' : 'paused', startedAt: now(), checkAttempts: 0 });
- if (!state.downloadId) {
- if ((await inspect()).available) { await publish({ phase: 'ready' }); await resume(); }
- return get();
- }
+ await publish({ ...state, phase: 'installing', startedAt: now(), checkAttempts: 0 });
return check();
},
stop
diff --git a/extension/video-component-view.js b/extension/video-component-view.js
index 4e32b50..de52da0 100644
--- a/extension/video-component-view.js
+++ b/extension/video-component-view.js
@@ -1,38 +1,65 @@
-import { t, translateUiMessage } from './i18n.js';
+import { t, translateUiMessage, currentLocale } from './i18n.js';
import { formatBytes } from './resource-limits.js';
import { setTaskFeedbackState } from './task-feedback.js';
+import { videoComponentInstallRequest } from './video-component-config.js';
-// One shared, inline next action in the collector and settings. Installation
+// Shared inline installation choices in the collector and settings. Installation
// never changes the online-only preference or clears the pending capture.
export function createVideoComponentView(container, { send = message => chrome.runtime.sendMessage(message),
- permission = () => chrome.permissions.request({ permissions: ['nativeMessaging', 'downloads.open'] }),
+ permission = permissions => chrome.permissions.request({ permissions }),
+ copy = text => navigator.clipboard.writeText(text),
+ homepage = () => chrome.runtime.getManifest().homepage_url,
open = id => chrome.downloads.open(id), onReady = () => {},
showDownloads = () => chrome.tabs.create({ url: 'chrome://downloads/' }),
message = document.createElement('span'), button = document.createElement('button'), primary = false } = {}) {
- let state = {}, busy = false;
- button.type = 'button'; button.className = primary ? 'primary' : 'button-secondary';
+ let state = {}, busy = false, copyError = '';
+ const agentButton = document.createElement('button');
+ agentButton.type = button.type = 'button';
+ agentButton.className = primary ? 'primary' : 'button-secondary';
+ button.className = 'button-secondary';
+ agentButton.dataset.videoComponentAction = 'agent';
+ button.dataset.videoComponentAction = 'manual';
container.classList.add('video-component-setup'); container.setAttribute('role', 'status');
if (!container.contains(button)) container.replaceChildren(message, button);
+ container.querySelector('[data-video-component-action="agent"]')?.remove();
+ container.insertBefore(agentButton, button);
function render(value = state) {
state = value;
const phase = state.phase;
- setTaskFeedbackState(message, { error: ['failed', 'permission'].includes(phase) });
+ setTaskFeedbackState(message, { error: Boolean(copyError) || ['failed', 'permission'].includes(phase) });
container.setAttribute('aria-busy', String(phase === 'downloading'));
- message.textContent = translateUiMessage(state.message || ({ update: '视频组件需要更新', downloading: '正在下载安装包…', review: '请在浏览器下载列表中查看安装包状态', installing: '解压安装包,按包内说明运行安装脚本,随后自动继续',
+ message.textContent = translateUiMessage(copyError || state.message || ({ update: '视频组件需要更新', downloading: '正在下载安装包…', review: '请在浏览器下载列表中查看安装包状态', installing: state.viaAgent ? '已复制,粘贴给本机 Agent,安装后自动继续' : '解压安装包,按包内说明运行安装脚本,随后自动继续',
ready: '视频组件已就绪', paused: '安装尚未完成,完成后点继续即可' }[phase] || '此视频需要安装视频组件'));
if (phase === 'downloading' && state.bytesReceived > 0) message.textContent += ` · ${formatBytes(state.bytesReceived)}${state.totalBytes > 0 ? ` / ${formatBytes(state.totalBytes)}` : ''}`;
const action = { permission: '开启权限', update: '更新视频组件', review: '查看下载', paused: '继续',
- failed: state.downloadId ? '重新下载' : '重试' }[phase] || (phase === 'installing' && state.downloadId ? '打开安装包' : '安装视频组件');
+ failed: state.downloadId ? '重新下载' : '重试' }[phase] || (phase === 'installing' && state.downloadId ? '打开安装包' : '手动安装');
button.textContent = t(action);
button.hidden = ['ready', 'downloading'].includes(phase); button.disabled = busy;
+ agentButton.textContent = t('让 Agent 安装');
+ agentButton.hidden = ['ready', 'downloading', 'review'].includes(phase); agentButton.disabled = busy;
}
+ agentButton.addEventListener('click', async () => {
+ busy = true; copyError = ''; render();
+ try {
+ if (!await permission(['nativeMessaging'])) { render({ ...state, phase: 'permission', message: '未开启组件连接权限,待保存内容已保留' }); return; }
+ const request = videoComponentInstallRequest(currentLocale(), homepage());
+ try { await copy(request); } catch { throw new Error('无法复制安装指令,请重试'); }
+ const result = await send({ type: 'START_VIDEO_COMPONENT_SETUP', viaAgent: true });
+ if (!result?.ok) throw new Error(result?.message || '视频组件安装未开始');
+ render(result.state);
+ if (result.state.phase === 'ready') await onReady();
+ } catch (error) {
+ copyError = translateUiMessage(error.message || '无法复制安装指令,请重试');
+ } finally { busy = false; render(); }
+ });
button.addEventListener('click', async () => {
- busy = true; render();
+ busy = true; copyError = ''; render();
try {
if (state.phase === 'review') { await showDownloads(); return; }
if (state.phase === 'installing' && state.downloadId) { await open(state.downloadId); return; }
- if (!await permission()) { render({ ...state, phase: 'permission', message: '未开启组件连接权限,待保存内容已保留' }); return; }
- const result = await send({ type: state.phase === 'paused' ? 'CONTINUE_VIDEO_COMPONENT_SETUP' : 'START_VIDEO_COMPONENT_SETUP', restart: state.phase === 'failed' });
+ if (!await permission(['nativeMessaging', 'downloads.open'])) { render({ ...state, phase: 'permission', message: '未开启组件连接权限,待保存内容已保留' }); return; }
+ const result = await send({ type: state.phase === 'paused' ? 'CONTINUE_VIDEO_COMPONENT_SETUP' : 'START_VIDEO_COMPONENT_SETUP',
+ restart: state.phase === 'failed' || (state.phase === 'installing' && !state.downloadId) });
if (!result?.ok) throw new Error(result?.message || '视频组件安装未开始');
render(result.state);
if (result.state.phase === 'ready') onReady();
@@ -43,5 +70,5 @@ export function createVideoComponentView(container, { send = message => chrome.r
finally { busy = false; render(); }
});
return { render, async refresh() { const result = await send({ type: 'GET_VIDEO_COMPONENT_SETUP' }); if (result?.ok) render(result.state); },
- async changed(value) { render(value); if (value.phase === 'ready') await onReady(); } };
+ async changed(value) { copyError = ''; render(value); if (value.phase === 'ready') await onReady(); } };
}
diff --git a/package-lock.json b/package-lock.json
index d411cab..2be7264 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "prompt-case-collector",
- "version": "1.27.0",
+ "version": "1.27.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "prompt-case-collector",
- "version": "1.27.0",
+ "version": "1.27.1",
"license": "Apache-2.0",
"dependencies": {
"@jonahschulte/rtf-toolkit": "0.5.0",
diff --git a/package.json b/package.json
index ba905ed..e66ba66 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "prompt-case-collector",
- "version": "1.27.0",
+ "version": "1.27.1",
"private": false,
"license": "Apache-2.0",
"repository": "https://github.com/wchao6891/PromptDirector",
diff --git a/store/DISTRIBUTION.md b/store/DISTRIBUTION.md
index b9ad912..5acb8aa 100644
--- a/store/DISTRIBUTION.md
+++ b/store/DISTRIBUTION.md
@@ -6,7 +6,7 @@ Public distribution formats and the permissions used by PromptDirector.
- Chrome Web Store item public key: stored in the source `manifest.json` for local identity verification only; `package:release` removes `key` from the upload manifest.
- Expected extension ID: `iahakaahijddcjjldidbclicedibgpjm`.
-- Current upload artifact: `dist/store/PromptDirector-1.27.0-Chrome-Web-Store.zip`. Keep this artifact local for Web Store submission. The sole GitHub extension installation package is `PromptDirector-1.27.0.zip`, with stable identity and the local updater.
+- Current upload artifact: `dist/store/PromptDirector-1.27.1-Chrome-Web-Store.zip`. Keep this artifact local for Web Store submission. The sole GitHub extension installation package is `PromptDirector-1.27.1.zip`, with stable identity and the local updater.
- Generate a candidate only with `npm run package:release`; the command verifies the source public key against the expected identity, then removes `key` from the Web Store upload manifest and excludes the local program installer.
## Store listing
diff --git a/test/appearance-controls.test.js b/test/appearance-controls.test.js
index 131dc00..c603a64 100644
--- a/test/appearance-controls.test.js
+++ b/test/appearance-controls.test.js
@@ -3,8 +3,7 @@ import assert from 'node:assert/strict';
import { bindAppearanceControls } from '../extension/appearance-controls.js';
function fixture(initial = {}, persist = async () => {}) {
- const controls = Object.fromEntries(['dark', 'system', 'motion', 'systemDark'].map(key => [key, new EventTarget()]));
- controls.systemDark.matches = false;
+ const controls = Object.fromEntries(['theme', 'motion'].map(key => [key, new EventTarget()]));
let preferences = { theme: 'dark', motion: 'system', locale: 'zh-CN', galleryZoom: 62, ...initial };
const writes = [], errors = [];
const binding = bindAppearanceControls({ ...controls, getPreferences: () => preferences,
@@ -14,36 +13,35 @@ function fixture(initial = {}, persist = async () => {}) {
return { ...controls, ...binding, writes, errors, preferences: () => preferences };
}
const flush = () => new Promise(resolve => setImmediate(resolve));
-function change(control, checked) { control.checked = checked; control.dispatchEvent(new Event('change')); }
+function change(control, value) {
+ if (typeof value === 'boolean') control.checked = value;
+ else control.value = value;
+ control.dispatchEvent(new Event('change'));
+}
test('existing theme/motion values render without writing or changing unrelated preferences', () => {
const view = fixture({ theme: 'system', motion: 'reduced' });
- assert.equal(view.system.checked, true);
- assert.equal(view.dark.checked, false);
- assert.equal(view.dark.disabled, true);
+ assert.equal(view.theme.value, 'system');
+ assert.equal(view.theme.disabled, false);
assert.equal(view.motion.checked, true);
assert.deepEqual(view.writes, []);
assert.equal(view.preferences().galleryZoom, 62);
});
-test('system appearance follows OS without persisting; turning follow off retains the displayed theme', async () => {
- const view = fixture({ theme: 'system' });
- view.systemDark.matches = true;
- view.systemDark.dispatchEvent(new Event('change'));
- assert.equal(view.dark.checked, true);
- assert.deepEqual(view.writes, []);
- change(view.system, false);
- await flush();
- assert.deepEqual(view.writes, [{ theme: 'dark' }]);
- assert.equal(view.dark.disabled, false);
+test('theme selection represents all three stored choices without writing on open', () => {
+ for (const theme of ['dark', 'light', 'system']) {
+ const view = fixture({ theme });
+ assert.equal(view.theme.value, theme);
+ assert.deepEqual(view.writes, []);
+ }
});
-test('manual dark/light and reduced/system switches send only existing preference values', async () => {
+test('theme choices and the reduced-motion switch send only existing preference values', async () => {
const view = fixture();
- change(view.dark, false); await flush();
+ change(view.theme, 'light'); await flush();
change(view.motion, true); await flush();
change(view.motion, false); await flush();
- change(view.system, true); await flush();
+ change(view.theme, 'system'); await flush();
assert.deepEqual(view.writes, [{ theme: 'light' }, { motion: 'reduced' }, { motion: 'system' }, { theme: 'system' }]);
assert.equal(view.preferences().locale, 'zh-CN');
assert.equal(view.preferences().galleryZoom, 62);
@@ -51,9 +49,9 @@ test('manual dark/light and reduced/system switches send only existing preferenc
test('failed preference writes restore the persisted choice and expose the failure', async () => {
const view = fixture({}, async () => { throw new Error('write failed'); });
- change(view.dark, false); await flush();
- assert.equal(view.dark.checked, true);
- assert.equal(view.dark.disabled, false);
+ change(view.theme, 'light'); await flush();
+ assert.equal(view.theme.value, 'dark');
+ assert.equal(view.theme.disabled, false);
assert.equal(view.preferences().theme, 'dark');
assert.deepEqual(view.errors, ['write failed']);
});
@@ -61,15 +59,14 @@ test('failed preference writes restore the persisted choice and expose the failu
test('pending writes keep the requested visual state and prevent overlapping preference writes', async () => {
let release;
const view = fixture({}, () => new Promise(resolve => { release = resolve; }));
- change(view.dark, false);
- assert.equal(view.dark.checked, false);
- assert.equal(view.dark.disabled, true);
- assert.equal(view.system.disabled, true);
+ change(view.theme, 'light');
+ assert.equal(view.theme.value, 'light');
+ assert.equal(view.theme.disabled, true);
assert.equal(view.motion.disabled, true);
change(view.motion, true);
assert.equal(view.writes.length, 1);
release(); await flush();
- assert.equal(view.dark.checked, false);
+ assert.equal(view.theme.value, 'light');
assert.equal(view.motion.checked, false);
assert.equal(view.motion.disabled, false);
});
diff --git a/test/capture-additions.test.js b/test/capture-additions.test.js
index c453287..f1701e6 100644
--- a/test/capture-additions.test.js
+++ b/test/capture-additions.test.js
@@ -24,6 +24,34 @@ test('duplicate image URLs and text do not override exclusions or grow the draft
const result=appendCaptureCandidate(base,addition,{...selection,selectedMediaIds:[]});
assert.equal(result.candidate.media.length,2);assert.equal(result.candidate.textBlocks.length,1);assert.deepEqual(result.selection.selectedMediaIds,[]);
});
+test('supplementing the same image upgrades its source while retaining prompt, IDs, exclusions and undo data', () => {
+ const small = 'https://example.com/art.jpg?w=640';
+ const original = 'https://example.com/art.jpg';
+ const base = normalizePageCaptureCandidate({ ...candidate(), media: [{
+ id: 'art', kind: 'image', url: small, width: 640, height: 360, sourceKind: 'current', originalPrompt: 'Edited original prompt'
+ }] });
+ const before = structuredClone(base);
+ const addition = {id:'pick',media:[{id:'picked-art',kind:'image',url:original,sourceKind:'site-original',
+ variants:[{url:original,sourceKind:'site-original'},{url:small,sourceKind:'current'}],originalPrompt:'Detected prompt'}]};
+ const excluded = {...selection,selectedMediaIds:[]};
+ const result = appendCaptureCandidate(base, addition, excluded);
+ assert.equal(result.candidate.media.length, 1);
+ assert.equal(result.candidate.media[0].id, 'art');
+ assert.equal(result.candidate.media[0].url, original);
+ assert.equal(result.candidate.media[0].width, 0, 'Small dimensions cannot describe the unmeasured original');
+ assert.equal(result.candidate.media[0].originalPrompt, 'Edited original prompt');
+ assert.equal(result.candidate.contentText, base.contentText);
+ assert.deepEqual(result.selection.selectedMediaIds, []);
+ assert.deepEqual(base, before);
+ const explicit = appendCaptureCandidate(base, addition, excluded, {includeExistingMedia:true});
+ assert.deepEqual(explicit.selection.selectedMediaIds, ['art']);
+});
+test('a repeated DOM ID from a different pick cannot silently discard a different image', () => {
+ const base = candidate();
+ const result = appendCaptureCandidate(base, {id:'pick',media:[{id:'one',kind:'image',url:'https://example.com/different.jpg'}]}, selection);
+ assert.equal(result.candidate.media.length, 3);
+ assert.ok(result.selection.selectedMediaIds.includes('added:pick:one'));
+});
test('explicit comment addition selects an already discovered video once and gives it the selected reply source',()=>{
const base=candidate();base.media.push({id:'discovered-video',kind:'video',placement:'unplaced',url:'https://video.twimg.com/reply.mp4'});
const addition={id:'reply',media:[{id:'owned-video',kind:'video',url:'https://video.twimg.com/reply.mp4',originalWorkUrl:'https://x.com/user/status/3',posterUrl:'https://pbs.twimg.com/poster.jpg'}],
diff --git a/test/capture_additions_e2e.py b/test/capture_additions_e2e.py
index 64a44d1..4cf05cf 100644
--- a/test/capture_additions_e2e.py
+++ b/test/capture_additions_e2e.py
@@ -18,7 +18,7 @@ def main():
const blob=await new Promise(r=>canvas.toBlob(r,'image/png'));await saveScreenshotBlob(id,blob);
return {id,mimeType:'image/png',width:100,height:120,sourceTitle:id};
}
- const first=await image('first-image','#336699'), extra=await image('extra-image','#996633');
+ const first=await image('first-image','#336699'), extra=await image('extra-image','#996633'), screenshot=await image('screenshot-image','#339966');
window.makeImage=image;window.extraImage=extra; window.captureKinds=[];window.cancelScreenshot=false;
const initial=createCaptureDraft({title:'已有草稿',fragments:[{id:'first-text',text:'已有的选中文字,必须与网页内容保存在同一个案例。',sourceUrl:'https://example.com/first'}],visuals:[first],customLabels:['保留标签']});
await send({type:'UPDATE_CAPTURE_DRAFT',draft:initial});
@@ -29,7 +29,7 @@ def main():
Object.defineProperty(navigator,'clipboard',{configurable:true,value:{read:async()=>[{types:['text/plain'],getType:async()=>new Blob(['剪贴板补充:保持动作连续。'],{type:'text/plain'})}]}});
chrome.runtime.sendMessage=async m=>{
if(m.type==='START_PAGE_CAPTURE')return {ok:true,batch:window.webSnapshot};
- if(m.type==='PICK_PAGE_CONTENT')return {ok:true,supplement:'comments',batch:{...snapshot,id:'picked-comment',candidates:[{
+ if(m.type==='PICK_PAGE_CONTENT')return {ok:true,batch:{...snapshot,id:'picked-content',candidates:[{
...snapshot.candidates[0],id:'selected-extra',contentText:'网页高亮补充:使用自然光与清晰构图。',
textBlocks:[{id:'selected-extra',text:'网页高亮补充:使用自然光与清晰构图。'}],media:[]
}]}};
@@ -42,7 +42,7 @@ def main():
const current=(await send({type:'GET_CAPTURE_WORKSPACE'})).draft;
const next=m.type==='ADD_ACTIVE_SELECTION_TO_DRAFT'
? addDraftFragment(current,{id:'selected-extra',text:'网页高亮补充:使用自然光与清晰构图。',sourceUrl:'https://example.com/post'}).draft
- :addDraftVisual(current,extra);
+ :addDraftVisual(current,m.type==='CAPTURE_ACTIVE_TAB_TO_DRAFT'?screenshot:extra);
return send({type:'UPDATE_CAPTURE_DRAFT',draft:next});
}
return send(m);
@@ -62,6 +62,13 @@ def main():
assert len(boxes)==5 and len({b['top'] for b in boxes})==1 and len({b['h'] for b in boxes})==1 and not any(b['overflow'] for b in boxes),boxes
page.locator('#add-selection').click()
expect(page.locator('.page-capture-excerpt')).to_contain_text('网页高亮补充')
+ expect(page.locator('.page-capture-excerpt')).to_contain_text('网页主帖原始提示词')
+ expect(page.locator('.page-capture-excerpt')).to_contain_text('已有的选中文字')
+ expect(page.locator('.page-capture-thumbnails img')).to_have_count(1)
+ page.locator('#page-capture-undo-region').click()
+ expect(page.locator('.page-capture-excerpt')).not_to_contain_text('网页高亮补充')
+ expect(page.locator('.page-capture-excerpt')).to_contain_text('网页主帖原始提示词')
+ page.locator('#add-selection').click()
page.locator('#add-clipboard').click()
expect(page.locator('.page-capture-excerpt')).to_contain_text('剪贴板补充')
page.locator('#add-smart-visuals').click()
@@ -78,15 +85,16 @@ def main():
expect(page.locator('.page-capture-thumbnails img')).to_have_count(2)
page.evaluate('()=>window.cancelScreenshot=false')
page.locator('#add-screenshot').click()
- expect(page.locator('.page-capture-thumbnails img')).to_have_count(2)
+ expect(page.locator('.page-capture-thumbnails img')).to_have_count(3)
+ expect(page.locator('.page-capture-excerpt')).to_contain_text('网页主帖原始提示词')
expect(page.locator('#page-capture')).to_be_visible()
# Supplementary webpage cancel and confirmation both retain the current case.
page.locator('#add-page-capture').click();page.locator('#page-capture-cancel').click()
expect(page.locator('.page-capture-excerpt')).to_contain_text('剪贴板补充')
page.locator('#add-page-capture').click();page.locator('.page-capture-confirm').click()
- expect(page.locator('.page-capture-thumbnails img')).to_have_count(2)
+ expect(page.locator('.page-capture-thumbnails img')).to_have_count(3)
expect(page.locator('.page-capture-excerpt')).to_contain_text('网页高亮补充')
- for width in (320,390):
+ for width in (320,390,860):
page.set_viewport_size({'width':width,'height':844})
page.locator('#capture-add-more-actions').scroll_into_view_if_needed()
page.screenshot(path=str(Path(tempfile.gettempdir()) / f'pd-capture-additions-{width}.png'))
@@ -100,7 +108,7 @@ def main():
assert len(saved)==1,saved
entry=saved[0]
for text in ['已有的选中文字','网页主帖','网页高亮补充','剪贴板补充']:assert text in entry['text'],entry['text']
- assert len(entry['mediaAssets'])==2,entry['mediaAssets']
+ assert len(entry['mediaAssets'])==3,entry['mediaAssets']
assert '保留标签' in entry['customLabels'],entry
assert entry['classification']['pathIds']==['content:prompt:image'],entry['classification']
projects=page.evaluate("async()=>(await chrome.runtime.sendMessage({type:'GET_STATE'})).organizerState.collections")
@@ -128,7 +136,7 @@ def main():
assert len(updated)==1 and updated[0]['id']==entry['id'],updated
assert updated[0]['text'].count('第二次补充:必须写回已经保存的案例。')==1,updated[0]['text']
for text in ['已有的选中文字','网页主帖','网页高亮补充','剪贴板补充']: assert text in updated[0]['text']
- assert len(updated[0]['mediaAssets'])==2
+ assert len(updated[0]['mediaAssets'])==3
remaining_draft=page.evaluate("async()=>(await chrome.runtime.sendMessage({type:'GET_CAPTURE_WORKSPACE'})).draft")
assert not remaining_draft['fragments'],remaining_draft
print({'recaptureSupplementSavedToSameCase':True,'retryNoDuplicateText':True})
@@ -148,5 +156,33 @@ def main():
assert [v['id'] for v in remaining['visuals']]==['pending-image'],remaining
assert page.evaluate("async()=>(await (await import('./image-store.js')).getScreenshotBlob('pending-image')).size")>0
print({'text_only_keeps_image':True,'project_saved':True,'manual_type_saved':True})
- print({'one_case':True,'all_five_methods':True,'cancel_preserved':True,'duplicate_ignored':True,'media_readback':blobs,'tags_preserved':True,'widths':[320,390]})
+ print({'one_case':True,'all_five_methods':True,'cancel_preserved':True,'duplicate_ignored':True,'media_readback':blobs,'tags_preserved':True,'widths':[320,390,860]})
+ # With no single target, a manual pick is an additional candidate, never a replacement.
+ page.evaluate("""async()=>{
+ const {createCaptureDraft}=await import('./capture-draft.js');
+ await chrome.runtime.sendMessage({type:'UPDATE_CAPTURE_DRAFT',draft:createCaptureDraft()});
+ const base=window.webSnapshot.candidates[0];
+ window.webSnapshot={...window.webSnapshot,id:'multiple-cases',captureMode:'list',selections:[],
+ candidates:['Alpha','Beta'].map(name=>({...base,id:name,title:name,canonicalUrl:'https://example.com/'+name}))};
+ window.dispatchEvent(new Event('focus'));
+ }""")
+ expect(page.locator('#normal-start')).to_be_visible()
+ page.locator('#start-page-capture').click()
+ expect(page.locator('.page-capture-item')).to_have_count(2)
+ page.locator('#add-selection').click()
+ expect(page.locator('.page-capture-item')).to_have_count(3)
+ expect(page.locator('.page-capture-item.confirmed')).to_have_count(1)
+ page.locator('#page-capture-undo-region').click()
+ expect(page.locator('.page-capture-item')).to_have_count(2)
+ expect(page.locator('.page-capture-item.confirmed')).to_have_count(0)
+ page.locator('.page-capture-confirm').nth(0).click()
+ page.locator('.page-capture-confirm').nth(1).click()
+ expect(page.locator('.page-capture-item.confirmed')).to_have_count(2)
+ page.locator('#add-selection').click()
+ expect(page.locator('.page-capture-item.confirmed')).to_have_count(3)
+ expect(page.locator('#page-capture-list')).to_contain_text('Alpha')
+ expect(page.locator('#page-capture-list')).to_contain_text('Beta')
+ page.locator('#page-capture-undo-region').click()
+ expect(page.locator('.page-capture-item.confirmed')).to_have_count(2)
+ print({'unselectedCandidatesPreserved':True,'multipleSelectedCasesPreserved':True,'undoPreserved':True})
if __name__=='__main__':main()
diff --git a/test/composer_defaults_share_e2e.py b/test/composer_defaults_share_e2e.py
index b2d4eca..057b072 100644
--- a/test/composer_defaults_share_e2e.py
+++ b/test/composer_defaults_share_e2e.py
@@ -51,7 +51,7 @@ def main():
if theme == 'light':
page.locator('[data-settings-tab="general"]').click()
with page.expect_navigation(wait_until='networkidle'):
- page.locator('#ui-theme').uncheck()
+ page.locator('#ui-theme').select_option('light')
page.locator('#open-settings').click()
page.locator('[data-settings-tab="rules"]').click()
page.locator('[data-analysis-kind="composer"]').click()
diff --git a/test/composer_generation_e2e.py b/test/composer_generation_e2e.py
index be28cab..13f46fb 100644
--- a/test/composer_generation_e2e.py
+++ b/test/composer_generation_e2e.py
@@ -8,7 +8,7 @@ from threading import Event, Thread
from playwright.sync_api import expect
from composer_e2e_support import composer_request_payload, set_composer_reference_media, set_composer_direction
-from e2e_support import ai_configuration_fixture, base_entry, extension_session
+from e2e_support import ai_configuration_fixture, base_entry, extension_session, wait_for_async_condition
GENERATED_PNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
@@ -79,16 +79,16 @@ def current_session(page) -> dict:
def completed_session(page) -> dict:
- page.wait_for_function(
+ # Poll the resolved background result, then assert against that same snapshot.
+ return wait_for_async_condition(page,
"""async () => {
const sessionId = new URL(location.href).searchParams.get('session');
const response = await chrome.runtime.sendMessage({type: 'GET_COMPOSER_SESSION', sessionId});
return response?.ok === true && response.session?.activeTurn == null
- && response.session.messages?.at(-1)?.role === 'assistant';
+ && response.session.messages?.at(-1)?.role === 'assistant' ? response.session : false;
}""",
timeout=10_000,
)
- return current_session(page)
def main() -> None:
diff --git a/test/diagnostic_controls_components_e2e.py b/test/diagnostic_controls_components_e2e.py
index b206130..0b265a0 100644
--- a/test/diagnostic_controls_components_e2e.py
+++ b/test/diagnostic_controls_components_e2e.py
@@ -24,7 +24,7 @@ def main():
composer_js = (ROOT / 'extension/composer-page.js').read_text()
assistant_js = (ROOT / 'extension/collector-capture-assistant.js').read_text()
parts = {
- 'settings': between(library[library.index('<section id="settings-general-panel"'):], '<section class="setting-section appearance-grid">', '</section>') + '</section>',
+ 'settings': between(library, '<section class="settings-diagnostics">', '</section>') + '</section>',
'options': between(composer, '<details id="composer-options"', '</details>') + '</details>',
'analysis': re.search(r'<button id="copy-analysis-diagnostics".*?</button>', library).group(),
'settingsBind': between(library_js, 'bindDiagnosticControls({', '\nbindAppearanceControls'),
@@ -91,7 +91,7 @@ def main():
results.append({'width':width,'theme':theme,'entries':len(diagnostic_ids),'defaultHidden':True,'enabledVisible':True,'closedDialog':True,'reopenPersisted':True})
page.evaluate('window.failSave=true')
page.locator('#ui-diagnostics').click()
- page.wait_for_function("document.querySelector('#library-settings-feedback').textContent==='保存失败'")
+ page.wait_for_function("document.querySelector('#diagnostic-settings-feedback').textContent==='保存失败'")
assert not page.locator('#ui-diagnostics').is_checked()
page.screenshot(path=str(output/'save-failure-390-dark.png'), animations='disabled')
(output/'results.json').write_text(json.dumps(results,ensure_ascii=False,indent=2))
diff --git a/test/extension-update-ui.test.js b/test/extension-update-ui.test.js
index 03c58b7..880e1cf 100644
--- a/test/extension-update-ui.test.js
+++ b/test/extension-update-ui.test.js
@@ -6,10 +6,12 @@ const root = new URL("../extension/", import.meta.url);
const [html, source, local] = await Promise.all(["library.html", "library.js", "local-extension-upgrade-ui.js"].map(path => readFile(new URL(path, root), "utf8")));
const $ = load(html);
-test("settings footer is compact with named icons and on-demand about details", () => {
+test("settings update actions stay in a shared footer with a visible check label", () => {
const about = $(".settings-about");
assert.equal(about.find("#about-version").length, 1);
assert.equal(about.find('#check-extension-update[aria-label="检查更新"] svg').length, 1);
+ assert.equal(about.parent().hasClass("settings-shell"), true);
+ assert.equal(about.find('#check-extension-update span').text(), "检查更新");
assert.equal(about.find("#apply-extension-update[hidden]").length, 1);
assert.equal(about.find("#open-about").length, 1);
assert.equal(about.find("#update-explanation, #update-channel, #update-checked-at").length, 0);
diff --git a/test/frontend_compact_surfaces_e2e.py b/test/frontend_compact_surfaces_e2e.py
index 07f0015..7fe1d8b 100644
--- a/test/frontend_compact_surfaces_e2e.py
+++ b/test/frontend_compact_surfaces_e2e.py
@@ -35,10 +35,10 @@ with extension_session('pd-six-surfaces-', viewport={'width':1440,'height':960})
for width,height,locale,theme in [(1440,960,'zh-CN','dark'),(390,844,'en','light')]:
page.set_viewport_size({'width':width,'height':height})
page.locator('[data-settings-tab="general"]').click()
- # Theme is a switch (dark on); language stays a multi-choice select.
- if page.locator('#ui-theme').is_checked()!=(theme=='dark'):
+ # Theme and language are explicit choices.
+ if page.locator('#ui-theme').input_value()!=theme:
with page.expect_navigation(wait_until='networkidle'):
- page.locator('#ui-theme').set_checked(theme=='dark')
+ page.locator('#ui-theme').select_option(theme)
page.locator('#open-settings').click()
page.locator('[data-settings-tab="general"]').click()
if page.locator('#ui-locale').input_value()!=locale:
diff --git a/test/generic_component_capture_e2e.py b/test/generic_component_capture_e2e.py
index 56479b4..bd19bf0 100644
--- a/test/generic_component_capture_e2e.py
+++ b/test/generic_component_capture_e2e.py
@@ -71,7 +71,14 @@ with extension_session('pd-component-capture-') as run:
assert 'all six shots' in broad['html'] and 'Unrelated' not in broad['html'], broad
# The actual extension preview and original save/readback on a clean profile.
run.seed_storage(panel, {'entries':[], 'uiPreferences':{'theme':'dark','motion':'reduced'}, 'capturePermissionOnboarding':{'version':1,'acknowledgedAt':'2026-10-10T00:00:00Z'}})
+ # Start the single-selection scenario with no automatic preview to append to.
+ page.goto('about:blank')
+ panel.bring_to_front()
panel.reload(wait_until='networkidle')
+ panel.evaluate("async()=>{await import('./collector.js');await chrome.tabs.query({active:true,currentWindow:true})}")
+ expect(panel.locator('#normal-start')).to_be_visible()
+ page.goto(ORIGIN + '/work', wait_until='networkidle')
+ page.add_script_tag(content=picker)
page.bring_to_front()
panel.evaluate("()=>document.querySelector('#start-selection').click()")
expect(page.locator('#promptdirector-content-picker')).to_be_attached()
diff --git a/test/image-original-priority.test.js b/test/image-original-priority.test.js
new file mode 100644
index 0000000..606b001
--- /dev/null
+++ b/test/image-original-priority.test.js
@@ -0,0 +1,65 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { normalizePageCaptureCandidate, pageCaptureMediaFetchCandidates, resolvePageCaptureImage } from '../extension/page-capture.js';
+import { normalizePageCaptureSitePayload } from '../extension/page-capture-site-adapters.js';
+
+const original = 'https://example.com/original.jpg';
+const preview = 'https://example.com/preview.jpg';
+const media = {kind:'image', url:preview, width:640, height:360, sourceKind:'current', variants:[
+ {url:preview, sourceKind:'picture-srcset', declaredWidth:8000},
+ {url:original, sourceKind:'site-original'}
+]};
+
+test('generic and adapter images share original priority through normalization and actual download', async () => {
+ for (const adapter of ['generic','x','pinterest','jimeng','krea','liblibai','higgsfield','midjourney']) {
+ const candidate = normalizePageCaptureCandidate({id:adapter,adapter,title:'Original priority',canonicalUrl:'https://example.com/art',media:[media]});
+ assert.deepEqual(pageCaptureMediaFetchCandidates(candidate.media[0]), [original,preview]);
+ assert.equal(candidate.media[0].width, 0);
+ const calls = [];
+ const result = await resolvePageCaptureImage(candidate.media[0], {
+ fetchMedia:async url=>{calls.push(`public:${url}`); if(url===original) throw Error('403'); return new Blob(['preview']);},
+ fetchSessionMedia:async url=>{calls.push(`session:${url}`); return new Blob(['original']);},
+ decodeDataUrl:()=>assert.fail('no pixels')
+ });
+ assert.equal(result.sourceUrl, original);
+ assert.equal(result.usedReducedImage, false);
+ assert.deepEqual(calls, [`public:${original}`,`session:${original}`]);
+ }
+});
+test('generic original failure is disclosed when a preview is saved', async () => {
+ const result = await resolvePageCaptureImage(media, {
+ fetchMedia:async url=>{if(url===original)throw Error('404');return new Blob(['preview']);},
+ sessionMediaAllowed:false, decodeDataUrl:()=>assert.fail('no pixels')
+ });
+ assert.equal(result.sourceUrl,preview);
+ assert.equal(result.usedReducedImage,true);
+});
+test('rediscovering an existing URL as original upgrades its priority without duplicate requests', () => {
+ assert.deepEqual(pageCaptureMediaFetchCandidates({...media,variants:[
+ {url:original,sourceKind:'current'},{url:preview,sourceKind:'picture-srcset',declaredWidth:8000},
+ {url:original,sourceKind:'site-original'}
+ ]}),[original,preview]);
+});
+test('Liblib, Krea and Higgsfield thumbnail-only payloads are not labelled as originals', () => {
+ const cases = [
+ [{adapter:'liblibai',data:{uuid:'art',images:[{previewUrl:'https://liblibai-online.liblib.cloud/preview.jpg'}]}},'https://www.liblib.art/imageinfo/art'],
+ [{adapter:'krea',jsonLd:[{'@type':'ImageObject',thumbnailUrl:'https://gen.krea.ai/preview.jpg'}]},'https://www.krea.ai/image/12345678-1234-4234-8234-123456789012'],
+ [{adapter:'higgsfield',jsonLd:[{'@type':'ImageObject',thumbnailUrl:'https://images.higgs.ai/preview.jpg'}]},'https://higgsfield.ai/@artist/projects/art']
+ ];
+ for (const [payload,url] of cases) {
+ const normalized = normalizePageCaptureSitePayload(payload,url);
+ assert.ok(normalized?.media.length, JSON.stringify(payload));
+ assert.equal(normalized.media[0].sourceKind,'current', JSON.stringify(payload));
+ }
+});
+
+test('a cross-frame video source keeps its concrete element provenance when the same URL has a generic fallback', () => {
+ const url = 'https://example.com/film.mp4';
+ const candidate = normalizePageCaptureCandidate({canonicalUrl:'https://example.com/work',media:[{
+ id:'film',kind:'video',url,width:1920,height:1080,sourceKind:'source',
+ variants:[{url,sourceKind:'source'},{url,sourceKind:'video-element'}]
+ }]});
+ assert.equal(candidate.media[0].sourceKind,'video-element');
+ assert.equal(candidate.media[0].url,url);
+ assert.deepEqual(candidate.media[0].variants.map(v=>v.url),[url]);
+});
diff --git a/test/library-feedback-routing.test.js b/test/library-feedback-routing.test.js
index 479d5b0..7b2686a 100644
--- a/test/library-feedback-routing.test.js
+++ b/test/library-feedback-routing.test.js
@@ -53,13 +53,13 @@ test('batch errors stay inside the current analysis dialog above settings', () =
assert.deepEqual(view.messages, [{ target: 'batch', message: 'preview failed', error: true }]);
});
-test('failed appearance writes display inside open settings and restore the saved switch value', async () => {
+test('failed appearance writes display inside open settings and restore the saved theme choice', async () => {
const view = fixture({ settingsOpen: true });
vm.runInContext(source.slice(appearance.start, appearance.end), view.context);
- view.elements.uiTheme.checked = false;
+ view.elements.uiTheme.value = 'light';
view.elements.uiTheme.dispatchEvent(new Event('change'));
await new Promise(resolve => setImmediate(resolve));
assert.deepEqual(view.messages, [{ target: 'settings', message: 'preference write failed', error: true }]);
- assert.equal(view.elements.uiTheme.checked, true);
+ assert.equal(view.elements.uiTheme.value, 'dark');
assert.equal(view.elements.uiTheme.disabled, false);
});
diff --git a/test/library-navigation.test.js b/test/library-navigation.test.js
index 0f50081..12ece2f 100644
--- a/test/library-navigation.test.js
+++ b/test/library-navigation.test.js
@@ -26,7 +26,7 @@ test("top navigation keeps search-adjacent actions focused on adding, creating,
assert.doesNotMatch(html, /动态视图|save-dynamic-view|dynamic-view-list/);
});
-test("about details are on demand while version stays at the bottom of general settings", async () => {
+test("about details are on demand while version stays at the bottom of settings", async () => {
const about = html.slice(html.indexOf('<footer class="settings-about"'), html.indexOf("</footer>", html.indexOf('<footer class="settings-about"')));
const script = await readFile(new URL("../extension/library.js", import.meta.url), "utf8");
assert.match(about, /id="about-version">PromptDirector</);
diff --git a/test/library-permission-settings.test.js b/test/library-permission-settings.test.js
index 0b0bd11..f94d925 100644
--- a/test/library-permission-settings.test.js
+++ b/test/library-permission-settings.test.js
@@ -15,7 +15,7 @@ test("general settings show separate web-capture and clipboard permission status
assert.match(html, /id="revoke-capture-web-permission"/);
assert.match(html, /id="revoke-capture-clipboard-permission"/);
assert.doesNotMatch(html, /这里不会读取剪贴板/);
- assert.match(css, /\.capture-permission-list\s*\{/);
+ assert.match(css, /\.capture-permission-list[^{}]*\{/);
assert.match(css, /\.capture-permission-row\s*\{/);
});
diff --git a/test/library_discovery_e2e.py b/test/library_discovery_e2e.py
index 31c6f7e..1f51e5a 100644
--- a/test/library_discovery_e2e.py
+++ b/test/library_discovery_e2e.py
@@ -84,12 +84,11 @@ def main() -> None:
});"""
)
library = session.open_page("library.html", wait_until="networkidle")
- # 2026-10-11 confirmed appearance model: the manual light/dark control is a switch
- # (checked = dark), next to the "follow system" switch.
+ # The single theme selector uses the stored light/dark/system choices.
library.locator("#ui-theme").evaluate(
"""input => {
- if (!input.checked) {
- input.checked = true;
+ if (input.value !== 'dark') {
+ input.value = 'dark';
input.dispatchEvent(new Event('change', {bubbles: true}));
}
}"""
@@ -251,7 +250,7 @@ def main() -> None:
library.screenshot(path=str(Path(os.environ['PD_E2E_ARTIFACT_DIR']) / 'similar-refreshed-390.png'))
library.locator("#ui-theme").evaluate(
"""input => {
- input.checked = false;
+ input.value = 'light';
input.dispatchEvent(new Event('change', {bubbles: true}));
}"""
)
diff --git a/test/library_selection_menu_scroll_e2e.py b/test/library_selection_menu_scroll_e2e.py
new file mode 100644
index 0000000..54d94a8
--- /dev/null
+++ b/test/library_selection_menu_scroll_e2e.py
@@ -0,0 +1,97 @@
+"""Management menus must remain reachable after the library leaves its first screen."""
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+
+from playwright.sync_api import expect
+
+from e2e_support import base_entry, extension_session, scroll_to_case
+
+
+def open_menu(page, name):
+ menu = page.locator(f"#selection-{name}-menu")
+ menu.locator(":scope > summary").click()
+ panel = menu.locator(".selection-menu-panel")
+ expect(panel).to_be_visible()
+ geometry = panel.evaluate("""panel => {
+ const r = panel.getBoundingClientRect();
+ const button = [...panel.querySelectorAll('button, input, select')]
+ .find(el => !el.disabled && el.getBoundingClientRect().height > 0);
+ const b = button.getBoundingClientRect();
+ return {top: r.top, bottom: r.bottom, left: r.left, right: r.right,
+ viewportWidth: innerWidth, viewportHeight: innerHeight,
+ reachable: button.contains(document.elementFromPoint(b.x + b.width / 2, b.y + b.height / 2))};
+ }""")
+ assert geometry["top"] >= 0 and geometry["bottom"] <= geometry["viewportHeight"], geometry
+ assert geometry["left"] >= 0 and geometry["right"] <= geometry["viewportWidth"], geometry
+ assert geometry["reachable"], geometry
+ return panel
+
+
+def main():
+ artifacts = Path(os.environ.get("PD_E2E_ARTIFACT_DIR", "/tmp/pd-selection-menu-scroll"))
+ artifacts.mkdir(parents=True, exist_ok=True)
+ results = []
+ for width, theme, locale in [(1280, "dark", "zh-CN"), (760, "light", "en"), (390, "dark", "zh-CN")]:
+ with extension_session("pd-selection-menu-scroll-", viewport={"width": width, "height": 760}) as session:
+ setup = session.open_page("collector.html")
+ session.seed_storage(setup, {
+ "schemaVersion": 28,
+ "entries": [base_entry(f"scroll-{i}", f"滚动管理案例 {i}", "管理回归内容\n" * 12,
+ "content:prompt:text", i % 60) for i in range(90)],
+ "uiPreferences": {"locale": locale, "theme": theme, "motion": "reduced"},
+ })
+ page = session.open_page("library.html", wait_until="networkidle")
+ expect(page.locator("body")).to_have_attribute("data-library-state", "ready")
+ page.locator("#select-cases").click()
+ expect(page.locator("#share-bar")).to_be_visible()
+ for index in range(2):
+ page.locator("#case-list > .case-card").nth(index).click()
+ selected = page.locator(".case-card.selected-for-share").evaluate_all(
+ "cards => cards.map(card => card.dataset.entryId)")
+
+ for scroll_y in [0, 900, 2000]:
+ page.evaluate("(y) => scrollTo(0, y)", scroll_y)
+ page.wait_for_function("(y) => Math.abs(scrollY - y) < 1", arg=scroll_y)
+ for name in ["project", "classification", "label", "more"]:
+ open_menu(page, name)
+ if name == "more" and scroll_y == 2000:
+ page.screenshot(path=str(artifacts / f"more-{width}-{theme}-{locale}.png"),
+ animations="disabled")
+ page.keyboard.press("Escape")
+ expect(page.locator(f"#selection-{name}-menu")).not_to_have_attribute("open", "")
+ assert page.evaluate("scrollY") == scroll_y
+
+ open_menu(page, "more")
+ page.locator("#selection-clear").click()
+ expect(page.locator("#selection-selected-actions")).to_be_hidden()
+ page.locator("#share-cancel").click()
+ expect(page.locator("#select-cases")).to_be_visible()
+
+ # A real batch action after scrolling must target the original selection.
+ page.locator("#select-cases").click()
+ expect(page.locator("#share-bar")).to_be_visible()
+ for entry_id in selected:
+ scroll_to_case(page, entry_id)
+ page.locator(f'.case-card[data-entry-id="{entry_id}"]').click()
+ page.evaluate("scrollTo(0, 900)")
+ page.wait_for_function("scrollY === 900")
+ open_menu(page, "label")
+ page.locator("#selection-label-input").fill("滚动后管理")
+ page.locator("#selection-add-labels").click()
+ expect(page.locator("#selection-label-menu")).not_to_have_attribute("open", "")
+ tagged = page.evaluate("""async () => {
+ const state = await chrome.runtime.sendMessage({type: 'GET_STATE'});
+ return state.entries.filter(e => e.customLabels.includes('滚动后管理')).map(e => e.id);
+ }""")
+ assert sorted(tagged) == sorted(selected), tagged
+ expect(page.locator("#select-cases")).to_be_visible()
+ results.append({"width": width, "theme": theme, "locale": locale,
+ "scrollPositions": [0, 900, 2000], "tagged": tagged})
+ print(json.dumps(results, ensure_ascii=False))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/test/native-video.test.js b/test/native-video.test.js
index 7443152..1ffb6d6 100644
--- a/test/native-video.test.js
+++ b/test/native-video.test.js
@@ -39,6 +39,10 @@ test('the installed standalone component reports actual readiness through the sa
assert.deepEqual(chrome.hosts, [VIDEO_COMPONENT.host]);
});
+test('an installer patch keeps an already working video component usable', async () => {
+ assert.deepEqual(await nativeVideoStatus(browser({ componentVersion: '0.1.0' })), { available: true, updateRequired: false });
+});
+
test('an outdated component offers the same simple update flow instead of failing the selected video later', async () => {
assert.deepEqual(await nativeVideoStatus(browser({ componentVersion: '0.0.1' })), { available: false, updateRequired: true });
await assert.rejects(openNativeVideoSession(browser({ componentVersion: '0.0.1' })), { code: 'video_component_required' });
diff --git a/test/packaged_video_setup_e2e.py b/test/packaged_video_setup_e2e.py
index e5ff8f7..c2ccde0 100644
--- a/test/packaged_video_setup_e2e.py
+++ b/test/packaged_video_setup_e2e.py
@@ -56,21 +56,21 @@ def main():
}""")
assert response.get('code') == 'video_component_required', response
collector.reload()
- expect(collector.locator('#video-component-setup button')).to_have_text('安装视频组件')
+ expect(collector.locator('#video-component-setup [data-video-component-action=manual]')).to_have_text('手动安装')
for width in [390, 1280]:
collector.set_viewport_size({'width': width, 'height': 850})
collector.screenshot(path=str(evidence / f'required-{width}.png'))
- collector.locator('#video-component-setup button').click()
+ collector.locator('#video-component-setup [data-video-component-action=manual]').click()
expect(collector.locator('#video-component-setup')).to_contain_text('正在下载安装包')
collector.screenshot(path=str(evidence / 'downloading.png'))
collector.close()
collector = run.open_page('collector.html')
expect(collector.locator('#video-component-setup')).to_contain_text('正在下载安装包')
collector.evaluate("async()=>chrome.storage.local.set({setupComplete:true})")
- expect(collector.locator('#video-component-setup button')).to_have_text('打开安装包', timeout=15000)
+ expect(collector.locator('#video-component-setup [data-video-component-action=manual]')).to_have_text('打开安装包', timeout=15000)
collector.screenshot(path=str(evidence / 'open-installer.png'))
collector.evaluate("() => {chrome.downloads.open = async id => chrome.storage.local.set({setupOpened:id});}")
- collector.locator('#video-component-setup button').click()
+ collector.locator('#video-component-setup [data-video-component-action=manual]').click()
assert wait_for_async_condition(collector, "async()=>(await chrome.storage.local.get('setupOpened')).setupOpened") == 123
# Register the real offline payload for this disposable browser only.
registration = run.profile_dir / 'NativeMessagingHosts/com.promptdirector.video.json'
diff --git a/test/page_capture_e2e.py b/test/page_capture_e2e.py
index a5da7b7..3e3d745 100644
--- a/test/page_capture_e2e.py
+++ b/test/page_capture_e2e.py
@@ -5,7 +5,7 @@ from pathlib import Path
from playwright.sync_api import expect
-from e2e_support import extension_session
+from e2e_support import extension_session, wait_for_async_condition
ARTICLE = b"""<!doctype html><html><head>
@@ -20,7 +20,7 @@ ARTICLE = b"""<!doctype html><html><head>
<p>This article contains enough deliberate editorial text to exercise the real injected page capture path. The scanner must produce a preview before anything is stored, and the reader must remain in control of the article text and every media item.</p>
<p>A second paragraph includes <a href="/evidence">evidence</a> and makes the article boundary unambiguous while keeping navigation, logos, avatars, buttons and advertising outside the saved content.</p>
<picture><source media="(min-width: 1px)" srcset="/hero-picture-800.png 800w, /hero-picture-2000.png 2000w" sizes="400px">
-<img alt="Primary artwork" src="/hero-400.png" srcset="/hero-400.png 400w, /hero-1600.png 1600w" sizes="400px" style="display:block;width:720px;height:480px"></picture>
+<img alt="Primary artwork" src="/hero-400.png" data-original="/hero-original.png" srcset="/hero-400.png 400w, /hero-1600.png 1600w" sizes="400px" style="display:block;width:720px;height:480px"></picture>
<img alt="Secondary artwork" src="/secondary-640.png" srcset="/secondary-640.png 640w, /secondary-1280.png 1280w" sizes="400px" style="display:block;width:640px;height:420px">
<img alt="Deferred artwork" src="/placeholder.png" data-src="/deferred-original.png" style="display:block;width:600px;height:400px">
<img alt="Animated process" src="/animation.gif" style="display:block;width:480px;height:320px">
@@ -149,8 +149,7 @@ def main() -> None:
media_labels = collector.locator(".page-capture-article-media").all_text_contents()
media_sources = collector.locator(".page-capture-article-media img").evaluate_all("nodes => nodes.map(node => node.src)")
assert len(media_labels) == 5, {"labels": media_labels, "sources": media_sources}
- assert media_sources[0].endswith("/hero-picture-2000.png"), {"labels": media_labels, "sources": media_sources}
- assert "候选 2000px" in media_labels[0] and "picture 响应图" in media_labels[0], media_labels
+ assert media_sources[0].endswith("/hero-original.png"), {"labels": media_labels, "sources": media_sources}
assert media_sources[1].endswith("/secondary-1280.png"), {"labels": media_labels, "sources": media_sources}
assert "候选 1280px" in media_labels[1], media_labels
assert "延迟加载原图" in media_labels[2], media_labels
@@ -179,8 +178,8 @@ def main() -> None:
expect(collector.locator(".page-capture-media-review-group")).to_have_count(0)
expect(collector.locator("#page-capture-media-review-status")).to_contain_text("5 项媒体")
expect(collector.locator("#page-capture-save")).to_be_enabled()
- # Direct picking replaces the automatic scope, then appends subsequent choices.
- for selector in ['article', '#appendix']:
+ # The first manual pick must retain the automatic article and its prompt.
+ for selector in ['img[alt="Primary artwork"]', '#appendix']:
fixture.bring_to_front()
collector.evaluate("() => document.querySelector('#add-selection').click()")
expect(fixture.locator('#promptdirector-content-picker')).to_be_attached(timeout=8000)
@@ -200,6 +199,20 @@ def main() -> None:
expect(collector.locator("#page-capture-media-review-list .page-capture-media-review-item")).to_have_count(6)
expect(collector.locator("#page-capture-media-review-status")).to_contain_text("6 项媒体")
expect(collector.locator("#page-capture-save")).to_be_enabled()
+ # Reopening the preview must preserve both the original article and the new pick.
+ wait_for_async_condition(collector, """async url => {
+ const {getLibraryStorage}=await import('./library-storage.js');
+ const batch=(await getLibraryStorage().get('captureAssistantDialog')).captureAssistantDialog?.pages?.[url]?.pendingBatch;
+ const chosen=batch?.candidates.find(c=>c.id===batch.selections[0]?.candidateId);
+ return chosen?.contentText.includes('downloadable production notes') && !chosen.contentText.includes('A second paragraph');
+ }""", arg=fixture_url)
+ fixture.bring_to_front()
+ collector.reload(wait_until="networkidle")
+ expect(collector.locator(".page-capture-item.confirmed")).to_have_count(1, timeout=10000)
+ collector.locator('.page-capture-preview-details').first.evaluate('node=>node.open=true')
+ expect(collector.locator(".page-capture-item.confirmed .page-capture-article")).to_contain_text("downloadable production notes")
+ expect(collector.locator(".page-capture-item.confirmed .page-capture-article")).to_contain_text("This article contains enough")
+ expect(collector.locator(".page-capture-item.confirmed .page-capture-article")).not_to_contain_text("A second paragraph")
collector.locator("#page-capture-save").click()
# Successful content is committed immediately; the failed video remains available for retry.
expect(collector.locator("#page-capture-help")).to_contain_text("有效视频文件", timeout=60000)
@@ -226,13 +239,13 @@ def main() -> None:
assert block_kinds.count("document") == 1, media_saved[0]
assert block_kinds.count("link") == 1, media_saved[0]
assert any(asset["sourceUrl"].endswith("/placeholder.png") for asset in media_saved[0]["mediaAssets"]), media_saved[0]
+ assert any(asset["sourceUrl"].endswith("/hero-original.png") for asset in media_saved[0]["mediaAssets"]), media_saved[0]
assert any(asset.get("mimeType") == "image/gif" and asset["sourceUrl"].endswith("/animation.gif") for asset in media_saved[0]["mediaAssets"]), media_saved[0]
assert any(asset.get("kind") == "video" and asset["sourceUrl"].endswith("/film.mp4") and asset['storageMode'] == 'managed' and asset['byteSize'] == len(video_bytes) for asset in media_saved[0]["mediaAssets"]), media_saved[0]
assert any(asset.get("kind") == "document" and asset.get("mimeType") == "application/pdf" for asset in media_saved[0]["mediaAssets"]), media_saved[0]
assert not any(asset.get("sourceUrl", "").endswith("/unsafe-package.zip") for asset in media_saved[0]["mediaAssets"]), media_saved[0]
- # The reader's own article + appendix picks keep the exact chosen scope,
- # which this save must record instead of claiming a whole-document scan.
- assert media_saved[0]["sourceFacts"]["captureScope"] == "selection", media_saved[0]
+ # Supplemental picking retains the original document rather than replacing its provenance.
+ assert media_saved[0]["sourceFacts"]["captureScope"] == "document", media_saved[0]
assert media_saved[0]["sourceFacts"]["pageType"] == "article", media_saved[0]
assert media_saved[0]["sourceFacts"]["extractionMethod"] == "page", media_saved[0]
library = run.open_page("library.html", wait_until="networkidle")
diff --git a/test/page_capture_reactive_template_e2e.py b/test/page_capture_reactive_template_e2e.py
index 34f9c96..e13079e 100644
--- a/test/page_capture_reactive_template_e2e.py
+++ b/test/page_capture_reactive_template_e2e.py
@@ -72,6 +72,11 @@ def main():
('zh-CN','手选范围已失效,请在当前页面重新选择一个案例')]:
panel.evaluate("locale=>chrome.storage.local.set({uiPreferences:{locale,theme:'dark',motion:'reduced'}})",locale)
panel.reload(wait_until='networkidle')
+ # Each locale checks a fresh explicit pick. A prior or automatic
+ # preview is now retained by supplementation until explicitly closed.
+ if panel.locator('#page-capture').is_visible():
+ panel.locator('#page-capture-cancel').click()
+ expect(panel.locator('#page-capture')).to_be_hidden()
source.bring_to_front()
panel.locator('#start-selection').evaluate('button=>button.click()')
expect(source.locator('#promptdirector-content-picker')).to_be_attached()
diff --git a/test/platform_video_capture_e2e.py b/test/platform_video_capture_e2e.py
index c94af18..9a645bb 100644
--- a/test/platform_video_capture_e2e.py
+++ b/test/platform_video_capture_e2e.py
@@ -74,7 +74,7 @@ def main():
assert len(state['entries']) == 2, 'Missing originals must not create a player or a false saved case'
collector.reload()
expect(collector.locator('#video-component-setup')).to_be_visible()
- expect(collector.locator('#video-component-setup button')).to_have_text('安装视频组件')
+ expect(collector.locator('#video-component-setup [data-video-component-action=manual]')).to_have_text('手动安装')
library = run.open_page('library.html')
expect(library.locator(f'.case-card[data-entry-id="{saved["id"]}"]')).to_be_visible()
expect(library.locator('#library-loading')).to_be_hidden()
diff --git a/test/run_e2e.py b/test/run_e2e.py
index d3847cd..e0a5867 100644
--- a/test/run_e2e.py
+++ b/test/run_e2e.py
@@ -21,6 +21,7 @@ SCRIPTS = [
"detail_media_stability_components_e2e.py",
"capture_source_text_e2e.py",
"video_setup_restart_e2e.py",
+ "video_setup_refresh_e2e.py",
"capture_access_gate_e2e.py",
"agent_capture_preview_e2e.py",
"agent_capture_commit_receipt_e2e.py",
@@ -150,6 +151,7 @@ SCRIPTS = [
"case_edit_persistence_e2e.py",
"case_covers_e2e.py",
"x_post_capture_e2e.py",
+ "x_image_originals_e2e.py",
"x_capture_injection_e2e.py",
"x_followup_capture_e2e.py",
"x_media_feedback_e2e.py",
@@ -252,12 +254,14 @@ SCRIPTS = [
"ui_regressions_e2e.py",
"settings_visual_anchor_e2e.py",
"settings_compact_e2e.py",
+ "settings_update_feedback_e2e.py",
"settings_simplification_e2e.py",
"settings_text_completion_e2e.py",
"settings_tab_stability_e2e.py",
"brand_i18n_e2e.py",
"english_interaction_states_e2e.py",
"case_management_batch_regression_e2e.py",
+ "library_selection_menu_scroll_e2e.py",
]
CASE_MANAGEMENT_SCRIPTS = [
@@ -297,6 +301,7 @@ CASE_MANAGEMENT_SCRIPTS = [
"projects_and_categories_e2e.py",
"project_tree_e2e.py",
"case_management_batch_regression_e2e.py",
+ "library_selection_menu_scroll_e2e.py",
]
diff --git a/test/settings_compact_e2e.py b/test/settings_compact_e2e.py
index 2658fad..ffcfc5d 100644
--- a/test/settings_compact_e2e.py
+++ b/test/settings_compact_e2e.py
@@ -9,12 +9,12 @@ with extension_session('pd-settings-compact-', viewport={'width':1440,'height':1
page=session.open_page('library.html')
page.locator('#open-settings').dispatch_event('click')
expect(page.locator('#settings-general-panel')).to_be_visible()
- # Theme is a switch now; toggling persists through the same preference service.
- if not page.locator('#ui-theme').is_checked():
+ # Theme choices persist through the same preference service.
+ if page.locator('#ui-theme').input_value() != 'dark':
with page.expect_navigation(wait_until='domcontentloaded'):
- page.locator('#ui-theme').check()
+ page.locator('#ui-theme').select_option('dark')
page.locator('#open-settings').dispatch_event('click')
- assert page.locator('#ui-theme').is_checked()
+ assert page.locator('#ui-theme').input_value() == 'dark'
assert page.evaluate("async()=> (await chrome.runtime.sendMessage({type:'GET_STATE'})).uiPreferences.theme")=='dark'
page.locator('#library-name-setting').fill('设置保存验证')
page.locator('#save-library-settings').click()
diff --git a/test/settings_simplification_e2e.py b/test/settings_simplification_e2e.py
index 5b3c275..4366c6d 100644
--- a/test/settings_simplification_e2e.py
+++ b/test/settings_simplification_e2e.py
@@ -68,7 +68,7 @@ def main():
expect(p.locator('#analysis-settings-feedback')).to_contain_text('Scope preview failed')
expect(p.locator('#analysis-batch-summary')).to_have_attribute('aria-busy','false')
snapshot(p, out/'analysis-preview-failed.png')
- p.locator('[data-settings-tab=general]').click()
+ p.locator('[data-settings-tab=tasks]').click()
p.locator('#ui-diagnostics').check()
p.locator('#settings-close').click()
p=run.open_page('composer.html',wait_until='networkidle')
diff --git a/test/settings_update_feedback_e2e.py b/test/settings_update_feedback_e2e.py
new file mode 100644
index 0000000..e82c87d
--- /dev/null
+++ b/test/settings_update_feedback_e2e.py
@@ -0,0 +1,137 @@
+"""Offline background checks stay quiet; explicit checks give local, temporary feedback."""
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+
+from playwright.sync_api import expect
+
+from e2e_support import base_entry, extension_session
+
+
+def screenshot(page, path):
+ page.mouse.move(0, 0)
+ page.screenshot(path=str(path), animations="disabled")
+
+
+def assert_frame(page):
+ metrics = page.locator("#settings-dialog").evaluate("""dialog => {
+ const footer = dialog.querySelector('.settings-about').getBoundingClientRect();
+ const panel = dialog.querySelector('[data-settings-panel]:not([hidden])');
+ const p = panel.getBoundingClientRect();
+ const button = dialog.querySelector('#check-extension-update').getBoundingClientRect();
+ return {footerTop: footer.top, footerBottom: footer.bottom, panelBottom: p.bottom,
+ buttonLeft: button.left, buttonRight: button.right, buttonBottom: button.bottom,
+ viewportWidth: innerWidth, viewportHeight: innerHeight,
+ panelOverflow: panel.scrollWidth > panel.clientWidth,
+ footerOverflow: dialog.querySelector('.settings-about').scrollWidth > dialog.querySelector('.settings-about').clientWidth};
+ }""")
+ assert metrics["panelBottom"] <= metrics["footerTop"] + 1, metrics
+ assert metrics["footerBottom"] <= metrics["viewportHeight"], metrics
+ assert 0 <= metrics["buttonLeft"] < metrics["buttonRight"] <= metrics["viewportWidth"], metrics
+ assert metrics["buttonBottom"] <= metrics["viewportHeight"], metrics
+ assert not metrics["panelOverflow"] and not metrics["footerOverflow"], metrics
+ return metrics
+
+
+def main():
+ output = Path(os.environ.get("PD_E2E_ARTIFACT_DIR", "/tmp/pd-settings-update-feedback"))
+ output.mkdir(parents=True, exist_ok=True)
+ results = []
+ for width, height, theme, locale in [
+ (1280, 900, "dark", "zh-CN"), (390, 844, "dark", "zh-CN"),
+ (1280, 900, "light", "en"), (390, 844, "light", "en"),
+ ]:
+ with extension_session("pd-settings-offline-", viewport={"width": width, "height": height}) as session:
+ setup = session.open_page("collector.html")
+ session.seed_storage(setup, {
+ "entries": [base_entry("kept", "保留案例", "原资料不变", "content:prompt:text")],
+ "uiPreferences": {"theme": theme, "locale": locale, "motion": "reduced"},
+ "extensionUpdateState": {"checkStatus": "error", "lastError": "Failed to fetch"},
+ })
+ session.context.set_offline(True)
+ # Chromium's page offline emulation does not cover extension workers.
+ # Fail only the release request at the worker's network boundary.
+ session.context.service_workers[0].evaluate("""() => {
+ const originalFetch = globalThis.fetch;
+ const release = chrome.runtime.getManifest().homepage_url.replace(/\\/$/, '') + '/releases/latest';
+ globalThis.fetch = (url, ...args) => String(url) === release
+ ? Promise.reject(new TypeError('Failed to fetch'))
+ : originalFetch(url, ...args);
+ }""")
+ page = session.open_page("library.html", wait_until="networkidle")
+ expect(page.locator("body")).to_have_attribute("data-library-state", "ready")
+ page.locator("#open-settings").click()
+ expect(page.locator("#settings-general-panel")).to_be_visible()
+ expect(page.locator("#ui-theme")).to_have_value(theme)
+ expect(page.locator("#ui-diagnostics")).to_be_hidden()
+ feedback = page.locator("#update-feedback")
+ expect(feedback).to_have_text("")
+ assert_frame(page)
+ screenshot(page, output / f"general-{width}-{locale}.png")
+ # A passive status event must not replay a saved error.
+ status = page.evaluate("async () => (await chrome.runtime.sendMessage({type: 'GET_EXTENSION_UPDATE_STATUS'})).status")
+ session.context.service_workers[0].evaluate("""async state => {
+ await chrome.runtime.sendMessage({type: 'EXTENSION_UPDATE_STATUS_CHANGED',
+ status: {...state, checkStatus: 'error', lastError: 'Failed to fetch'}});
+ }""", status)
+ expect(feedback).to_have_text("")
+ page.locator("#settings-general-panel").evaluate("el => el.scrollTop = el.scrollHeight")
+ assert_frame(page)
+ screenshot(page, output / f"scrolled-{width}-{locale}.png")
+
+ # The real update lifecycle persists and broadcasts the injected network failure.
+ page.locator("#check-extension-update").click()
+ expected = "当前未联网,联网后再检查更新" if locale == "zh-CN" else "You’re offline. Reconnect to check for updates."
+ expect(feedback).to_have_text(expected)
+ assert feedback.evaluate("e => !e.classList.contains('is-error') && !e.classList.contains('error')")
+ assert_frame(page)
+ screenshot(page, output / f"offline-check-{width}-{locale}.png")
+ expect(feedback).to_have_text("", timeout=6000)
+ page.locator("#settings-close").click()
+ page.locator("#open-settings").click()
+ expect(feedback).to_have_text("")
+
+ page.locator('[data-settings-tab="tasks"]').click()
+ page.locator("#ui-diagnostics").scroll_into_view_if_needed()
+ expect(page.locator("#ui-diagnostics")).to_be_visible()
+ assert_frame(page)
+ screenshot(page, output / f"maintenance-{width}-{locale}.png")
+ page.locator("#ui-diagnostics").check()
+ page.wait_for_function("""async () => (await chrome.storage.local.get('uiPreferences')).uiPreferences.diagnosticsEnabled""")
+ # A known available release still retains its badge/action while offline.
+ status = page.evaluate("async () => (await chrome.runtime.sendMessage({type: 'GET_EXTENSION_UPDATE_STATUS'})).status")
+ session.context.service_workers[0].evaluate("""async state => {
+ await chrome.runtime.sendMessage({type: 'EXTENSION_UPDATE_STATUS_CHANGED',
+ status: {...state, updateAvailable: true, canApply: true, lastError: 'Failed to fetch'}});
+ }""", status)
+ expect(page.locator("#apply-extension-update")).to_be_visible()
+ expect(page.locator("#settings-update-badge")).not_to_have_attribute("hidden", "")
+ expect(feedback).to_have_text("")
+ assert_frame(page)
+ screenshot(page, output / f"available-{width}-{locale}.png")
+ saved = page.evaluate("async () => (await chrome.runtime.sendMessage({type: 'GET_STATE'})).entries[0]")
+ assert saved["text"] == "原资料不变"
+ if width == 1280 and locale == "zh-CN":
+ dark_surface = page.locator("#settings-dialog").evaluate("el => getComputedStyle(el).backgroundColor")
+ page.locator('[data-settings-tab="general"]').click()
+ with page.expect_navigation(wait_until="networkidle"):
+ page.locator("#ui-theme").select_option("system")
+ expect(page.locator("body")).to_have_attribute("data-library-state", "ready")
+ page.locator("#open-settings").click()
+ expect(page.locator("#ui-theme")).to_have_value("system")
+ page.emulate_media(color_scheme="dark")
+ expect(page.locator("html")).to_have_attribute("data-theme", "system")
+ expect(page.locator("#settings-dialog")).to_have_css("background-color", dark_surface)
+ page.emulate_media(color_scheme="light")
+ expect(page.locator("#settings-dialog")).not_to_have_css("background-color", dark_surface)
+ assert page.evaluate("async () => (await chrome.storage.local.get('uiPreferences')).uiPreferences.theme") == "system"
+ expect(feedback).to_have_text("")
+ results.append({"width": width, "theme": theme, "locale": locale, "offlineQuiet": True,
+ "explicitCheckTransient": True, "availableActionPreserved": True})
+ print(json.dumps(results, ensure_ascii=False))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/test/share-preview.test.js b/test/share-preview.test.js
index b9cea10..d5de8d9 100644
--- a/test/share-preview.test.js
+++ b/test/share-preview.test.js
@@ -52,7 +52,7 @@ test("share preview uses the current visual foundation and exposes the read-only
assert.match(html, /\.case-card:focus-visible::after,\.related-card:focus-visible::after\{[^}]*border-width:2px/);
assert.match(html, /\.fallback-cover\.audio\{background:linear-gradient\(160deg,var\(--ui-raised\),var\(--ui-surface\)\)\}/);
assert.match(html, /\.eyebrow,\.fallback-cover small,[^}]*\{color:var\(--ui-text\)\}/);
- assert.match(html, /设置 → 界面与资料库 → 导入分享包/);
+ assert.match(html, /添加 → 导入本机资料/);
assert.match(html, /data-zh="视觉创作灵感库" data-en="Visual Inspiration Library"/);
assert.match(html, /提示词导演,你的视觉创作私人灵感库。/);
assert.match(html, /class="app-footer"/);
diff --git a/test/ui_foundation_e2e.py b/test/ui_foundation_e2e.py
index d6e0668..08d1018 100644
--- a/test/ui_foundation_e2e.py
+++ b/test/ui_foundation_e2e.py
@@ -218,8 +218,7 @@ def main() -> None:
storedTheme: localStorage.getItem('promptDirectorTheme'),
storedMotion: localStorage.getItem('promptDirectorMotion'),
selectedMotion: document.querySelector('#ui-motion').checked,
- selectedDarkTheme: document.querySelector('#ui-theme').checked,
- selectedSystemTheme: document.querySelector('#ui-theme-system').checked
+ selectedTheme: document.querySelector('#ui-theme').value
})"""
)
assert migrated == {
@@ -228,8 +227,7 @@ def main() -> None:
"storedTheme": "light",
"storedMotion": "reduced",
"selectedMotion": True,
- "selectedDarkTheme": False,
- "selectedSystemTheme": False,
+ "selectedTheme": "light",
}, migrated
light_tokens = light_page.evaluate(
diff --git a/test/video-component-onboarding.test.js b/test/video-component-onboarding.test.js
new file mode 100644
index 0000000..7e1eb2e
--- /dev/null
+++ b/test/video-component-onboarding.test.js
@@ -0,0 +1,21 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { videoComponentInstallRequest } from '../extension/video-component-config.js';
+
+for (const locale of ['zh-CN', 'en']) {
+ test(`the ${locale} Agent request uses the configured public guide and asks for real verification, without pinning a stale release`, () => {
+ const request = videoComponentInstallRequest(locale, 'https://github.com/example/product/');
+ assert(request.includes('https://github.com/example/product/blob/main/tools/video-component/INSTALL-AGENT.md'));
+ assert(!request.includes('video-v0.1.0'));
+ assert(request.includes('Python'));
+ assert(request.includes('Chrome'));
+ assert.match(request, /未验证|unverified/u);
+ assert.match(request, /本机|computer/u);
+ });
+}
+
+test('the installation request does not send users to an insecure or non-GitHub guide', () => {
+ for (const homepage of ['http://github.com/example/product', 'https://example.com/product']) {
+ assert.throws(() => videoComponentInstallRequest('zh-CN', homepage), /下载地址/u);
+ }
+});
diff --git a/test/video-component-setup.test.js b/test/video-component-setup.test.js
index 662508c..98bf747 100644
--- a/test/video-component-setup.test.js
+++ b/test/video-component-setup.test.js
@@ -134,3 +134,88 @@ test('worker restoration never polls an idle or terminal setup, and interrupted
assert.equal((await createVideoComponentSetup(f.options).check()).phase, 'failed');
assert.equal(f.alarms.size, 0); assert.equal(f.resumed, 0);
});
+
+for (const phase of ['failed', 'paused', 'idle', 'ready', 'update', 'permission']) {
+ test(`page refresh rechecks ${phase} setup and clears stale failure after manual installation without downloading or restarting a save`, async () => {
+ const f = fixture({ phase, message: 'previous failure', startedAt: 10 });
+ let probes = 0;
+ f.options.inspect = async () => { probes++; return { available: true, versions: { component: '0.1.0' } }; };
+ const setup = createVideoComponentSetup(f.options);
+ const results = await Promise.all([setup.refresh(), setup.refresh()]);
+ assert.equal(probes, 1);
+ assert(results.every(state => state.phase === 'ready' && !state.message));
+ assert.equal((await setup.get()).phase, 'ready');
+ assert.equal(f.downloads, 0); assert.equal(f.resumed, 0); assert.equal(f.scheduled.length, 0);
+ });
+}
+
+test('a failed page refresh retains the actionable error and does not poll or download again', async () => {
+ const original = { phase: 'failed', message: '安装包下载中断,请重试', downloadId: 7 };
+ const f = fixture(original);
+ assert.deepEqual(await f.setup.refresh(), original);
+ assert.equal(f.downloads, 0); assert.equal(f.scheduled.length, 0);
+});
+
+test('refresh detects a removed or obsolete host instead of leaving a cached ready state', async () => {
+ const f = fixture({ phase: 'ready' });
+ assert.equal((await f.setup.refresh()).phase, 'idle');
+ f.options.inspect = async () => ({ available: false, updateRequired: true });
+ assert.equal((await createVideoComponentSetup(f.options).refresh()).phase, 'update');
+});
+
+test('a late page probe does not overwrite a newer installation state', async () => {
+ const f = fixture({ phase: 'failed' });
+ let release, entered;
+ const waiting = new Promise(resolve => { entered = resolve; });
+ f.options.inspect = () => { entered(); return new Promise(resolve => { release = resolve; }); };
+ const setup = createVideoComponentSetup(f.options);
+ const refresh = setup.refresh(); await waiting;
+ const newer = { phase: 'installing', downloadId: 99, startedAt: 1000 };
+ await f.options.storage.set({ [VIDEO_SETUP_KEY]: newer });
+ release({ available: true });
+ assert.deepEqual(await refresh, newer);
+ assert.deepEqual(await setup.get(), newer);
+});
+
+test('Agent installation starts only readiness checks, never a package download, then resumes the pending capture once', async () => {
+ const f = fixture({ phase: 'failed', message: 'previous download failure' });
+ f.options.fetchImpl = async () => { throw new Error('Agent installation must not fetch an installer'); };
+ const setup = createVideoComponentSetup(f.options);
+ assert.equal((await setup.start({ viaAgent: true })).phase, 'installing');
+ assert.equal((await setup.get()).downloadId, undefined);
+ assert.equal((await setup.get()).message, undefined);
+ assert.equal(f.downloads, 0); assert(f.alarms.has(VIDEO_SETUP_ALARM));
+ await setup.start({ viaAgent: true });
+ f.ready(); await setup.check(); await setup.check();
+ assert.equal((await setup.get()).phase, 'ready');
+ assert.equal(f.resumed, 1); assert.equal(f.downloads, 0); assert.equal(f.alarms.size, 0);
+});
+
+test('a paused Agent installation can continue watching without downloading an installer', async () => {
+ const f = fixture({ phase: 'paused', startedAt: 0 });
+ assert.equal((await f.setup.continue()).phase, 'installing');
+ assert(f.alarms.has(VIDEO_SETUP_ALARM));
+ assert.equal(f.downloads, 0);
+ f.ready(); await f.setup.check(); assert.equal(f.resumed, 1);
+});
+
+test('the manual download remains available after starting installation with an Agent', async () => {
+ const f = fixture(); await f.setup.start({ viaAgent: true });
+ assert.equal((await f.setup.start({ restart: true })).phase, 'downloading');
+ assert.equal(f.downloads, 1);
+});
+
+test('asking an Agent to finish a downloaded installer keeps its download and deadline while showing the copied request', async () => {
+ const f = fixture({ phase: 'installing', downloadId: 7, startedAt: 500, checkAttempts: 2 });
+ const state = await f.setup.start({ viaAgent: true });
+ assert.equal(state.viaAgent, true);
+ assert.equal(state.downloadId, 7); assert.equal(state.startedAt, 500);
+ assert.equal(f.downloads, 0);
+});
+
+test('Agent setup rejects unsupported systems without starting installation polling', async () => {
+ const f = fixture(); f.options.platform = async () => ({ os: 'linux' });
+ const state = await createVideoComponentSetup(f.options).start({ viaAgent: true });
+ assert.equal(state.phase, 'failed'); assert.match(state.message, /Windows 和 macOS/u);
+ assert.equal(f.alarms.size, 0); assert.equal(f.scheduled.length, 0);
+});
diff --git a/test/video_component_setup_ui_e2e.py b/test/video_component_setup_ui_e2e.py
index cc37b58..8c7cb37 100644
--- a/test/video_component_setup_ui_e2e.py
+++ b/test/video_component_setup_ui_e2e.py
@@ -28,9 +28,9 @@ def main():
permission:async()=>false,send:async()=>{throw Error('Denied permission must not start a download')}});
fixtureView.render({phase:'idle'});
}""")
- page.locator('#video-component-setup button').click()
+ page.locator('#video-component-setup [data-video-component-action=manual]').click()
expect(page.locator('#video-component-setup')).to_contain_text('未开启组件连接权限')
- expect(page.locator('#video-component-setup button')).to_have_text('开启权限')
+ expect(page.locator('#video-component-setup [data-video-component-action=manual]')).to_have_text('开启权限')
page.screenshot(path=str(evidence / 'permission-denied.png'))
task = page.evaluate("async()=>(await chrome.runtime.sendMessage({type:'GET_CAPTURE_SAVE_TASK'})).task")
assert task['status'] == 'waiting-component' and task['input']['batch']['candidates'][0]['contentText'] == 'Full original source'
@@ -41,14 +41,14 @@ def main():
open:async()=>{throw Error('Installer file was moved. Download it again.')},showDownloads:()=>fixtureCalls.push('show-downloads')});
fixtureView.render({phase:'idle'});
}""")
- page.locator('#video-component-setup button').click()
- expect(page.locator('#video-component-setup button')).to_have_text('打开安装包')
- page.locator('#video-component-setup button').click()
- expect(page.locator('#video-component-setup button')).to_have_text('重新下载')
+ page.locator('#video-component-setup [data-video-component-action=manual]').click()
+ expect(page.locator('#video-component-setup [data-video-component-action=manual]')).to_have_text('打开安装包')
+ page.locator('#video-component-setup [data-video-component-action=manual]').click()
+ expect(page.locator('#video-component-setup [data-video-component-action=manual]')).to_have_text('重新下载')
for width in [390, 1280]:
page.set_viewport_size({'width':width,'height':850})
page.screenshot(path=str(evidence / f'installer-moved-{width}.png'))
- page.locator('#video-component-setup button').click()
+ page.locator('#video-component-setup [data-video-component-action=manual]').click()
expect(page.locator('#video-component-setup')).to_contain_text('正在下载安装包')
calls = page.evaluate('fixtureCalls')
assert calls[-1]['restart'] is True, calls
@@ -61,11 +61,11 @@ def main():
window.fixtureView=createVideoComponentView(document.querySelector('#video-component-setup'),{primary:true,showDownloads:()=>fixtureCalls.push('show-downloads')});
fixtureView.render({phase:'review'});
}""")
- expect(page.locator('#video-component-setup button')).to_have_text('View downloads' if locale == 'en' else '查看下载')
+ expect(page.locator('#video-component-setup [data-video-component-action=manual]')).to_have_text('View downloads' if locale == 'en' else '查看下载')
for width in [390, 1280]:
page.set_viewport_size({'width':width,'height':850})
page.screenshot(path=str(evidence / f'review-{locale}-{width}.png'))
- page.locator('#video-component-setup button').click()
+ page.locator('#video-component-setup [data-video-component-action=manual]').click()
assert page.evaluate('fixtureCalls.at(-1)') == 'show-downloads'
page.evaluate("fixtureView.render({phase:'installing',downloadId:88})")
expect(page.locator('#video-component-setup')).to_contain_text('Extract the package' if locale == 'en' else '解压安装包')
diff --git a/test/video_setup_refresh_e2e.py b/test/video_setup_refresh_e2e.py
new file mode 100644
index 0000000..0347d8b
--- /dev/null
+++ b/test/video_setup_refresh_e2e.py
@@ -0,0 +1,125 @@
+"""Reload settings after a manual installation; native availability and macOS are fixtures.
+
+The settings UI, background message route and durable setup state are real.
+No system install, real-library write or media download is performed.
+"""
+import json
+import os
+import shutil
+import tempfile
+from pathlib import Path
+from playwright.sync_api import expect
+from e2e_support import EXTENSION_DIR, extension_session, wait_for_async_condition
+
+
+def main():
+ evidence = Path(os.environ.get('VIDEO_REFRESH_EVIDENCE', tempfile.mkdtemp(prefix='video-refresh-')))
+ evidence.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(prefix='pd-video-refresh-extension-') as temporary:
+ extension = Path(temporary) / 'extension'
+ shutil.copytree(EXTENSION_DIR, extension)
+ manifest = json.loads((extension / 'manifest.json').read_text())
+ manifest['optional_permissions'].remove('nativeMessaging')
+ manifest['permissions'].append('nativeMessaging')
+ (extension / 'manifest.json').write_text(json.dumps(manifest))
+ background = extension / 'background.js'
+ source = background.read_text()
+ needle = 'inspect: nativeVideoStatus, platform:'
+ assert source.count(needle) == 1
+ source = source.replace(needle, """inspect: async () => {
+ const state=await chrome.storage.local.get(['fixtureNativeStatus','fixtureInspections']);
+ await chrome.storage.local.set({fixtureInspections:(state.fixtureInspections||0)+1});
+ if (!state.fixtureNativeStatus) throw Error('Host unavailable');
+ return state.fixtureNativeStatus;
+ }, platform:""")
+ source = source.replace('platform: () => chrome.runtime.getPlatformInfo(),', "platform: async () => ({os:'mac'}),")
+ source = source.replace('resume: () => captureSaveTasks.resumeVideo(),', """resume: async () => {
+ const s=await chrome.storage.local.get('fixtureResumes');
+ await chrome.storage.local.set({fixtureResumes:(s.fixtureResumes||0)+1});
+ return captureSaveTasks.resumeVideo();
+ },""")
+ background.write_text(source)
+ with extension_session('pd-video-refresh-', extension_dir=extension) as run:
+ page = run.open_page('collector.html')
+ run.seed_storage(page, {'entries': [], 'dataSafetyOnboardingSeen': True,
+ 'uiPreferences': {'theme': 'dark', 'locale': 'zh-CN'},
+ 'videoComponentSetup': {'phase': 'failed', 'message': '暂时无法下载安装包,请稍后重试'}})
+ page.goto(f'chrome-extension://{run.extension_id}/library.html')
+ page.locator('#open-settings').click()
+ expect(page.locator('#settings-dialog')).to_be_visible()
+ expect(page.locator('#video-component-status')).to_have_text('暂时无法下载安装包,请稍后重试')
+ expect(page.locator('#connect-video-component')).to_have_text('重试')
+ for width in [1280, 540]:
+ page.set_viewport_size({'width': width, 'height': 900})
+ page.locator('#video-component-status').scroll_into_view_if_needed()
+ page.screenshot(path=str(evidence / f'failed-{width}.png'), animations='disabled')
+ page.evaluate("() => chrome.storage.local.set({fixtureNativeStatus:{available:true,versions:{component:'0.1.0'}},fixtureInspections:0})")
+ # No Retry or installer button is used: a normal page reload must
+ # replace the stale failure with the newly detected host status.
+ page.reload()
+ page.locator('#open-settings').click()
+ expect(page.locator('#settings-dialog')).to_be_visible()
+ expect(page.locator('#video-component-status')).to_have_text('视频组件已就绪')
+ expect(page.locator('#connect-video-component')).to_be_hidden()
+ result = page.evaluate("() => chrome.storage.local.get(['videoComponentSetup','fixtureInspections'])")
+ assert result['videoComponentSetup']['phase'] == 'ready', result
+ assert not result['videoComponentSetup'].get('message'), result
+ assert result['fixtureInspections'] == 1, result
+ assert not page.evaluate("() => chrome.alarms.get('video-component-setup')")
+ for width in [1280, 540]:
+ page.set_viewport_size({'width': width, 'height': 900})
+ page.locator('#video-component-status').scroll_into_view_if_needed()
+ page.screenshot(path=str(evidence / f'ready-{width}.png'), animations='disabled')
+ page.evaluate("() => chrome.storage.local.remove('fixtureNativeStatus')")
+ page.reload()
+ page.locator('#open-settings').click()
+ expect(page.locator('#connect-video-component')).to_be_visible()
+ expect(page.locator('#video-component-status')).not_to_have_text('视频组件已就绪')
+ assert page.evaluate("async()=>(await chrome.runtime.sendMessage({type:'GET_STATE'})).entries.length") == 0
+ agent = page.locator('#settings-dialog [data-video-component-action=agent]')
+ page.bring_to_front()
+ page.evaluate("""() => {
+ window.restoreCopy=navigator.clipboard.writeText.bind(navigator.clipboard);
+ navigator.clipboard.writeText=async()=>{throw Error('Clipboard blocked')};
+ }""")
+ await_copy_state = page.evaluate("() => chrome.storage.local.get('videoComponentSetup')")
+ agent.click()
+ expect(page.locator('#video-component-status')).to_have_text('无法复制安装指令,请重试')
+ assert page.evaluate("() => chrome.storage.local.get('videoComponentSetup')") == await_copy_state
+ assert not page.evaluate("() => chrome.alarms.get('video-component-setup')")
+ expect(page.locator('#connect-video-component')).to_be_enabled()
+ page.evaluate("() => {navigator.clipboard.writeText=window.restoreCopy}")
+ agent.click()
+ expect(page.locator('#video-component-status')).to_have_text('已复制,粘贴给本机 Agent,安装后自动继续')
+ copied = page.evaluate("() => navigator.clipboard.readText()")
+ assert 'INSTALL-AGENT.md' in copied and 'Chrome' in copied and 'Python' in copied, copied
+ setup = page.evaluate("async()=>(await chrome.storage.local.get('videoComponentSetup')).videoComponentSetup")
+ assert setup['phase'] == 'installing' and not setup.get('downloadId'), setup
+ assert page.evaluate("() => chrome.downloads.search({})") == [], 'Agent path downloaded an unnecessary installer'
+ for locale, theme in [('zh-CN', 'dark'), ('en', 'light')]:
+ if locale == 'en':
+ with page.expect_navigation(wait_until='domcontentloaded'):
+ page.evaluate("preferences=>{void chrome.runtime.sendMessage({type:'UPDATE_UI_PREFERENCES',preferences})}", {'locale':locale,'theme':theme})
+ else:
+ page.reload()
+ page.locator('#open-settings').click()
+ expect(page.locator('#settings-dialog')).to_be_visible()
+ expect(agent).to_have_text('Install with Agent' if locale == 'en' else '让 Agent 安装')
+ for width in [1280, 390]:
+ page.set_viewport_size({'width':width,'height':900})
+ page.locator('#settings-dialog .video-component-setup').scroll_into_view_if_needed()
+ page.screenshot(path=str(evidence / f'agent-{locale}-{width}.png'), animations='disabled')
+ # The same copied request follows the current interface language.
+ page.bring_to_front(); agent.click()
+ expect(page.locator('#video-component-status')).to_contain_text('Copied.')
+ assert page.evaluate("() => navigator.clipboard.readText()").startswith('Install the PromptDirector')
+ page.evaluate("() => chrome.storage.local.set({fixtureNativeStatus:{available:true},fixtureResumes:0})")
+ wait_for_async_condition(page, "async()=>{const s=await chrome.storage.local.get(['videoComponentSetup','fixtureResumes']);return s.videoComponentSetup?.phase==='ready'&&s.fixtureResumes===1}")
+ expect(agent).to_be_hidden(); expect(page.locator('#connect-video-component')).to_be_hidden()
+ assert not page.evaluate("() => chrome.alarms.get('video-component-setup')")
+ print(json.dumps({'refreshClearsFailedState': True, 'probeCount': result['fixtureInspections'],
+ 'removedHostDetected': True, 'agentClipboardAndReadiness': True, 'copyFailurePreservesState': True, 'realInstallations': 0, 'evidence': str(evidence)}))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/test/x-image-originals.test.js b/test/x-image-originals.test.js
new file mode 100644
index 0000000..5a8b757
--- /dev/null
+++ b/test/x-image-originals.test.js
@@ -0,0 +1,116 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { normalizePageCaptureCandidate, pageCaptureMediaFetchCandidates, resolvePageCaptureImage } from "../extension/page-capture.js";
+
+const small = "https://pbs.twimg.com/media/example?format=jpg&name=small";
+const original = small.replace("name=small", "name=orig");
+const photo = (url = small) => ({ id: "photo", kind: "image", url, width: 680, height: 380, sourceKind: "current" });
+const candidate = (media) => normalizePageCaptureCandidate({
+ title: "Character sheet", canonicalUrl: "https://x.com/artist/status/123", media
+});
+const bytes = new Blob(["original bytes"], { type: "image/jpeg" });
+
+test("X previews and restored small-image drafts prefer original bytes without labelling them with thumbnail dimensions", () => {
+ for (const name of ["small", "900x900", "large"]) {
+ const raw = photo(small.replace("small", name));
+ const result = candidate([raw]);
+ assert.equal(result.media[0].id, raw.id);
+ assert.equal(result.media[0].url, original);
+ assert.equal(result.media[0].sourceKind, "site-original");
+ assert.equal(result.media[0].width, 0);
+ assert.equal(result.media[0].height, 0);
+ assert.deepEqual(pageCaptureMediaFetchCandidates(raw), [original, raw.url]);
+ assert.deepEqual(candidate(result.media).media, result.media, "restored preview remains stable");
+ }
+});
+
+test("original X photos retain their known dimensions, format and unrelated URL parameters", () => {
+ const raw = photo("https://pbs.twimg.com/media/example?format=png&name=orig&tag=one");
+ raw.width = 4096; raw.height = 2286;
+ const result = candidate([raw]).media[0];
+ assert.equal(result.width, 4096);
+ assert.equal(result.height, 2286);
+ assert.deepEqual(pageCaptureMediaFetchCandidates(result), [raw.url]);
+ assert.deepEqual(pageCaptureMediaFetchCandidates(photo("https://pbs.twimg.com/media/example.jpg:small")), [
+ "https://pbs.twimg.com/media/example.jpg:orig", "https://pbs.twimg.com/media/example.jpg:small"
+ ]);
+});
+test("a site attribute incorrectly calling a resized X URL original cannot outrank name=orig", () => {
+ assert.deepEqual(pageCaptureMediaFetchCandidates({...photo(), sourceKind:"site-original"}), [original,small]);
+});
+
+test("X original selection leaves avatars, video posters, other hosts and explicit local assets alone", () => {
+ for (const url of [
+ "https://pbs.twimg.com/profile_images/person/small.jpg",
+ "https://pbs.twimg.com/amplify_video_thumb/123/img/cover?format=jpg&name=small",
+ "https://pbs.twimg.com.evil.example/media/example?name=small",
+ "https://example.com/media/example?name=small",
+ "https://[email protected]/media/example?name=small"
+ ]) assert.deepEqual(pageCaptureMediaFetchCandidates(photo(url)), [url]);
+ for (const extra of [{ kind: "video" }, { localAssetId: "selected-original" }, { localTransferId: "upload" }]) {
+ assert.deepEqual(pageCaptureMediaFetchCandidates({ ...photo(), ...extra }), [small]);
+ }
+ const local = { ...photo(), localAssetId: "selected-original" };
+ assert.deepEqual(pageCaptureMediaFetchCandidates(candidate([local, local]).media[0]), [small]);
+});
+
+test("two renditions of the same X photo collapse to one original without dropping either fallback", () => {
+ const large = small.replace("small", "large");
+ const result = candidate([photo(), { ...photo(large), id: "other-dom-node" }]);
+ assert.equal(result.media.length, 1);
+ assert.deepEqual(new Set(pageCaptureMediaFetchCandidates(result.media[0])), new Set([original, small, large]));
+});
+
+test("original download is used without fetching thumbnails and exposes actual file dimensions", async () => {
+ const calls = [];
+ const result = await resolvePageCaptureImage(photo(), {
+ fetchMedia: async url => { calls.push(url); return { blob: bytes, metadata: { width: 4096, height: 2286 } }; },
+ decodeDataUrl: () => assert.fail("no pixel fallback")
+ });
+ assert.deepEqual(calls, [original]);
+ assert.equal(result.blob, bytes);
+ assert.deepEqual(result.metadata, { width: 4096, height: 2286 });
+ assert.equal(result.usedReducedImage, false);
+});
+
+test("an allowed page-session original wins over a publicly downloadable thumbnail", async () => {
+ const calls = [];
+ const result = await resolvePageCaptureImage(photo(), {
+ fetchMedia: async url => { calls.push(`public:${url}`); if (url === original) throw Error("403"); return bytes; },
+ fetchSessionMedia: async url => { calls.push(`session:${url}`); return bytes; },
+ decodeDataUrl: () => assert.fail("no pixel fallback")
+ });
+ assert.deepEqual(calls, [`public:${original}`, `session:${original}`]);
+ assert.equal(result.usedReducedImage, false);
+ assert.equal(result.sourceUrl, original);
+});
+
+test("failed originals preserve a usable smaller photo and report the quality downgrade", async () => {
+ const calls = [];
+ const result = await resolvePageCaptureImage(photo(), {
+ fetchMedia: async url => { calls.push(url); if (url === original) throw Error("404"); return bytes; },
+ fetchSessionMedia: async () => { throw Error("unavailable"); },
+ decodeDataUrl: () => assert.fail("no pixel fallback")
+ });
+ assert.deepEqual(calls, [original, small]);
+ assert.equal(result.sourceUrl, small);
+ assert.equal(result.usedReducedImage, true);
+ assert.equal(result.failures.length, 2);
+});
+
+test("original retries respect denied session access and cancellation", async () => {
+ const result = await resolvePageCaptureImage(photo(), {
+ sessionMediaAllowed: false,
+ fetchMedia: async url => { if (url === original) throw Error("403"); return bytes; },
+ fetchSessionMedia: () => assert.fail("session permission denied"),
+ decodeDataUrl: () => assert.fail("no pixels")
+ });
+ assert.equal(result.usedReducedImage, true);
+ const controller = new AbortController();
+ await assert.rejects(resolvePageCaptureImage(photo(), {
+ signal: controller.signal,
+ fetchMedia: async () => { controller.abort(); throw Error("cancelled"); },
+ fetchSessionMedia: () => assert.fail("cancelled"),
+ decodeDataUrl: () => assert.fail("cancelled")
+ }), { name: "AbortError" });
+});
diff --git a/test/x_image_originals_e2e.py b/test/x_image_originals_e2e.py
new file mode 100644
index 0000000..9cfe668
--- /dev/null
+++ b/test/x_image_originals_e2e.py
@@ -0,0 +1,141 @@
+"""Real X DOM extraction, shared capture save and original-file readback in an isolated profile."""
+import base64
+import json
+import struct
+import tempfile
+import zlib
+from pathlib import Path
+from urllib.parse import parse_qs, urlparse
+
+from e2e_support import EXTENSION_DIR, extension_session
+
+
+def png(width, height, color):
+ def chunk(kind, value):
+ return struct.pack(">I", len(value)) + kind + value + struct.pack(">I", zlib.crc32(kind + value))
+ pixels = (b"\0" + bytes(color) * width) * height
+ return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
+ + chunk(b"IDAT", zlib.compress(pixels)) + chunk(b"IEND", b""))
+
+
+def main(originals=None):
+ images = {"first": (png(680, 380, (40, 80, 120)), png(4096, 2286, (40, 80, 120))),
+ "second": (png(900, 506, (120, 80, 40)), png(3840, 2160, (120, 80, 40)))}
+ if originals:
+ images = {name: (images[name][0], Path(path).read_bytes()) for name, path in originals.items()}
+ with tempfile.TemporaryDirectory(prefix="pd-x-originals-extension-") as temp:
+ ext = Path(temp)
+ for path in EXTENSION_DIR.iterdir():
+ if path.name not in ("manifest.json", "background.js"):
+ (ext / path.name).symlink_to(path, target_is_directory=path.is_dir())
+ manifest = json.loads((EXTENSION_DIR / "manifest.json").read_text())
+ manifest["host_permissions"] += ["https://x.com/*", "https://pbs.twimg.com/*"]
+ (ext / "manifest.json").write_text(json.dumps(manifest))
+ (ext / "background.js").write_text((EXTENSION_DIR / "background.js").read_text()
+ + "\nglobalThis.imageTestDispatch=dispatchAgentOperation;\n")
+ with extension_session("pd-x-originals-", extension_dir=ext) as run:
+ panel = run.open_page("collector.html")
+ run.seed_storage(panel, {"entries": [], "capturePermissionOnboarding": {
+ "version": 1, "acknowledgedAt": "2026-10-20T00:00:00Z", "clipboardIncluded": False}})
+ def media_route(route):
+ url = urlparse(route.request.url)
+ data = images[url.path.split("/")[-1]][parse_qs(url.query).get("name") == ["orig"]]
+ route.fulfill(body=data, content_type="image/jpeg" if data[:2] == b"\xff\xd8" else "image/png",
+ headers={"Access-Control-Allow-Origin": "*"})
+ run.context.route("https://pbs.twimg.com/media/**", media_route)
+ def page_route(route):
+ work = route.request.url
+ body = f"""<!doctype html><title>X original photo fixture</title>
+ <link rel="canonical" href="{work}">
+ <article data-testid="tweet"><div data-testid="User-Name"><a href="/artist">Artist</a></div>
+ <a href="{work}"><time>Today</time></a>
+ <div data-testid="tweetText">Character reference with exact original photos.</div>
+ <a href="{work}/photo/1"><img width="340" height="190"
+ src="https://pbs.twimg.com/media/first?format=png&name=small"></a>
+ <a href="{work}/photo/2"><img width="450" height="253"
+ src="https://pbs.twimg.com/media/second?format=png&name=900x900"></a></article>"""
+ route.fulfill(body=body, content_type="text/html")
+ run.context.route("https://x.com/**", page_route)
+ source = run.context.new_page()
+ source.goto("https://x.com/artist/status/123")
+ worker = run.context.service_workers[0]
+ # Replace only the remote CDN transport; production download validation, save and storage run unchanged.
+ worker.evaluate("""images => {
+ const networkFetch = fetch; globalThis.imageRequests = []; globalThis.originalFailure = false;
+ globalThis.fetch = async (input, options) => {
+ const url = new URL(typeof input === 'string' ? input : input.url);
+ if (url.hostname !== 'pbs.twimg.com') return networkFetch(input, options);
+ imageRequests.push(url.href);
+ const original = url.searchParams.get('name') === 'orig';
+ if (original && originalFailure) return new Response('unavailable', {status:403});
+ const data = images[url.pathname.split('/').pop()][original ? 1 : 0];
+ const bytes=Uint8Array.from(atob(data), c => c.charCodeAt(0));
+ return new Response(bytes, {headers:{'content-type':bytes[0]===255 ? 'image/jpeg' : 'image/png'}});
+ };
+ }""", {key: [base64.b64encode(data).decode() for data in values] for key, values in images.items()})
+ def call(name, value):
+ return worker.evaluate("([name,value])=>imageTestDispatch(name,value)", [name, value])
+ def done(name, value):
+ result = call(name, value)
+ while result["state"] in ("queued", "running"):
+ result = call("get_task", {"requestId": value["requestId"], "waitMs": 15000})
+ assert result["state"] == "completed", result
+ return result["result"]
+ def capture(identifier, fail=False):
+ worker.evaluate("(fail)=>{originalFailure=fail;imageRequests=[]}", fail)
+ work = f"https://x.com/artist/status/{identifier}"
+ source.goto(work)
+ tab_id = panel.evaluate("async url=>(await chrome.tabs.query({})).find(t=>t.url===url).id", work)
+ prepared = done("prepare_capture", {"requestId": f"preview-{identifier}", "tabId": tab_id})
+ photo_case = next(c for c in prepared["candidates"] if c["canonicalUrl"] == work)
+ assert len(photo_case["media"]) == 2, photo_case
+ assert all("name=orig" in m["url"] for m in photo_case["media"]), photo_case
+ selected = done("update_capture", {"requestId": f"select-{identifier}",
+ "captureId": prepared["captureId"], "expectedRevision": prepared["revision"],
+ "selections": [{"candidateId": photo_case["id"], "includeText": True,
+ "selectedMediaIds": [m["id"] for m in photo_case["media"]]}]})
+ # Denied session permission must remain denied; public smaller photos still remain usable.
+ if fail:
+ worker.evaluate("""async captureId => {
+ const key='agentCapture:'+captureId;
+ const capture=(await chrome.storage.local.get(key))[key];
+ capture.batch.sessionMediaAllowed=false;
+ await chrome.storage.local.set({[key]:capture});
+ }""", prepared["captureId"])
+ receipt = done("save_capture", {"requestId": f"save-{identifier}",
+ "captureId": prepared["captureId"], "expectedRevision": selected["revision"]})
+ result = receipt["results"][0]
+ assert result["status"] == ("partial" if fail else "saved"), receipt
+ if fail:
+ assert len([w for w in result["warnings"] if "较小图片" in w]) == 2, result
+ state = panel.evaluate("async()=>chrome.runtime.sendMessage({type:'GET_STATE'})")
+ entry = next(e for e in state["entries"] if e["id"] == result["entryId"])
+ assert len(entry["mediaAssets"]) == 2, entry
+ for asset in entry["mediaAssets"]:
+ name = urlparse(asset["sourceUrl"]).path.split("/")[-1]
+ expected = images[name][0 if fail else 1]
+ actual = panel.evaluate("""async id => {
+ const blob=await (await import('./media-store.js')).getMediaBlob(id);
+ const bitmap=await createImageBitmap(blob);
+ const size=[bitmap.width,bitmap.height];bitmap.close();
+ return {bytes:Array.from(new Uint8Array(await blob.arrayBuffer())),size};
+ }""", asset["id"])
+ assert bytes(actual["bytes"]) == expected
+ assert actual["size"] == [asset["width"], asset["height"]], asset
+ assert ("name=orig" in asset["sourceUrl"]) != fail
+ return entry["id"], worker.evaluate("()=>imageRequests")
+ saved_id, requests = capture("123")
+ assert len(requests) == 2 and all("name=orig" in u for u in requests), requests
+ fallback_id, _ = capture("124", fail=True)
+ run.restart_browser(extension_dir=ext)
+ panel = run.open_page("collector.html")
+ entries = panel.evaluate("async()=>(await chrome.runtime.sendMessage({type:'GET_STATE'})).entries")
+ assert {e["id"] for e in entries} == {saved_id, fallback_id}
+ restored = next(e for e in entries if e["id"] == saved_id)
+ assert [(m["width"], m["height"]) for m in restored["mediaAssets"]] == [(4096, 2286), (3840, 2160)]
+ print(json.dumps({"originalBytesAndDimensions": True, "smallerImageReportsPartial": True,
+ "restartReadback": True, "realLibraryWrites": 0, "paidCalls": 0}))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/video-component/INSTALL-AGENT.md b/tools/video-component/INSTALL-AGENT.md
new file mode 100644
index 0000000..4931a34
--- /dev/null
+++ b/tools/video-component/INSTALL-AGENT.md
@@ -0,0 +1,40 @@
+# Install PromptDirector Video for the user
+
+Use this guide when the user asks you to install or update the video component. Carry out the work on their computer; do not turn these steps into a checklist for them. No Agent connector pairing, paid service, developer certificate, Python installation or system-security changes are required.
+
+## Find the package and local tools
+
+1. Confirm that your tools execute on the user's computer. A remote sandbox cannot install a Chrome native host on their desktop; report that limit before making unrelated changes.
+2. Prefer the extracted component package supplied by the user. Otherwise read this repository's Releases and choose the newest published, non-prerelease **video component** release containing `PromptDirector-Video-Source.zip`. Do not use the repository-wide latest release, which may be the Chrome extension or Agent connector. Download the asset and its `SHA256SUMS`, check the archive once against that release, and extract it completely. Do not overwrite the user's unrelated files.
+3. Read `component.json` and `package.json` in that extracted package. Use their version, extension identity and Node requirement; do not invent or replace them. Read its [Chinese](INSTALL.zh.md) or [English](INSTALL.en.md) dependency sources.
+4. Detect Windows/macOS, architecture and usable existing Node.js, yt-dlp, FFmpeg and FFprobe. Execute their version commands to confirm they run. Reuse working dependencies; do not replace another project's runtime or require edits to the user's global PATH.
+
+## Supply only missing dependencies
+
+The user has asked for installation. Resolve ordinary download, extraction and per-user installation steps yourself. Ask only when a real system prompt or a new permission, payment or broader change requires the user's action; do not ask them to type routine commands.
+
+- Node.js: obtain a compatible LTS build from [Node.js](https://nodejs.org/en/download/). An existing compatible installation is sufficient. If you use a portable runtime, keep it in a durable user-owned location outside the temporary download/extraction directory: the component records the Node executable's absolute path.
+- yt-dlp: use the matching official standalone executable from its [release files](https://github.com/yt-dlp/yt-dlp#release-files). The generic `yt-dlp` zipimport file requires Python; use `yt-dlp.exe` on Windows or `yt-dlp_macos` on macOS. Official standalone distributions include EJS. If an existing package-managed version reports missing EJS, follow its upstream installation guidance rather than installing a new Python environment.
+- FFmpeg and FFprobe: use the [build sources linked by FFmpeg](https://ffmpeg.org/download.html), including both programs and any adjacent files the selected build needs. These binaries are maintained by the linked distributors; preserve their license notices. Do not install a similarly named Python package.
+- Reuse an already available package manager when appropriate; inspect its package identity and source. Do not install a new package manager just to install this component. Preserve upstream integrity checks and existing platform security controls.
+- For standalone media tools, the package's `tools/` directory accepts `yt-dlp.exe`, `ffmpeg.exe`, `ffprobe.exe` on Windows, or `yt-dlp_macos`/`yt-dlp`, `ffmpeg`, `ffprobe` on macOS. This path supports self-contained executables; do not copy only the launcher from a directory build that needs adjacent runtime files. For such builds, keep the entire distribution at a durable location and use the environment overrides below.
+- The install process accepts absolute paths in `PROMPTDIRECTOR_YTDLP`, `PROMPTDIRECTOR_FFMPEG` and `PROMPTDIRECTOR_FFPROBE`. Set them only for the installer process when automatic discovery cannot find a verified tool. The installed host records these paths and does not depend on Chrome inheriting the terminal PATH. Do not persist unrelated global configuration.
+
+## Install and verify
+
+From the extracted package directory, invoke the verified Node executable with arguments `connector/register-video.mjs` and `install`. Use an argument array with your process API and a working directory; preserve Chinese, spaces and shell characters in paths. This is the same implementation used by the double-click installers, without their final interactive pause. No npm install is needed.
+
+The installer validates dependencies, copies the component, writes the native manifest and checks registration. Windows uses `reg.exe` for both HKCU views; it does not require PowerShell .NET methods or a less restrictive language mode. A second install updates the same component. If installation fails, retain the exact error and reported rollback status; do not manually replace registrations, change security policies, delete unrelated installations or describe a failed readback as success.
+
+Verify in layers:
+
+1. **Files and registration:** the command must exit successfully. Read the installed `component.json`, `video-tools.json` and `com.promptdirector.video.json` under the installer-reported root. Check the launcher and dependencies still exist. Do not print unrelated environment variables or credentials.
+2. **Native handshake:** when using a local process tool, launch the installed `native-host`/`native-host.cmd` with a test environment whose PATH is empty. The stdin/stdout protocol is a four-byte unsigned little-endian byte length followed by UTF-8 JSON, implemented in `connector/framing.mjs`. Send `video_hello` with the package's extensionId and `VIDEO_PROTOCOL_VERSION` from its config; require `video_ready`. Then send `video_request` with a unique id and `operation: "status"`; require the matching successful `video_response` with `result.available: true`. Close the process when finished. Do not count the installer's exit alone as a handshake.
+3. **Chrome:** when browser access is available, open the installed PromptDirector extension and verify its video component is ready. Ask for native-messaging authorization only if Chrome requires it. Refresh the extension after manual installation; older extension builds may require their existing Retry/Continue button. Do not uninstall the Chrome extension or clear its data.
+4. **Capture:** if the user has a pending or explicitly selected video and you can operate their browser, let that same capture finish; reopen its saved case and confirm the video plays. Do not pick an unrelated video or create duplicate cases to claim success. If browser access or a selected video is unavailable, state exactly which checks remain unverified.
+
+Give a short result: installed version, verified stages, and any remaining user action. Do not expose the internal procedure as a new manual tutorial.
+
+## Updates and removal
+
+For an update, use the new extracted source package and the same `install` entry point. Keep existing working tools unless the new package actually requires a change. Uninstall only when the user requests it: invoke the verified Node executable with `connector/register-video.mjs uninstall`. It removes this component and its matching registration, preserving browser cases and external dependencies. Do not uninstall after a successful installation merely as a test on the user's computer.
diff --git a/tools/video-component/INSTALL.en.md b/tools/video-component/INSTALL.en.md
index ee346e6..1d25d26 100644
--- a/tools/video-component/INSTALL.en.md
+++ b/tools/video-component/INSTALL.en.md
@@ -4,6 +4,16 @@
This source package supports macOS and Windows. No paid account, developer certificate or Agent pairing is required. It connects free local Node.js, yt-dlp, FFmpeg and FFprobe installations. It does not download dependencies, accept agreements or change system security settings for you.
+## Install with a local Agent (recommended)
+
+Give this package to an Agent with permission to run on your computer, such as Codex, and send:
+
+> Install the PromptDirector video component using INSTALL-AGENT.md in this package. Reuse or install the missing free dependencies, then install and verify it. Do not install Python or change system security settings; involve me only for required system authorization.
+
+The Agent handles extraction, dependency checks, installation and verification. **Install with Agent** in the extension copies the complete request. Older extensions without that button can use the sentence above. See the [Agent installation guide](INSTALL-AGENT.md).
+
+## Manual installation (alternative)
+
1. Install the dependencies below, or reuse existing installations.
2. **Extract the entire ZIP**. Do not run scripts inside the archive preview. Double-click `Install-macOS.command` on macOS or `Install-Windows.cmd` on Windows.
3. After the window confirms installation, return to PromptDirector. The pending capture resumes; select **Continue** if installation checks have paused.
diff --git a/tools/video-component/INSTALL.zh.md b/tools/video-component/INSTALL.zh.md
index ee89a0e..f3f0f36 100644
--- a/tools/video-component/INSTALL.zh.md
+++ b/tools/video-component/INSTALL.zh.md
@@ -4,6 +4,16 @@
此源码包支持 macOS 和 Windows,不需要付费账号、开发者证书或 Agent 配对。它连接本机免费的 Node.js、yt-dlp、FFmpeg 和 FFprobe;不会替你下载软件、接受协议或调整系统保护。
+## 让 Agent 安装(推荐)
+
+将这个组件包交给有本机执行权限的 Agent(例如 Codex),发送一句话:
+
+> 帮我按包内 INSTALL-AGENT.md 安装 PromptDirector 视频组件:自动复用或补齐免费依赖,完成安装与验证;不要安装 Python 或修改系统安全设置,仅在需要系统授权时叫我。
+
+Agent 会负责解压、检查依赖、安装和验证。插件中的“让 Agent 安装”可直接复制完整指令;较旧插件没有此按钮时,也可以使用上面这句话。具体执行规则见 [Agent 安装指南](INSTALL-AGENT.md)。
+
+## 手动安装(备用)
+
1. 安装下方依赖。已安装的可以直接复用。
2. **完整解压 ZIP**,不要在压缩文件预览里运行。macOS 双击 `Install-macOS.command`;Windows 双击 `Install-Windows.cmd`。
3. 窗口显示安装成功后,返回 PromptDirector,待保存视频会继续;如侧栏已暂停,点“继续”。关闭安装窗口不影响浏览器资料库。
diff --git a/tools/video-component/check-source-registration.mjs b/tools/video-component/check-source-registration.mjs
index a6d3508..80161fd 100644
--- a/tools/video-component/check-source-registration.mjs
+++ b/tools/video-component/check-source-registration.mjs
@@ -1,9 +1,8 @@
import assert from 'node:assert/strict';
import { readFile, access } from 'node:fs/promises';
import { homedir } from 'node:os';
-import { join, resolve, win32 } from 'node:path';
-import { execFile } from 'node:child_process';
-import { promisify } from 'node:util';
+import { join, resolve } from 'node:path';
+import { windowsVideoRegistry } from '../../connector/register-video.mjs';
import { isMain } from '../../connector/is-main.mjs';
const exists = async path => {
@@ -17,21 +16,8 @@ export async function checkSourceRegistration({ root, nativeDirectory, removed =
const windows = process.platform === 'win32';
const registration = join(nativeDirectory || (windows ? root : join(homedir(), 'Library/Application Support/Google/Chrome/NativeMessagingHosts')), 'com.promptdirector.video.json');
if (windows) {
- assert(process.env.SystemRoot, 'Windows system directory is required');
- const script = `$ErrorActionPreference='Stop'
-$found=@()
-foreach ($view in @([Microsoft.Win32.RegistryView]::Registry32,[Microsoft.Win32.RegistryView]::Registry64)) {
- $base=[Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::CurrentUser,$view)
- try {
- $key=$base.OpenSubKey('Software\\Google\\Chrome\\NativeMessagingHosts\\com.promptdirector.video')
- if ($null -eq $key) { $found += $null }
- else { try { $found += $key.GetValue('') } finally { $key.Dispose() } }
- } finally { $base.Dispose() }
-}
-ConvertTo-Json -InputObject @($found) -Compress`;
- const { stdout } = await promisify(execFile)(win32.join(process.env.SystemRoot, 'System32/WindowsPowerShell/v1.0/powershell.exe'),
- ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')], { windowsHide: true, timeout: 30_000 });
- const actual = JSON.parse(stdout);
+ const snapshots = await windowsVideoRegistry({ registration }).snapshot();
+ const actual = snapshots.map(value => value.hasValue ? value.value : null);
assert.deepEqual(actual, removed ? [null, null] : [registration, registration], 'Both HKCU views must reflect the actual source installation');
}
if (removed) {
diff --git a/tools/video-component/package-source.mjs b/tools/video-component/package-source.mjs
index e284a77..94ca7e0 100644
--- a/tools/video-component/package-source.mjs
+++ b/tools/video-component/package-source.mjs
@@ -55,8 +55,9 @@ export async function sourcePackageFiles(repo = repository) {
const component = { distribution: 'source', version: VIDEO_COMPONENT.version, extensionId: extensionIdFromPublicKey(manifest) };
const files = await Promise.all([...VIDEO_SOURCE_FILES, 'docs/VIDEO_COMPONENT.md'].map(async name => ({ name, data: await readFile(join(repo, name)) })));
const guide = files.find(file => file.name === 'docs/VIDEO_COMPONENT.md');
- guide.data = encoder.encode(guide.data.toString('utf8').replaceAll('../tools/video-component/INSTALL.', '../INSTALL.'));
+ guide.data = encoder.encode(guide.data.toString('utf8').replaceAll('../tools/video-component/', '../'));
for (const language of ['zh', 'en']) files.push({ name: `INSTALL.${language}.md`, data: await readFile(new URL(`./INSTALL.${language}.md`, import.meta.url)) });
+ files.push({ name: 'INSTALL-AGENT.md', data: await readFile(new URL('./INSTALL-AGENT.md', import.meta.url)) });
files.push({ name: 'component.json', data: encoder.encode(JSON.stringify(component, null, 2)) },
{ name: 'package.json', data: encoder.encode(JSON.stringify({ private: true, type: 'module', engines: { node: '>=22.13' } }, null, 2)) });
for (const [verb, command] of [['Install', 'install'], ['Uninstall', 'uninstall']]) {