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): Git 拉取有进度时持续等待,停滞后再超时

DavidShen20ed28ba27f9
diff --git a/apps/desktop/scripts/ui-page/README.md b/apps/desktop/scripts/ui-page/README.md
index ade2ea8a6e..4e6ac31239 100644
--- a/apps/desktop/scripts/ui-page/README.md
+++ b/apps/desktop/scripts/ui-page/README.md
@@ -39,6 +39,9 @@ FAIL group-chat.no-sidebar.dark.zh-CN.1280x800
列出,可以直接比对。元素在某次截图时不存在会跳过,全程都不存在才给警告。
- 截图按 2 倍像素密度渲染(与 Retina Mac 一致,不随外接显示器变化),整页截图按 CSS
尺寸保存。
+- 后台检查使用无边框窗口,Windows 额外启用离屏渲染,避免原生边框的 DPI 取整和隐藏
+ 窗口不刷新导致尺寸偏差或截图超时;仍严格核对实际视口与目标尺寸。`ui:preview` 保留
+ 正常的可见窗口。
- 报告写到 stdout。环境里设置了 `NODE_DEBUG` 时 Node 会往 stderr 刷调试日志,用
`env -u NODE_DEBUG pnpm ui:check …` 或丢弃 stderr。
- `real` 是本页面真实加载的产品代码,`not covered` 是这些场景没有验证的行为,`replaced`
diff --git a/apps/desktop/scripts/ui-page/electron.cjs b/apps/desktop/scripts/ui-page/electron.cjs
index ae079cadca..f9e194f2bc 100644
--- a/apps/desktop/scripts/ui-page/electron.cjs
+++ b/apps/desktop/scripts/ui-page/electron.cjs
@@ -5,6 +5,7 @@ const path = require('node:path');
const profile = process.env.CINDY_UI_PROFILE;
const bundleDir = process.env.CINDY_UI_BUNDLE_DIR;
const evidenceDir = process.env.CINDY_UI_EVIDENCE_DIR;
+const preview = process.env.CINDY_UI_PREVIEW === '1';
if (![profile, bundleDir, evidenceDir].every((dir) => dir && path.isAbsolute(dir)))
throw new Error('Missing isolated UI profile, bundle or evidence directory');
// Same policy the runner sends with the page document in Chromium mode.
@@ -34,7 +35,7 @@ const types = {
'.otf': 'font/otf',
};
// Background checks must not take focus or add a Dock icon to the user's desktop.
-if (process.env.CINDY_UI_PREVIEW !== '1') app.dock?.hide();
+if (!preview) app.dock?.hide();
app.whenReady().then(() => {
const ownSession = session.fromPartition('ui-check');
ownSession.setPermissionRequestHandler((_wc, _permission, callback) => callback(false));
@@ -73,9 +74,16 @@ app.whenReady().then(() => {
width: Number(process.env.CINDY_UI_WIDTH),
height: Number(process.env.CINDY_UI_HEIGHT),
useContentSize: true,
- show: process.env.CINDY_UI_PREVIEW === '1',
+ // Native decorations round at forced 2x DPI on Windows (400 CSS px became
+ // 401). Background captures need only the content, not a platform frame.
+ frame: preview,
+ show: preview,
title: 'Cindy UI Check',
webPreferences: {
+ // A hidden native Windows window can retain its old renderer size and
+ // stop producing frames. Offscreen rendering keeps checks hidden while
+ // allowing exact resizing and screenshots without showing a native window.
+ offscreen: !preview && process.platform === 'win32',
session: ownSession,
sandbox: true,
contextIsolation: true,
diff --git a/apps/desktop/scripts/ui-page/runner.selftest.mjs b/apps/desktop/scripts/ui-page/runner.selftest.mjs
index 61c5df2b5e..4a5f1d8a88 100644
--- a/apps/desktop/scripts/ui-page/runner.selftest.mjs
+++ b/apps/desktop/scripts/ui-page/runner.selftest.mjs
@@ -117,6 +117,33 @@ mountPage({
assert.match(await readFile(summary.pr, 'utf8'), /未通过:`entry\.throws\./);
});
+// Windows regression: forced 2x DPI plus native window decorations added one
+// CSS pixel, and hidden windows could not capture a frame. Drive the real CLI
+// across sizes/themes and inspect PNG dimensions; existing failure tests do not
+// verify resizing. Dedicated Electron integration tier, not default unit tests.
+test('captures exact viewports and overviews in a hidden Electron window', async () => {
+ const file = await entry('viewport', 'mountPage({ render: () => <div>Viewport ready</div> });');
+ const { code, stdout } = await run([
+ '--entry', file, '--engine', 'electron', '--theme', 'all',
+ '--viewport', '560x400,360x640', '--json',
+ ]);
+ const summary = JSON.parse(stdout);
+ assert.equal(code, 0, JSON.stringify(summary.variants.map((v) => v.errors)));
+ assert.equal(summary.variants.length, 4);
+ for (const variant of summary.variants) {
+ assert.equal(variant.status, 'passed');
+ assert.ok(variant.screenshots.length);
+ const png = await readFile(path.join(summary.evidence, variant.screenshots[0]));
+ assert.deepEqual(
+ { width: png.readUInt32BE(16), height: png.readUInt32BE(20) },
+ variant.viewport,
+ );
+ }
+ assert.ok(summary.overviews.length);
+ for (const overview of summary.overviews) assert.ok(existsSync(overview));
+ assert.equal(summary.cleanup.scratchRemoved, true);
+});
+
test('a page that never mounts fails at the timeout and leaves no runtime behind', async () => {
const file = await entry('stuck', `export {};\n`);
const started = Date.now();
diff --git a/apps/desktop/src/main/worktree/__tests__/branchSync.git-integration.test.ts b/apps/desktop/src/main/worktree/__tests__/branchSync.git-integration.test.ts
index 1558b8a9dc..58815cafdf 100644
--- a/apps/desktop/src/main/worktree/__tests__/branchSync.git-integration.test.ts
+++ b/apps/desktop/src/main/worktree/__tests__/branchSync.git-integration.test.ts
@@ -33,7 +33,7 @@ function git(cwd: string, ...args: string[]) {
cwd,
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
- env: { ...process.env, GIT_CONFIG_GLOBAL: os.devNull, GIT_CONFIG_NOSYSTEM: '1' },
+ env: { ...process.env, GIT_CONFIG_GLOBAL: path.join(root, 'gitconfig'), GIT_CONFIG_NOSYSTEM: '1' },
},
).trim();
}
@@ -45,6 +45,11 @@ function commit(cwd: string, file: string, content: string) {
}
beforeAll(() => {
root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-branch-sync-'));
+ // Git for Windows does not accept Node's \\.\nul as a config file. An empty
+ // fixture also isolates production syncBranch calls from the user's config.
+ fs.writeFileSync(path.join(root, 'gitconfig'), '');
+ vi.stubEnv('GIT_CONFIG_GLOBAL', path.join(root, 'gitconfig'));
+ vi.stubEnv('GIT_CONFIG_NOSYSTEM', '1');
seed = path.join(root, 'seed');
remote = path.join(root, 'remote.git');
fs.mkdirSync(seed);
@@ -53,7 +58,10 @@ beforeAll(() => {
git(root, 'clone', '--bare', seed, remote);
git(seed, 'remote', 'add', 'origin', remote);
});
-afterAll(() => fs.rmSync(root, { recursive: true, force: true }));
+afterAll(() => {
+ vi.unstubAllEnvs();
+ fs.rmSync(root, { recursive: true, force: true });
+});
function fixture() {
const branch = `case-${++sequence}`;
const repo = path.join(root, branch);
@@ -83,6 +91,26 @@ it('fetches and fast-forwards the checked-out branch while preserving unrelated
expect(fs.readFileSync(path.join(f.repo, 'keep'), 'utf8')).toBe('uncommitted');
expect(result.status.dirtyFiles).toBe(1);
});
+// Regression: unpack-objects is silent while receiving a single large blob.
+// The real sync entry must select a receiver that emits byte progress even for
+// fewer than 100 objects; fake progress tests cannot detect the wrong Git mode.
+it('reports receiving progress for a small object count instead of silently unpacking it', async () => {
+ const f = fixture();
+ f.advance();
+ const original = gitModule.gitExec;
+ const progress: string[] = [];
+ const spy = vi.spyOn(gitModule, 'gitExec').mockImplementation(async (...args) => {
+ const result = await original(...args);
+ if (args[0].includes('--progress')) progress.push(result.stderr);
+ return result;
+ });
+ try {
+ expect((await syncBranch(f.req)).updated).toBe(1);
+ expect(progress.join('')).toMatch(/Receiving objects:.*100%/);
+ } finally {
+ spy.mockRestore();
+ }
+});
it('updates an unchecked local ref without changing the current checkout', async () => {
const f = fixture();
const sha = f.advance();
diff --git a/apps/desktop/src/main/worktree/__tests__/branchSyncHandlers.test.ts b/apps/desktop/src/main/worktree/__tests__/branchSyncHandlers.test.ts
index db878986e7..131dc6005c 100644
--- a/apps/desktop/src/main/worktree/__tests__/branchSyncHandlers.test.ts
+++ b/apps/desktop/src/main/worktree/__tests__/branchSyncHandlers.test.ts
@@ -4,22 +4,26 @@
* option-shaped ref, credential URL in failure. Tier: unit, injected identity.
*/
import path from 'node:path';
-import { beforeEach, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { createBranchSyncHandlers } from '../branchSyncHandlers';
import { GitExecError } from '../gitExec';
const calls = vi.hoisted(() => ({ status: vi.fn(), sync: vi.fn() }));
vi.mock('../branchSync', () => ({ readBranchSyncStatus: calls.status, syncBranch: calls.sync }));
const assertSender = vi.fn();
const remote = vi.fn();
+const scope = vi.fn(() => 'owner:1:device-a');
const handlers = createBranchSyncHandlers({
assertTrustedAppRendererEvent: assertSender,
isDeviceLinkInvoke: remote,
+ getCallerScope: scope,
});
const req = { baseRepo: path.resolve('/repo'), branch: 'main' };
beforeEach(() => {
vi.resetAllMocks();
remote.mockReturnValue(false);
+ scope.mockReturnValue('owner:1:device-a');
});
+afterEach(() => vi.useRealTimers());
it('rejects an untrusted frame before reading or mutating any repository', () => {
assertSender.mockImplementation(() => {
throw new Error('[PERMISSION_DENIED] Untrusted frame');
@@ -57,3 +61,69 @@ it('returns a readable reason without leaking Git credentials or output', async
await expect(handlers.sync({}, req)).rejects.toThrow('branch-sync:auth');
await expect(handlers.sync({}, req)).rejects.not.toThrow('secret');
});
+
+// Regression: a healthy download outlives the 90s device-link invoke. Exercise
+// the real IPC handlers with fake time; previous cases only await final replies.
+// Minimum input: one pending sync and continuations from two controller scopes.
+it('waits across multiple bounded replies without rerunning Git, scoped to owner, device and repository', async () => {
+ vi.useFakeTimers();
+ let finish!: (value: { updated: number }) => void;
+ calls.sync.mockReturnValue(
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const initial = handlers.sync({}, { ...req, waitForResult: true });
+ await vi.advanceTimersByTimeAsync(10_000);
+ const pending = await initial;
+ expect(pending).toMatchObject({ pending: true });
+ if (!('operationId' in pending)) throw new Error('expected continuation');
+ const continuation = { ...req, waitForResult: true, operationId: pending.operationId };
+ for (const other of ['owner:1:device-b', 'owner:2:device-a']) {
+ scope.mockReturnValue(other);
+ expect(() => handlers.sync({}, continuation)).toThrow('branch-sync:changed');
+ }
+ scope.mockReturnValue('owner:1:device-a');
+ expect(() => handlers.sync({}, { ...continuation, branch: 'other' })).toThrow(
+ 'branch-sync:changed',
+ );
+ for (let i = 0; i < 10; i++) {
+ const next = handlers.sync({}, continuation);
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(await next).toEqual(pending);
+ }
+ finish({ updated: 2 });
+ expect(await handlers.sync({}, continuation)).toEqual({ updated: 2 });
+ expect(calls.sync).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(5 * 60_000);
+ expect(() => handlers.sync({}, continuation)).toThrow('branch-sync:changed');
+ expect(calls.sync).toHaveBeenCalledTimes(1);
+});
+
+it('retains a sanitized failure for continuations without unhandled rejections or a second fetch', async () => {
+ vi.useFakeTimers();
+ let fail!: (error: Error) => void;
+ calls.sync.mockReturnValue(
+ new Promise((_, reject) => {
+ fail = reject;
+ }),
+ );
+ const initial = handlers.sync({}, { ...req, waitForResult: true });
+ await vi.advanceTimersByTimeAsync(10_000);
+ const pending = await initial;
+ if (!('operationId' in pending)) throw new Error('expected continuation');
+ fail(
+ new GitExecError({
+ args: ['fetch'],
+ exitCode: null,
+ stdout: '',
+ stderr: 'secret',
+ timedOut: true,
+ }),
+ );
+ await expect(
+ handlers.sync({}, { ...req, waitForResult: true, operationId: pending.operationId }),
+ ).rejects.toThrow('branch-sync:timeout');
+ expect(calls.sync).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(5 * 60_000);
+});
diff --git a/apps/desktop/src/main/worktree/__tests__/gitExec.test.ts b/apps/desktop/src/main/worktree/__tests__/gitExec.test.ts
index 0f8798c50f..fa949e65a9 100644
--- a/apps/desktop/src/main/worktree/__tests__/gitExec.test.ts
+++ b/apps/desktop/src/main/worktree/__tests__/gitExec.test.ts
@@ -294,6 +294,50 @@ describe('gitExec timeoutMs', () => {
await enqueueGitRepoWrite('/independent-snapshot', write);
expect(write).toHaveBeenCalledOnce();
});
+ // Regression: manual fetch used to die at 30s even while downloading. Existing
+ // tests only cover absolute deadlines. Unit tier: real gitExec, fake child/time.
+ it('keeps advancing Git progress alive beyond the idle budget, but repeated progress still times out', async () => {
+ setPlatform('win32');
+ const state = installExecFileMock();
+ state.psTable = [];
+ mocks.killProcessTree.mockImplementation((_pid, _child, done) => done?.());
+ const result = gitExec(['fetch', '--progress'], undefined, { idleTimeoutMs: 60_000 });
+ const rejected = expect(result).rejects.toMatchObject({ timedOut: true });
+ await vi.advanceTimersByTimeAsync(50_000);
+ state.child.stderr.emit('data', Buffer.from('Receiving objects: 1% (1/100), 10.00 Ki'));
+ state.child.stderr.emit('data', Buffer.from('B | 1.00 KiB/s\r'));
+ await vi.advanceTimersByTimeAsync(50_000);
+ state.child.stderr.emit('data', Buffer.from('Receiving objects: 1% (1/100), 20.00 KiB | 1.00 KiB/s\r'));
+ await vi.advanceTimersByTimeAsync(50_000);
+ expect(mocks.killProcessTree).not.toHaveBeenCalled();
+ state.child.stderr.emit('data', Buffer.from('Receiving objects: 1% (1/100), 20.00 KiB | 2.00 KiB/s\r'));
+ state.child.stderr.emit('data', Buffer.from('remote: keepalive\n'));
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(mocks.killProcessTree).toHaveBeenCalledTimes(1);
+ state.gitCb!(new Error('terminated'), '', '');
+ await rejected;
+ expect(mocks.killProcessTree).toHaveBeenCalledTimes(1);
+ });
+
+ it('cleans up an idle watchdog on success and still honors an explicit absolute deadline', async () => {
+ setPlatform('win32');
+ const state = installExecFileMock();
+ state.psTable = [];
+ mocks.killProcessTree.mockImplementation((_pid, _child, done) => done?.());
+ const success = gitExec(['fetch', '--progress'], undefined, { idleTimeoutMs: 60_000 });
+ state.gitCb!(null, 'done', '');
+ await expect(success).resolves.toMatchObject({ stdout: 'done' });
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(mocks.killProcessTree).not.toHaveBeenCalled();
+ const bounded = gitExec(['fetch', '--progress'], undefined, { idleTimeoutMs: 60_000, timeoutMs: 30_000 });
+ const rejected = expect(bounded).rejects.toMatchObject({ timedOut: true });
+ await vi.advanceTimersByTimeAsync(20_000);
+ state.child.stderr.emit('data', 'Resolving deltas: 10% (1/10)\r');
+ await vi.advanceTimersByTimeAsync(10_000);
+ state.gitCb!(new Error('terminated'), '', '');
+ await rejected;
+ });
+
it('keeps a dead checkout root leased while a Windows descendant remains', async () => {
setPlatform('win32');
const state = installExecFileMock();
diff --git a/apps/desktop/src/main/worktree/branchSync.ts b/apps/desktop/src/main/worktree/branchSync.ts
index 4bfbdb7637..4a38294324 100644
--- a/apps/desktop/src/main/worktree/branchSync.ts
+++ b/apps/desktop/src/main/worktree/branchSync.ts
@@ -1,6 +1,5 @@
import path from 'node:path';
import { gitExec, GitExecError } from './gitExec';
-import { boundedNetworkGitOpts } from './freshBase';
import type {
BranchSyncRequest,
BranchSyncResult,
@@ -168,7 +167,13 @@ async function syncBranchOnce(req: BranchSyncRequest): Promise<BranchSyncResult>
try {
await gitExec(
[
+ // Small fetches otherwise use unpack-objects, which can receive one
+ // large blob without reporting any bytes. index-pack reports throughput
+ // while reading, so the inactivity budget also works for that case.
+ '-c',
+ 'fetch.unpackLimit=1',
'fetch',
+ '--progress',
'--no-tags',
'--recurse-submodules=no',
'--',
@@ -177,8 +182,8 @@ async function syncBranchOnce(req: BranchSyncRequest): Promise<BranchSyncResult>
],
req.baseRepo,
{
- ...boundedNetworkGitOpts(30_000),
- extraEnv: { ...boundedNetworkGitOpts(30_000).extraEnv, LC_ALL: 'C' },
+ idleTimeoutMs: 60_000,
+ extraEnv: { GIT_TERMINAL_PROMPT: '0', LC_ALL: 'C' },
},
);
} catch (error) {
diff --git a/apps/desktop/src/main/worktree/branchSyncHandlers.ts b/apps/desktop/src/main/worktree/branchSyncHandlers.ts
index 517dea179a..47b62aecce 100644
--- a/apps/desktop/src/main/worktree/branchSyncHandlers.ts
+++ b/apps/desktop/src/main/worktree/branchSyncHandlers.ts
@@ -1,4 +1,5 @@
import path from 'node:path';
+import { randomUUID } from 'node:crypto';
import { readBranchSyncStatus, syncBranch } from './branchSync';
import { GitExecError } from './gitExec';
import { requireObject, requireString, throwIpcError } from '../utils/ipcValidate';
@@ -6,13 +7,43 @@ import {
BRANCH_SYNC_ERROR_PREFIX,
type BranchSyncRequest,
type BranchSyncFailureReason,
+ type BranchSyncResult,
+ type BranchSyncReply,
} from '../../shared/worktreeBranchSync';
/** Small IPC boundary, testable without loading Electron or the WorktreeManager. */
export function createBranchSyncHandlers<Event>(deps: {
assertTrustedAppRendererEvent(event: Event): void;
isDeviceLinkInvoke(): boolean;
+ getCallerScope(): string | null;
}) {
+ type Outcome = { result: BranchSyncResult } | { error: unknown };
+ const operations = new Map<
+ string,
+ {
+ scope: string;
+ req: BranchSyncRequest;
+ outcome: Promise<Outcome>;
+ }
+ >();
+
+ // Each poll fits inside the existing invoke budget. Only the initial request
+ // starts work; lost replies, changed peers and expired tokens never replay it.
+ async function wait(operationId: string): Promise<BranchSyncReply> {
+ const operation = operations.get(operationId)!;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const pending = new Promise<null>((resolve) => {
+ timer = setTimeout(() => resolve(null), 10_000);
+ });
+ try {
+ const outcome = await Promise.race([operation.outcome, pending]);
+ if (!outcome) return { pending: true, operationId };
+ if ('error' in outcome) throw outcome.error;
+ return outcome.result;
+ } finally {
+ clearTimeout(timer);
+ }
+ }
function request(event: Event, input: unknown): BranchSyncRequest {
// Remote invokes already passed the same-account device-link allowlist.
if (!deps.isDeviceLinkInvoke()) deps.assertTrustedAppRendererEvent(event);
@@ -61,7 +92,47 @@ export function createBranchSyncHandlers<Event>(deps: {
},
sync: (event: Event, input: unknown) => {
const req = request(event, input);
- return run(() => syncBranch(req));
+ const body = requireObject(input);
+ if (body.waitForResult !== undefined && typeof body.waitForResult !== 'boolean')
+ throwIpcError('INVALID_PARAMS', 'Invalid branch sync wait mode');
+ if (
+ body.operationId !== undefined &&
+ (body.waitForResult !== true ||
+ typeof body.operationId !== 'string' ||
+ !/^[a-f0-9-]{36}$/.test(body.operationId))
+ )
+ throwIpcError('INVALID_PARAMS', 'Invalid branch sync operation');
+ if (body.waitForResult !== true) return run(() => syncBranch(req));
+ const scope = deps.getCallerScope();
+ if (!scope) throwIpcError('INTERNAL', BRANCH_SYNC_ERROR_PREFIX + 'changed');
+ let operationId = body.operationId as string | undefined;
+ if (operationId) {
+ const operation = operations.get(operationId);
+ if (
+ !operation ||
+ operation.scope !== scope ||
+ operation.req.baseRepo !== req.baseRepo ||
+ operation.req.branch !== req.branch
+ )
+ throwIpcError('INTERNAL', BRANCH_SYNC_ERROR_PREFIX + 'changed');
+ } else {
+ if (operations.size >= 64) throwIpcError('INTERNAL', BRANCH_SYNC_ERROR_PREFIX + 'busy');
+ operationId = randomUUID();
+ const id = operationId;
+ const outcome: Promise<Outcome> = Promise.resolve()
+ .then(() => run(() => syncBranch(req)))
+ .then(
+ (result) => ({ result }),
+ (error: unknown) => ({ error }),
+ );
+ operations.set(id, { scope, req, outcome });
+ // 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?.();
+ });
+ }
+ return wait(operationId);
},
};
}
diff --git a/apps/desktop/src/main/worktree/gitExec.ts b/apps/desktop/src/main/worktree/gitExec.ts
index f3e8b726c6..61320d9b49 100644
--- a/apps/desktop/src/main/worktree/gitExec.ts
+++ b/apps/desktop/src/main/worktree/gitExec.ts
@@ -90,6 +90,10 @@ export interface GitExecOpts {
* 省略 = 不超时。
*/
timeoutMs?: number;
+ /** Optional inactivity budget for Git --progress stderr (LC_ALL=C). Only
+ * advancing object/delta/byte counters renew it; unrelated output does not.
+ * Independent of timeoutMs/deadlineAtMs, which remain absolute ceilings. */
+ idleTimeoutMs?: number;
/** Optional absolute performance.now() deadline shared by ownership repair and retries. */
deadlineAtMs?: number;
signal?: AbortSignal;
@@ -286,6 +290,7 @@ function execFileOnce(
// 后代还活着时提前结束 Promise,调用方随即发起的 git 操作与残留进程争锁。
let timedOut = false;
let timer: ReturnType<typeof setTimeout> | undefined;
+ let idleTimer: ReturnType<typeof setTimeout> | undefined;
let reaper: ReturnType<typeof setTimeout> | undefined;
let groupPoll: ReturnType<typeof setInterval> | undefined;
let finishWatchdog: ReturnType<typeof setTimeout> | undefined;
@@ -297,6 +302,7 @@ function execFileOnce(
if (settled) return;
settled = true;
if (timer !== undefined) clearTimeout(timer);
+ if (idleTimer !== undefined) clearTimeout(idleTimer);
if (reaper !== undefined) clearTimeout(reaper);
if (groupPoll !== undefined) clearInterval(groupPoll);
if (finishWatchdog !== undefined) clearTimeout(finishWatchdog);
@@ -425,6 +431,51 @@ function execFileOnce(
child.stdout?.once('error', handleChildProcessError);
child.stderr?.once('error', handleChildProcessError);
+ // --progress emits CR-delimited records even without a terminal. Preserve
+ // split records, but never retain arbitrary stderr or credentials here.
+ if (opts?.idleTimeoutMs && opts.idleTimeoutMs > 0) {
+ const idleMs = opts.idleTimeoutMs;
+ let pending = '';
+ const counters = new Map<string, { objects: number; bytes: number }>();
+ const renew = () => {
+ if (settled || timedOut) return;
+ if (idleTimer !== undefined) clearTimeout(idleTimer);
+ idleTimer = setTimeout(() => {
+ startTreeCleanup((gone) => new GitExecError({
+ args,
+ exitCode: null,
+ stdout: '',
+ timedOut: true,
+ cleanupUnconfirmed: !gone,
+ stderr: `no Git progress for ${idleMs}ms; process tree ${gone ? 'terminated' : 'cleanup unconfirmed'}`,
+ }));
+ }, idleMs);
+ };
+ const onProgress = (chunk: Buffer | string) => {
+ if (settled || timedOut) return;
+ const records = (pending + chunk.toString()).split(/[\r\n]/);
+ pending = records.pop()!.slice(-1024);
+ for (const record of records) {
+ const match = /^(?:remote:\s*)?(Enumerating objects|Counting objects|Compressing objects|Receiving objects|Resolving deltas|Checking connectivity):\s*(?:\d+%\s*\((\d+)\/\d+\)|(\d+))(?:,\s*([\d.]+)\s*(bytes|KiB|MiB|GiB))?/.exec(record.trim());
+ if (!match) continue;
+ const objects = Number(match[2] ?? match[3]);
+ const units: Record<string, number> = { bytes: 1, KiB: 1024, MiB: 1024 ** 2, GiB: 1024 ** 3 };
+ const bytes = Number(match[4] ?? 0) * (units[match[5]] ?? 1);
+ const previous = counters.get(match[1]);
+ if (!previous || objects > previous.objects || bytes > previous.bytes) {
+ counters.set(match[1], {
+ objects: Math.max(objects, previous?.objects ?? 0),
+ bytes: Math.max(bytes, previous?.bytes ?? 0),
+ });
+ renew();
+ }
+ }
+ };
+ child.stderr?.on('data', onProgress);
+ child.once('close', () => child.stderr?.removeListener('data', onProgress));
+ renew();
+ }
+
function startTreeCleanup(
createFailure: (treeConfirmedGone: boolean) => GitExecError,
): void {
diff --git a/apps/desktop/src/main/worktree/index.ts b/apps/desktop/src/main/worktree/index.ts
index a8b3e0c8ed..25c1d84175 100644
--- a/apps/desktop/src/main/worktree/index.ts
+++ b/apps/desktop/src/main/worktree/index.ts
@@ -10,7 +10,8 @@ import path from 'node:path';
import { readOriginDefaultBranch } from './branchSync';
import { createBranchSyncHandlers } from './branchSyncHandlers';
import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer';
-import { isDeviceLinkInvoke } from '../device-link/invoke-context';
+import { getDeviceLinkInvokeContext, isDeviceLinkInvoke } from '../device-link/invoke-context';
+import { getCurrentDbClientSnapshot } from '../localDb/client/current';
import { ipcMain as ipcMainType, type IpcMain, shell } from 'electron';
import * as WorktreeManager from './WorktreeManager';
@@ -53,7 +54,20 @@ export * from './types';
* 调用方保证只调一次。
*/
export function registerWorktreeIpc(ipcMain: IpcMain = ipcMainType): void {
- const branchSync = createBranchSyncHandlers({ assertTrustedAppRendererEvent, isDeviceLinkInvoke });
+ const branchSync = createBranchSyncHandlers({
+ assertTrustedAppRendererEvent,
+ isDeviceLinkInvoke,
+ getCallerScope: () => {
+ const owner = getCurrentDbClientSnapshot();
+ return owner
+ ? JSON.stringify([
+ owner.userId,
+ owner.clientEpoch,
+ getDeviceLinkInvokeContext()?.controllerDeviceId ?? 'local',
+ ])
+ : null;
+ },
+ });
ipcMain.handle('worktree:branch-sync-status', branchSync.status);
ipcMain.handle('worktree:sync-branch', branchSync.sync);
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index caa095930b..e4b988e52d 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -5293,7 +5293,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
worktreeSuggestName: (req: { baseRepo: string }): Promise<unknown> =>
ipcRenderer.invoke('worktree:suggest-name', req),
worktreeBranchSyncStatus: (req: import('../shared/worktreeBranchSync').BranchSyncRequest): Promise<import('../shared/worktreeBranchSync').BranchSyncStatus> => ipcRenderer.invoke('worktree:branch-sync-status', req),
- worktreeSyncBranch: (req: import('../shared/worktreeBranchSync').BranchSyncRequest): Promise<import('../shared/worktreeBranchSync').BranchSyncResult> => ipcRenderer.invoke('worktree:sync-branch', req),
+ worktreeSyncBranch: (req: import('../shared/worktreeBranchSync').BranchSyncRequest): Promise<import('../shared/worktreeBranchSync').BranchSyncReply> => ipcRenderer.invoke('worktree:sync-branch', req),
worktreeListBranches: (req: { baseRepo: string }): Promise<unknown> =>
ipcRenderer.invoke('worktree:list-branches', req),
// P1: 删除/归档确认预检(有无 worktree、是否有未提交更改)
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 4733de4ae7..48566cb997 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
@@ -80,6 +80,25 @@ afterEach(() => {
});
const branchButton = () => screen.getByRole('button', { name: 'newChat.branchChip.label' });
const refreshButton = () => screen.getByRole('button', { name: /newChat.branchSync.action/ });
+// Regression: remote Git continues after the old 90s request budget; follow the
+// operation handle rather than repeating the mutation. Unit tier, real hook/UI.
+it('continues waiting for the same remote fetch and shows its final result', async () => {
+ const operationId = '8a7768e7-e652-4458-9c15-96af310bc9cb';
+ const replies = [{ pending: true, operationId }, { pending: true, operationId }, { status: baseStatus, updated: 3 }];
+ invoke.mockImplementation(async (_device, channel) => channel === 'worktree:sync-branch' ? replies.shift() : baseStatus);
+ render(<BranchWorktreeChip {...props} deviceId="remote-a" />);
+ await screen.findByRole('button', { name: /newChat.branchSync.action/ });
+ fireEvent.click(refreshButton());
+ await screen.findByRole('button', { name: /newChat.branchSync.updated/ });
+ const writes = invoke.mock.calls.filter((call) => call[1] === 'worktree:sync-branch');
+ expect(writes.map((call) => call[2])).toEqual([
+ [{ baseRepo: '/repo', branch: 'main', waitForResult: true }],
+ [{ baseRepo: '/repo', branch: 'main', waitForResult: true, operationId }],
+ [{ baseRepo: '/repo', branch: 'main', waitForResult: true, operationId }],
+ ]);
+ expect(mocks.toast).not.toHaveBeenCalled();
+});
+
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());
@@ -213,7 +232,7 @@ it('routes to the selected device and discards a late status from the previous b
fireEvent.click(refreshButton());
await waitFor(() =>
expect(invoke).toHaveBeenLastCalledWith('pc', 'worktree:sync-branch', [
- { baseRepo: '/repo', branch: 'next' },
+ { baseRepo: '/repo', branch: 'next', waitForResult: true },
]),
);
expect(status).not.toHaveBeenCalled();
diff --git a/apps/desktop/src/renderer/hooks/useBranchSync.ts b/apps/desktop/src/renderer/hooks/useBranchSync.ts
index c57583c5e9..b9a44fcff4 100644
--- a/apps/desktop/src/renderer/hooks/useBranchSync.ts
+++ b/apps/desktop/src/renderer/hooks/useBranchSync.ts
@@ -4,6 +4,7 @@ import {
BRANCH_SYNC_ERROR_PREFIX,
type BranchSyncStatus,
type BranchSyncResult,
+ type BranchSyncReply,
} from '../../shared/worktreeBranchSync';
import { extractIpcError } from '@/utils/ipcError';
import { toast } from '@/lib/toast';
@@ -32,8 +33,12 @@ export function useBranchSync(
const hoverTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const doneTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const invoke = useCallback(
- (sync: boolean) => {
- const req = { baseRepo: baseRepo!, branch };
+ (sync: boolean, operationId?: string) => {
+ const req = {
+ baseRepo: baseRepo!,
+ branch,
+ ...(sync ? { waitForResult: true, ...(operationId ? { operationId } : {}) } : {}),
+ };
if (deviceId)
return window.electronAPI.deviceLink.invoke(
deviceId,
@@ -105,7 +110,12 @@ export function useBranchSync(
const id = ++request.current;
setSnapshot((old) => ({ ...old, key, busy: true, error: undefined, result: undefined }));
try {
- const result = (await invoke(true)) as BranchSyncResult;
+ let reply = (await invoke(true)) as BranchSyncReply;
+ while ('pending' in reply) {
+ if (currentKey.current !== key || id !== request.current) return;
+ reply = (await invoke(true, reply.operationId)) as BranchSyncReply;
+ }
+ const result = reply;
if (currentKey.current !== key || id !== request.current) return;
if (result.status.blocked) toast.warning(blockedHint(result.status));
setSnapshot({
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 241e8e9477..4c1a726636 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -4422,7 +4422,7 @@ interface ElectronAPI {
baseRepo: string;
}) => Promise<import('@/lib/worktree.types').SuggestNameResp>;
worktreeBranchSyncStatus: (req: import('../shared/worktreeBranchSync').BranchSyncRequest) => Promise<import('../shared/worktreeBranchSync').BranchSyncStatus>;
- worktreeSyncBranch: (req: import('../shared/worktreeBranchSync').BranchSyncRequest) => Promise<import('../shared/worktreeBranchSync').BranchSyncResult>;
+ worktreeSyncBranch: (req: import('../shared/worktreeBranchSync').BranchSyncRequest) => Promise<import('../shared/worktreeBranchSync').BranchSyncReply>;
worktreeListBranches: (req: {
baseRepo: string;
}) => Promise<import('@/lib/worktree.types').ListBranchesResp>;
diff --git a/apps/desktop/src/shared/worktreeBranchSync.ts b/apps/desktop/src/shared/worktreeBranchSync.ts
index df067dce33..22b246a9c6 100644
--- a/apps/desktop/src/shared/worktreeBranchSync.ts
+++ b/apps/desktop/src/shared/worktreeBranchSync.ts
@@ -2,6 +2,10 @@
export interface BranchSyncRequest {
baseRepo: string;
branch: string;
+ /** Opt-in bounded replies. Omitted by old clients, which receive the final result. */
+ waitForResult?: boolean;
+ /** Continue waiting for an existing operation; never starts another fetch. */
+ operationId?: string;
}
export interface BranchSyncStatus {
branch: string;
@@ -27,6 +31,8 @@ export interface BranchSyncResult {
updated: number;
}
+export type BranchSyncReply = BranchSyncResult | { pending: true; operationId: string };
+
export const BRANCH_SYNC_ERROR_PREFIX = 'branch-sync:';
export type BranchSyncFailureReason =
'git' | 'timeout' | 'auth' | 'network' | 'missing' | 'busy' | 'changed';
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 7e81db2389..360a8bf74e 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -69,8 +69,18 @@ Server 保留原市场资源 ID 和不可变旧 Release;无能力声明的客
仅拉取确认远程分支不存在后,在本次胶囊选择内置灰;换分支或重新挂载即重新判断。
同步仅由用户点击触发,按配置的 tracking remote/ref(否则 origin 同名分支)拉取一个显式
refspec,再按需快进本地分支。
-设备互联对单次同步预留 90 秒(网络 Git 30 秒及清理、本地探测),失败不重放写请求、
-不重置 peer 或 relay;创建和发送不等待同步,不改用其它源引用。手机本轮不提供入口。
+手动 fetch 使用 `--progress`,连续 60 秒没有新增对象、接收字节或解包进度才超时;
+重复进度行与普通输出不续期。本地探测仍有 5 秒上限,超时沿用整棵进程树清理。
+单次命令用 `-c fetch.unpackLimit=1` 让小批对象也经过会报告字节进度的 `index-pack`,
+避免单个大对象被 `unpack-objects` 静默接收时误判停滞;不修改用户 Git 配置。
+新版控制端在 `worktree:sync-branch` 请求追加可选 `waitForResult: true`,被控端至多等待
+10 秒,未完成时返回 `{ pending: true, operationId }`。后续请求带同一 `operationId`,
+只等待原操作,绝不重新 fetch;句柄绑定账号代次、控制设备、仓库和分支,完成后保留 5 分钟。
+未知、过期或不匹配的句柄报 `branch-sync:changed`,不自动重新执行。每次 invoke 仍沿用
+90 秒传输预算,不修改共享链路的超时、重试或恢复策略;两个控制端的句柄互不通用。
+旧控制端不传新字段,新被控端仍返回原终态;新控制端连接旧被控端时接受原终态,沿用旧端
+Git 超时。长下载的完整体验需要两端更新。失败不重放写请求、不重置 peer 或 relay;
+创建和发送不等待同步,不改用其它源引用。手机本轮不提供入口。无服务端或数据库变更。
实现见 `apps/desktop/src/main/worktree/branchSync.ts`;真实 Git 回归在
`branchSync.git-integration.test.ts`。