Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(library): 核验已存在 media 副本并隔离 updateService 测试夹具 (#3999)
Praisec6aecf8dc7c7
diff --git a/apps/desktop/src/main/__tests__/updateService.test.ts b/apps/desktop/src/main/__tests__/updateService.test.tsindex 1bb113d1dd..fad4660242 100644--- a/apps/desktop/src/main/__tests__/updateService.test.ts+++ b/apps/desktop/src/main/__tests__/updateService.test.ts@@ -182,10 +182,19 @@ async function freshUpdateService(platform: NodeJS.Platform, arch: string = origreturn import('../updateService');}-beforeAll(() => {+function resetUpdateServiceFixture() {+ if (TEST_ROOT) {+ fs.rmSync(TEST_ROOT, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 });+ }TEST_ROOT = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-maker-update-service-test-'));TEST_USER_DATA = path.join(TEST_ROOT, 'user-data');TEST_EXE = path.join(TEST_ROOT, 'app', 'xdt-maker.exe');+ fs.mkdirSync(TEST_USER_DATA, { recursive: true });+ fs.mkdirSync(path.dirname(TEST_EXE), { recursive: true });+}++beforeAll(() => {+ resetUpdateServiceFixture();});afterAll(() => {if (!TEST_ROOT) return;@@ -251,7 +260,7 @@ beforeEach(() => {logWarn.mockReset();logError.mockReset();logDebug.mockReset();- fs.rmSync(TEST_ROOT, { recursive: true, force: true });+ resetUpdateServiceFixture();});afterEach(() => {vi.clearAllTimers();@@ -260,6 +269,7 @@ afterEach(() => {setArch(originalArch);});+describe.sequential('updateService', () => {describe('binary version checks after a user-requested update', () => {beforeEach(() => {readAutoUpdateSettings.mockReturnValue({ autoRelaunchOnIdle: false });@@ -1153,6 +1163,8 @@ describe('startup update relaunch safety', () => {enabled: true,manifest: updateManifest('0.0.65', sharedHotfix),});+ service.stopUpdateService();+ vi.useRealTimers();let releaseProbe: ((busy: boolean) => void) | undefined;const probeStarted = new Promise<void>((resolveStarted) => {service.setUpdateAutoRelaunchBusyProbe(@@ -1179,7 +1191,10 @@ describe('startup update relaunch safety', () => {expect(service.getUpdateStatus()).toBe('ready');const destPath = path.join(TEST_USER_DATA, 'updates', path.basename(sharedHotfix));+ const patchInfoPath = path.join(TEST_USER_DATA, 'updates', 'patch-info.json');expect(fs.existsSync(destPath)).toBe(true);+ expect(fs.existsSync(patchInfoPath)).toBe(true);+ expect(fs.readFileSync(patchInfoPath, 'utf-8')).toContain('0.0.66');releaseProbe?.(true);await vi.waitFor(() => {@@ -1191,8 +1206,8 @@ describe('startup update relaunch safety', () => {});expect(service.getUpdateStatus()).toBe('ready');expect(fs.existsSync(destPath)).toBe(true);- expect(fs.readFileSync(path.join(TEST_USER_DATA, 'updates', 'patch-info.json'), 'utf-8')).toContain('0.0.66');} finally {+ releaseProbe?.(true);service.stopUpdateService();}});@@ -1233,6 +1248,8 @@ describe('startup update relaunch safety', () => {enabled: true,manifest: updateManifest('0.0.65', sharedHotfix),});+ service.stopUpdateService();+ vi.useRealTimers();let releaseProbe: ((busy: boolean) => void) | undefined;const probeStarted = new Promise<void>((resolveStarted) => {service.setUpdateAutoRelaunchBusyProbe(@@ -1244,7 +1261,12 @@ describe('startup update relaunch safety', () => {);});let finishDownload: (() => void) | undefined;+ let downloadEntered: (() => void) | undefined;+ const downloadStarted = new Promise<void>((resolve) => {+ downloadEntered = resolve;+ });download.mockImplementation(async ({ targetPath }: { targetPath: string }) => {+ downloadEntered?.();await new Promise<void>((resolve) => {finishDownload = resolve;});@@ -1262,13 +1284,9 @@ describe('startup update relaunch safety', () => {});fetchManifest.mockResolvedValue(updateManifest('0.0.66', sharedHotfix));const checkPromise = service.checkForUpdate();- await vi.waitFor(() => {- expect(finishDownload).toBeTypeOf('function');- });+ await downloadStarted;+ expect(service.getUpdateStatus()).toBe('superseding');releaseProbe?.(true);- await vi.waitFor(() => {- expect(service.getUpdateStatus()).toBe('superseding');- });finishDownload?.();await expect(checkPromise).resolves.toBe('ready');expect(service.getUpdateStatus()).toBe('ready');@@ -1276,6 +1294,8 @@ describe('startup update relaunch safety', () => {fs.readFileSync(path.join(TEST_USER_DATA, 'updates', 'patch-info.json'), 'utf-8'),).toContain('0.0.66');} finally {+ finishDownload?.();+ releaseProbe?.(true);service.stopUpdateService();}});@@ -1298,6 +1318,8 @@ describe('startup update relaunch safety', () => {it('does not restore a superseded patch after a channel change', async () => {const { DownloadError } = await import('../downloader/index');const service = await bootWithStagedPatch({ enabled: true });+ service.stopUpdateService();+ vi.useRealTimers();let releaseProbe: ((busy: boolean) => void) | undefined;const probeStarted = new Promise<void>((resolveStarted) => {service.setUpdateAutoRelaunchBusyProbe(@@ -1309,9 +1331,16 @@ describe('startup update relaunch safety', () => {);});let failDownload: ((error: Error) => void) | undefined;- download.mockImplementation(() => new Promise((_, reject) => {- failDownload = reject;- }));+ let downloadEntered: (() => void) | undefined;+ const downloadStarted = new Promise<void>((resolve) => {+ downloadEntered = resolve;+ });+ download.mockImplementation(() => {+ downloadEntered?.();+ return new Promise((_, reject) => {+ failDownload = reject;+ });+ });try {await probeStarted;await expect(service.enableUncustomizedBetaChannel()).resolves.toBe(true);@@ -1322,18 +1351,15 @@ describe('startup update relaunch safety', () => {});fetchManifest.mockResolvedValue(updateManifest('0.0.66'));const checkPromise = service.checkForUpdate();- await vi.waitFor(() => {- expect(failDownload).toBeTypeOf('function');- });+ await downloadStarted;+ expect(service.getUpdateStatus()).toBe('superseding');releaseProbe?.(true);- await vi.waitFor(() => {- expect(service.getUpdateStatus()).toBe('superseding');- });failDownload?.(new DownloadError('NETWORK', 'boom'));await expect(checkPromise).resolves.toBe('idle');expect(service.getUpdateStatus()).toBe('idle');expect(fs.existsSync(path.join(TEST_USER_DATA, 'updates', 'patch-info.json'))).toBe(false);} finally {+ releaseProbe?.(true);service.stopUpdateService();}});@@ -1716,9 +1742,11 @@ describe('startup update relaunch safety', () => {error: 'manifest_failed',});expect(service.getUpdateStatus()).toBe('idle');- expect(fs.existsSync(path.join(updatesDir, 'patch-info.json'))).toBe(false);- expect(fs.existsSync(path.join(updatesDir, 'xdt-maker-0.0.65.zip'))).toBe(false);- expect(fs.existsSync(flagPath)).toBe(false);+ await vi.waitFor(() => {+ expect(fs.existsSync(path.join(updatesDir, 'patch-info.json'))).toBe(false);+ expect(fs.existsSync(path.join(updatesDir, 'xdt-maker-0.0.65.zip'))).toBe(false);+ expect(fs.existsSync(flagPath)).toBe(false);+ });} finally {service.stopUpdateService();}@@ -1990,3 +2018,4 @@ describe('splash 启动下载 0% 显式广播', () => {expect(progressCountWhenDownloadStarted).toBe(0);});});+});diff --git a/apps/desktop/src/main/cindy-media/__tests__/blobStore.test.ts b/apps/desktop/src/main/cindy-media/__tests__/blobStore.test.tsindex 7a6463141b..4712c96aa4 100644--- a/apps/desktop/src/main/cindy-media/__tests__/blobStore.test.ts+++ b/apps/desktop/src/main/cindy-media/__tests__/blobStore.test.ts@@ -5,13 +5,16 @@* 文件落 os.tmpdir() 临时目录并收尾清理(规则 23:凭证不入仓同族约束)。*/-import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest';+import { describe, it, expect, vi, beforeAll, afterAll, afterEach } from 'vitest';import { createHash } from 'node:crypto';+import { spawn } from 'node:child_process';import fs from 'node:fs';+import fsp from 'node:fs/promises';import os from 'node:os';import path from 'node:path';let tmpUserData = '';+let scratchRoot = '';vi.mock('electron', () => ({app: { getPath: () => tmpUserData },@@ -24,12 +27,54 @@ const PNG_HASH = createHash('sha256').update(PNG_BYTES).digest('hex');beforeAll(() => {tmpUserData = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-media-test-'));+ scratchRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-media-scratch-'));});afterAll(() => {fs.rmSync(tmpUserData, { recursive: true, force: true });+ fs.rmSync(scratchRoot, { recursive: true, force: true });});+afterEach(() => {+ vi.restoreAllMocks();+});++function hashedPng(label: string) {+ const buffer = Buffer.concat([PNG_BYTES, Buffer.from(label)]);+ const hash = createHash('sha256').update(buffer).digest('hex');+ const dest = path.join(tmpUserData, 'cindy-media', 'blobs', hash.slice(0, 2), `${hash}.png`);+ return { buffer, hash, dest, shard: path.dirname(dest) };+}++function scratchDir(label: string): string {+ return fs.mkdtempSync(path.join(scratchRoot, `${label}-`));+}++function seedDest(dest: string, contents: Buffer | 'dir' | { symlink: string }) {+ fs.mkdirSync(path.dirname(dest), { recursive: true });+ fs.rmSync(dest, { recursive: true, force: true });+ if (contents === 'dir') {+ fs.mkdirSync(dest);+ return;+ }+ if (typeof contents === 'object' && 'symlink' in contents) {+ fs.symlinkSync(contents.symlink, dest);+ return;+ }+ fs.writeFileSync(dest, contents);+}++async function withUnsupportedLink<T>(fn: () => Promise<T>): Promise<T> {+ const spy = vi.spyOn(fsp, 'link').mockRejectedValue(+ Object.assign(new Error('hard-link unsupported'), { code: 'ENOTSUP' }),+ );+ try {+ return await fn();+ } finally {+ spy.mockRestore();+ }+}+describe('writeBlob(内容寻址写入)', () => {it('支持 Telegram voice 使用的 Ogg/Opus 容器 MIME', () => {expect(blobStore.supportedMime('audio/ogg')).toBe(true);@@ -70,6 +115,311 @@ describe('writeBlob(内容寻址写入)', () => {});});+describe('writeBlob(已存在副本核验与自愈)', () => {+ it.each(['link', 'rename'] as const)('%s 分支:正确副本去重不重写', async (mode) => {+ const sample = hashedPng(`ok-${mode}`);+ seedDest(sample.dest, sample.buffer);+ const before = fs.statSync(sample.dest);+ const run = () => blobStore.writeBlob({ buffer: sample.buffer, mimeType: 'image/png' });+ const written = mode === 'rename' ? await withUnsupportedLink(run) : await run();+ expect(written.deduplicated).toBe(true);+ const after = fs.statSync(sample.dest);+ expect(after.ino).toBe(before.ino);+ expect(after.mtimeMs).toBe(before.mtimeMs);+ expect(fs.readFileSync(sample.dest)).toEqual(sample.buffer);+ });++ it.each(['link', 'rename'] as const)('%s 分支:损坏文件按输入 hash 修复', async (mode) => {+ const sample = hashedPng(`bad-${mode}`);+ seedDest(sample.dest, Buffer.from('poisoned-bytes'));+ const run = () => blobStore.writeBlob({ buffer: sample.buffer, mimeType: 'image/png' });+ const written = mode === 'rename' ? await withUnsupportedLink(run) : await run();+ expect(written.deduplicated).toBe(false);+ expect(written.hash).toBe(sample.hash);+ expect(fs.readFileSync(sample.dest)).toEqual(sample.buffer);+ expect(createHash('sha256').update(fs.readFileSync(sample.dest)).digest('hex')).toBe(sample.hash);+ });++ it.each(['link', 'rename'] as const)('%s 分支:缺失补写', async (mode) => {+ const sample = hashedPng(`missing-${mode}`);+ fs.mkdirSync(sample.shard, { recursive: true });+ const run = () => blobStore.writeBlob({ buffer: sample.buffer, mimeType: 'image/png' });+ const written = mode === 'rename' ? await withUnsupportedLink(run) : await run();+ expect(written.deduplicated).toBe(false);+ expect(fs.readFileSync(sample.dest)).toEqual(sample.buffer);+ });++ it.each(['link', 'rename'] as const)('%s 分支:symlink 不当成去重成功', async (mode) => {+ const sample = hashedPng(`symlink-${mode}`);+ const outsideDir = scratchDir(`outside-${mode}`);+ const outside = path.join(outsideDir, 'payload.bin');+ fs.writeFileSync(outside, sample.buffer);+ seedDest(sample.dest, { symlink: outside });+ const run = () => blobStore.writeBlob({ buffer: sample.buffer, mimeType: 'image/png' });+ await expect(mode === 'rename' ? withUnsupportedLink(run) : run()).rejects.toThrow(/symlink/);+ expect(fs.lstatSync(sample.dest).isSymbolicLink()).toBe(true);+ expect(fs.readFileSync(outside)).toEqual(sample.buffer);+ });++ it.each(['link', 'rename'] as const)('%s 分支:目录不当成去重成功', async (mode) => {+ const sample = hashedPng(`dir-${mode}`);+ seedDest(sample.dest, 'dir');+ const run = () => blobStore.writeBlob({ buffer: sample.buffer, mimeType: 'image/png' });+ await expect(mode === 'rename' ? withUnsupportedLink(run) : run()).rejects.toThrow(/directory/);+ expect(fs.statSync(sample.dest).isDirectory()).toBe(true);+ });++ it.each(['link', 'rename'] as const)('%s 分支:检查期间替换不当成去重成功', async (mode) => {+ const sample = hashedPng(`swap-${mode}`);+ seedDest(sample.dest, sample.buffer);+ const outsideDir = scratchDir(`swap-${mode}`);+ const outside = path.join(outsideDir, 'not-the-blob.bin');+ fs.writeFileSync(outside, Buffer.from('not-the-blob'));+ const originalOpen = fsp.open.bind(fsp);+ const spy = vi.spyOn(fsp, 'open').mockImplementation(async (target, flags, perm) => {+ if (path.resolve(String(target)) === path.resolve(sample.dest)) {+ fs.rmSync(sample.dest, { force: true });+ fs.symlinkSync(outside, sample.dest);+ }+ return originalOpen(target, flags, perm);+ });+ try {+ const run = () => blobStore.writeBlob({ buffer: sample.buffer, mimeType: 'image/png' });+ await expect(mode === 'rename' ? withUnsupportedLink(run) : run()).rejects.toThrow();+ expect(fs.lstatSync(sample.dest).isSymbolicLink()).toBe(true);+ expect(fs.readFileSync(outside).toString()).toBe('not-the-blob');+ } finally {+ spy.mockRestore();+ }+ });++ it('bucket 被换成指向仓外的 symlink 时 fail closed,不追随写入', async () => {+ const sample = hashedPng('bucket-symlink');+ const outsideDir = scratchDir('bucket-outside');+ fs.mkdirSync(sample.shard, { recursive: true });+ fs.rmSync(sample.shard, { recursive: true, force: true });+ fs.symlinkSync(outsideDir, sample.shard);+ await expect(+ blobStore.writeBlob({ buffer: sample.buffer, mimeType: 'image/png' }),+ ).rejects.toThrow(/symlink|out of bounds/);+ expect(fs.lstatSync(sample.shard).isSymbolicLink()).toBe(true);+ expect(fs.readdirSync(outsideDir)).toEqual([]);+ });++ it.each(['cindy-media', 'blobs'] as const)('%s 祖先 symlink fail closed', async (kind) => {+ const sample = hashedPng(`anc-${kind}`);+ const target = path.join(tmpUserData, 'cindy-media', ...(kind === 'blobs' ? ['blobs'] : []));+ const outside = scratchDir(`anc-${kind}`);+ fs.rmSync(target, { recursive: true, force: true });+ fs.symlinkSync(outside, target);+ await expect(blobStore.writeBlob({ buffer: sample.buffer, mimeType: 'image/png' })).rejects.toThrow(/symlink|out of bounds/);+ expect(fs.lstatSync(target).isSymbolicLink()).toBe(true);+ expect(fs.readdirSync(outside)).toEqual([]);+ fs.rmSync(target, { recursive: true, force: true });+ fs.mkdirSync(path.join(tmpUserData, 'cindy-media', 'blobs'), { recursive: true });+ });++ it('hash 后 size 变化视为替换,不得去重成功', async () => {+ const sample = hashedPng('size-drift');+ seedDest(sample.dest, sample.buffer);+ const originalOpen = fsp.open.bind(fsp);+ let n = 0;+ vi.spyOn(fsp, 'open').mockImplementation(async (target, flags, perm) => {+ const handle = await originalOpen(target, flags, perm);+ if (path.resolve(String(target)) !== path.resolve(sample.dest)) return handle;+ const originalStat = handle.stat.bind(handle);+ handle.stat = async () => {+ const st = await originalStat();+ return ++n < 2 ? st : Object.assign(Object.create(Object.getPrototypeOf(st)), st, { size: st.size + 1 });+ };+ return handle;+ });+ await expect(blobStore.writeBlob({ buffer: sample.buffer, mimeType: 'image/png' })).rejects.toThrow(/not a regular file|did not match input hash/);+ });++ it('Windows 上 path/fd stat 一侧 dev=0 时仍识别同一正确副本', async () => {+ const sample = hashedPng('win-dev');+ seedDest(sample.dest, sample.buffer);+ const originalLstat = fsp.lstat.bind(fsp);+ const originalOpen = fsp.open.bind(fsp);+ vi.spyOn(fsp, 'lstat').mockImplementation(async (target, opts) => {+ const st = await originalLstat(target, opts);+ if (path.resolve(String(target)) === path.resolve(sample.dest)) {+ return Object.assign(Object.create(Object.getPrototypeOf(st)), st, { dev: 0 });+ }+ return st;+ });+ vi.spyOn(fsp, 'open').mockImplementation(async (target, flags, perm) => {+ const handle = await originalOpen(target, flags, perm);+ if (path.resolve(String(target)) !== path.resolve(sample.dest)) return handle;+ const originalStat = handle.stat.bind(handle);+ handle.stat = async () => {+ const st = await originalStat();+ return Object.assign(Object.create(Object.getPrototypeOf(st)), st, { dev: 42 });+ };+ return handle;+ });+ const previous = process.platform;+ Object.defineProperty(process, 'platform', { value: 'win32' });+ try {+ const written = await blobStore.writeBlob({ buffer: sample.buffer, mimeType: 'image/png' });+ expect(written.deduplicated).toBe(true);+ expect(fs.readFileSync(sample.dest)).toEqual(sample.buffer);+ } finally {+ Object.defineProperty(process, 'platform', { value: previous });+ }+ });+});++describe('writeBlob(串行与原子发布)', () => {+ it('进程内同目标串行,正确副本幂等收敛', async () => {+ const sample = hashedPng('serial');+ const [first, second] = await Promise.all([+ blobStore.writeBlob({ buffer: sample.buffer, mimeType: 'image/png' }),+ blobStore.writeBlob({ buffer: sample.buffer, mimeType: 'image/png' }),+ ]);+ expect([first.deduplicated, second.deduplicated].sort()).toEqual([false, true]);+ expect(fs.readdirSync(sample.shard).filter((name) => !name.startsWith('.tmp-'))).toEqual([+ `${sample.hash}.png`,+ ]);+ expect(fs.readFileSync(sample.dest)).toEqual(sample.buffer);+ });++ it('损坏目标并发写入后读回正确内容,不暴露半截文件', async () => {+ const sample = hashedPng('race-repair');+ seedDest(sample.dest, Buffer.from('truncated'));+ const results = await Promise.all([+ blobStore.writeBlob({ buffer: sample.buffer, mimeType: 'image/png' }),+ blobStore.writeBlob({ buffer: sample.buffer, mimeType: 'image/png' }),+ ]);+ expect(results.every((item) => item.hash === sample.hash)).toBe(true);+ expect(fs.readFileSync(sample.dest)).toEqual(sample.buffer);+ expect(fs.readdirSync(sample.shard).some((name) => name.startsWith('.tmp-'))).toBe(false);+ });++ it.each(['link', 'rename'] as const)('%s 分支:跨进程同 hash 并发发布后读回验证,正确即幂等收敛', async (mode) => {+ const sample = hashedPng(`cross-proc-${mode}`);+ seedDest(sample.dest, Buffer.from('poison'));+ const workDir = scratchDir(`cross-proc-${mode}`);+ const helper = path.join(workDir, 'write-blob-child.mjs');+ const childReady = path.join(workDir, 'child-ready');+ const parentReady = path.join(workDir, 'parent-ready');+ const resultFile = path.join(workDir, 'result.json');+ const payloadB64 = sample.buffer.toString('base64');+ fs.writeFileSync(+ helper,+ `+ import { createHash, randomUUID } from 'node:crypto';+ import { writeFileSync, existsSync, mkdirSync, lstatSync } from 'node:fs';+ import { writeFile, link, rename, rm, lstat } from 'node:fs/promises';+ const dest = ${JSON.stringify(sample.dest)};+ const shard = ${JSON.stringify(sample.shard)};+ const buffer = Buffer.from(${JSON.stringify(payloadB64)}, 'base64');+ const hash = createHash('sha256').update(buffer).digest('hex');+ mkdirSync(shard, { recursive: true });+ const tmpPath = ${JSON.stringify(path.join(sample.shard, `.tmp-${sample.hash}-child-`))} + randomUUID();+ await writeFile(tmpPath, buffer, { flag: 'wx' });+ writeFileSync(${JSON.stringify(childReady)}, 'ready');+ const waitUntil = async (file) => {+ const deadline = Date.now() + 5000;+ while (!existsSync(file)) {+ if (Date.now() > deadline) throw new Error('timeout waiting ' + file);+ await new Promise((resolve) => setTimeout(resolve, 5));+ }+ };+ await waitUntil(${JSON.stringify(parentReady)});+ try {+ try {+ await link(tmpPath, dest);+ } catch {+ const st = await lstat(dest).catch((err) => (err.code === 'ENOENT' ? null : Promise.reject(err)));+ if (st && (st.isSymbolicLink() || st.isDirectory() || !st.isFile())) {+ throw Object.assign(new Error('child refused non-regular dest'), { code: 'EINVAL' });+ }+ try {+ await rename(tmpPath, dest);+ } catch {+ const again = await lstat(dest);+ if (!again.isFile() || again.size !== buffer.length) throw new Error('child publish did not converge');+ }+ }+ } finally {+ await rm(tmpPath, { force: true }).catch(() => {});+ }+ writeFileSync(${JSON.stringify(resultFile)}, JSON.stringify({ hash, bytes: buffer.length }));+ `,+ );+ const child = spawn(process.execPath, [helper], { stdio: 'pipe' });+ const waitFor = async (file: string) => {+ const deadline = Date.now() + 5000;+ while (!fs.existsSync(file)) {+ if (Date.now() > deadline) throw new Error(`missing ${path.basename(file)}`);+ await new Promise((resolve) => setTimeout(resolve, 5));+ }+ };+ try {+ await waitFor(childReady);+ const parentPromise =+ mode === 'rename'+ ? withUnsupportedLink(() => blobStore.writeBlob({ buffer: sample.buffer, mimeType: 'image/png' }))+ : blobStore.writeBlob({ buffer: sample.buffer, mimeType: 'image/png' });+ fs.writeFileSync(parentReady, 'ready');+ const [parent, childCode] = await Promise.all([+ parentPromise,+ new Promise((resolve, reject) => {+ child.once('error', reject);+ child.once('exit', (code) => resolve(code));+ }),+ ]);+ expect(childCode).toBe(0);+ const childWritten = JSON.parse(fs.readFileSync(resultFile, 'utf8'));+ expect(parent.hash).toBe(sample.hash);+ expect(childWritten.hash).toBe(sample.hash);+ expect(fs.readFileSync(sample.dest)).toEqual(sample.buffer);+ expect(fs.readdirSync(sample.shard).some((name) => name.startsWith('.tmp-'))).toBe(false);+ } finally {+ if (child.exitCode === null && child.signalCode === null) child.kill();+ }+ });++ it.each(['link', 'rename'] as const)('%s 分支:发布失败后读回仍错误且清理自建 temp', async (mode) => {+ const sample = hashedPng(`publish-fail-${mode}`);+ seedDest(sample.dest, Buffer.from('still-bad'));+ const spy = vi.spyOn(fsp, 'rename').mockRejectedValue(+ Object.assign(new Error('permission denied'), { code: 'EACCES' }),+ );+ try {+ const run = () => blobStore.writeBlob({ buffer: sample.buffer, mimeType: 'image/png' });+ await expect(mode === 'rename' ? withUnsupportedLink(run) : run()).rejects.toMatchObject({+ code: 'EACCES',+ });+ expect(fs.readFileSync(sample.dest).toString()).toBe('still-bad');+ expect(fs.readdirSync(sample.shard).some((name) => name.startsWith('.tmp-'))).toBe(false);+ } finally {+ spy.mockRestore();+ }+ });++ it.each(['link', 'rename'] as const)('%s 分支:磁盘满时失败且不把半截内容当成功', async (mode) => {+ const sample = hashedPng(`enospc-${mode}`);+ const spy = vi.spyOn(fsp, 'writeFile').mockRejectedValue(+ Object.assign(new Error('no space left'), { code: 'ENOSPC' }),+ );+ try {+ const run = () => blobStore.writeBlob({ buffer: sample.buffer, mimeType: 'image/png' });+ await expect(mode === 'rename' ? withUnsupportedLink(run) : run()).rejects.toMatchObject({+ code: 'ENOSPC',+ });+ expect(fs.existsSync(sample.dest)).toBe(false);+ if (fs.existsSync(sample.shard)) {+ expect(fs.readdirSync(sample.shard).some((name) => name.startsWith('.tmp-'))).toBe(false);+ }+ } finally {+ spy.mockRestore();+ }+ });+});+describe('parseBlobUrl / resolveSafe(取件形状校验)', () => {it('合法地址往返解析', () => {const parsed = blobStore.parseBlobUrl(`cindy-media://blobs/${PNG_HASH}.png`);@@ -126,6 +476,7 @@ describe('parseBlobUrl / resolveSafe(取件形状校验)', () => {describe('readFile(读回一致性)', () => {it('读回的字节与写入完全一致', async () => {+ await blobStore.writeBlob({ buffer: PNG_BYTES, mimeType: 'image/png' });const { buffer, mimeType } = await blobStore.readFile(`cindy-media://blobs/${PNG_HASH}.png`,);diff --git a/apps/desktop/src/main/cindy-media/__tests__/ingest.test.ts b/apps/desktop/src/main/cindy-media/__tests__/ingest.test.tsindex f992451ccf..bc2d8eae4d 100644--- a/apps/desktop/src/main/cindy-media/__tests__/ingest.test.ts+++ b/apps/desktop/src/main/cindy-media/__tests__/ingest.test.ts@@ -220,6 +220,53 @@ describe('ingestMedia(全局去重)', () => {expect(db.select().from(schema.mediaBlobs).all()).toHaveLength(1);expect(db.select().from(schema.mediaRefs).all()).toHaveLength(2);});++ it('已存在损坏副本先按输入 hash 修复再记账,不把坏文件当去重', async () => {+ const dest = blobPathOf(PNG_HASH, '.png');+ fs.mkdirSync(path.dirname(dest), { recursive: true });+ fs.writeFileSync(dest, Buffer.from('poisoned-media-copy'));+ const result = await ingest.ingestMedia(+ {+ buffer: PNG_BYTES,+ mimeType: 'image/png',+ refs: [{ refKind: 'session-attachment', refId: 's-repaired' }],+ },+ db,+ );+ expect(result.deduplicated).toBe(false);+ expect(fs.readFileSync(dest)).toEqual(PNG_BYTES);+ expect(db.select().from(schema.mediaBlobs).all()).toHaveLength(1);+ expect(db.select().from(schema.mediaRefs).all()).toHaveLength(1);+ });++ it('symlink 拒绝后账本零副作用,不追随链接改仓外文件', async () => {+ const dest = blobPathOf(PNG_HASH, '.png');+ const outsideDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-media-ingest-outside-'));+ const outside = path.join(outsideDir, 'leave-me-alone.bin');+ fs.writeFileSync(outside, Buffer.from('leave-me-alone'));+ try {+ fs.mkdirSync(path.dirname(dest), { recursive: true });+ fs.rmSync(dest, { recursive: true, force: true });+ fs.symlinkSync(outside, dest);+ await expect(+ ingest.ingestMedia(+ {+ buffer: PNG_BYTES,+ mimeType: 'image/png',+ refs: [{ refKind: 'session-attachment', refId: 's-symlink' }],+ },+ db,+ ),+ ).rejects.toThrow(/symlink/);+ expect(fs.lstatSync(dest).isSymbolicLink()).toBe(true);+ expect(fs.readFileSync(outside).toString()).toBe('leave-me-alone');+ expect(db.select().from(schema.mediaBlobs).all()).toHaveLength(0);+ expect(db.select().from(schema.mediaRefs).all()).toHaveLength(0);+ } finally {+ fs.rmSync(dest, { force: true });+ fs.rmSync(outsideDir, { recursive: true, force: true });+ }+ });});describe('ingestMedia(崩溃语义:先字节后记账)', () => {diff --git a/apps/desktop/src/main/cindy-media/blobStore.ts b/apps/desktop/src/main/cindy-media/blobStore.tsindex 8b562e24d8..77648ea7e5 100644--- a/apps/desktop/src/main/cindy-media/blobStore.ts+++ b/apps/desktop/src/main/cindy-media/blobStore.ts@@ -5,7 +5,8 @@* - 文件名 = SHA-256 指纹(**主机侧对字节计算**;外部/插件自称的指纹一律无效);* - 落盘 `userData/cindy-media/blobs/<指纹前2位>/<指纹>.<ext>`——256 抽屉是* 纯性能分桶(防单目录数万文件变卡,同 git objects),无任何语义;- * - 幂等写:同内容重复写入直接命中既有文件(天然去重);+ * - 幂等写:同内容重复写入先核验既有普通文件的尺寸与 SHA-256,正确才去重;+ * 缺失补写,损坏按输入实算 hash 原子修复,symlink/目录/检查期间替换不当成去重;* - 文件永不改名、永不搬家:指纹跟内容走,归属变化只动账本(ledger.ts)。** URL 形态:`cindy-media://blobs/<指纹>.<ext>`,指纹即地址,永久稳定。@@ -14,12 +15,14 @@*/import { app } from 'electron';-import { createHash } from 'node:crypto';+import { createHash, randomUUID } from 'node:crypto';+import { constants as fsConstants, type Stats } from 'node:fs';import path from 'node:path';import fs from 'node:fs/promises';const SCHEME = 'cindy-media';const HOST_BLOBS = 'blobs';+const destLocks = new Map<string, Promise<unknown>>();/** 指纹形状:SHA-256 十六进制,恰 64 位小写。 */const HASH_RE = /^[0-9a-f]{64}$/;@@ -107,50 +110,297 @@ export async function writeBlob(params: {}const hash = createHash('sha256').update(buffer).digest('hex');- const dir = path.join(getBlobsRoot(), hash.slice(0, 2));- await fs.mkdir(dir, { recursive: true });+ const bytes = buffer.byteLength;+ const { dir, dest } = await prepareBlobDestination(hash, ext);++ return withDestLock(dest, async () => {+ // 同目录 tmp + link/rename 发布:终点不以半截内容出现;已存在分支+ // (EEXIST 与不支持 hard-link 且 dest 已在)共用 inspectExistingBlob。+ let deduplicated = false;+ const tmpPath = path.join(dir, `.tmp-${hash}-${process.pid}-${randomUUID()}`);+ try {+ await fs.writeFile(tmpPath, buffer, { flag: 'wx' });+ try {+ await fs.link(tmpPath, dest);+ } catch (err) {+ const code = (err as NodeJS.ErrnoException)?.code;+ if (code === 'EEXIST') {+ deduplicated = await reconcileExistingBlob(tmpPath, dest, hash, bytes);+ } else {+ // 个别文件系统不支持硬链接(exFAT 等):已存在走同一校验出口,+ // 缺失才 rename 发布。destExists 不得在未核验时当去重成功。+ const destExists = await fs.lstat(dest).then(+ () => true,+ (accessErr: NodeJS.ErrnoException) => {+ if (accessErr.code === 'ENOENT') return false;+ throw accessErr;+ },+ );+ if (destExists) {+ deduplicated = await reconcileExistingBlob(tmpPath, dest, hash, bytes);+ } else {+ await publishByRename(tmpPath, dest, hash, bytes);+ }+ }+ }++ let finalState = await inspectExistingBlob(dest, hash, bytes);+ if (finalState.kind !== 'ok') {+ finalState = await rereadOnce(dest, hash, bytes);+ }+ if (finalState.kind !== 'ok') {+ throw finalState.kind === 'invalid'+ ? existingBlobError(finalState)+ : new Error('cindy-media: blob destination did not match input hash');+ }+ await assertBlobPathContained(dest);+ return {+ hash,+ ext,+ mimeType,+ bytes,+ url: blobUrl(hash, ext),+ deduplicated,+ };+ } finally {+ await fs.rm(tmpPath, { force: true }).catch(() => {});+ }+ });+}++async function withDestLock<T>(dest: string, fn: () => Promise<T>): Promise<T> {+ const previous = destLocks.get(dest) ?? Promise.resolve();+ let release!: () => void;+ const done = new Promise<void>((resolve) => { release = resolve; });+ const next = previous.then(() => done, () => done);+ destLocks.set(dest, next);+ try {+ await previous.catch(() => undefined);+ return await fn();+ } finally {+ release();+ if (destLocks.get(dest) === next) destLocks.delete(dest);+ }+}++type ExistingBlob =+ | { kind: 'ok' }+ | { kind: 'missing' }+ | { kind: 'corrupt' }+ | { kind: 'invalid'; reason: 'symlink' | 'directory' | 'non-regular' | 'replaced' };++function isZeroDev(value: number | bigint): boolean {+ return typeof value === 'bigint' ? value === 0n : value === 0;+}++function sameFileIdentity(left: Stats, right: Stats, platform = process.platform): boolean {+ if (left.ino !== right.ino) return false;+ if (left.dev === right.dev) return true;+ // Windows path-based stat can report dev=0 while fd-based stat reports a+ // real volume serial; treat either-side 0 as unknown device (fs-safe).+ return platform === 'win32' && (isZeroDev(left.dev) || isZeroDev(right.dev));+}++async function lstatRegularDir(absPath: string): Promise<Stats> {+ const st = await fs.lstat(absPath);+ if (st.isSymbolicLink()) {+ throw Object.assign(new Error('cindy-media: blob ancestor is a symlink'), { code: 'ELOOP' });+ }+ if (!st.isDirectory()) {+ throw Object.assign(new Error('cindy-media: blob ancestor is not a directory'), { code: 'ENOTDIR' });+ }+ return st;+}++async function ensureContainedDir(absPath: string, parent: string): Promise<Stats> {+ const st = await lstatRegularDir(absPath);+ const resolvedParent = path.resolve(parent);+ const resolvedChild = path.resolve(absPath);+ const relative = path.relative(resolvedParent, resolvedChild);+ if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative)) {+ throw new Error('cindy-media: blob path out of bounds');+ }+ return st;+}++async function ensureChildDir(parent: string, name: string): Promise<string> {+ const child = path.join(parent, name);+ try {+ await ensureContainedDir(child, parent);+ } catch (err) {+ if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') throw err;+ try { await fs.mkdir(child, { recursive: false }); }+ catch (mkdirErr) { if ((mkdirErr as NodeJS.ErrnoException)?.code !== 'EEXIST') throw mkdirErr; }+ await ensureContainedDir(child, parent);+ }+ return child;+}++async function prepareBlobDestination(hash: string, ext: string): Promise<{ dir: string; dest: string }> {+ const userData = path.resolve(app.getPath('userData'));+ await lstatRegularDir(userData);+ const mediaRoot = await ensureChildDir(userData, 'cindy-media');+ const root = await ensureChildDir(mediaRoot, 'blobs');+ const dir = await ensureChildDir(root, hash.slice(0, 2));const dest = path.join(dir, `${hash}${ext}`);+ if (!path.resolve(dest).startsWith(root + path.sep)) {+ throw new Error('cindy-media: blob path out of bounds');+ }+ return { dir, dest };+}- // 原子发布(review P1):先写同目录临时文件,再 link 到终点。直接 'wx' 写- // 终点的问题:进程半写崩溃会在终点留下截断文件,之后同内容 ingest 全部- // EEXIST 去重命中——内容寻址槽被永久毒化且无自愈;并发双写时后到者可能- // 在首写者完成前就 resolveSafe 读到半截字节。改为 tmp+link 后,终点路径- // 只会以完整字节出现;崩溃残留的只是 .tmp-* 垃圾(对账工具可辨识清理)。- let deduplicated = false;- const tmpPath = path.join(dir, `.tmp-${hash}-${process.pid}-${Date.now().toString(36)}`);- await fs.writeFile(tmpPath, buffer, { flag: 'wx' });+async function assertBlobPathContained(absPath: string): Promise<void> {+ const userData = path.resolve(app.getPath('userData'));+ const root = path.resolve(getBlobsRoot());+ if (!path.resolve(absPath).startsWith(root + path.sep)) {+ throw new Error('cindy-media: blob path out of bounds');+ }+ const destStat = await fs.lstat(absPath);+ if (destStat.isSymbolicLink()) throw Object.assign(new Error('cindy-media: blob destination is a symlink'), { code: 'ELOOP' });+ let current = path.resolve(absPath);+ while (current !== userData) {+ const parent = path.dirname(current);+ if (parent === current) break;+ await lstatRegularDir(parent);+ current = parent;+ }+}++function noFollowReadFlags(): number {+ return fsConstants.O_RDONLY | (process.platform === 'win32' ? 0 : (fsConstants.O_NOFOLLOW ?? 0));+}++async function inspectExistingBlob(+ absPath: string,+ expectedHash: string,+ expectedSize: number,+): Promise<ExistingBlob> {+ let pathStat: Stats;+ try {+ pathStat = await fs.lstat(absPath);+ } catch (err) {+ if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return { kind: 'missing' };+ throw err;+ }+ if (pathStat.isSymbolicLink()) return { kind: 'invalid', reason: 'symlink' };+ if (pathStat.isDirectory()) return { kind: 'invalid', reason: 'directory' };+ if (!pathStat.isFile()) return { kind: 'invalid', reason: 'non-regular' };+ if (pathStat.size !== expectedSize) return { kind: 'corrupt' };++ let handle: Awaited<ReturnType<typeof fs.open>>;try {- // link 原子且目标已存在必 EEXIST——内容寻址下同名必同内容,命中即去重。- await fs.link(tmpPath, dest);+ handle = await fs.open(absPath, noFollowReadFlags());} catch (err) {const code = (err as NodeJS.ErrnoException)?.code;- if (code === 'EEXIST') {- deduplicated = true;- } else {- // 个别文件系统不支持硬链接(exFAT 等):退化为 rename 发布;目标已- // 存在时 Windows rename 抛错、POSIX 覆盖同内容,两者都视为去重。- const destExists = await fs.access(dest).then(- () => true,- () => false,- );- if (destExists) {- deduplicated = true;- } else {- await fs.rename(tmpPath, dest);- }+ if (code === 'ENOENT') return { kind: 'missing' };+ if (code === 'ELOOP') return { kind: 'invalid', reason: 'symlink' };+ throw err;+ }+ try {+ const opened = await handle.stat();+ if (!opened.isFile() || opened.isSymbolicLink() || !sameFileIdentity(pathStat, opened)) {+ return { kind: 'invalid', reason: 'replaced' };}+ if (opened.size !== expectedSize) return { kind: 'corrupt' };++ const hasher = createHash('sha256');+ const stream = handle.createReadStream({ autoClose: false, emitClose: false });+ for await (const chunk of stream) hasher.update(chunk);+ const digest = hasher.digest('hex');++ const afterHandle = await handle.stat();+ let afterPath: Stats;+ try {+ afterPath = await fs.lstat(absPath);+ } catch (err) {+ if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return { kind: 'invalid', reason: 'replaced' };+ throw err;+ }+ if (+ !sameFileIdentity(opened, afterHandle) ||+ !sameFileIdentity(opened, afterPath) ||+ afterPath.isSymbolicLink() ||+ !afterPath.isFile() ||+ afterHandle.size !== expectedSize ||+ afterPath.size !== expectedSize+ ) {+ return { kind: 'invalid', reason: 'replaced' };+ }+ return digest === expectedHash ? { kind: 'ok' } : { kind: 'corrupt' };} finally {- await fs.rm(tmpPath, { force: true }).catch(() => {});+ await handle.close().catch(() => {});+ }+}++async function rereadOnce(+ dest: string,+ expectedHash: string,+ expectedSize: number,+): Promise<ExistingBlob> {+ return inspectExistingBlob(dest, expectedHash, expectedSize);+}++async function reconcileExistingBlob(+ tmpPath: string,+ dest: string,+ expectedHash: string,+ expectedSize: number,+): Promise<boolean> {+ const existing = await inspectExistingBlob(dest, expectedHash, expectedSize);+ if (existing.kind === 'ok') return true;+ if (existing.kind === 'missing' || existing.kind === 'corrupt') {+ await publishByRename(tmpPath, dest, expectedHash, expectedSize);+ return false;+ }+ const again = await rereadOnce(dest, expectedHash, expectedSize);+ if (again.kind === 'ok') return true;+ throw existingBlobError(again.kind === 'invalid' ? again : existing);+}++function existingBlobError(state: ExistingBlob): Error {+ if (state.kind === 'invalid' && state.reason === 'symlink') {+ return Object.assign(new Error('cindy-media: blob destination is a symlink'), { code: 'ELOOP' });+ }+ if (state.kind === 'invalid' && state.reason === 'directory') {+ return Object.assign(new Error('cindy-media: blob destination is a directory'), { code: 'EISDIR' });+ }+ return Object.assign(new Error('cindy-media: blob destination is not a regular file'), {+ code: 'EINVAL',+ });+}++async function publishByRename(+ tmpPath: string,+ dest: string,+ expectedHash: string,+ expectedSize: number,+): Promise<void> {+ let destStat: Stats | null;+ try {+ destStat = await fs.lstat(dest);+ } catch (err) {+ if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') throw err;+ destStat = null;+ }+ if (destStat && (destStat.isSymbolicLink() || destStat.isDirectory() || !destStat.isFile())) {+ const again = await inspectExistingBlob(dest, expectedHash, expectedSize);+ if (again.kind === 'ok') return;+ throw existingBlobError(again.kind === 'invalid' ? again : { kind: 'invalid', reason: 'replaced' });+ }++ try {+ await fs.rename(tmpPath, dest);+ } catch (err) {+ const again = await inspectExistingBlob(dest, expectedHash, expectedSize);+ if (again.kind === 'ok') return;+ throw err;}- return {- hash,- ext,- mimeType,- bytes: buffer.byteLength,- url: blobUrl(hash, ext),- deduplicated,- };+ const published = await inspectExistingBlob(dest, expectedHash, expectedSize);+ if (published.kind === 'ok') return;+ const once = await inspectExistingBlob(dest, expectedHash, expectedSize);+ if (once.kind === 'ok') return;+ throw new Error('cindy-media: blob destination changed during publish');}/**diff --git a/apps/desktop/src/main/cindy-media/ingest.ts b/apps/desktop/src/main/cindy-media/ingest.tsindex d02988c7dd..392c8f136f 100644--- a/apps/desktop/src/main/cindy-media/ingest.ts+++ b/apps/desktop/src/main/cindy-media/ingest.ts@@ -13,7 +13,8 @@* - 绝不反向(先记账后写盘会产生"有账无文件"的坏账,读路径直接 404,* 且回收器无从判断该行是垃圾还是丢文件)。* - 去重命中(deduplicated=true)仍照常记账:recordBlob 幂等只刷 lastAccess,- * addRef 是新引用行——"同内容再次被引用"正是账本要记的事实。+ * addRef 是新引用行——"同内容再次被引用"正是账本要记的事实。writeBlob+ * 只在最终实际内容 hash 正确时成功;错误去重不会进入账本。** 所有函数接受可注入 db(规则 14),生产默认走 DbClient 的 drizzle 代理。*/@@ -94,6 +95,7 @@ export async function ingestMedia(throw new Error('cindy-media: guarded ingest requires a reference compensation scope');}params.assertStillValid?.();+ // writeBlob 只在最终实际内容 hash 正确时返回;损坏/symlink/目录不会被当成去重。const written = await blobStore.writeBlob({buffer: params.buffer,mimeType: params.mimeType,