From 7e80b04b5bdca849a5751744739c4118c03ce100 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Fri, 27 Nov 2026 20:19:20 +0800 Subject: [PATCH 01/36] =?UTF-8?q?fix(bilibili):=20=E5=88=86=E9=A1=B5?= =?UTF-8?q?=E6=81=A2=E5=A4=8D=E6=9C=AA=E7=BB=91=E5=AE=9A=E6=9D=A5=E6=BA=90?= =?UTF-8?q?=E9=94=9A=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .changeset/tidy-bilibili-anchor-recovery.md | 5 ++++ extensions/bilibili/src/repository.ts | 26 ++++++++++++++------ extensions/bilibili/tests/repository.test.ts | 15 ++++++++--- 3 files changed, 36 insertions(+), 10 deletions(-) create mode 100644 .changeset/tidy-bilibili-anchor-recovery.md diff --git a/.changeset/tidy-bilibili-anchor-recovery.md b/.changeset/tidy-bilibili-anchor-recovery.md new file mode 100644 index 00000000..9710ec44 --- /dev/null +++ b/.changeset/tidy-bilibili-anchor-recovery.md @@ -0,0 +1,5 @@ +--- +'@inkcre/ext-bilibili': patch +--- + +恢复收藏采集时分页查找已有来源锚点,避免来源更新失败后因数据库单页上限重复创建锚点。 diff --git a/extensions/bilibili/src/repository.ts b/extensions/bilibili/src/repository.ts index 783af44f..78be63a6 100644 --- a/extensions/bilibili/src/repository.ts +++ b/extensions/bilibili/src/repository.ts @@ -158,13 +158,25 @@ export class BilibiliRepository { .throwOnError() anchor = result.data } else { - const result = await Block.dbApi - .from() - .select() - .eq('resolver', 'core.source.v1') - .order('id', { ascending: true }) - .throwOnError() - anchor = result.data?.find((row) => objectContent(row.content)?.id === source.id) + let offset = 0 + while (true) { + const result = await Block.dbApi + .from() + .select('*', { count: 'exact' }) + .eq('resolver', 'core.source.v1') + .order('id', { ascending: true }) + .range(offset, offset + 999) + .throwOnError() + const rows = result.data ?? [] + anchor = rows.find((row) => objectContent(row.content)?.id === source.id) + offset += rows.length + if ( + anchor || + !rows.length || + (result.count !== null ? offset >= result.count : rows.length < 1000) + ) + break + } } if ( anchor && diff --git a/extensions/bilibili/tests/repository.test.ts b/extensions/bilibili/tests/repository.test.ts index f171de69..fa3b8194 100644 --- a/extensions/bilibili/tests/repository.test.ts +++ b/extensions/bilibili/tests/repository.test.ts @@ -331,11 +331,13 @@ void test('a lost create response is not replayed and a later execution reuses t savedGraph(database, value) }) -void test('failure of the final Source update reuses the already saved graph and unbound Source anchor on the next execution', async (context) => { +void test('failure of the final Source update reuses the saved graph and an unbound Source anchor beyond the service row cap', async (context) => { const database = new Database() attach(context, database) const value = source() database.rows.sources.push(structuredClone(value) as unknown as Row) + for (let id = 1; id <= database.pageLimit; id++) + database.rows.blocks.push(block(id, 'core.source.v1', { id: 1000 + id })) database.failBefore = (query) => query.table === 'sources' && query.action === 'update' await assert.rejects( new BilibiliRepository().reconcilePage(value, favoriteGraph(account, page()), next(value)), @@ -346,13 +348,20 @@ void test('failure of the final Source update reuses the already saved graph and const ids = database.rows.blocks.map((row) => row.id) const relations = structuredClone(database.rows.relations) database.failBefore = null - await new BilibiliRepository().reconcilePage(value, favoriteGraph(account, page()), next(value)) + const resumed = structuredClone(database.rows.sources[0]) as unknown as Source + await new BilibiliRepository().reconcilePage( + resumed, + favoriteGraph(account, page()), + next(resumed) + ) assert.deepEqual( database.rows.blocks.map((row) => row.id), ids ) assert.deepEqual(database.rows.relations, relations) - savedGraph(database, value) + assert.equal(database.rows.sources[0]!.block, resumed.block) + assert.ok(Object.hasOwn(database.rows.sources[0]!.state as object, 'bilibili')) + savedGraph(database, resumed) }) void test('normal paginated graph reads find existing objects beyond the service row cap', async (context) => { From 887e4bcbd7e593e9e463954ab4b38c85c462c023 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 10:24:21 +0800 Subject: [PATCH 02/36] =?UTF-8?q?ref(core):=20=E7=94=A8=E7=8B=AC=E7=AB=8B?= =?UTF-8?q?=E7=BB=93=E6=9E=9C=E9=AA=8C=E8=AF=81=E9=A2=86=E5=8F=96=E3=80=81?= =?UTF-8?q?=E6=81=A2=E5=A4=8D=E3=80=81=E5=8F=96=E6=B6=88=E4=B8=8E=E5=8F=91?= =?UTF-8?q?=E5=B8=83=E5=90=88=E5=90=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- extensions/bilibili/tests/favorites.test.ts | 26 ++- .../caldav/scripts/tests/content.test.ts | 2 +- .../scripts/tests/graph-content.test.ts | 29 +-- scripts/check-local-runtime-contract.mjs | 19 -- scripts/test-core-sdk-publication.mjs | 25 ++- scripts/tests/core-sdk-compatibility.test.mjs | 37 +++- .../independent-extension-release.test.mjs | 20 ++- scripts/tests/job-cancellation.test.mjs | 38 +++- scripts/tests/job-observation.test.mjs | 59 +++---- scripts/tests/local-files-contract.test.ts | 25 ++- scripts/tests/observability.test.mjs | 165 +++++++++++++----- scripts/tests/saved-connections.test.mjs | 142 +++++++++------ scripts/tests/ui-source.test.mjs | 61 ++++++- 13 files changed, 431 insertions(+), 217 deletions(-) diff --git a/extensions/bilibili/tests/favorites.test.ts b/extensions/bilibili/tests/favorites.test.ts index fbd777dc..ec233fe3 100644 --- a/extensions/bilibili/tests/favorites.test.ts +++ b/extensions/bilibili/tests/favorites.test.ts @@ -239,17 +239,23 @@ void test('a changed head restarts scanning and failed persistence never advance void test('cancellation and repeated pagination fail without a false completed checkpoint', async () => { const controller = new AbortController() - controller.abort() + const reason = new Error('collection cancelled before starting') + let writes = 0 + controller.abort(reason) await assert.rejects( collectFavorites( config, startProgress({}, config), { max_pages: 2 }, controller.signal, - session([], []), - async () => assert.fail('must not write') - ) + session([page([11], false)], []), + async () => { + writes++ + } + ), + (error) => error === reason ) + assert.equal(writes, 0) let persisted: Record = {} await assert.rejects( collectFavorites( @@ -302,9 +308,11 @@ void test('a changed committed boundary restarts even when the first page has no void test('an abort during page reading prevents dispatching an uncommitted batch', async () => { const controller = new AbortController() + const reason = new Error('collection cancelled during page reading') + let writes = 0 const target = session([page([11], false)], []) target.read = async () => { - controller.abort() + controller.abort(reason) return page([11], false) } await assert.rejects( @@ -314,9 +322,13 @@ void test('an abort during page reading prevents dispatching an uncommitted batc { max_pages: 1 }, controller.signal, target, - async () => assert.fail('must not write an aborted batch') - ) + async () => { + writes++ + } + ), + (error) => error === reason ) + assert.equal(writes, 0) }) void test('a head reorder during the same run prevents a false completed scan', async () => { diff --git a/extensions/caldav/scripts/tests/content.test.ts b/extensions/caldav/scripts/tests/content.test.ts index 9f037fa9..882926b2 100644 --- a/extensions/caldav/scripts/tests/content.test.ts +++ b/extensions/caldav/scripts/tests/content.test.ts @@ -23,7 +23,7 @@ void test('the phone calendar retains the master, offline exception and all-day assert.deepEqual(allDay.end, { value: '2026-10-21', zone: '', dateOnly: true }) }) -void test('Tasks.org parent references and completion state remain readable', () => { +void test('Tasks.org parent references and incomplete task status remain readable', () => { const result = parseResource(resource(fixture('tasks.ics')), 'calendar') assert.equal(result.kind, 'calendar') if (result.kind !== 'calendar') return diff --git a/extensions/caldav/scripts/tests/graph-content.test.ts b/extensions/caldav/scripts/tests/graph-content.test.ts index c89a5100..0f392152 100644 --- a/extensions/caldav/scripts/tests/graph-content.test.ts +++ b/extensions/caldav/scripts/tests/graph-content.test.ts @@ -21,20 +21,27 @@ function properties(sample: (typeof samples)[number]): GraphProperty[] { })) } -void test('Python-authored contact graph composes the same phones, photo and unknown properties', () => { +void test('Python-authored contact graph preserves phones, photo and subsequent phone edits', () => { const sample = samples.find((item: any) => item.kind === 'contact') const text = composeGraph(sample.remainder, properties(sample)) const actual = parseResource(JSON.stringify({ href: 'contact.vcf', text }), 'contact') - const expected = parseResource( - JSON.stringify({ href: 'contact.vcf', text: sample.text }), - 'contact' - ) - assert.notEqual(actual.kind, 'invalid') - if (actual.kind !== 'contact' || expected.kind !== 'contact') return - assert.equal(actual.title, expected.title) - assert.deepEqual(actual.fields, expected.fields) - assert.equal(actual.photo, expected.photo) - assert.equal(resourceUid(text), resourceUid(sample.text)) + assert.equal(actual.kind, 'contact') + if (actual.kind !== 'contact') return + assert.equal(actual.title, 'InKCre Preview Photo Contact') + assert.deepEqual(actual.fields, [ + { + name: 'tel', + values: [ + { value: '+8613800000000', label: 'cell' }, + { value: '+8613900000000', label: 'work' }, + ], + }, + { name: 'email', values: [{ value: 'preview146@example.invalid', label: '' }] }, + { name: 'note', values: [{ value: 'PR 146 HTTPS acceptance test', label: '' }] }, + ]) + const photoBytes = sample.properties.find((field: any) => field.link.name === 'PHOTO').value + assert.equal(actual.photo, `data:image/jpeg;base64,${photoBytes}`) + assert.equal(resourceUid(text), 'inkcre-preview146-contact') const changed = properties(sample) changed.find((field) => field.link.name === 'TEL')!.value = '+8613800000001' assert.match(composeGraph(sample.remainder, changed), /\+8613800000001/) diff --git a/scripts/check-local-runtime-contract.mjs b/scripts/check-local-runtime-contract.mjs index 022cefff..a5f0b966 100644 --- a/scripts/check-local-runtime-contract.mjs +++ b/scripts/check-local-runtime-contract.mjs @@ -251,25 +251,6 @@ if (!devScript.includes("'database'")) { errors.push('pnpm dev must ensure the worktree-scoped database capability') } -const uiSourceHelper = await readFile(`${repoRoot}/scripts/ui-source.mjs`, 'utf8') -for (const required of [ - "'@inkcre/ui-web'", - "'@inkcre/ui-web/styles'", - "'@inkcre/ui-web/styles/functions'", - "'@inkcre/ui-web/styles/mixins'", - "'@inkcre/ui-web/tokens/ref'", - "'@inkcre/ui-web/tokens/sys'", - "'@inkcre/ui-web/tokens/comp'", - "'@inkcre/ui-web/utils'", - "'@inkcre/ui-web/locales'", - "'@inkcre/ui-web/uno'", - 'development-only', -]) { - if (!uiSourceHelper.includes(required)) { - errors.push(`UI source helper is missing contract fragment "${required}"`) - } -} - for (const path of ['apps/web/vite.config.ts', 'extensions/twitter/vite.config.ts']) { const config = await readFile(`${repoRoot}/${path}`, 'utf8') for (const required of [ diff --git a/scripts/test-core-sdk-publication.mjs b/scripts/test-core-sdk-publication.mjs index 791979b2..ce61556e 100644 --- a/scripts/test-core-sdk-publication.mjs +++ b/scripts/test-core-sdk-publication.mjs @@ -43,6 +43,7 @@ void test('draft recovery uploads missing saved assets without replacing an exis try { await mkdir(`${root}/packages/core`, { recursive: true }) await mkdir(`${root}/.core-sdk-delivery`) + await mkdir(`${root}/remote-assets`) await writeFile(`${root}/packages/core/package.json`, JSON.stringify({ version: '0.5.0' })) await writeFile(`${root}/.core-sdk-delivery/source.json`, JSON.stringify(receipt)) await writeFile(`${root}/.core-sdk-delivery/${receipt.asset}`, bytes) @@ -56,10 +57,10 @@ const route = args[1]; const method = args[args.indexOf('--method') + 1]; let response; const asset = (name) => ({ name, url: 'https://api.github.com/' + (name.endsWith('.tgz') ? 'archive' : 'receipt'), browser_download_url: 'https://api.github.com/' + (name.endsWith('.tgz') ? 'archive' : 'receipt') }); -const release = () => ({ id: 12, tag_name: 'core-v0.4.0', target_commitish: process.env.SOURCE_REVISION, draft: !fs.existsSync('published'), assets: [fs.existsSync('archiveUploaded') && asset('inkcre-core-0.4.0.tgz'), fs.existsSync('uploaded') && asset('source.json')].filter(Boolean) }); +const release = () => ({ id: 12, tag_name: 'core-v0.4.0', target_commitish: process.env.SOURCE_REVISION, draft: !fs.existsSync('published'), assets: ['inkcre-core-0.4.0.tgz', 'source.json'].filter((name) => fs.existsSync('remote-assets/' + name)).map(asset) }); if (route.startsWith('https://uploads.github.com/')) { const name = new URL(route).searchParams.get('name'); - fs.writeFileSync(name.endsWith('.tgz') ? 'archiveUploaded' : 'uploaded', 'yes'); + fs.writeFileSync('remote-assets/' + name, fs.readFileSync(args[args.indexOf('--input') + 1])); response = asset(name); } else if (method === 'POST') { fs.writeFileSync('created', 'yes'); @@ -73,14 +74,15 @@ process.stdout.write(JSON.stringify(response)); ) await chmod(`${root}/gh`, 0o700) await writeFile(`${root}/created`, 'yes') - await writeFile(`${root}/archiveUploaded`, 'yes') + await writeFile(`${root}/remote-assets/${receipt.asset}`, bytes) process.chdir(root) process.env.PATH = `${root}:${originalPath}` process.env.SOURCE_REVISION = source delete process.env.GITHUB_STEP_SUMMARY globalThis.fetch = async (url) => { - if (url.endsWith('/archive')) return new Response(bytes) - if (url.endsWith('/receipt')) return new Response(JSON.stringify(receipt)) + if (url.endsWith('/archive')) + return new Response(await readFile(`remote-assets/${receipt.asset}`)) + if (url.endsWith('/receipt')) return new Response(await readFile('remote-assets/source.json')) if (url.includes('/git/ref/')) return Response.json({ object: { type: 'commit', sha: source } }) const exists = async (file) => @@ -90,13 +92,13 @@ process.stdout.write(JSON.stringify(response)); ) if (!(await exists('created')) || (await exists('invisibleList'))) return Response.json([]) const assets = [] - if (await exists('archiveUploaded')) + if (await exists(`remote-assets/${receipt.asset}`)) assets.push({ name: receipt.asset, url: 'https://api.github.com/archive', browser_download_url: 'https://api.github.com/archive', }) - if (await exists('uploaded')) + if (await exists('remote-assets/source.json')) assets.push({ name: 'source.json', url: 'https://api.github.com/receipt', @@ -118,13 +120,16 @@ process.stdout.write(JSON.stringify(response)); assert.equal(calls.length, 2) assert.match(calls[0][1], /releases\/12\/assets\?name=source.json$/) assert.ok(calls[1].includes('PATCH')) + assert.deepEqual(await readFile(`remote-assets/${receipt.asset}`), bytes) + assert.deepEqual(JSON.parse(await readFile('remote-assets/source.json', 'utf8')), receipt) await main('publish') assert.equal( await readFile('calls.jsonl', 'utf8'), calls.map((args) => JSON.stringify(args)).join('\n') + '\n' ) - for (const file of ['created', 'archiveUploaded', 'uploaded', 'published', 'calls.jsonl']) - await rm(file) + for (const file of ['created', 'published', 'calls.jsonl']) await rm(file) + await rm('remote-assets', { recursive: true }) + await mkdir('remote-assets') await writeFile('invisibleList', 'yes') await main('publish') const freshCalls = (await readFile('calls.jsonl', 'utf8')).trim().split('\n').map(JSON.parse) @@ -136,6 +141,8 @@ process.stdout.write(JSON.stringify(response)); assert.match(freshCalls[1][1], /releases\/12\/assets/) assert.match(freshCalls[2][1], /releases\/12\/assets/) assert.ok(freshCalls[3].includes('PATCH')) + assert.deepEqual(await readFile(`remote-assets/${receipt.asset}`), bytes) + assert.deepEqual(JSON.parse(await readFile('remote-assets/source.json', 'utf8')), receipt) } finally { process.chdir(originalDirectory) process.env.PATH = originalPath diff --git a/scripts/tests/core-sdk-compatibility.test.mjs b/scripts/tests/core-sdk-compatibility.test.mjs index 4cfc7307..6cdae387 100644 --- a/scripts/tests/core-sdk-compatibility.test.mjs +++ b/scripts/tests/core-sdk-compatibility.test.mjs @@ -24,14 +24,15 @@ void test('SDK 0.4 preserves the legacy JWT default without changing database ad ) assert.equal(Object.hasOwn(generated.jwt, 'maximum_lifetime_seconds'), false) assert.equal(peerJwtContract.maximum_lifetime_seconds, 86_400) - assert.equal(databaseRuntimeContract.jwt, peerJwtContract) + assert.equal(databaseRuntimeContract.jwt.maximum_lifetime_seconds, 86_400) + const priorSecret = configStore.metaConfig.INKCRE_JWT_SECRET configStore.metaConfig.INKCRE_JWT_SECRET = 'sdk-compatibility-test-only' try { const token = await authStore.newToken() const claims = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString()) - assert.equal(claims.exp - claims.iat, peerJwtContract.maximum_lifetime_seconds) + assert.equal(claims.exp - claims.iat, 86_400) } finally { - configStore.metaConfig.INKCRE_JWT_SECRET = '' + configStore.metaConfig.INKCRE_JWT_SECRET = priorSecret } }) @@ -41,7 +42,12 @@ void test('binary storage keeps its explicit connection for create, read, update const id = '00000000-0000-4000-8000-000000000009' globalThis.fetch = async (input, init) => { const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url - calls.push({ url, token: new Headers(init.headers).get('Authorization') }) + calls.push({ + url: new URL(url), + headers: new Headers(init.headers), + method: init.method, + body: init.body, + }) if (url.includes('create_storage_blob')) return Response.json(id) if (url.includes('read_storage_blob')) return new Response(new Uint8Array([37, 80, 68, 70])) return Response.json([{ id }]) @@ -60,13 +66,30 @@ void test('binary storage keeps its explicit connection for create, read, update await storage.getRawContent({ id: 1, storage: -4, content: pointer }), new Uint8Array([37, 80, 68, 70]) ) - assert.equal(await storage.updateRawContent(pointer, new Uint8Array([1])), true) + assert.equal(await storage.updateRawContent(pointer, new Uint8Array([0, 1, 127, 255])), true) assert.equal(await storage.deleteRawContent(pointer), true) assert.equal(calls.length, 4) for (const call of calls) { - assert.equal(call.url.startsWith(baseUrl + '/'), true) - assert.equal(call.token, 'Bearer explicit-connection-test-token') + assert.equal(call.url.href.startsWith(baseUrl + '/'), true) + assert.equal(call.headers.get('Authorization'), 'Bearer explicit-connection-test-token') + assert.equal(call.headers.get('Content-Profile'), 'inkcre') } + assert.deepEqual( + calls.map(({ method, url }) => [method, url.pathname]), + [ + ['POST', '/database/rpc/create_storage_blob'], + ['POST', '/database/rpc/read_storage_blob'], + ['PATCH', '/database/storage_blobs'], + ['DELETE', '/database/storage_blobs'], + ] + ) + assert.equal(calls[0].headers.get('Content-Type'), 'application/octet-stream') + assert.deepEqual([...new Uint8Array(calls[0].body)], [37, 80, 68, 70]) + assert.equal(calls[1].headers.get('Accept'), 'application/octet-stream') + assert.deepEqual(JSON.parse(calls[1].body), { blob_id: id }) + assert.deepEqual(JSON.parse(calls[2].body), { data: '\\x00017fff' }) + assert.equal(calls[2].url.searchParams.get('id'), `eq.${id}`) + assert.equal(calls[3].url.searchParams.get('id'), `eq.${id}`) } finally { globalThis.fetch = originalFetch } diff --git a/scripts/tests/independent-extension-release.test.mjs b/scripts/tests/independent-extension-release.test.mjs index c7cf94c7..eccdfdc3 100644 --- a/scripts/tests/independent-extension-release.test.mjs +++ b/scripts/tests/independent-extension-release.test.mjs @@ -27,12 +27,16 @@ void test('MF snapshots permit unused UI dependencies and validate emitted UI sh await writeFile(path.join(workspace, 'remoteEntry.js'), 'export default {}') const inspect = () => inspectNativeModuleFederation({ packagePath, corePackagePath, artifactDirectory: workspace }) - for (const [uiShares, declaresUi, valid] of [ - [[], true, true], - [[uiShare], true, true], - [[{ ...uiShare, requiredVersion: '2.7.0' }], true, false], - [[uiShare, uiShare], true, false], - [[uiShare], false, false], + for (const [uiShares, declaresUi, error] of [ + [[], true, undefined], + [[uiShare], true, undefined], + [ + [{ ...uiShare, requiredVersion: '2.7.0' }], + true, + { code: 'ERR_ASSERTION', actual: '2.7.0', expected: '2.3.0' }, + ], + [[uiShare, uiShare], true, /must not duplicate @inkcre\/ui-web shares/], + [[uiShare], false, /shared @inkcre\/ui-web must declare the producer UI version/], ]) { await writeFile( packagePath, @@ -46,8 +50,8 @@ void test('MF snapshots permit unused UI dependencies and validate emitted UI sh exposes: [], }) ) - if (valid) assert.equal((await inspect()).name, 'inkcre/capture') - else await assert.rejects(inspect(), assert.AssertionError) + if (error) await assert.rejects(inspect(), error) + else assert.equal((await inspect()).name, 'inkcre/capture') } } finally { await rm(workspace, { recursive: true, force: true }) diff --git a/scripts/tests/job-cancellation.test.mjs b/scripts/tests/job-cancellation.test.mjs index 3e1640a1..a8312b77 100644 --- a/scripts/tests/job-cancellation.test.mjs +++ b/scripts/tests/job-cancellation.test.mjs @@ -17,20 +17,29 @@ function pending(id, type, abortRequested) { }) } -function database(t, job, abortWhenClaimed) { +function database(t, job, abortWhenClaimed, claimSucceeded = true) { const updates = [] t.mock.method(Job, 'get', async () => job) t.mock.method(Job.dbApi, 'update', (fields) => ({ - eq() { + filters: {}, + eq(key, value) { + this.filters[key] = value return this }, select() { if (fields.status === JobStatus.RUNNING) return { - maybeSingle: async () => ({ - data: { ...job, status: JobStatus.RUNNING, abort_requested: abortWhenClaimed }, - }), + maybeSingle: async () => { + assert.deepEqual(this.filters, { id: job.id, status: JobStatus.PENDING }) + updates.push(JobStatus.RUNNING) + return { + data: claimSucceeded + ? { ...job, status: JobStatus.RUNNING, abort_requested: abortWhenClaimed } + : null, + } + }, } + assert.deepEqual(this.filters, { id: job.id, status: JobStatus.RUNNING }) updates.push(fields.status) return Promise.resolve({ data: [{ id: job.id }] }) }, @@ -49,7 +58,7 @@ void test('an already cancelled pending Job closes without asking business eligi assert.equal(await JobManager.run(job.id), true) assert.equal(canHandle.mock.callCount(), 0) assert.equal(handle.mock.callCount(), 0) - assert.deepEqual(updates, [JobStatus.ABORTED]) + assert.deepEqual(updates, [JobStatus.RUNNING, JobStatus.ABORTED]) } finally { JobManager.unregisterHandler(type) } @@ -64,7 +73,7 @@ void test('a cancellation arriving during atomic claim prevents the handler from try { assert.equal(await JobManager.run(job.id), true) assert.equal(handle.mock.callCount(), 0) - assert.deepEqual(updates, [JobStatus.ABORTED]) + assert.deepEqual(updates, [JobStatus.RUNNING, JobStatus.ABORTED]) } finally { JobManager.unregisterHandler(type) } @@ -84,3 +93,18 @@ void test('ordinary ineligible work remains pending', async (t) => { JobManager.unregisterHandler(type) } }) + +void test('work claimed by another Peer never starts or closes locally', async (t) => { + const type = `test.cancel.${crypto.randomUUID()}` + const job = pending(4, type, false) + const updates = database(t, job, false, false) + const handle = t.mock.fn(async () => undefined) + JobManager.registerHandler(type, { parameters: MetaConfigSchema, canHandle: () => true, handle }) + try { + assert.equal(await JobManager.run(job.id), false) + assert.equal(handle.mock.callCount(), 0) + assert.deepEqual(updates, [JobStatus.RUNNING]) + } finally { + JobManager.unregisterHandler(type) + } +}) diff --git a/scripts/tests/job-observation.test.mjs b/scripts/tests/job-observation.test.mjs index a6fda130..96baab72 100644 --- a/scripts/tests/job-observation.test.mjs +++ b/scripts/tests/job-observation.test.mjs @@ -3,8 +3,8 @@ import { readFile } from 'node:fs/promises' import { createRequire } from 'node:module' import { test } from 'node:test' import { pathToFileURL } from 'node:url' -import { Job, configStore, flushTelemetry } from '../../packages/core/dist/index.js' -import { DatabaseClient, ObservabilityClient } from '../../packages/core/dist/sdk/sdk.js' +import { configStore, flushTelemetry } from '../../packages/core/dist/index.js' +import { ObservabilityClient } from '../../packages/core/dist/sdk/sdk.js' import { defaultObservationWindow } from '../../apps/web/src/components/obsrv/ObservationExplorer/ObservationExplorer.ts' import { useJobCreator } from '../../apps/web/src/views/sources/source/use-job-creator.ts' @@ -79,6 +79,7 @@ void test('a long Job offers bounded windows and earlier stages remain queryable const records = [ observation(1, '2025-10-01T10:00:00.000Z', 'job.submitted'), observation(2, '2025-12-01T10:00:02.052Z', 'job.closed'), + observation(3, '2026-11-05T11:30:00Z', 'job.progress'), ] const reader = observationReader(records) for (const end of [closed, undefined]) { @@ -86,7 +87,10 @@ void test('a long Job offers bounded windows and earlier stages remain queryable assert.equal(window.limited, true) const result = await reader.query({ ...window, job_id: 11 }) assert.equal(Date.parse(result.until) - Date.parse(result.since), 31 * 86400 * 1000) - assert.ok(result.records.every((record) => record.event_name !== 'job.submitted')) + assert.deepEqual( + result.records.map((record) => record.event_name), + [end ? 'job.closed' : 'job.progress'] + ) } const earlier = await reader.query({ job_id: 11, @@ -97,13 +101,11 @@ void test('a long Job offers bounded windows and earlier stages remain queryable earlier.records.map((record) => record.event_name), ['job.submitted'] ) - await assert.rejects(reader.query({ job_id: 11, since: created, until: closed })) }) -void test('submission closes the saved draft and another Peer can read it when diagnostics fail', async (context) => { +void test('successful Job submission clears the draft despite diagnostic failure, while rejected submission keeps it', async (context) => { const priorMeta = { ...configStore.metaConfig } const priorWindow = globalThis.window - let storedJob = null let rejectSubmission = false let writes = 0 let diagnosticWrites = 0 @@ -129,20 +131,18 @@ void test('submission closes the saved draft and another Peer can read it when d default_timeout_seconds: 30, }) assert.equal(url.pathname, '/jobs') - if (init.method === 'POST') { - if (rejectSubmission) return Response.json({ message: 'Unavailable' }, { status: 503 }) - writes++ - storedJob = { - ...JSON.parse(init.body), - id: 13, - status: 'pending', - abort_requested: false, - created_at: '2026-11-05T12:00:00.082Z', - started_at: null, - closed_at: null, - } - } - return Response.json(storedJob) + assert.equal(init.method, 'POST') + if (rejectSubmission) return Response.json({ message: 'Unavailable' }, { status: 503 }) + writes++ + return Response.json({ + ...JSON.parse(init.body), + id: 13, + status: 'pending', + abort_requested: false, + created_at: '2026-11-05T12:00:00.082Z', + started_at: null, + closed_at: null, + }) } context.mock.method(globalThis, 'fetch', transport) context.mock.method(console, 'warn', () => {}) @@ -185,27 +185,12 @@ void test('submission closes the saved draft and another Peer can read it when d assert.equal(confirmations, 0) assert.equal(navigatedJob, 13) assert.equal(jobs.value[0].id, 13) + assert.deepEqual(jobs.value[0].parameters, { source: 4, config: { limit: 20 } }) + assert.equal(jobs.value[0].created_at.toISOString(), '2026-11-05T12:00:00.082Z') assert.equal(writes, 1) await flushTelemetry() assert.ok(diagnosticWrites > 0) - const connection = { - baseUrl: 'https://reading-peer.example', - tokenProvider: async () => 'other-peer-token', - fetch: transport, - } - const reader = new DatabaseClient('jobs', Job, connection) - const persisted = Job.parse((await reader.from().select().eq('id', 13).single()).data) - assert.equal(persisted.status, 'pending') - assert.equal(persisted.created_at.toISOString(), storedJob.created_at) - assert.deepEqual(persisted.parameters, { source: 4, config: { limit: 20 } }) - const observations = await new ObservabilityClient(connection).query({ - job_id: 13, - since: '2026-11-05T11:00:00Z', - until: '2026-11-05T13:00:00Z', - }) - assert.deepEqual(observations.records, []) - form.onNewJob() form.jobConfig.value = '{"limit":40}' rejectSubmission = true diff --git a/scripts/tests/local-files-contract.test.ts b/scripts/tests/local-files-contract.test.ts index c1f74481..f1f1f8d8 100644 --- a/scripts/tests/local-files-contract.test.ts +++ b/scripts/tests/local-files-contract.test.ts @@ -6,17 +6,24 @@ void test('Peer file location preserves Unicode and reserved path characters', ( const result = peerFileLocation( 'inkcre-peer-file://a143b185-f43d-47d1-8ef7-1d3857284b01/Users/a/%E4%B8%AD%E6%96%87%20%23%3F.md' ) - assert.equal(result.path, '/Users/a/中文 #?.md') + assert.deepEqual(result, { + peer: 'a143b185-f43d-47d1-8ef7-1d3857284b01', + path: '/Users/a/中文 #?.md', + }) for (const invalid of [ - 'file:///Users/a', - 'inkcre-peer-file://bad-peer/a', + 'https://a143b185-f43d-47d1-8ef7-1d3857284b01/a', 'inkcre-peer-file://a143b185-f43d-47d1-8ef7-1d3857284b01/a#', ]) { - assert.throws(() => peerFileLocation(invalid)) + assert.throws(() => peerFileLocation(invalid), /原件位置格式无效/) } + assert.throws( + () => peerFileLocation('inkcre-peer-file://bad-peer/a'), + (error) => + error instanceof Error && error.name === 'ZodError' && error.message.includes('Invalid UUID') + ) }) -void test('Missing originals and failed extraction retain a distinct successful revision', () => { +void test('File metadata represents an unavailable original and extraction issue alongside the last successful revision', () => { const metadata = fileMetadata.parse({ location: 'inkcre-peer-file://a143b185-f43d-47d1-8ef7-1d3857284b01/Users/a/report.docx', format: 'docx', @@ -33,5 +40,11 @@ void test('Missing originals and failed extraction retain a distinct successful assert.equal(metadata.available, false) assert.equal(metadata.revision?.scope, 'main_document') assert.equal(metadata.revision?.extracted_at, '2026-10-22T06:00:00Z') - assert.equal(fileMetadata.safeParse({ ...metadata, format: 'executable' }).success, false) + const invalid = fileMetadata.safeParse({ ...metadata, format: 'executable' }) + assert.equal(invalid.success, false) + if (!invalid.success) + assert.deepEqual( + invalid.error.issues.map((issue) => issue.path), + [['format']] + ) }) diff --git a/scripts/tests/observability.test.mjs b/scripts/tests/observability.test.mjs index 6548afc8..975750ce 100644 --- a/scripts/tests/observability.test.mjs +++ b/scripts/tests/observability.test.mjs @@ -132,12 +132,18 @@ void test('selected external backend delegates query and writes using Peer autho }) void test('unknown selection, missing capability, external failure and backend disagreement never fall back', async () => { - for (const failure of ['selection', 'capability', 'request', 'mismatch']) { + for (const [failure, message, expectedActions] of [ + ['selection', 'Unsupported observability configuration version.', []], + ['capability', 'No live Peer provides the selected observability backend.', []], + ['request', 'Observability backend request failed (503).', ['status', 'query']], + ['mismatch', 'Observability backend changed during this query.', ['status', 'query']], + ]) { let queriedDatabase = false + const actions = [] const client = new ObservabilityClient({ baseUrl: 'https://db.example', tokenProvider: async () => 'token', - fetch: async (input) => { + fetch: async (input, init) => { const url = new URL(input) if (url.pathname === '/configs') return Response.json( @@ -148,23 +154,46 @@ void test('unknown selection, missing capability, external failure and backend d queriedDatabase = true return Response.json([]) } + assert.equal(url.href, 'https://peer.example/observability') + const body = JSON.parse(init.body) + actions.push(body.action) + if (body.action === 'status') + return Response.json({ + backend: 'loki', + configured: true, + recording: true, + queryable: true, + scope: 'selected_backend', + history: '', + dropped: null, + error: null, + }) + assert.equal(body.action, 'query') + assert.equal(body.expected_backend, 'loki') return failure === 'request' ? new Response('unavailable', { status: 503 }) : Response.json({ ...range, records: [], truncated: false, backend: 'postgresql' }) }, }) - await assert.rejects(client.query(range), ObservabilityUnavailableError) + await assert.rejects(client.query(range), { + name: 'ObservabilityUnavailableError', + message, + }) + assert.deepEqual(actions, expectedActions, failure) assert.equal(queriedDatabase, false) } }) void test('database ingestion preserves portable identity, kind and event metadata', async () => { let stored + let writes = 0 const client = new ObservabilityClient({ baseUrl: 'https://db.example', tokenProvider: async () => 'token', fetch: async (input, init) => { if (new URL(input).pathname === '/configs') return Response.json(null) + assert.equal(new URL(input).pathname, '/logs') + writes++ stored = JSON.parse(init.body) return new Response(null, { status: 201 }) }, @@ -174,20 +203,39 @@ void test('database ingestion preserves portable identity, kind and event metada assert.equal(stored.attributes['inkcre.record.kind'], 'event') assert.equal(stored.attributes['inkcre.event.name'], 'job.closed') assert.equal(stored.id, undefined) - await assert.rejects(client.emit({ ...record, body: 'x'.repeat(8193) })) - for (const [key, length] of [ - ['event_name', 128], - ['severity_text', 32], - ['trace_id', 128], - ['span_id', 128], + const rejectsField = (field, message) => (error) => { + assert.equal(error.name, 'ZodError') + assert.ok( + error.issues.some( + (issue) => issue.path.join('.') === field && (!message || issue.message === message) + ), + error.message + ) + return true + } + for (const [input, field] of [ + [{ ...record, body: 'x'.repeat(8193) }, 'body'], + [{ ...record, event_name: 'x'.repeat(129) }, 'event_name'], + [{ ...record, severity_text: 'x'.repeat(33) }, 'severity_text'], + [{ ...record, trace_id: 'x'.repeat(129) }, 'trace_id'], + [{ ...record, span_id: 'x'.repeat(129) }, 'span_id'], + [{ ...record, attributes: { nested: { value: 1 } } }, 'attributes.nested'], + [{ ...record, attributes: { large: 'x'.repeat(1025) } }, 'attributes.large'], + [{ ...record, attributes: { large: Array(33).fill(1) } }, 'attributes.large'], + ]) + await assert.rejects(client.emit(input), rejectsField(field)) + for (const [input, field, message] of [ + [{ ...range, until: range.since }, '', 'Observation time range must end after it starts.'], + [{ ...range, limit: 501 }, 'limit'], + [ + { since: '2026-01-01T00:00:00Z', until: '2026-11-01T00:00:00Z' }, + '', + 'Observation time range must not exceed 31 days.', + ], ]) - await assert.rejects(client.emit({ ...record, [key]: 'x'.repeat(length + 1) })) - await assert.rejects(client.emit({ ...record, attributes: { nested: { value: 1 } } })) - await assert.rejects(client.emit({ ...record, attributes: { large: 'x'.repeat(1025) } })) - await assert.rejects(client.emit({ ...record, attributes: { large: Array(33).fill(1) } })) + await assert.rejects(client.query(input), rejectsField(field, message)) + assert.equal(writes, 1, 'invalid input must fail before database I/O') assert.equal(stored.body, record.body) - await assert.rejects(client.query({ ...range, until: range.since })) - await assert.rejects(client.query({ ...range, limit: 501 })) }) void test('an initialized instance keeps its selected backend until a new instance is created', async () => { @@ -216,10 +264,9 @@ void test('an initialized instance keeps its selected backend until a new instan new ObservabilityClient(connection).query(range), ObservabilityUnavailableError ) - await assert.rejects(old.query({ since: '2026-01-01T00:00:00Z', until: '2026-11-01T00:00:00Z' })) }) -void test('a not-ready Peer is skipped before dispatch and writes carry atomic backend expectation', async () => { +void test('external writes skip unready Peers, carry backend expectation, and never retry rejected dispatch', async () => { const stale = { ...peer, id: '00000000-0000-4000-8000-000000000000', @@ -233,34 +280,59 @@ void test('a not-ready Peer is skipped before dispatch and writes carry atomic b }, ], } - let stored = false - const client = new ObservabilityClient({ - baseUrl: 'https://db.example', - tokenProvider: async () => 'token', - fetch: async (input, init) => { - const url = new URL(input) - if (url.pathname === '/configs') return Response.json(selector) - if (url.pathname === '/peers') return Response.json([stale, peer]) - const body = JSON.parse(init.body) - if (body.action === 'status') - return Response.json({ - backend: 'loki', - configured: url.hostname !== 'stale.example', - recording: url.hostname !== 'stale.example', - queryable: url.hostname !== 'stale.example', - scope: 'selected_backend', - history: '', - dropped: null, - error: null, - }) - assert.equal(url.hostname, 'peer.example') - assert.equal(body.expected_backend, 'loki') - stored = true - return Response.json({ accepted: 1, dropped: 0 }) - }, - }) - await client.emit(record) - assert.equal(stored, true) + const alternative = { + ...peer, + id: '00000000-0000-4000-8000-000000000002', + capabilities: [ + { + ...peer.capabilities[0], + inbound: { + ...peer.capabilities[0].inbound, + parameters: { method: 'POST', url: 'https://alternative.example/observability' }, + }, + }, + ], + } + for (const [outcome, message] of [ + ['accepted', null], + ['unavailable', 'Observability backend request failed (503).'], + ['dropped', 'The selected backend did not accept this observation.'], + ]) { + const writes = [] + const client = new ObservabilityClient({ + baseUrl: 'https://db.example', + tokenProvider: async () => 'token', + fetch: async (input, init) => { + const url = new URL(input) + if (url.pathname === '/configs') return Response.json(selector) + if (url.pathname === '/peers') return Response.json([stale, peer, alternative]) + const body = JSON.parse(init.body) + if (body.action === 'status') + return Response.json({ + backend: 'loki', + configured: url.hostname !== 'stale.example', + recording: url.hostname !== 'stale.example', + queryable: url.hostname !== 'stale.example', + scope: 'selected_backend', + history: '', + dropped: null, + error: null, + }) + assert.equal(url.hostname, 'peer.example') + assert.equal(body.action, 'ingest') + assert.equal(body.expected_backend, 'loki') + writes.push(url.href) + if (outcome === 'unavailable') return new Response(null, { status: 503 }) + return Response.json( + outcome === 'dropped' ? { accepted: 0, dropped: 1 } : { accepted: 1, dropped: 0 } + ) + }, + }) + if (message) + await assert.rejects(client.emit(record), { name: 'ObservabilityUnavailableError', message }) + else await client.emit(record) + assert.deepEqual(writes, ['https://peer.example/observability'], outcome) + } }) void test('Job lifecycle and terminal severities are recorded without optional OTEL or raw content', async () => { @@ -311,6 +383,7 @@ void test('Job lifecycle and terminal severities are recorded without optional O canHandle: () => true, handle: async (job, _parameters, signal) => { job.state = { count: 11 } + if (outcome === 'failed') throw new Error('private-handler-error-must-not-be-recorded') if (outcome === 'timed_out') await new Promise((resolve) => signal.addEventListener('abort', resolve, { once: true })) if (outcome === 'aborted') { @@ -336,6 +409,7 @@ void test('Job lifecycle and terminal severities are recorded without optional O ) assert.equal(JSON.stringify(records).includes('must-not-be-recorded'), false) for (const [terminalStatus, severity, expectedOutcome] of [ + ['failed', 17, 'error'], ['timed_out', 17, 'timeout'], ['aborted', 9, 'cancelled'], ]) { @@ -352,6 +426,7 @@ void test('Job lifecycle and terminal severities are recorded without optional O assert.equal(closed.severity_number, severity) assert.equal(execution.severity_number, severity) assert.equal(execution.attributes.outcome, expectedOutcome) + assert.equal(JSON.stringify(records).includes('must-not-be-recorded'), false) } assert.equal(configReads, 1, 'all operations share one captured backend selection') } finally { diff --git a/scripts/tests/saved-connections.test.mjs b/scripts/tests/saved-connections.test.mjs index 7f001e19..78e8cb7f 100644 --- a/scripts/tests/saved-connections.test.mjs +++ b/scripts/tests/saved-connections.test.mjs @@ -1,4 +1,7 @@ import assert from 'node:assert/strict' +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import os from 'node:os' +import path from 'node:path' import test from 'node:test' import { configStore, @@ -7,25 +10,38 @@ import { readConnectionSettings, } from '../../packages/core/dist/index.js' -void test('saved connections preserve identity, switch atomically, and survive restart/import', async () => { +void test('saved connection snapshots restore identity and preserve the selection on connection or write failure', async (t) => { + const directory = await mkdtemp(path.join(os.tmpdir(), 'inkcre-connections-')) + const file = path.join(directory, 'connections.json') + t.after(() => rm(directory, { recursive: true, force: true })) + const priorMeta = configStore.metaConfig + const priorSettings = configStore.connectionSettings + const priorPeer = configStore.peerConfig + const priorAdapter = configStore.metaAdapter + t.after(() => { + configStore.metaConfig = priorMeta + configStore.connectionSettings = priorSettings + configStore.peerConfig = priorPeer + configStore.metaAdapter = priorAdapter + }) const first = MetaConfigSchema.parse({ INKCRE_PGREST_URL: 'https://one.example', INKCRE_JWT_SECRET: 'fixture-one', }) - let persisted = structuredClone(first) + await writeFile(file, JSON.stringify(first)) + const readSnapshot = async () => JSON.parse(await readFile(file, 'utf8')) let rejectWrite = false const adapter = { - name: 'memory', - read: async () => persisted, + name: 'file-fixture', + read: readSnapshot, write: async (value) => { if (rejectWrite) throw new Error('disk full') - persisted = structuredClone(value) + await writeFile(file, JSON.stringify(value)) }, } - const connect = WebPeerRuntime.connect.bind(WebPeerRuntime) let stopped = 0 let rejectConnection = false - WebPeerRuntime.connect = async () => { + t.mock.method(WebPeerRuntime, 'connect', async () => { if (rejectConnection) throw new Error('unreachable') return { runtime: { @@ -35,55 +51,67 @@ void test('saved connections preserve identity, switch atomically, and survive r }, peer: { config: {} }, } + }) + await configStore.initializeMeta(adapter) + const firstId = configStore.connectionSettings.activeConnectionId + assert.equal(configStore.connectionSettings.connections.length, 1) + assert.equal(configStore.metaConfig.INKCRE_PEER_ID, first.INKCRE_PEER_ID) + await configStore.saveMeta() + const second = MetaConfigSchema.parse({ + INKCRE_PGREST_URL: 'https://two.example', + INKCRE_JWT_SECRET: 'fixture-two', + }) + const secondId = crypto.randomUUID() + await configStore.connectAndSave(second, {}, { id: secondId, name: '工作' }) + assert.equal((await readSnapshot()).connections.length, 2) + await configStore.connectAndSave(first, {}, { id: firstId, name: '个人' }) + // Rebuild runtime state from bytes written by the production store, without old selections. + configStore.metaConfig = MetaConfigSchema.parse({}) + configStore.connectionSettings = { connections: [], activeConnectionId: null } + await configStore.initializeMeta(adapter) + assert.equal(configStore.connectionSettings.activeConnectionId, firstId) + assert.equal(configStore.metaConfig.INKCRE_PEER_ID, first.INKCRE_PEER_ID) + assert.equal( + configStore.connectionSettings.connections[1].config.INKCRE_PEER_ID, + second.INKCRE_PEER_ID + ) + const snapshot = await readSnapshot() + const selectedMeta = JSON.parse(JSON.stringify(configStore.metaConfig)) + rejectConnection = true + await assert.rejects(configStore.connectAndSave(second, {}, { id: secondId, name: '工作' }), { + message: 'unreachable', + }) + assert.deepEqual(await readSnapshot(), snapshot) + assert.equal(configStore.connectionSettings.activeConnectionId, firstId) + assert.deepEqual(JSON.parse(JSON.stringify(configStore.metaConfig)), selectedMeta) + rejectConnection = false + rejectWrite = true + await assert.rejects(configStore.connectAndSave(second, {}, { id: secondId, name: '工作' }), { + message: 'disk full', + }) + assert.equal(stopped, 1) + assert.deepEqual(await readSnapshot(), snapshot) + assert.equal(configStore.connectionSettings.activeConnectionId, firstId) + assert.deepEqual(JSON.parse(JSON.stringify(configStore.metaConfig)), selectedMeta) + rejectWrite = false + const exported = JSON.parse(JSON.stringify(configStore.connectionSettings)) + await configStore.resetMeta() + await configStore.connectAndSave(first, {}, exported.connections[0], exported) + assert.deepEqual(JSON.parse(JSON.stringify(configStore.connectionSettings)), exported) + assert.deepEqual((await readSnapshot()).connections, exported.connections) + assert.equal( + readConnectionSettings(first, first).connections[0].config.INKCRE_PEER_ID, + first.INKCRE_PEER_ID + ) + const invalid = { + ...first, + connections: exported.connections, + activeConnectionId: crypto.randomUUID(), } - try { - await configStore.initializeMeta(adapter) - const firstId = configStore.connectionSettings.activeConnectionId - assert.equal(configStore.connectionSettings.connections.length, 1) - assert.equal(configStore.metaConfig.INKCRE_PEER_ID, first.INKCRE_PEER_ID) - await configStore.saveMeta() - const second = MetaConfigSchema.parse({ - INKCRE_PGREST_URL: 'https://two.example', - INKCRE_JWT_SECRET: 'fixture-two', - }) - const secondId = crypto.randomUUID() - await configStore.connectAndSave(second, {}, { id: secondId, name: '工作' }) - assert.equal(persisted.connections.length, 2) - await configStore.connectAndSave(first, {}, { id: firstId, name: '个人' }) - await configStore.initializeMeta(adapter) - assert.equal(configStore.connectionSettings.activeConnectionId, firstId) - assert.equal(configStore.metaConfig.INKCRE_PEER_ID, first.INKCRE_PEER_ID) - assert.equal( - configStore.connectionSettings.connections[1].config.INKCRE_PEER_ID, - second.INKCRE_PEER_ID - ) - const snapshot = JSON.stringify(persisted) - rejectConnection = true - await assert.rejects(configStore.connectAndSave(second, {}, { id: secondId, name: '工作' })) - assert.equal(JSON.stringify(persisted), snapshot) - assert.equal(configStore.connectionSettings.activeConnectionId, firstId) - rejectConnection = false - rejectWrite = true - await assert.rejects(configStore.connectAndSave(second, {}, { id: secondId, name: '工作' })) - assert.equal(stopped, 1) - assert.equal(configStore.connectionSettings.activeConnectionId, firstId) - rejectWrite = false - const exported = JSON.parse(JSON.stringify(configStore.connectionSettings)) - await configStore.resetMeta() - await configStore.connectAndSave(first, {}, exported.connections[0], exported) - assert.deepEqual(JSON.parse(JSON.stringify(configStore.connectionSettings)), exported) - assert.equal( - readConnectionSettings(first, first).connections[0].config.INKCRE_PEER_ID, - first.INKCRE_PEER_ID - ) - persisted = { - ...first, - connections: exported.connections, - activeConnectionId: crypto.randomUUID(), - } - await assert.rejects(configStore.initializeMeta(adapter)) - assert.equal(persisted.connections.length, 2) - } finally { - WebPeerRuntime.connect = connect - } + await writeFile(file, JSON.stringify(invalid)) + await assert.rejects(configStore.initializeMeta(adapter), { + name: 'ZodError', + message: /Invalid connection selection/, + }) + assert.deepEqual(await readSnapshot(), invalid) }) diff --git a/scripts/tests/ui-source.test.mjs b/scripts/tests/ui-source.test.mjs index b60ba5b3..b4a5adb4 100644 --- a/scripts/tests/ui-source.test.mjs +++ b/scripts/tests/ui-source.test.mjs @@ -1,14 +1,69 @@ import assert from 'node:assert/strict' import { spawnSync } from 'node:child_process' -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises' import { createRequire } from 'node:module' import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { dirname, join } from 'node:path' import test from 'node:test' -import { createUiSourceTsconfig } from '../ui-source.mjs' +import { + createUiSourceAliases, + createUiSourceTsconfig, + resolveUiSourceForVite, + resolveUiSourcePackage, +} from '../ui-source.mjs' const require = createRequire(import.meta.url) +void test('UI source overlays resolve public entries for development and reject release builds', async (context) => { + const root = await realpath(await mkdtemp(join(tmpdir(), 'inkcre-ui-source-'))) + context.after(() => rm(root, { recursive: true, force: true })) + // These are the producer's public source paths, independent of the resolver's alias table. + const entries = { + '@inkcre/ui-web': 'src/index.ts', + '@inkcre/ui-web/styles': 'styles/index.scss', + '@inkcre/ui-web/styles/functions': 'styles/_functions.scss', + '@inkcre/ui-web/styles/mixins': 'styles/_mixins.scss', + '@inkcre/ui-web/tokens/ref': 'styles/tokens/_ref.scss', + '@inkcre/ui-web/tokens/sys': 'styles/tokens/_sys.scss', + '@inkcre/ui-web/tokens/comp': 'styles/tokens/_comp.scss', + '@inkcre/ui-web/utils': 'src/utils/index.ts', + '@inkcre/ui-web/locales': 'src/locales/index.ts', + '@inkcre/ui-web/uno': 'styles/uno/preset-ink.ts', + } + for (const path of [...Object.values(entries), 'src/components.d.ts']) { + await mkdir(dirname(join(root, path)), { recursive: true }) + await writeFile(join(root, path), '') + } + await writeFile( + join(root, 'package.json'), + JSON.stringify({ name: '@inkcre/ui-web', version: '2.3.0' }) + ) + const environment = { INKCRE_UI_SOURCE_ROOT: root } + const source = await resolveUiSourceForVite('serve', environment) + assert.equal(source.root, root) + const aliases = createUiSourceAliases(source) + for (const [specifier, path] of Object.entries(entries)) { + assert.deepEqual( + aliases.filter((alias) => alias.find.test(specifier)).map((alias) => alias.replacement), + [join(root, path)] + ) + assert.equal( + aliases.some((alias) => alias.find.test(`${specifier}/private`)), + false + ) + } + assert.equal(await resolveUiSourceForVite('build', {}), null) + await assert.rejects( + resolveUiSourceForVite('build', environment), + /source overlay is development-only/ + ) + await rm(join(root, 'styles/_mixins.scss')) + await assert.rejects( + resolveUiSourcePackage(root), + /UI source package is missing styles\/_mixins.scss/ + ) +}) + void test('UI source type checking accepts an external checkout and rejects its type errors', async (context) => { const root = await mkdtemp(join(tmpdir(), 'inkcre-ui-types-')) context.after(() => rm(root, { recursive: true, force: true })) From 9d11afd1af759f283bf03897f03d93b357fa8579 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 10:24:42 +0800 Subject: [PATCH 03/36] =?UTF-8?q?ref(ci):=20=E7=BB=9F=E4=B8=80=E6=9C=AC?= =?UTF-8?q?=E5=9C=B0=E4=B8=8E=20CI=20=E5=A5=91=E7=BA=A6=E5=85=A5=E5=8F=A3?= =?UTF-8?q?=E5=B9=B6=E4=B8=BA=E6=B5=8F=E8=A7=88=E5=99=A8=E9=AA=8C=E6=94=B6?= =?UTF-8?q?=E5=88=9B=E5=BB=BA=E7=8B=AC=E5=8D=A0=E6=95=B0=E6=8D=AE=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ci.yml | 44 +++---- CONTRIBUTING.md | 7 +- docs/40-deployment/development-runtime.md | 21 ++- extensions/mail/tests/playwright.config.ts | 1 + package.json | 11 +- pnpm-lock.yaml | 6 +- scripts/e2e-database.mjs | 67 ++++++++++ scripts/test-e2e.mjs | 146 ++++++--------------- scripts/test-webext-e2e.mjs | 30 +++-- scripts/tests/webext-artifacts.mjs | 70 ++++++++++ scripts/tests/webext-release.test.mjs | 75 +---------- 11 files changed, 252 insertions(+), 226 deletions(-) create mode 100644 scripts/e2e-database.mjs create mode 100644 scripts/tests/webext-artifacts.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b4e14f8d..7ec5b669 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -129,22 +129,8 @@ jobs: - name: 构建并校验相互兼容的 Host 与 MF 产物 run: pnpm build - - name: Verify independent SDK and Job observations - run: pnpm check:sdk && pnpm check:web - - - name: 验证 B 站收藏采集规则 - run: pnpm --filter @inkcre/ext-bilibili test - - - name: Verify independent MF publication - run: >- - node --test scripts/test-extension-publication.mjs scripts/test-core-sdk-publication.mjs - scripts/tests/independent-extension-release.test.mjs - scripts/tests/release-checkout.test.mjs - scripts/tests/core-sdk-compatibility.test.mjs - scripts/tests/pages-preview.test.mjs - scripts/tests/browser-automation-transport.test.mjs - scripts/tests/job-cancellation.test.mjs - scripts/tests/source-anchor.test.mjs + - name: 验证 SDK、运行时、采集与发布的独立契约 + run: pnpm test:contracts peer-database: # Existing branch protection binds this exact check name. @@ -180,6 +166,9 @@ jobs: username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} + - name: 验证邮件阅读与不可信内容隔离 + run: pnpm test:mail + - name: Run the selected real core service and isolated browser/database chain run: pnpm test:e2e:web env: @@ -193,12 +182,14 @@ jobs: path: | test-results/playwright test-results/database + test-results/mail-newsletter if-no-files-found: ignore retention-days: 7 browser-extension: # Existing branch protection binds this exact check name. name: client-webext E2E + needs: core-release runs-on: ubuntu-latest steps: - name: Checkout @@ -221,20 +212,25 @@ jobs: - name: Install the exact browser engine run: pnpm exec playwright install --with-deps chromium - - name: Load the exact Chromium extension build - run: pnpm test:e2e:webext - - - name: Build the Firefox extension - run: pnpm --filter @inkcre/webext build:firefox + - name: Authenticate to GHCR + uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} - - name: Verify WebExt delivery rules - run: node --test scripts/tests/webext-release.test.mjs + - name: 验证浏览器扩展产物与独占数据库采集、重启恢复 + run: pnpm test:e2e:webext + env: + INKCRE_CORE_IMAGE: ${{ needs.core-release.outputs.image }} - name: Upload browser evidence on failure if: failure() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: browser-extension-failure-evidence - path: test-results/playwright + path: | + test-results/playwright + test-results/database if-no-files-found: ignore retention-days: 7 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1ddcfcb0..938e8ce6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -58,10 +58,9 @@ and the distinction between applications, SDK packages, and native Extension rel ## Verification and pull requests -Run `pnpm check` before opening or updating a pull request. Also run the behavior-level command that -matches the change, normally `pnpm test:e2e:web`, `pnpm test:e2e:webext`, or a narrower documented -acceptance command. Record what actually ran and any unmet environment condition in the pull-request -body; a package build is not evidence of browser behavior. +打开或更新 PR 前运行 `pnpm check`,并执行与变更行为对应的验收入口。`pnpm test:e2e` 包含 Web、WebExt 的独占数据库/浏览器路径和 Mail 阅读验收;局部复验使用 `pnpm test:e2e:web`、`pnpm test:e2e:webext`、`pnpm test:mail` 或文档中说明的专项入口。 + +Core 构建完成后,`pnpm test:contracts` 可集中验证 SDK、运行时、采集和发布合同;本地默认检查与 CI 使用同一入口。在 PR 正文记录实际执行结果、跳过项和未满足的环境条件。产物构建通过不能代替浏览器行为证明。 External fork workflows require maintainer approval and receive no preview or production credentials. A maintainer may perform a trusted Pages preview after the ordinary checks pass. Frozen dependency diff --git a/docs/40-deployment/development-runtime.md b/docs/40-deployment/development-runtime.md index 74618660..33f08ac1 100644 --- a/docs/40-deployment/development-runtime.md +++ b/docs/40-deployment/development-runtime.md @@ -18,6 +18,23 @@ 规则例外必须说明真实合同。Twitter 可见区间使用 Unicode 码点,不能为了消除告警改成字素索引。顶层 `node:test` 注册显式丢弃返回 Promise,失败仍由测试运行器处理;子测试与业务异步操作仍须等待或处理失败。 +## 测试与验收入口 + +`pnpm check` 依次执行格式、lint、类型、全部工作区构建和 `pnpm test:contracts`。CI 的 Workspace contract 在准备待发布的兼容版本后调用同一个 `test:contracts`,不另维护一份测试文件清单。该入口运行 `scripts/tests/*.test.mjs`、三个发布/准入测试入口,以及 Bilibili、CalDAV 和本地文件的 TypeScript 契约。`test:contracts` 需要本次源码对应的 Core `dist`;独立执行前先构建 Core。它包含 tarball 消费、声明编译、外部格式、故障注入和受控 HTTP 合同,不证明真实数据库或浏览器行为。 + +| 入口 | 证明与执行边界 | +| --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `pnpm test:e2e:web` | 创建并清理独占数据库,构建 Web、GitHub/Mail MF,运行浏览器数据库、已连接页面无障碍、Mail Host 读取与恢复。保留真实写入、重新读取及数据库 reset 后的基线核对。 | +| `pnpm test:e2e:webext` | 构建 Chromium/Firefox 产物并验证身份与图标合同,运行真实浏览器自动化桥,再创建独占数据库执行采集、连接、部分进度和浏览器重启恢复;默认入口必须提供数据库,不能把缺少环境导致的跳过计为通过。Firefox 此处是构建/产物合同,不是 Firefox 运行时 E2E。 | +| `pnpm test:mail` | 真实 Mail renderer/Resolver 的浏览器阅读、键盘、窄屏、内容隔离和阅读位置恢复;图数据来自合成 I/O fixture,不代表 Python 邮箱采集或共享数据库持久化。 | +| `pnpm test:e2e` / `pnpm ci` | 前者执行以上三个浏览器入口;后者先执行 `pnpm check`。 | + +两个数据库 E2E 共享实例准备、就绪、失败证据和清理 owner,但各自持有独立实例。CI 两个浏览器 job 使用同次解析的不可变 Core 镜像。本机 `local` 与 `ssh` provider 沿用运行时配置;选择 `external` 时,E2E 转用 `INKCRE_E2E_DATABASE_PROVIDER`(缺省 `ssh`),拒绝继续附着共享外部数据库。失败输出在 `test-results/database//`,浏览器输出在 `test-results/playwright/`;清理失败保留 descriptor 并以非零退出,不能当作通过。 + +聚焦复验可传 Playwright 参数,例如 `pnpm test:e2e:web --project accessibility` 或 `pnpm test:e2e:webext --grep "browser restart"`。显式 `--project` 替换 Web 默认项目集合;App 的 `test:a11y` 转发到同一个隔离入口,不启动日常 SVC/Portless 环境。根配置在 CI 拒绝 `test.only`。直接调用 Playwright 的专项/子集结果不代替上述完整入口。 + +测试主要归属于产生承诺的 owner:SDK 打包与请求字节、Job 执行资格、采集检查点、格式兼容、浏览器存储与跨进程恢复、产物分发各保留独立风险。故障注入需要到达目标检查并核对具体诊断;读取恢复必须消费生产代码写下的状态。新增用例应说明已有证明漏掉的可信回归;删除或合并前先确认剩余 keeper。静态配置、慢速、负向或测试接缝本身不是删除理由。 + ## Capability Contract The committed [`svc.json`](../../svc.json) declares four worktree-scoped capabilities: `database`, @@ -93,7 +110,7 @@ Vite 变量、Cloudflare bindings 或浏览器产物。业务链接、第三方 数据库签名凭据及浏览器扩展 API 默认值。它分析 JavaScript、TypeScript 和 Vue script 中的语法, 跟踪同文件字符串常量与 schema 默认值。同一个自定义域名用作业务链接时通过,写入部署配置时拒绝; URL 路径和托管商域名都不是部署身份。跨模块导入的常量及任意跨模块数据流仍由代码审查负责。 -`pnpm check:runtime` 先运行判定规则的行为回归,再检查所有浏览器消费者和原生扩展。 +`pnpm check:runtime` 检查所有浏览器消费者和原生扩展;判定规则的行为回归由 `pnpm test:contracts` 统一执行。 产物检查和正式 Web release 检查也先执行源码检查,再验证静态产物结构及已知凭据、旧配置通道的泄漏特征, 不根据托管商域名封锁业务链接。 @@ -170,7 +187,7 @@ pnpm contract:sync pnpm test:e2e ``` -Twitter 与本地 Core 镜像的候选验收保存在 `scripts/tests/`,不加入默认 `check`、`test:e2e` 或 CI 门禁。可独立执行: +本地 Core 镜像的准入契约已纳入 `test:contracts`,也可用 `verify:core-release` 单独复验。Twitter 跨部署验收需要下文指定的独占环境,按需执行。 ```bash pnpm verify:core-release diff --git a/extensions/mail/tests/playwright.config.ts b/extensions/mail/tests/playwright.config.ts index 2ee9fc11..b84a7030 100644 --- a/extensions/mail/tests/playwright.config.ts +++ b/extensions/mail/tests/playwright.config.ts @@ -1,6 +1,7 @@ import { defineConfig } from '@playwright/test' export default defineConfig({ + forbidOnly: !!process.env.CI, testDir: '.', testMatch: '*.spec.ts', outputDir: new URL('../../../test-results/mail-newsletter', import.meta.url).pathname, diff --git a/package.json b/package.json index abc7adc2..386a5f22 100644 --- a/package.json +++ b/package.json @@ -26,24 +26,27 @@ "lint:type-aware": "pnpm lint", "type-check": "pnpm check:workspace && pnpm check:runtime && pnpm check:database && pnpm check:locale && pnpm -r run type-check", "type-check:ui": "node scripts/type-check-ui.mjs", - "check:runtime": "node --test scripts/tests/browser-runtime-contract.test.mjs scripts/tests/database-probe.test.mjs scripts/tests/ui-source.test.mjs && node scripts/check-local-runtime-contract.mjs", + "check:runtime": "node scripts/check-local-runtime-contract.mjs", "check:database": "node scripts/check-database-contract.mjs", "check:release:web": "node scripts/verify-web-release.mjs", "check:locale": "node scripts/check-locale-keys.mjs", "check:workspace": "node scripts/check-workspace-contract.mjs", "check:package": "node scripts/check-package-contract.mjs", - "test:e2e": "pnpm test:e2e:web && pnpm test:e2e:webext", + "test:e2e": "pnpm test:e2e:web && pnpm test:e2e:webext && pnpm test:mail", "test:e2e:web": "node scripts/test-e2e.mjs", "test:e2e:webext": "node scripts/test-webext-e2e.mjs", "verify:twitter": "playwright test --config scripts/tests/twitter-acceptance.config.ts", "verify:core-release": "node --test scripts/tests/core-release.test.mjs", "build": "pnpm check:workspace && pnpm -r run build && pnpm check:package", - "check": "pnpm format:check && pnpm lint && pnpm type-check && pnpm build && pnpm check:sdk && pnpm check:web", + "check": "pnpm format:check && pnpm lint && pnpm type-check && pnpm build && pnpm test:contracts", "ci": "pnpm check && pnpm test:e2e", "check:sdk": "pnpm --filter @inkcre/core build && node --test scripts/tests/core-independent.test.mjs scripts/tests/observability.test.mjs", - "check:web": "node --test scripts/tests/job-observation.test.mjs" + "check:web": "node --test scripts/tests/job-observation.test.mjs", + "test:contracts": "node --experimental-strip-types --test scripts/test-core-release.mjs scripts/test-core-sdk-publication.mjs scripts/test-extension-publication.mjs scripts/tests/*.test.mjs scripts/tests/local-files-contract.test.ts extensions/bilibili/tests/*.test.ts extensions/caldav/scripts/tests/*.test.ts", + "test:mail": "pnpm --filter @inkcre/core build && playwright test --config extensions/mail/tests/playwright.config.ts" }, "devDependencies": { + "@axe-core/playwright": "^4.14.0", "@changesets/cli": "3.0.0", "@playwright/test": "1.61.1", "@tanstack/intent": "0.3.6", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d3d463a8..91fbe2a7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -47,6 +47,9 @@ importers: .: devDependencies: + '@axe-core/playwright': + specifier: ^4.14.0 + version: 4.14.0(playwright-core@1.61.1) '@changesets/cli': specifier: 3.0.0 version: 3.0.0 @@ -156,9 +159,6 @@ importers: specifier: ^1.4.0 version: 1.4.0(dotenv@17.4.2)(json5@2.2.3)(yaml@2.9.0)(zod@4.6.7) devDependencies: - '@axe-core/playwright': - specifier: ^4.14.0 - version: 4.14.0(playwright-core@1.61.1) '@iconify-json/mdi': specifier: ^1.2.3 version: 1.2.3 diff --git a/scripts/e2e-database.mjs b/scripts/e2e-database.mjs new file mode 100644 index 00000000..92686532 --- /dev/null +++ b/scripts/e2e-database.mjs @@ -0,0 +1,67 @@ +import { createHash } from 'node:crypto' +import { mkdir, writeFile } from 'node:fs/promises' +import { + compose, + ensureDatabaseRuntime, + exists, + repoRoot, + runtimeCredentials, + runtimeDirectory, + stopDatabaseRuntime, + waitForRuntime, +} from './database-runtime-lib.mjs' +import { resolveDatabaseProviderConfig } from './database-provider.mjs' + +/** Both browser lanes own a fresh database; neither may attach to shared development data. */ +export async function runIsolatedDatabaseTest(lane, run) { + if (resolveDatabaseProviderConfig().kind === 'external') { + process.env.INKCRE_DATABASE_PROVIDER = process.env.INKCRE_E2E_DATABASE_PROVIDER ?? 'ssh' + } + if (resolveDatabaseProviderConfig().kind === 'external') { + throw new Error('Browser E2E requires an owned local or SSH database, not an external runtime') + } + + const identity = createHash('sha256') + .update(`${repoRoot}/${process.pid}/${Date.now()}`) + .digest('hex') + .slice(0, 16) + const instance = `e2e-${lane}-${identity}` + let credentials + const redact = (value) => + Object.entries(credentials ?? {}).reduce( + (result, [name, secret]) => + name === 'format' ? result : result.replaceAll(secret, `[REDACTED:${name}]`), + value + ) + + try { + const state = await ensureDatabaseRuntime(instance) + credentials = await runtimeCredentials(instance) + await waitForRuntime(state) + await run(state, credentials) + } catch (error) { + const directory = `${repoRoot}/test-results/database/${lane}` + await mkdir(directory, { recursive: true }) + const failure = error instanceof Error ? (error.stack ?? error.message) : String(error) + await writeFile(`${directory}/orchestration-error.txt`, `${redact(failure)}\n`) + try { + if (await exists(`${runtimeDirectory(instance)}/runtime.json`)) { + const logs = compose(instance, ['logs', '--no-color'], { timeout: 30_000 }) + await writeFile(`${directory}/compose.log`, redact(logs)) + } + } catch (logError) { + await writeFile(`${directory}/compose-log-error.txt`, `${redact(String(logError))}\n`) + } + console.error(redact(failure)) + process.exitCode = 1 + } finally { + try { + if (await exists(`${runtimeDirectory(instance)}/runtime.json`)) { + await stopDatabaseRuntime(instance) + } + } catch (cleanupError) { + console.error(`E2E cleanup failed for ${instance}: ${redact(String(cleanupError))}`) + process.exitCode = 1 + } + } +} diff --git a/scripts/test-e2e.mjs b/scripts/test-e2e.mjs index 27d4d2a8..a685a6d4 100644 --- a/scripts/test-e2e.mjs +++ b/scripts/test-e2e.mjs @@ -1,19 +1,7 @@ import { execFileSync, spawn } from 'node:child_process' -import { createHash } from 'node:crypto' -import { mkdir, writeFile } from 'node:fs/promises' -import { - availablePort, - compose, - ensureDatabaseRuntime, - exists, - repoRoot, - runtimeCredentials, - runtimeDirectory, - stopDatabaseRuntime, - waitForRuntime, -} from './database-runtime-lib.mjs' -import { resolveDatabaseProviderConfig } from './database-provider.mjs' +import { availablePort, compose, repoRoot } from './database-runtime-lib.mjs' +import { runIsolatedDatabaseTest } from './e2e-database.mjs' function run(command, args, options = {}) { return execFileSync(command, args, { @@ -51,64 +39,42 @@ async function waitForWeb(url) { throw new Error(`built web artifact did not become ready at ${url}`) } -const identityHash = createHash('sha256') - .update(`${repoRoot}/${process.pid}/${Date.now()}`) - .digest('hex') - .slice(0, 16) -const instance = `e2e-${identityHash}` -let preview -let credentials - -if (resolveDatabaseProviderConfig().kind === 'external') { - process.env.INKCRE_DATABASE_PROVIDER = process.env.INKCRE_E2E_DATABASE_PROVIDER ?? 'ssh' -} - -function redact(value) { - if (!credentials) return value - return Object.entries(credentials).reduce( - (redacted, [name, secret]) => - name === 'format' ? redacted : redacted.replaceAll(secret, `[REDACTED:${name}]`), - value - ) -} - -try { - const state = await ensureDatabaseRuntime(instance) - await waitForRuntime(state) - const ownsRuntime = state.provider.kind !== 'external' - const baseline = ownsRuntime ? developmentFingerprint(instance) : null - - run('pnpm', ['--filter', '@inkcre/web', 'build-only']) - run('pnpm', ['--filter', '@inkcre/ext-github...', 'build']) - const webPort = await availablePort() - const webUrl = `http://127.0.0.1:${webPort}/` - preview = spawn( - 'pnpm', - [ - '--filter', - '@inkcre/web', - 'exec', - 'vite', - 'preview', - '--host', - '127.0.0.1', - '--port', - String(webPort), - '--strictPort', - ], - { - cwd: repoRoot, - env: process.env, - stdio: 'inherit', - } - ) - await waitForWeb(webUrl) +await runIsolatedDatabaseTest('web', async (state, credentials) => { + const instance = state.identity + const baseline = developmentFingerprint(instance) + let preview + try { + run('pnpm', ['--filter', '@inkcre/web', 'build-only']) + run('pnpm', ['--filter', '@inkcre/ext-github...', '--filter', '@inkcre/ext-mail...', 'build']) + const webPort = await availablePort() + const webUrl = `http://127.0.0.1:${webPort}/` + preview = spawn( + 'pnpm', + [ + '--filter', + '@inkcre/web', + 'exec', + 'vite', + 'preview', + '--host', + '127.0.0.1', + '--port', + String(webPort), + '--strictPort', + ], + { + cwd: repoRoot, + env: process.env, + stdio: 'inherit', + } + ) + await waitForWeb(webUrl) - credentials = await runtimeCredentials(instance) - run( - 'pnpm', - ['exec', 'playwright', 'test', '--project', 'web-database', ...process.argv.slice(2)], - { + const args = process.argv.slice(2) + const projects = args.some((arg) => arg === '--project' || arg.startsWith('--project=')) + ? [] + : ['--project', 'web-database', '--project', 'accessibility', '--project', 'mail-info-base'] + run('pnpm', ['exec', 'playwright', 'test', ...projects, ...args], { // Playwright owns its suite deadline so reporters and teardown can finish. timeout: 0, env: { @@ -118,10 +84,8 @@ try { INKCRE_E2E_WEB_URL: webUrl, INKCRE_E2E_JWT_SECRET: credentials.JWT_SECRET, }, - } - ) + }) - if (ownsRuntime) { compose(instance, [ 'run', '--rm', @@ -138,35 +102,7 @@ try { if (resetBaseline !== baseline) { throw new Error('reset-dev did not restore the deterministic E2E baseline') } + } finally { + preview?.kill('SIGTERM') } -} catch (error) { - const evidenceDirectory = `${repoRoot}/test-results/database` - await mkdir(evidenceDirectory, { recursive: true }) - - const failure = error instanceof Error ? (error.stack ?? error.message) : String(error) - await writeFile(`${evidenceDirectory}/orchestration-error.txt`, `${redact(failure)}\n`) - - try { - if (await exists(`${runtimeDirectory(instance)}/runtime.json`)) { - const logs = compose(instance, ['logs', '--no-color'], { timeout: 30_000 }) - await writeFile(`${evidenceDirectory}/compose.log`, redact(logs)) - } - } catch (logError) { - const message = logError instanceof Error ? logError.message : String(logError) - await writeFile(`${evidenceDirectory}/compose-log-error.txt`, `${redact(message)}\n`) - } - - console.error(redact(failure)) - process.exitCode = 1 -} finally { - preview?.kill('SIGTERM') - try { - if (await exists(`${runtimeDirectory(instance)}/runtime.json`)) { - await stopDatabaseRuntime(instance) - } - } catch (cleanupError) { - // Keep the descriptor when cleanup fails, and preserve the original test failure above. - console.error(`E2E cleanup failed for ${instance}: ${redact(String(cleanupError))}`) - process.exitCode = 1 - } -} +}) diff --git a/scripts/test-webext-e2e.mjs b/scripts/test-webext-e2e.mjs index de78ba4a..dce0b552 100644 --- a/scripts/test-webext-e2e.mjs +++ b/scripts/test-webext-e2e.mjs @@ -1,23 +1,33 @@ import { execFileSync } from 'node:child_process' import { repoRoot } from './database-runtime-lib.mjs' +import { runIsolatedDatabaseTest } from './e2e-database.mjs' -function run(command, args) { +function run(command, args, options = {}) { execFileSync(command, args, { cwd: repoRoot, - env: process.env, + env: options.env ?? process.env, stdio: 'inherit', - timeout: 300_000, + timeout: options.timeout ?? 300_000, }) } run('pnpm', ['--filter', '@inkcre/core', 'build']) run('pnpm', ['--filter', '@inkcre/webext', 'build']) -run('node', [ - '--test', - 'scripts/tests/browser-automation-transport.test.mjs', - 'scripts/tests/job-cancellation.test.mjs', - 'scripts/tests/source-anchor.test.mjs', -]) +run('pnpm', ['--filter', '@inkcre/webext', 'build:firefox']) +run('node', ['--test', 'scripts/tests/webext-artifacts.mjs']) run('node', ['scripts/verify-browser-automation.mjs']) -run('pnpm', ['exec', 'playwright', 'test', '--project', 'browser-extension']) +await runIsolatedDatabaseTest('webext', async (state, credentials) => { + run( + 'pnpm', + ['exec', 'playwright', 'test', '--project', 'browser-extension', ...process.argv.slice(2)], + { + timeout: 0, + env: { + ...process.env, + INKCRE_E2E_WEBEXT_PGREST: state.urls.postgrest, + INKCRE_E2E_WEBEXT_JWT_SECRET: credentials.JWT_SECRET, + }, + } + ) +}) diff --git a/scripts/tests/webext-artifacts.mjs b/scripts/tests/webext-artifacts.mjs new file mode 100644 index 00000000..b255c78c --- /dev/null +++ b/scripts/tests/webext-artifacts.mjs @@ -0,0 +1,70 @@ +import assert from 'node:assert/strict' +import { readFile } from 'node:fs/promises' +import { createRequire } from 'node:module' +import { test } from 'node:test' +import { checkManifest, extensionId } from '../webext-release.mjs' + +const require = createRequire(new URL('../../apps/webext/package.json', import.meta.url)) + +void test('browser artifacts preserve identity, numeric version and readable toolbar variants', async () => { + const root = new URL('../../apps/webext/', import.meta.url) + const metadata = JSON.parse(await readFile(new URL('package.json', root), 'utf8')) + const { key } = JSON.parse(await readFile(new URL('chromium-key.json', root), 'utf8')) + assert.match(extensionId(key), /^[a-p]{32}$/) + for (const browser of ['chrome', 'firefox']) { + const manifest = JSON.parse( + await readFile(new URL(`.output/${browser}-mv3/manifest.json`, root), 'utf8') + ) + checkManifest(manifest, metadata.version, browser, key) + assert.throws(() => + checkManifest({ ...manifest, version: '0.0.1' }, metadata.version, browser, key) + ) + if (browser === 'chrome') + assert.throws(() => + checkManifest({ ...manifest, key: undefined }, metadata.version, browser, key) + ) + assert.deepEqual( + manifest.icons, + Object.fromEntries([16, 32, 48, 96, 128].map((size) => [size, `icon/${size}.png`])) + ) + for (const size of [16, 32, 48, 96, 128]) { + const image = await readFile(new URL(`.output/${browser}-mv3/icon/${size}.png`, root)) + const asset = + size === 96 + ? 'png/2x/original-white/inkcre-original-white-48px@2x.png' + : `png/original-white/inkcre-original-white-${size}.png` + assert.equal(image.readUInt32BE(16), size) + assert.equal(image.readUInt32BE(20), size) + assert.deepEqual(image, await readFile(require.resolve(`@inkcre/ui-web/logo/${asset}`))) + } + for (const [size, density, suffix] of [ + [16, '', '16'], + [32, '2x/', '16px@2x'], + [48, '3x/', '16px@3x'], + ]) { + assert.equal(manifest.action.default_icon[size], `toolbar/canvas-${size}.png`) + for (const [prefix, variant] of [ + ['', 'original-transparent'], + ['reverse-', 'reverse-transparent'], + ['canvas-', 'original-white'], + ]) { + const image = await readFile( + new URL(`.output/${browser}-mv3/toolbar/${prefix}${size}.png`, root) + ) + const asset = `png/${density}${variant}/inkcre-${variant}-${suffix}.png` + assert.equal(image.readUInt32BE(16), size) + assert.equal(image.readUInt32BE(20), size) + assert.deepEqual(image, await readFile(require.resolve(`@inkcre/ui-web/logo/${asset}`))) + } + } + if (browser === 'firefox') + assert.deepEqual( + manifest.action.theme_icons, + [16, 32, 48].map((size) => ({ + size, + light: `toolbar/reverse-${size}.png`, + dark: `toolbar/${size}.png`, + })) + ) + } +}) diff --git a/scripts/tests/webext-release.test.mjs b/scripts/tests/webext-release.test.mjs index d607df24..0acc6101 100644 --- a/scripts/tests/webext-release.test.mjs +++ b/scripts/tests/webext-release.test.mjs @@ -1,16 +1,6 @@ import assert from 'node:assert/strict' -import { readFile } from 'node:fs/promises' -import { createRequire } from 'node:module' import { test } from 'node:test' -import { - assertDraft, - checkManifest, - createDraftRelease, - extensionId, - preparedVersion, -} from '../webext-release.mjs' - -const require = createRequire(new URL('../../apps/webext/package.json', import.meta.url)) +import { assertDraft, createDraftRelease, preparedVersion } from '../webext-release.mjs' void test('only a prepared numeric WebExt version is selected, independently of other units', () => { assert.equal(preparedVersion('0.2.0', '# WebExt\n\n## 0.2.0\nNews', false), true) @@ -48,66 +38,3 @@ void test('a new draft uses its creation response before release inventory catch draft ) }) - -void test('browser artifacts preserve identity, numeric version and readable toolbar variants', async () => { - const root = new URL('../../apps/webext/', import.meta.url) - const metadata = JSON.parse(await readFile(new URL('package.json', root), 'utf8')) - const { key } = JSON.parse(await readFile(new URL('chromium-key.json', root), 'utf8')) - assert.match(extensionId(key), /^[a-p]{32}$/) - for (const browser of ['chrome', 'firefox']) { - const manifest = JSON.parse( - await readFile(new URL(`.output/${browser}-mv3/manifest.json`, root), 'utf8') - ) - checkManifest(manifest, metadata.version, browser, key) - assert.throws(() => - checkManifest({ ...manifest, version: '0.0.1' }, metadata.version, browser, key) - ) - if (browser === 'chrome') - assert.throws(() => - checkManifest({ ...manifest, key: undefined }, metadata.version, browser, key) - ) - assert.deepEqual( - manifest.icons, - Object.fromEntries([16, 32, 48, 96, 128].map((size) => [size, `icon/${size}.png`])) - ) - for (const size of [16, 32, 48, 96, 128]) { - const image = await readFile(new URL(`.output/${browser}-mv3/icon/${size}.png`, root)) - const asset = - size === 96 - ? 'png/2x/original-white/inkcre-original-white-48px@2x.png' - : `png/original-white/inkcre-original-white-${size}.png` - assert.equal(image.readUInt32BE(16), size) - assert.equal(image.readUInt32BE(20), size) - assert.deepEqual(image, await readFile(require.resolve(`@inkcre/ui-web/logo/${asset}`))) - } - for (const [size, density, suffix] of [ - [16, '', '16'], - [32, '2x/', '16px@2x'], - [48, '3x/', '16px@3x'], - ]) { - assert.equal(manifest.action.default_icon[size], `toolbar/canvas-${size}.png`) - for (const [prefix, variant] of [ - ['', 'original-transparent'], - ['reverse-', 'reverse-transparent'], - ['canvas-', 'original-white'], - ]) { - const image = await readFile( - new URL(`.output/${browser}-mv3/toolbar/${prefix}${size}.png`, root) - ) - const asset = `png/${density}${variant}/inkcre-${variant}-${suffix}.png` - assert.equal(image.readUInt32BE(16), size) - assert.equal(image.readUInt32BE(20), size) - assert.deepEqual(image, await readFile(require.resolve(`@inkcre/ui-web/logo/${asset}`))) - } - } - if (browser === 'firefox') - assert.deepEqual( - manifest.action.theme_icons, - [16, 32, 48].map((size) => ({ - size, - light: `toolbar/reverse-${size}.png`, - dark: `toolbar/${size}.png`, - })) - ) - } -}) From 0a70e73bcdde2d0e299719c9601d6c2159ea8665 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 10:26:07 +0800 Subject: [PATCH 04/36] =?UTF-8?q?fix(web):=20=E5=9C=A8=E5=B7=B2=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E9=A1=B5=E9=9D=A2=E9=AA=8C=E8=AF=81=E5=8F=AF=E8=AE=BF?= =?UTF-8?q?=E9=97=AE=E6=80=A7=E5=B9=B6=E4=BF=AE=E5=A4=8D=E6=A0=87=E9=A2=98?= =?UTF-8?q?=E4=B8=8E=E5=9C=B0=E6=A0=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .changeset/clear-web-heading-hierarchy.md | 5 + apps/web/package.json | 5 +- apps/web/playwright.config.ts | 27 ----- .../extensionCard/extensionCard.scss | 2 + .../extension/extensionCard/extensionCard.vue | 7 +- .../components/peer/peerCard/peerCard.scss | 2 +- .../src/components/peer/peerCard/peerCard.vue | 4 +- apps/web/src/styles/entity-card.scss | 2 +- apps/web/src/views/sources/sources.vue | 1 + apps/web/tests/accessibility.spec.ts | 40 ------- playwright.config.ts | 8 ++ tests/e2e/accessibility.spec.ts | 110 ++++++++++++++++++ tests/e2e/github-native.ts | 43 ++----- tests/e2e/peer-database.spec.ts | 80 ++++++++----- 14 files changed, 195 insertions(+), 141 deletions(-) create mode 100644 .changeset/clear-web-heading-hierarchy.md delete mode 100644 apps/web/playwright.config.ts delete mode 100644 apps/web/tests/accessibility.spec.ts create mode 100644 tests/e2e/accessibility.spec.ts diff --git a/.changeset/clear-web-heading-hierarchy.md b/.changeset/clear-web-heading-hierarchy.md new file mode 100644 index 00000000..73712b41 --- /dev/null +++ b/.changeset/clear-web-heading-hierarchy.md @@ -0,0 +1,5 @@ +--- +'@inkcre/web': patch +--- + +补齐来源页面的一级标题,并修正 Peer 与扩展卡片的标题层级。将扩展卡片内的 Peer 控制行标记为具名分组,避免多张卡片产生同名地标,使辅助技术能够按页面和卡片导航,同时保留现有视觉样式。 diff --git a/apps/web/package.json b/apps/web/package.json index 56ed36ed..b94627de 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -9,8 +9,8 @@ "preview": "vite preview", "build-only": "vite build", "type-check": "vue-tsc --build", - "test:a11y": "playwright test accessibility.spec.ts", - "test:a11y:report": "playwright test accessibility.spec.ts --reporter=html" + "test:a11y": "node ../../scripts/test-e2e.mjs --project accessibility", + "test:a11y:report": "node ../../scripts/test-e2e.mjs --project accessibility --reporter=html" }, "dependencies": { "@dagrejs/dagre": "^3.1.2", @@ -34,7 +34,6 @@ "zod-config": "^1.4.0" }, "devDependencies": { - "@axe-core/playwright": "^4.14.0", "@iconify-json/mdi": "^1.2.3", "@module-federation/vite": "^1.1.0", "@playwright/test": "1.61.1", diff --git a/apps/web/playwright.config.ts b/apps/web/playwright.config.ts deleted file mode 100644 index f9419da7..00000000 --- a/apps/web/playwright.config.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' - -export default defineConfig({ - testDir: './tests', - fullyParallel: true, - forbidOnly: !!process.env.CI, - retries: process.env.CI ? 2 : 0, - workers: process.env.CI ? 1 : undefined, - reporter: 'html', - use: { - baseURL: 'http://localhost:5199', - trace: 'on-first-retry', - }, - - projects: [ - { - name: 'chromium', - use: { ...devices['Desktop Chrome'] }, - }, - ], - - webServer: { - command: 'pnpm dev', - url: 'http://localhost:5199', - reuseExistingServer: !process.env.CI, - }, -}) diff --git a/apps/web/src/components/extension/extensionCard/extensionCard.scss b/apps/web/src/components/extension/extensionCard/extensionCard.scss index 4702eae9..9246376c 100644 --- a/apps/web/src/components/extension/extensionCard/extensionCard.scss +++ b/apps/web/src/components/extension/extensionCard/extensionCard.scss @@ -20,6 +20,8 @@ &__id { @include apply-font(label-lg); + display: inline; + margin: 0; } &__version { diff --git a/apps/web/src/components/extension/extensionCard/extensionCard.vue b/apps/web/src/components/extension/extensionCard/extensionCard.vue index 44a158dd..28fd07c7 100644 --- a/apps/web/src/components/extension/extensionCard/extensionCard.vue +++ b/apps/web/src/components/extension/extensionCard/extensionCard.vue @@ -81,7 +81,7 @@ const {
- {{ extension.nickname ?? extension.name }} +

{{ extension.nickname ?? extension.name }}

{{ extension.name }}

@@ -102,9 +102,10 @@ const {

{{ t('extension.usedOnPeers') }}

-
@@ -177,7 +178,7 @@ const { @click="removePeer(peer)" /> -
+ {
-

+

-

+ {{ statusConfig.text }} diff --git a/apps/web/src/styles/entity-card.scss b/apps/web/src/styles/entity-card.scss index c189beb2..eb474c75 100644 --- a/apps/web/src/styles/entity-card.scss +++ b/apps/web/src/styles/entity-card.scss @@ -4,7 +4,7 @@ //
//
//
-//

…

+//

…

// … //
//
diff --git a/apps/web/src/views/sources/sources.vue b/apps/web/src/views/sources/sources.vue index d6690e26..67c3a7f4 100644 --- a/apps/web/src/views/sources/sources.vue +++ b/apps/web/src/views/sources/sources.vue @@ -41,6 +41,7 @@ async function onCreateSource(source: Source) {