Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(files): 保持 SSH 缓存版本不受 LRU 时间刷新影响

Dashba653af85f0a
diff --git a/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts b/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts
index 2f31178b8d..e1b6deeba6 100644
--- a/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts
@@ -343,7 +343,7 @@ describe('authorized file peer source', () => {
action: 'open',
connection,
url: 'xdt-file://local/?path=/test',
- })) as { ticket: string; size: number };
+ })) as { ticket: string; size: number; version: string };
}
const read = (connection: string, ticket: string, offset: number) =>
mock.handlers.get('file-peer:host:read')!({}, connection, ticket, offset);
@@ -892,6 +892,24 @@ describe('authorized file peer source', () => {
await expect(read(connection, ticket, 0)).rejects.toThrow('CHANGED');
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 });
+ const { connection } = await connect();
+ const first = await open(connection);
+ await fsPromises.utimes(file, new Date(1_000), new Date(1_000));
+ if (!versionedCache) {
+ await expect(read(connection, first.ticket, 0)).rejects.toThrow('CHANGED');
+ return;
+ }
+ expect(await read(connection, first.ticket, 0)).toBe(Buffer.from('hello').toString('base64'));
+ await fsPromises.utimes(file, new Date(2_000), new Date(2_000));
+ expect(await read(connection, first.ticket, 5)).toBe('');
+ const second = await open(connection);
+ expect(second.version).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');
+ });
it('rejects revoked or old-owner chunks without affecting a second peer', async () => {
const a = await connect(),
b = await connect('device-b');
diff --git a/apps/desktop/src/main/device-link/__tests__/mediaFetch.test.ts b/apps/desktop/src/main/device-link/__tests__/mediaFetch.test.ts
index 9df977ca80..7b672eea4e 100644
--- a/apps/desktop/src/main/device-link/__tests__/mediaFetch.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/mediaFetch.test.ts
@@ -182,6 +182,25 @@ 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) => {
+ let clock = 1;
+ let cachePath = path.join(os.tmpdir(), 'ssh-version-a.png');
+ materializeSshRemoteMedia.mockImplementation(async () => ({
+ ok: true, cachePath, size, mime: 'image/png', relPath: 'artifacts/plot.png',
+ }));
+ openMock.mockResolvedValue({
+ stat: async () => ({ isFile: () => true, size, mtimeMs: clock++, ctimeMs: clock++, ino: 1, dev: 1 }),
+ read: async (bytes: Buffer) => { bytes.fill(7); return { bytesRead: bytes.length }; },
+ close: vi.fn(),
+ });
+ const args = { url: 'xdt-file://open?path=%2Fhome%2Fu%2Fproj%2Fartifacts%2Fplot.png&sessionId=session-ssh&remoteHostId=host-1&workdir=%2Fhome%2Fu%2Fproj', prepareOnly: true };
+ const first = await fetchLocalMediaToOss(args);
+ 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).not.toBe(first.version);
+ });
+
it('xdt-video:// → videoCacheStore.resolveSafe', async () => {
videoResolve.mockReturnValue({ absPath: '/cache/v.mp4', mimeType: 'video/mp4' });
const r = await fetchLocalMediaToOss({ url: 'xdt-video://sess/v.mp4' });
diff --git a/apps/desktop/src/main/device-link/filePeer.ts b/apps/desktop/src/main/device-link/filePeer.ts
index f2e278057d..b13de623b6 100644
--- a/apps/desktop/src/main/device-link/filePeer.ts
+++ b/apps/desktop/src/main/device-link/filePeer.ts
@@ -64,6 +64,7 @@ interface Source {
size: number;
mtime: number;
ctime: number;
+ versionedCache: boolean;
offset: number;
busy: boolean;
openedAt: number;
@@ -516,6 +517,7 @@ async function handleFilePeerRequest(
size: stat.size,
mtime: stat.mtimeMs,
ctime: stat.ctimeMs,
+ versionedCache: authorized.versionedCache,
offset: 0,
busy: false,
openedAt: Date.now(),
@@ -523,7 +525,10 @@ async function handleFilePeerRequest(
sources.set(ticket, source);
touch(r.connection);
monitorSend(ticket, source);
- return { ticket, size: stat.size, mimeType, version: fileVersion(authorized.absPath, stat) };
+ return {
+ ticket, size: stat.size, mimeType,
+ version: fileVersion(authorized.absPath, stat, authorized.versionedCache),
+ };
} catch (error) {
await file.close();
throw error;
@@ -616,7 +621,11 @@ export function registerFilePeerIpc() {
s.busy = true;
try {
const stat = await s.file.stat();
- if (stat.size !== s.size || stat.mtimeMs !== s.mtime || stat.ctimeMs !== s.ctime) throw new Error('FILE_PEER_CHANGED');
+ // SSH versioned copies can be LRU-touched by another preview while open.
+ if (
+ stat.size !== s.size ||
+ (!s.versionedCache && (stat.mtimeMs !== s.mtime || stat.ctimeMs !== s.ctime))
+ ) throw new Error('FILE_PEER_CHANGED');
const bytes = Buffer.alloc(Math.min(FILE_PEER_CHUNK_BYTES, s.size - s.offset));
if (bytes.length) {
const read = await s.file.read(bytes, 0, bytes.length, s.offset);
diff --git a/apps/desktop/src/main/device-link/fileVersion.ts b/apps/desktop/src/main/device-link/fileVersion.ts
index 4b7d56c115..cfd42b45f3 100644
--- a/apps/desktop/src/main/device-link/fileVersion.ts
+++ b/apps/desktop/src/main/device-link/fileVersion.ts
@@ -2,8 +2,16 @@ 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): string {
+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.
return createHash('sha256')
- .update(JSON.stringify([absPath, stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs]))
+ .update(
+ JSON.stringify(
+ versionedCache
+ ? [absPath, stat.size]
+ : [absPath, stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs],
+ ),
+ )
.digest('hex');
}
diff --git a/apps/desktop/src/main/device-link/mediaFetch.ts b/apps/desktop/src/main/device-link/mediaFetch.ts
index 0f7336ce3f..9f26a4d525 100644
--- a/apps/desktop/src/main/device-link/mediaFetch.ts
+++ b/apps/desktop/src/main/device-link/mediaFetch.ts
@@ -428,7 +428,11 @@ export async function resolveAuthorizedMedia(arg: unknown, maximumBytes?: number
}
}
- return { absPath, mimeType, uploadExtHint, maxBytes: constraints.maxBytes };
+ return {
+ absPath, mimeType, uploadExtHint, maxBytes: constraints.maxBytes,
+ // Only the authorized SSH materializer supplies immutable versioned copies.
+ versionedCache: sshOrigin !== null,
+ };
}
export async function fetchLocalMediaToOss(arg: unknown): Promise<MediaFetchResult> {
@@ -436,7 +440,7 @@ export async function fetchLocalMediaToOss(arg: unknown): Promise<MediaFetchResu
arg && typeof arg === 'object'
? (arg as { url?: unknown; skipCache?: unknown; thumbnail?: unknown; prepareOnly?: unknown })
: {};
- const { absPath, mimeType, uploadExtHint, maxBytes } = await resolveAuthorizedMedia(arg);
+ const { absPath, mimeType, uploadExtHint, maxBytes, versionedCache } = await resolveAuthorizedMedia(arg);
const url = record.url as string;
const sharedTask = getDeviceLinkInvokeContext()?.sharedTask;
const mediaScope = sharedTask?.author.sharedTaskId ?? sharedTaskMediaId();
@@ -451,7 +455,7 @@ export async function fetchLocalMediaToOss(arg: unknown): Promise<MediaFetchResu
const result = {
ossKey: '',
size: before.size,
- version: fileVersion(absPath, before),
+ version: fileVersion(absPath, before, versionedCache),
mimeType:
mimeType ??
mimeOf((uploadExtHint ?? path.extname(absPath)).replace(/^\./, '').toLowerCase()),
@@ -469,7 +473,7 @@ export async function fetchLocalMediaToOss(arg: unknown): Promise<MediaFetchResu
offset += read.bytesRead;
}
const after = await file.stat();
- if (after.size !== before.size || after.mtimeMs !== before.mtimeMs)
+ if (fileVersion(absPath, after, versionedCache) !== 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') };