Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(device-link): derive SSH versions from stable remote identity
Dashb26e6badd5f6
diff --git a/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts b/apps/desktop/src/main/device-link/__tests__/filePeer.test.tsindex e1b6deeba6..62f58d3fe1 100644--- a/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts@@ -893,7 +893,7 @@ describe('authorized file peer source', () => {await expect(read(connection, ticket, 0)).rejects.toThrow();});it.each([false, true])('handles LRU touches only for versioned cache sources (%s)', async (versionedCache) => {- mock.resolve.mockResolvedValue({ absPath: file, maxBytes: 100, versionedCache });+ mock.resolve.mockResolvedValue({ absPath: file, maxBytes: 100, sourceVersion: versionedCache ? 'remote-version-a' : undefined });const { connection } = await connect();const first = await open(connection);await fsPromises.utimes(file, new Date(1_000), new Date(1_000));@@ -906,9 +906,21 @@ describe('authorized file peer source', () => {expect(await read(connection, first.ticket, 5)).toBe('');const second = await open(connection);expect(second.version).toBe(first.version);+ await read(connection, second.ticket, 0);+ await read(connection, second.ticket, 5);+ const relocated = `${file}-new-generation`;+ await fsPromises.copyFile(file, relocated);+ mock.resolve.mockResolvedValue({ absPath: relocated, maxBytes: 100, sourceVersion: 'remote-version-a' });+ const third = await open(connection);+ expect(third.version).toBe(first.version);+ await read(connection, third.ticket, 0);+ await read(connection, third.ticket, 5);+ mock.resolve.mockResolvedValue({ absPath: relocated, maxBytes: 100, sourceVersion: 'remote-version-b' });+ const changed = await open(connection);+ expect(changed.version).not.toBe(first.version);// Ignoring LRU timestamps must not hide truncated or corrupt cache copies.- await truncate(file, 4);- await expect(read(connection, second.ticket, 0)).rejects.toThrow('CHANGED');+ await truncate(relocated, 4);+ await expect(read(connection, changed.ticket, 0)).rejects.toThrow('CHANGED');});it('rejects revoked or old-owner chunks without affecting a second peer', async () => {const a = await connect(),diff --git a/apps/desktop/src/main/device-link/__tests__/mediaFetch.test.ts b/apps/desktop/src/main/device-link/__tests__/mediaFetch.test.tsindex 7b672eea4e..e29b7e4e30 100644--- a/apps/desktop/src/main/device-link/__tests__/mediaFetch.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/mediaFetch.test.ts@@ -66,6 +66,7 @@ beforeEach(() => {materializeSshRemoteMedia.mockResolvedValue({ok: true,cachePath: '/cache/ssh/plot.png',+ sourceVersion: 'ssh-source-a',size: 42,mime: 'image/png',relPath: 'artifacts/plot.png',@@ -182,14 +183,15 @@ describe('fetchLocalMediaToOss — scheme 路由', () => {expect(r).toEqual({ ossKey: 'cindy/device-link/u/uuid.ext', mimeType: 'image/png', size: 42 });});- it.each([5, 100_000])('keeps SSH version stable across LRU touches (%s bytes)', async (size) => {+ it.each([5, 100_000])('keeps SSH version stable across LRU touches and cache relocation (%s bytes)', async (size) => {let clock = 1;+ let sourceVersion = 'remote-version-a';let cachePath = path.join(os.tmpdir(), 'ssh-version-a.png');materializeSshRemoteMedia.mockImplementation(async () => ({- ok: true, cachePath, size, mime: 'image/png', relPath: 'artifacts/plot.png',+ ok: true, cachePath, sourceVersion, size, mime: 'image/png', relPath: 'artifacts/plot.png',}));openMock.mockResolvedValue({- stat: async () => ({ isFile: () => true, size, mtimeMs: clock++, ctimeMs: clock++, ino: 1, dev: 1 }),+ stat: async () => ({ isFile: () => true, size, mtimeMs: clock++, ctimeMs: clock++, ino: clock++, dev: 1 }),read: async (bytes: Buffer) => { bytes.fill(7); return { bytesRead: bytes.length }; },close: vi.fn(),});@@ -198,6 +200,8 @@ describe('fetchLocalMediaToOss — scheme 路由', () => {expect(first.version).toMatch(/^[a-f0-9]{64}$/);expect((await fetchLocalMediaToOss(args)).version).toBe(first.version);cachePath = path.join(os.tmpdir(), 'ssh-version-b.png');+ expect((await fetchLocalMediaToOss(args)).version).toBe(first.version);+ sourceVersion = 'remote-version-b';expect((await fetchLocalMediaToOss(args)).version).not.toBe(first.version);});diff --git a/apps/desktop/src/main/device-link/filePeer.ts b/apps/desktop/src/main/device-link/filePeer.tsindex b13de623b6..ced1c85fd6 100644--- a/apps/desktop/src/main/device-link/filePeer.ts+++ b/apps/desktop/src/main/device-link/filePeer.ts@@ -517,7 +517,7 @@ async function handleFilePeerRequest(size: stat.size,mtime: stat.mtimeMs,ctime: stat.ctimeMs,- versionedCache: authorized.versionedCache,+ versionedCache: authorized.sourceVersion !== undefined,offset: 0,busy: false,openedAt: Date.now(),@@ -527,7 +527,7 @@ async function handleFilePeerRequest(monitorSend(ticket, source);return {ticket, size: stat.size, mimeType,- version: fileVersion(authorized.absPath, stat, authorized.versionedCache),+ version: fileVersion(authorized.absPath, stat, authorized.sourceVersion),};} catch (error) {await file.close();diff --git a/apps/desktop/src/main/device-link/fileVersion.ts b/apps/desktop/src/main/device-link/fileVersion.tsindex cfd42b45f3..40eba4ac46 100644--- a/apps/desktop/src/main/device-link/fileVersion.ts+++ b/apps/desktop/src/main/device-link/fileVersion.ts@@ -2,14 +2,14 @@ import { createHash } from 'node:crypto';import type { Stats } from 'node:fs';/** Same opened file identity in prepare/open; no raw path or stat fields cross the wire. */-export function fileVersion(absPath: string, stat: Stats, versionedCache = false): string {- // SSH cache paths already encode owner/endpoint/workdir/path + remote size/mtime.- // Those copies are immutable; local mtime/ctime are touched solely for LRU.+export function fileVersion(absPath: string, stat: Stats, sourceVersion?: string): string {+ // SSH materialization supplies the remote identity; local paths include login generation.+ // Immutable copies may move or receive LRU touches without changing their version.return createHash('sha256').update(JSON.stringify(- versionedCache- ? [absPath, stat.size]+ sourceVersion !== undefined+ ? [sourceVersion, stat.size]: [absPath, stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs],),)diff --git a/apps/desktop/src/main/device-link/mediaFetch.ts b/apps/desktop/src/main/device-link/mediaFetch.tsindex 9f26a4d525..567add273b 100644--- a/apps/desktop/src/main/device-link/mediaFetch.ts+++ b/apps/desktop/src/main/device-link/mediaFetch.ts@@ -332,6 +332,7 @@ export async function resolveAuthorizedMedia(arg: unknown, maximumBytes?: numberif (maximumBytes !== undefined)constraints.maxBytes = Math.min(constraints.maxBytes ?? maximumBytes, maximumBytes);let absPath: string;+ let sourceVersion: string | undefined;let mimeType: string | undefined;if (sshOrigin) {// SSH 分支的两道约束必须在 materialize **内部**生效:它 stat 完就会把整份文件分片拉进@@ -348,6 +349,7 @@ export async function resolveAuthorizedMedia(arg: unknown, maximumBytes?: numberthrow new Error(`SSH 媒体取回失败(${materialized.status}):${materialized.message}`);}absPath = materialized.cachePath;+ sourceVersion = materialized.sourceVersion;mimeType = materialized.mime;} else {({ absPath, mimeType } = resolveLocalMedia(url));@@ -431,7 +433,7 @@ export async function resolveAuthorizedMedia(arg: unknown, maximumBytes?: numberreturn {absPath, mimeType, uploadExtHint, maxBytes: constraints.maxBytes,// Only the authorized SSH materializer supplies immutable versioned copies.- versionedCache: sshOrigin !== null,+ sourceVersion,};}@@ -440,7 +442,7 @@ export async function fetchLocalMediaToOss(arg: unknown): Promise<MediaFetchResuarg && typeof arg === 'object'? (arg as { url?: unknown; skipCache?: unknown; thumbnail?: unknown; prepareOnly?: unknown }): {};- const { absPath, mimeType, uploadExtHint, maxBytes, versionedCache } = await resolveAuthorizedMedia(arg);+ const { absPath, mimeType, uploadExtHint, maxBytes, sourceVersion } = await resolveAuthorizedMedia(arg);const url = record.url as string;const sharedTask = getDeviceLinkInvokeContext()?.sharedTask;const mediaScope = sharedTask?.author.sharedTaskId ?? sharedTaskMediaId();@@ -455,7 +457,7 @@ export async function fetchLocalMediaToOss(arg: unknown): Promise<MediaFetchResuconst result = {ossKey: '',size: before.size,- version: fileVersion(absPath, before, versionedCache),+ version: fileVersion(absPath, before, sourceVersion),mimeType:mimeType ??mimeOf((uploadExtHint ?? path.extname(absPath)).replace(/^\./, '').toLowerCase()),@@ -473,7 +475,7 @@ export async function fetchLocalMediaToOss(arg: unknown): Promise<MediaFetchResuoffset += read.bytesRead;}const after = await file.stat();- if (fileVersion(absPath, after, versionedCache) !== result.version)+ if (fileVersion(absPath, after, sourceVersion) !== result.version)throw new Error('REMOTE_FILE_CHANGED');log.debug(`media:fetch prepare → inline size=${before.size} mime=${result.mimeType}`);return { ...result, inlineBase64: bytes.toString('base64') };diff --git a/apps/desktop/src/main/file-browser/__tests__/sshMedia.test.ts b/apps/desktop/src/main/file-browser/__tests__/sshMedia.test.tsindex 802bcce9e0..987fd443ef 100644--- a/apps/desktop/src/main/file-browser/__tests__/sshMedia.test.ts+++ b/apps/desktop/src/main/file-browser/__tests__/sshMedia.test.ts@@ -100,6 +100,37 @@ describe('serveSshRemoteMedia', () => {};}+ it('versions remote identity independently of the materialized cache location', async () => {+ let cachePath = '/cache/generation-1/a.png';+ let size = 4;+ let mtimeMs = 1;+ const deps = makeDeps({+ request: vi.fn(async () => ({ type: 'file', size, mtimeMs })) as unknown as SshMediaDeps['request'],+ fetchToCache: vi.fn(async () => cachePath),+ });+ const version = async (host = 'host-1', workdir = '/home/u/proj', rel = 'a.png') => {+ const result = await materializeSshRemoteMedia(+ { remoteHostId: host, workdir },+ `xdt-file://local/?path=${encodeURIComponent(`${workdir}/${rel}`)}`,+ deps,+ );+ if (!result.ok) throw new Error(result.message);+ expect(result.sourceVersion).toMatch(/^[a-f0-9]{64}$/);+ return result.sourceVersion;+ };+ const first = await version();+ cachePath = '/cache/generation-2/a.png';+ expect(await version()).toBe(first);+ expect(await version('host-2')).not.toBe(first);+ expect(await version('host-1', '/other')).not.toBe(first);+ expect(await version('host-1', '/home/u/proj', 'b.png')).not.toBe(first);+ mtimeMs++;+ expect(await version()).not.toBe(first);+ mtimeMs--;+ size++;+ expect(await version()).not.toBe(first);+ });+it('无路径语义(cache-id / 非 path scheme)→ 400,不触上游', async () => {const deps = makeDeps();const r = await serveSshRemoteMedia(origin, 'xdt-image://sess/a.png', null, deps);@@ -170,6 +201,7 @@ describe('serveSshRemoteMedia', () => {expect(result).toEqual({ok: true,cachePath: path.join(tmpDir, 'cached.png'),+ sourceVersion: expect.stringMatching(/^[a-f0-9]{64}$/),size: 4,mime: 'image/png',relPath: 'out/a.png',diff --git a/apps/desktop/src/main/file-browser/ssh-media.ts b/apps/desktop/src/main/file-browser/ssh-media.tsindex c88bb6eb2d..bec1b6702f 100644--- a/apps/desktop/src/main/file-browser/ssh-media.ts+++ b/apps/desktop/src/main/file-browser/ssh-media.ts@@ -20,6 +20,7 @@* electron;生产默认走 RemoteFileBrowserManager 单例(getRemoteFileBrowser)。*/+import { createHash } from 'node:crypto';import { createReadStream, promises as fsPromises } from 'node:fs';import path from 'node:path';import { Readable } from 'node:stream';@@ -50,6 +51,7 @@ export type MaterializedSshRemoteMedia =| {ok: true;cachePath: string;+ sourceVersion: string;size: number;mime: string;relPath: string;@@ -285,7 +287,14 @@ export async function materializeSshRemoteMedia(makeSshChunkExecutor(deps.request, origin.remoteHostId, origin.workdir, relPath),noopProgress,);- return { ok: true, cachePath, size: stat.size, mime, relPath };+ // Source identity belongs to the remote file, not the generation-scoped local copy.+ // Consumers already isolate their persistent cache by stable account and device.+ const sourceVersion = createHash('sha256')+ .update(+ JSON.stringify(['ssh', origin.remoteHostId, origin.workdir, relPath, stat.size, stat.mtimeMs]),+ )+ .digest('hex');+ return { ok: true, cachePath, sourceVersion, size: stat.size, mime, relPath };} catch (err) {log.warn('ssh remote media fetch failed', { relPath, error: String(err) });return { ok: false, status: 502, message: 'SSH 远程媒体取回失败' };diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 5b1f2d4f02..6580911c9f 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -797,7 +797,10 @@ Desktop 显式断链、账号变化、共享连接离线,以及 Mobile 退后`device-link:media:fetch` 的 `prepareOnly` 结果和文件 `open` 结果追加可选 `version`(64 位十六进制摘要)。Host 每次先走原授权解析,再从打开的文件句柄取-dev/ino/size/mtime/ctime,连同解析后的路径生成不透明版本;不把版本当作授权凭据。+dev/ino/size/mtime/ctime,连同解析后的路径生成不透明版本。SSH 的不可变本地副本+例外:由 materializer 用远端主机、工作目录、相对路径及远端 size/mtime 生成源版本,+prepare/open 复用该源版本并校验副本大小,不使用带登录代次的本地路径或 LRU 时间。+缓存仍按稳定账号隔离,原有代次取消校验保留;不把版本当作授权凭据。新版控制端只有两次版本一致且传输成功才保留私有缓存副本;读取缓存前仍执行prepare 授权与版本查询。缺失/非法版本的旧端不启用此缓存,旧控制端忽略新增字段。缓存按稳定账号、目标设备、完整媒体 URL 隔离(含 SSH 与目录约束),跨重启保留,