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(task-copy): 被控端按动作级预算等待统计,打包遍历按剩余额度执行文件数上限

Dash8e0810c44312
diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts
index ed48448c92..99ea2c8d06 100644
--- a/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts
@@ -20,6 +20,8 @@ import {
DL_SUBSCRIBE_CHANNEL,
INVOKE_TIMEOUT_OVERRIDES_MS,
PROTOCOL_VERSION,
+ TASK_MIGRATION_CHANNEL,
+ TASK_MIGRATION_ESTIMATE_TIMEOUT_MS,
type Envelope,
} from '@cindy/device-link';
@@ -673,6 +675,15 @@ describe('[5] orphan 截止时间按 channel 收窄', () => {
compactBudget * 2,
);
});
+
+ it('按与控制端相同的动作级预算给任务复制统计留足时间', () => {
+ const orphan = (action: string) =>
+ __testing.remoteInvokeOrphanTimeoutForChannelMs(TASK_MIGRATION_CHANNEL, [
+ { action, sessionId: 's' },
+ ]);
+ expect(orphan('estimate')).toBe(TASK_MIGRATION_ESTIMATE_TIMEOUT_MS * 2);
+ expect(orphan('status')).toBe(60_000);
+ });
});
describe('[6] active controller 生命周期与故障半径', () => {
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 6b8696e9f9..6ec5dc7675 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -36,6 +36,7 @@ import {
canCoalesceRemoteListing,
isCompletedInvokeRetryableReadChannel,
INVOKE_TIMEOUT_OVERRIDES_MS,
+ resolveRemoteInvokeTimeoutMs,
MAX_FRAME_BYTES,
PROTOCOL_VERSION,
REMOTE_INVOKE_ALLOWLIST,
@@ -769,9 +770,12 @@ const REMOTE_INVOKE_ORPHAN_TIMEOUT_MS = REMOTE_INVOKE_MAX_CLIENT_WAIT_MS * 2;
* 默认 30s handler 都会占满 controller 的 in-flight 配额整整 22 分钟,后续远程控制
* 动作看起来卡住(BACKPRESSURE)。
*/
-function remoteInvokeOrphanTimeoutMs(channel: string | undefined): number {
+function remoteInvokeOrphanTimeoutMs(channel: string | undefined, args?: unknown[]): number {
+ // Same resolver as the desktop controller, so action-specific budgets (task copy
+ // estimate/receive) are honoured here too instead of the channel default.
const budgetMs =
- (channel && INVOKE_TIMEOUT_OVERRIDES_MS[channel]) || DEFAULT_REMOTE_INVOKE_CLIENT_WAIT_MS;
+ (channel && resolveRemoteInvokeTimeoutMs(channel, args, 'desktop')) ||
+ DEFAULT_REMOTE_INVOKE_CLIENT_WAIT_MS;
return Math.min(budgetMs * 2, REMOTE_INVOKE_ORPHAN_TIMEOUT_MS);
}
interface CachedRemoteInvokeResult {
@@ -2721,6 +2725,7 @@ async function handleInvoke(
executionPromise,
src,
payload?.channel,
+ payload?.args,
).finally(releaseBusyLease);
const inFlightEntry = {
promise: resultPromise,
@@ -2777,9 +2782,10 @@ function settleRemoteInvokeWithOrphanDeadline(
execution: Promise<InvokeResultPayload>,
src: string,
channel: string | undefined,
+ args?: unknown[],
): Promise<InvokeResultPayload> {
let timer: ReturnType<typeof setTimeout> | null = null;
- const orphanMs = remoteInvokeOrphanTimeoutMs(channel);
+ const orphanMs = remoteInvokeOrphanTimeoutMs(channel, args);
const timeout = new Promise<InvokeResultPayload>((resolve) => {
timer = setTimeout(() => {
timer = null;
diff --git a/apps/desktop/src/main/task-migration/__tests__/service.test.ts b/apps/desktop/src/main/task-migration/__tests__/service.test.ts
index 7a6e67e6fa..0b32399654 100644
--- a/apps/desktop/src/main/task-migration/__tests__/service.test.ts
+++ b/apps/desktop/src/main/task-migration/__tests__/service.test.ts
@@ -216,11 +216,18 @@ vi.mock('../workspace', async (original) => ({
if (state.tooManyFiles) throw new Error('MIGRATION_TOO_MANY_FILES');
return { fileCount: 1, bytes: 8 };
},
- snapshotWorkspace: async (source: string, directory: string) => {
- state.snapshot();
+ snapshotWorkspace: async (source: string, directory: string, _id: string, maxFiles: number) => {
+ state.snapshot(maxFiles);
await fs.mkdir(directory, { recursive: true });
await fs.copyFile(path.join(source, 'draft'), path.join(directory, 'a.tar.gz.enc'));
- return { unpackedBytes: 8, archive: { file: 'a.tar.gz.enc', files: {} } };
+ const file = { kind: 'file', mode: 0o644, hash: 'a'.repeat(64) };
+ return {
+ unpackedBytes: 8,
+ archive: {
+ file: 'a.tar.gz.enc',
+ files: { dir: { kind: 'directory', mode: 0o755, hash: '' }, 'dir/a': file, b: file },
+ },
+ };
},
restoreWorkspace: async (_manifest: unknown, directory: string, target: string) => {
await fs.copyFile(path.join(directory, 'a.tar.gz.enc'), path.join(target, 'draft'));
@@ -496,6 +503,16 @@ describe('resumable cross-computer copy', () => {
expect(receipt().workingDir).not.toBe(firstDir);
expect(receipt().workingDir).not.toBe(secondDir);
});
+ it('hands each team snapshot only the file allowance the earlier ones left', async () => {
+ await team();
+ await start();
+ expect((await settled()).stage).toBe('complete');
+ // Two files per mocked snapshot; directories do not count toward the cap.
+ expect(state.snapshot.mock.calls).toEqual([
+ [TASK_MIGRATION_MAX_FILES],
+ [TASK_MIGRATION_MAX_FILES - 2],
+ ]);
+ });
it('estimates each physical team workspace once without exporting or uploading', async () => {
await team();
const result = await requestTaskMigration({ action: 'estimate', sessionId: 'fork' });
diff --git a/apps/desktop/src/main/task-migration/__tests__/workspace.git-integration.test.ts b/apps/desktop/src/main/task-migration/__tests__/workspace.git-integration.test.ts
index 4825cd33e3..0eca265ef6 100644
--- a/apps/desktop/src/main/task-migration/__tests__/workspace.git-integration.test.ts
+++ b/apps/desktop/src/main/task-migration/__tests__/workspace.git-integration.test.ts
@@ -138,6 +138,16 @@ describe('cross-machine project snapshots', () => {
expect(await inventoryWorktree(target)).toEqual(before);
expect(Object.keys(before)).toContain(path.join('.cindy-worktrees', 'notes'));
});
+ it('stops the snapshot walk once the file allowance is exceeded', async () => {
+ await fs.mkdir(path.join(source, 'sub'));
+ for (const name of ['a', 'b', path.join('sub', 'c')])
+ await fs.writeFile(path.join(source, name), name);
+ await expect(snapshotWorkspace(source, artifacts, randomUUID(), 2)).rejects.toThrow(
+ 'MIGRATION_TOO_MANY_FILES',
+ );
+ const snapshot = await snapshotWorkspace(source, artifacts, randomUUID(), 3);
+ expect(Object.keys(snapshot.archive.files).sort()).toEqual(['a', 'b', 'sub', 'sub/c']);
+ });
it('refuses to overwrite a destination directory', async () => {
await fs.writeFile(path.join(source, 'source'), 'copy');
const snapshot = await snapshotWorkspace(source, artifacts, randomUUID());
diff --git a/apps/desktop/src/main/task-migration/service.ts b/apps/desktop/src/main/task-migration/service.ts
index 62a0621962..5afb01abfa 100644
--- a/apps/desktop/src/main/task-migration/service.ts
+++ b/apps/desktop/src/main/task-migration/service.ts
@@ -341,10 +341,20 @@ async function prepare(scope: Scope, record: MigrationHandoff) {
if (result.status !== 'ok' || result.fidelity !== 'full' || result.mediaMissing)
throw new Error('MIGRATION_INCOMPLETE_CONTEXT');
const snapshots: PortableWorkspace[] = [];
- for (const [index, dir] of sourceKeys.entries())
- snapshots.push(
- await snapshotWorkspace(dir, workspaceDirectory(directory, index), record.id),
+ // Files can still appear after the re-check above; bound the snapshot walk itself too.
+ let remainingFiles = TASK_MIGRATION_MAX_FILES;
+ for (const [index, dir] of sourceKeys.entries()) {
+ const snapshot = await snapshotWorkspace(
+ dir,
+ workspaceDirectory(directory, index),
+ record.id,
+ remainingFiles,
);
+ remainingFiles -= Object.values(snapshot.archive.files).filter(
+ (entry) => entry.kind !== 'directory',
+ ).length;
+ snapshots.push(snapshot);
+ }
// Copy does not freeze input. Discard preparation if the task or team changed
// while capturing conversation and files, including a turn that already finished.
await sourceBoundary!.drain();
diff --git a/apps/desktop/src/main/task-migration/workspace.ts b/apps/desktop/src/main/task-migration/workspace.ts
index c5ced98535..36cf791983 100644
--- a/apps/desktop/src/main/task-migration/workspace.ts
+++ b/apps/desktop/src/main/task-migration/workspace.ts
@@ -121,6 +121,7 @@ export async function snapshotWorkspace(
root: string,
directory: string,
id: string,
+ maxFiles?: number,
): Promise<PortableWorkspace> {
if ((await fs.lstat(root)).isSymbolicLink()) root = await fs.realpath(root);
await fs.mkdir(directory, { recursive: true, mode: 0o700 });
@@ -171,6 +172,7 @@ export async function snapshotWorkspace(
maxBytes: Math.floor((space.bavail * space.bsize) / 1.1),
// `git` is set exactly when the probe above found `root` to be a repository root.
excludeRootNames: git ? [...MANAGED_WORKTREE_DIR_NAMES] : [],
+ maxFiles,
});
archive.files = Object.fromEntries(
Object.entries(archive.files).map(([name, entry]) => [name.split(path.sep).join('/'), entry]),
diff --git a/apps/desktop/src/main/worktree/recoveryArchiveIO.ts b/apps/desktop/src/main/worktree/recoveryArchiveIO.ts
index 3cfd1188a9..a0e18fc96e 100644
--- a/apps/desktop/src/main/worktree/recoveryArchiveIO.ts
+++ b/apps/desktop/src/main/worktree/recoveryArchiveIO.ts
@@ -25,10 +25,12 @@ function restorableMode(mode: number): number {
return mode & (process.platform === 'win32' ? 0o666 : 0o777);
}
-/** `excludeRootNames` skips top-level directories (never files) — task copy leaves other tasks' worktrees behind. */
-export async function inventoryWorktree(root: string, maxBytes?: number, excludeRootNames: readonly string[] = []): Promise<Record<string, FileEvidence>> {
+/** `excludeRootNames` skips top-level directories (never files) — task copy leaves other tasks' worktrees behind.
+ * `maxFiles` bounds files plus links, stopping the walk as soon as it is exceeded. */
+export async function inventoryWorktree(root: string, maxBytes?: number, excludeRootNames: readonly string[] = [], maxFiles?: number): Promise<Record<string, FileEvidence>> {
const files: Record<string, FileEvidence> = Object.create(null);
let bytes = 0;
+ let count = 0;
const walk = async (directory: string): Promise<void> => {
for (const name of await fs.readdir(directory)) {
if (directory === root && name === '.git') continue;
@@ -37,6 +39,7 @@ export async function inventoryWorktree(root: string, maxBytes?: number, exclude
if (directory === root && stat.isDirectory() && excludeRootNames.includes(name)) continue;
const relative = path.relative(root, absolute);
const mode = restorableMode(stat.mode);
+ if (!stat.isDirectory() && maxFiles !== undefined && ++count > maxFiles) throw new Error('MIGRATION_TOO_MANY_FILES');
if (stat.isSymbolicLink()) {
files[relative] = { kind: 'link', hash: await fs.readlink(absolute), mode };
} else if (stat.isDirectory()) {
@@ -130,8 +133,8 @@ export async function verifyRecoveryArchive(archive: WorktreeRecoveryArchive, di
if (!sameWorktreeFiles(files, archive.files)) throw new Error('archive content does not match worktree inventory');
}
-export async function createRecoveryArchive(root: string, resourceId: string, directory: string, key: Uint8Array, encryptedKey: string, iv: Uint8Array, maxBytes?: number, excludeRootNames: readonly string[] = []): Promise<WorktreeRecoveryArchive> {
- const files = await inventoryWorktree(root, maxBytes, excludeRootNames);
+export async function createRecoveryArchive(root: string, resourceId: string, directory: string, key: Uint8Array, encryptedKey: string, iv: Uint8Array, maxBytes?: number, excludeRootNames: readonly string[] = [], maxFiles?: number): Promise<WorktreeRecoveryArchive> {
+ const files = await inventoryWorktree(root, maxBytes, excludeRootNames, maxFiles);
const cipher = createCipheriv('aes-256-gcm', key, iv);
const file = `${resourceId}-${randomUUID()}.tar.gz.enc`;
await fs.mkdir(directory, { recursive: true });
diff --git a/apps/desktop/src/main/worktree/recoveryArchiveTask.ts b/apps/desktop/src/main/worktree/recoveryArchiveTask.ts
index a0a8d1444d..d7d3897c64 100644
--- a/apps/desktop/src/main/worktree/recoveryArchiveTask.ts
+++ b/apps/desktop/src/main/worktree/recoveryArchiveTask.ts
@@ -4,7 +4,7 @@ import type { FileEvidence, WorktreeRecoveryArchive } from './recoveryArchiveIO'
type ArchiveInput = { archive: WorktreeRecoveryArchive; directory: string; key: Uint8Array; maxBytes?: number };
export type RecoveryArchiveTask =
| { operation: 'inventory'; root: string }
- | { operation: 'create'; root: string; resourceId: string; directory: string; key: Uint8Array; encryptedKey: string; iv: Uint8Array; maxBytes?: number; excludeRootNames?: string[] }
+ | { operation: 'create'; root: string; resourceId: string; directory: string; key: Uint8Array; encryptedKey: string; iv: Uint8Array; maxBytes?: number; excludeRootNames?: string[]; maxFiles?: number }
| ({ operation: 'verify' } & ArchiveInput)
| ({ operation: 'extract'; staging: string; keep: boolean } & ArchiveInput);
export type RecoveryArchiveResult<T extends RecoveryArchiveTask> =
@@ -16,7 +16,7 @@ export async function executeRecoveryArchiveTask(task: RecoveryArchiveTask) {
try {
switch (task.operation) {
case 'inventory': return await io.inventoryWorktree(task.root);
- case 'create': return await io.createRecoveryArchive(task.root, task.resourceId, task.directory, task.key, task.encryptedKey, task.iv, task.maxBytes, task.excludeRootNames);
+ case 'create': return await io.createRecoveryArchive(task.root, task.resourceId, task.directory, task.key, task.encryptedKey, task.iv, task.maxBytes, task.excludeRootNames, task.maxFiles);
case 'verify': return await io.verifyRecoveryArchive(task.archive, task.directory, task.key, task.maxBytes);
case 'extract': return await io.extractRecoveryArchive(task.archive, task.staging, task.keep, task.directory, task.key, task.maxBytes);
}