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(desktop): 分离拉取缓存配额并保留失败轮询句柄

DavidShen5db9be88d526
diff --git a/apps/desktop/src/main/worktree/__tests__/branchSyncHandlers.test.ts b/apps/desktop/src/main/worktree/__tests__/branchSyncHandlers.test.ts
index 131dc6005c..373cb08f96 100644
--- a/apps/desktop/src/main/worktree/__tests__/branchSyncHandlers.test.ts
+++ b/apps/desktop/src/main/worktree/__tests__/branchSyncHandlers.test.ts
@@ -127,3 +127,45 @@ it('retains a sanitized failure for continuations without unhandled rejections o
expect(calls.sync).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(5 * 60_000);
});
+
+// PR #7464: completed results consumed the active-operation quota. Unit tier:
+// keep one real handler operation pending while 65 others finish (including
+// failures); completed cache pressure must neither block starts nor evict it.
+it('does not let retained terminal results block new work or evict an active operation', async () => {
+ vi.useFakeTimers();
+ let finish!: (value: { updated: number }) => void;
+ calls.sync.mockReturnValueOnce(new Promise((resolve) => { finish = resolve; }));
+ const waiting = handlers.sync({}, { ...req, waitForResult: true });
+ await vi.advanceTimersByTimeAsync(10_000);
+ const pending = await waiting;
+ if (!('operationId' in pending)) throw new Error('expected continuation');
+ for (let i = 0; i < 65; i++) {
+ if (i % 2) {
+ calls.sync.mockRejectedValueOnce(new Error('failed'));
+ await expect(handlers.sync({}, { ...req, waitForResult: true })).rejects.toThrow('branch-sync:git');
+ } else {
+ calls.sync.mockResolvedValueOnce({ updated: 1 });
+ expect(await handlers.sync({}, { ...req, waitForResult: true })).toEqual({ updated: 1 });
+ }
+ }
+ finish({ updated: 3 });
+ expect(await handlers.sync({}, { ...req, waitForResult: true, operationId: pending.operationId })).toEqual({ updated: 3 });
+ expect(calls.sync).toHaveBeenCalledTimes(66);
+ expect(vi.getTimerCount()).toBe(64);
+ await vi.advanceTimersByTimeAsync(5 * 60_000);
+ expect(vi.getTimerCount()).toBe(0);
+});
+
+it('still bounds active work and releases its quota when the operations finish', async () => {
+ vi.useFakeTimers();
+ let finish!: (value: { updated: number }) => void;
+ calls.sync.mockReturnValue(new Promise((resolve) => { finish = resolve; }));
+ const requests = Array.from({ length: 64 }, () => handlers.sync({}, { ...req, waitForResult: true }));
+ expect(() => handlers.sync({}, { ...req, waitForResult: true })).toThrow('branch-sync:busy');
+ finish({ updated: 1 });
+ await Promise.all(requests);
+ expect(await handlers.sync({}, { ...req, waitForResult: true })).toEqual({ updated: 1 });
+ expect(calls.sync).toHaveBeenCalledTimes(65);
+ await vi.advanceTimersByTimeAsync(5 * 60_000);
+ expect(vi.getTimerCount()).toBe(0);
+});
diff --git a/apps/desktop/src/main/worktree/branchSyncHandlers.ts b/apps/desktop/src/main/worktree/branchSyncHandlers.ts
index 47b62aecce..a17d5df8f8 100644
--- a/apps/desktop/src/main/worktree/branchSyncHandlers.ts
+++ b/apps/desktop/src/main/worktree/branchSyncHandlers.ts
@@ -26,6 +26,13 @@ export function createBranchSyncHandlers<Event>(deps: {
outcome: Promise<Outcome>;
}
>();
+ let activeOperations = 0;
+ const completed = new Map<string, ReturnType<typeof setTimeout>>();
+ function forgetCompleted(id: string) {
+ clearTimeout(completed.get(id));
+ completed.delete(id);
+ operations.delete(id);
+ }
// Each poll fits inside the existing invoke budget. Only the initial request
// starts work; lost replies, changed peers and expired tokens never replay it.
@@ -116,7 +123,8 @@ export function createBranchSyncHandlers<Event>(deps: {
)
throwIpcError('INTERNAL', BRANCH_SYNC_ERROR_PREFIX + 'changed');
} else {
- if (operations.size >= 64) throwIpcError('INTERNAL', BRANCH_SYNC_ERROR_PREFIX + 'busy');
+ if (activeOperations >= 64) throwIpcError('INTERNAL', BRANCH_SYNC_ERROR_PREFIX + 'busy');
+ activeOperations += 1;
operationId = randomUUID();
const id = operationId;
const outcome: Promise<Outcome> = Promise.resolve()
@@ -129,7 +137,13 @@ export function createBranchSyncHandlers<Event>(deps: {
// Retain terminal outcomes briefly for a delayed continuation. Running
// downloads are bounded by Git inactivity, not by polling wall time.
void outcome.then(() => {
- setTimeout(() => operations.delete(id), 5 * 60_000).unref?.();
+ activeOperations -= 1;
+ const timer = setTimeout(() => forgetCompleted(id), 5 * 60_000);
+ timer.unref?.();
+ completed.set(id, timer);
+ // Bound retained outcomes independently; never evict active work or
+ // reject a new fetch just because earlier fetches completed quickly.
+ if (completed.size > 64) forgetCompleted(completed.keys().next().value!);
});
}
return wait(operationId);
diff --git a/apps/desktop/src/renderer/components/new-chat/__tests__/BranchWorktreeChip.test.tsx b/apps/desktop/src/renderer/components/new-chat/__tests__/BranchWorktreeChip.test.tsx
index 48566cb997..5d563368d4 100644
--- a/apps/desktop/src/renderer/components/new-chat/__tests__/BranchWorktreeChip.test.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/__tests__/BranchWorktreeChip.test.tsx
@@ -99,6 +99,36 @@ it('continues waiting for the same remote fetch and shows its final result', asy
expect(mocks.toast).not.toHaveBeenCalled();
});
+// PR #7464: a transport rejection used to lose the operation handle. Drive the
+// real component through a failed continuation and an explicit retry; terminal
+// failures must instead release the handle so a later click can start new work.
+it.each(['transport', 'terminal', 'selection-change'] as const)('retries after a %s failure with the correct operation identity', async (failure) => {
+ const operationId = '8a7768e7-e652-4458-9c15-96af310bc9cb';
+ let polls = 0;
+ invoke.mockImplementation(async (_device, channel) => {
+ if (channel !== 'worktree:sync-branch') return baseStatus;
+ if (++polls === 1) return { pending: true, operationId };
+ if (polls === 2) throw new Error(failure === 'terminal' ? 'branch-sync:changed' : 'connection lost');
+ return { status: baseStatus, updated: 3 };
+ });
+ const view = render(<BranchWorktreeChip {...props} deviceId="remote-a" />);
+ fireEvent.click(await screen.findByRole('button', { name: /newChat.branchSync.action/ }));
+ let retry = await screen.findByRole('button', { name: /newChat.branchSync.failed/ });
+ expect(polls).toBe(2);
+ if (failure === 'selection-change') {
+ view.rerender(<BranchWorktreeChip {...props} branchLabel="next" deviceId="remote-a" />);
+ retry = await screen.findByRole('button', { name: /newChat.branchSync.action/ });
+ }
+ fireEvent.click(retry);
+ await screen.findByRole('button', { name: /newChat.branchSync.updated/ });
+ expect(invoke.mock.calls.filter((call) => call[1] === 'worktree:sync-branch')[2][2]).toEqual([
+ { baseRepo: '/repo', branch: failure === 'selection-change' ? 'next' : 'main', waitForResult: true, ...(failure === 'transport' ? { operationId } : {}) },
+ ]);
+ fireEvent.click(screen.getByRole('button', { name: /newChat.branchSync.updated/ }));
+ await waitFor(() => expect(polls).toBe(4));
+ expect(invoke.mock.calls.filter((call) => call[1] === 'worktree:sync-branch')[3][2][0]).not.toHaveProperty('operationId');
+});
+
it('shares counts with the selected row and keeps full remote refs distinct during keyboard search', async () => {
render(<BranchWorktreeChip {...props} />);
await waitFor(() => expect(status).toHaveBeenCalledOnce());
diff --git a/apps/desktop/src/renderer/hooks/useBranchSync.ts b/apps/desktop/src/renderer/hooks/useBranchSync.ts
index b9a44fcff4..a6fda67de1 100644
--- a/apps/desktop/src/renderer/hooks/useBranchSync.ts
+++ b/apps/desktop/src/renderer/hooks/useBranchSync.ts
@@ -30,6 +30,7 @@ export function useBranchSync(
}>({ key });
const request = useRef(0);
const busy = useRef(false);
+ const continuation = useRef<{ key: string; operationId: string } | undefined>(undefined);
const hoverTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const doneTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const invoke = useCallback(
@@ -90,6 +91,7 @@ export function useBranchSync(
}, [baseRepo, invoke, key, deviceId]);
useEffect(() => {
busy.current = false;
+ continuation.current = undefined;
setSnapshot({ key });
void refresh();
return () => {
@@ -110,13 +112,17 @@ export function useBranchSync(
const id = ++request.current;
setSnapshot((old) => ({ ...old, key, busy: true, error: undefined, result: undefined }));
try {
- let reply = (await invoke(true)) as BranchSyncReply;
+ let reply = (await invoke(true,
+ continuation.current?.key === key ? continuation.current.operationId : undefined,
+ )) as BranchSyncReply;
while ('pending' in reply) {
if (currentKey.current !== key || id !== request.current) return;
+ continuation.current = { key, operationId: reply.operationId };
reply = (await invoke(true, reply.operationId)) as BranchSyncReply;
}
const result = reply;
if (currentKey.current !== key || id !== request.current) return;
+ continuation.current = undefined;
if (result.status.blocked) toast.warning(blockedHint(result.status));
setSnapshot({
key,
@@ -132,6 +138,10 @@ export function useBranchSync(
if (currentKey.current !== key || id !== request.current) return;
const message =
extractIpcError(error)?.message ?? (error instanceof Error ? error.message : String(error));
+ // Host-classified failures are terminal (including expired handles).
+ // Transport errors leave the operation unknown: an explicit click resumes
+ // the same handle instead of starting another mutation.
+ if (message.startsWith(BRANCH_SYNC_ERROR_PREFIX)) continuation.current = undefined;
setSnapshot((old) => ({ ...old, busy: false, error: message }));
toast.error(
t('newChat.branchSync.failed', {
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 360a8bf74e..3169021ebf 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -75,7 +75,10 @@ refspec,再按需快进本地分支。
避免单个大对象被 `unpack-objects` 静默接收时误判停滞;不修改用户 Git 配置。
新版控制端在 `worktree:sync-branch` 请求追加可选 `waitForResult: true`,被控端至多等待
10 秒,未完成时返回 `{ pending: true, operationId }`。后续请求带同一 `operationId`,
-只等待原操作,绝不重新 fetch;句柄绑定账号代次、控制设备、仓库和分支,完成后保留 5 分钟。
+只等待原操作,绝不重新 fetch;句柄绑定账号代次、控制设备、仓库和分支。
+运行中操作上限 64 个;已完成结果独立保留最多 64 个、最长 5 分钟,超量淘汰最早完成者,
+不占用运行配额,也不淘汰运行中的操作。轮询连接错误后保留已收到的句柄,用户再次点击
+只续接原操作;收到终态、终态错误或切换选择后清除句柄,不自动重放初始写请求。
未知、过期或不匹配的句柄报 `branch-sync:changed`,不自动重新执行。每次 invoke 仍沿用
90 秒传输预算,不修改共享链路的超时、重试或恢复策略;两个控制端的句柄互不通用。
旧控制端不传新字段,新被控端仍返回原终态;新控制端连接旧被控端时接受原终态,沿用旧端