Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 同目录多任务并行不再被变更捕获整轮串行
DavidShen1eb499f52b12
diff --git a/apps/desktop/src/main/turn-change-set/__tests__/store.git-integration.test.ts b/apps/desktop/src/main/turn-change-set/__tests__/store.git-integration.test.tsindex 9611938acc..4932a1a95f 100644--- a/apps/desktop/src/main/turn-change-set/__tests__/store.git-integration.test.ts+++ b/apps/desktop/src/main/turn-change-set/__tests__/store.git-integration.test.ts@@ -194,7 +194,7 @@ describe('turn change-set sidecar store', () => {});});- it('serializes exact captures for sessions sharing one workspace', async () => {+ it('keeps overlapping same-workspace captures parallel and degrades both to review-only', async () => {const target = path.join(workdir, 'shared.txt');const workspaceAlias = path.join(root, 'workspace-alias');await fs.writeFile(target, 'old\n', 'utf8');@@ -215,37 +215,191 @@ describe('turn change-set sidecar store', () => {targetPath: 'shared.txt',});- let secondResolved = false;- const second = beginTurnChangeSet({+ // The second dispatch through the workspace alias must not wait for the first+ // session's turn — overlap is marked instead of serialized.+ await beginTurnChangeSet({sessionId: 'session-2',anchorClientId: 'user-2',provider: 'pi',cwd: workspaceAlias,- }).then(() => {- secondResolved = true;});- await Promise.resolve();- expect(secondResolved).toBe(false);+ await captureKnownFileBefore({+ sessionId: 'session-2',+ provider: 'pi',+ cwd: workspaceAlias,+ targetPath: 'shared.txt',+ });await fs.writeFile(target, 'first\n', 'utf8');await finalizeTurnChangeSet('session-1', null, 'complete');- await second;+ await fs.writeFile(target, 'second\n', 'utf8');+ await finalizeTurnChangeSet('session-2', null, 'complete');++ const [first] = await listTurnChangeSets('session-1');+ const [second] = await listTurnChangeSets('session-2');+ expect(first).toMatchObject({+ state: 'partial',+ incompleteReasons: expect.arrayContaining(['concurrent-workspace']),+ isReversible: false,+ });+ expect(second).toMatchObject({+ state: 'partial',+ incompleteReasons: expect.arrayContaining(['concurrent-workspace']),+ isReversible: false,+ });+ // Captures are still recorded for review even though they overlapped.+ const [firstDetail] = await getTurnChangeSets('session-1', [first!.id]);+ expect(firstDetail?.diffs[0]?.rawPatch).toContain('-old');+ await expect(applyTurnChangeSetAction('session-1', first!.id, 'undo'))+ .rejects.toMatchObject({ kind: 'unsupported' } satisfies Partial<TurnChangeSetActionError>);+ });++ it('does not degrade sequential turns or different workspaces', async () => {+ const target = path.join(workdir, 'seq.txt');+ await fs.writeFile(target, 'a\n', 'utf8');+ await beginTurnChangeSet({+ sessionId: 'session-1',+ anchorClientId: 'user-1',+ provider: 'claude-code',+ cwd: workdir,+ });+ await captureKnownFileBefore({+ sessionId: 'session-1',+ provider: 'claude-code',+ cwd: workdir,+ targetPath: 'seq.txt',+ });+ await fs.writeFile(target, 'b\n', 'utf8');+ // A concurrent turn in a *different* directory shares nothing.+ const otherDir = path.join(root, 'other-workspace');+ await fs.mkdir(otherDir);+ const otherTarget = path.join(otherDir, 'other.txt');+ await fs.writeFile(otherTarget, 'x\n', 'utf8');+ await beginTurnChangeSet({+ sessionId: 'session-2',+ anchorClientId: 'user-2',+ provider: 'pi',+ cwd: otherDir,+ });await captureKnownFileBefore({sessionId: 'session-2',provider: 'pi',- cwd: workspaceAlias,- targetPath: 'shared.txt',+ cwd: otherDir,+ targetPath: 'other.txt',});- await fs.writeFile(target, 'second\n', 'utf8');+ await fs.writeFile(otherTarget, 'y\n', 'utf8');++ await finalizeTurnChangeSet('session-1', null, 'complete');await finalizeTurnChangeSet('session-2', null, 'complete');- const [first] = await getTurnChangeSets('session-1', (await listTurnChangeSets('session-1')).map(({ id }) => id));- const [secondDetail] = await getTurnChangeSets('session-2', (await listTurnChangeSets('session-2')).map(({ id }) => id));- expect(first?.diffs[0]?.rawPatch).toContain('-old');- expect(first?.diffs[0]?.rawPatch).toContain('+first');- expect(secondDetail?.diffs[0]?.rawPatch).toContain('-first');- expect(secondDetail?.diffs[0]?.rawPatch).toContain('+second');+ expect((await listTurnChangeSets('session-1'))[0]).toMatchObject({+ state: 'complete',+ incompleteReasons: [],+ isReversible: true,+ });+ expect((await listTurnChangeSets('session-2'))[0]).toMatchObject({+ state: 'complete',+ incompleteReasons: [],+ isReversible: true,+ });++ // A sequential turn in the same directory (begun after the prior finalize) is+ // untouched by overlap marking.+ await beginTurnChangeSet({+ sessionId: 'session-2',+ anchorClientId: 'user-2',+ provider: 'pi',+ cwd: workdir,+ });+ await captureKnownFileBefore({+ sessionId: 'session-2',+ provider: 'pi',+ cwd: workdir,+ targetPath: 'seq.txt',+ });+ await fs.writeFile(target, 'c\n', 'utf8');+ await finalizeTurnChangeSet('session-2', null, 'complete');+ const sequential = (await listTurnChangeSets('session-2')).find(+ (entry) => entry.cwd === workdir,+ );+ expect(sequential).toMatchObject({+ state: 'complete',+ incompleteReasons: [],+ isReversible: true,+ });+ });++ it('waits for the prior after-image seal instead of marking a non-overlapping dispatch', async () => {+ const target = path.join(workdir, 'seal.txt');+ await fs.writeFile(target, 'before\n', 'utf8');+ await beginTurnChangeSet({+ sessionId: 'session-1',+ anchorClientId: 'user-1',+ provider: 'claude-code',+ cwd: workdir,+ });+ await captureKnownFileBefore({+ sessionId: 'session-1',+ provider: 'claude-code',+ cwd: workdir,+ targetPath: 'seal.txt',+ });+ await fs.writeFile(target, 'after\n', 'utf8');++ // Finalize is not awaited: the next dispatch must wait for the seal, then see+ // no active capture — no degradation on either side.+ const sealing = finalizeTurnChangeSet('session-1', null, 'complete');+ await beginTurnChangeSet({+ sessionId: 'session-2',+ anchorClientId: 'user-2',+ provider: 'pi',+ cwd: workdir,+ });+ await sealing;+ await finalizeTurnChangeSet('session-2', null, 'complete');++ expect((await listTurnChangeSets('session-1'))[0]).toMatchObject({+ state: 'complete',+ incompleteReasons: [],+ isReversible: true,+ });+ expect(await listTurnChangeSets('session-2')).toHaveLength(0);+ });++ it('drops an overlapping turn that never touched files instead of persisting an empty card', async () => {+ await beginTurnChangeSet({+ sessionId: 'session-1',+ anchorClientId: 'user-1',+ provider: 'claude-code',+ cwd: workdir,+ });+ const target = path.join(workdir, 'busy-work.txt');+ await fs.writeFile(target, 'v1\n', 'utf8');+ await captureKnownFileBefore({+ sessionId: 'session-1',+ provider: 'claude-code',+ cwd: workdir,+ targetPath: 'busy-work.txt',+ });+ // Chat-only turn overlapping in the same directory: no captures, no card.+ await beginTurnChangeSet({+ sessionId: 'session-2',+ anchorClientId: 'user-2',+ provider: 'pi',+ cwd: workdir,+ });+ await finalizeTurnChangeSet('session-2', null, 'complete');+ await fs.writeFile(target, 'v2\n', 'utf8');+ await finalizeTurnChangeSet('session-1', null, 'complete');++ expect(await listTurnChangeSets('session-2')).toHaveLength(0);+ expect((await listTurnChangeSets('session-1'))[0]).toMatchObject({+ state: 'partial',+ incompleteReasons: expect.arrayContaining(['concurrent-workspace']),+ isReversible: false,+ fileCount: 1,+ });});it('undoes and reapplies an exact text patch without changing chat history', async () => {diff --git a/apps/desktop/src/main/turn-change-set/store.ts b/apps/desktop/src/main/turn-change-set/store.tsindex 3156ae4c15..c02ecb5c08 100644--- a/apps/desktop/src/main/turn-change-set/store.ts+++ b/apps/desktop/src/main/turn-change-set/store.ts@@ -95,6 +95,7 @@ const INCOMPLETE_REASONS = new Set<TurnChangeIncompleteReason>(['diff-too-large','provider-diff-conflict','turn-failed',+ 'concurrent-workspace',]);const FILE_STATUSES = new Set<FileDiff['status']>(['added',@@ -133,8 +134,8 @@ export interface BeginTurnChangeSetInput {const pendingBySession = new Map<string, PendingTurnChangeSet>();const sessionWriteChains = new Map<string, Promise<unknown>>();const workspaceActionChains = new Map<string, Promise<unknown>>();-const workspaceCaptureChains = new Map<string, Promise<void>>();-const workspaceCaptureLeasesBySession = new Map<string, WorkspaceCaptureLease>();+const workspaceSealChains = new Map<string, Promise<void>>();+const beginEpochBySession = new Map<string, number>();const pendingWorkspaceBySession = new Map<string, string>();const pendingWorkspaceCounts = new Map<string, number>();const retainedSessionDirs = new Map<string, number>();@@ -142,16 +143,6 @@ const activeActionPromises = new Set<Promise<unknown>>();const legacyReversibleCapabilityByDetailPath = new Map<string, boolean>();let storageWriteChain = Promise.resolve();-interface WorkspaceCaptureLease {- key: string;- anchorClientId: string;- ready: Promise<void>;- resolveReady: () => void;- rejectReady: (error: unknown) => void;- cancelled: boolean;- release: () => void;-}-function byteLength(value: string): number {return Buffer.byteLength(value, 'utf8');}@@ -249,6 +240,10 @@ function isReversiblePatch(value: PersistedTurnChangeSetV1): boolean {) {return false;}+ // An after-image read while another turn overlapped in the same workspace may+ // contain the other turn's writes; applying it in either direction could undo+ // work this turn never did. Keep overlapped captures review-only.+ if (value.incompleteReasons.includes('concurrent-workspace')) return false;if (/^(?:GIT binary patch|Binary files .* differ)$/m.test(value.unifiedDiff)) return false;if (/^(?:old mode|new mode)\s+/m.test(value.unifiedDiff)) return false;if (/\b160000\b/.test(value.unifiedDiff)) return false;@@ -555,59 +550,55 @@ function unregisterPendingWorkspace(sessionId: string): void {else pendingWorkspaceCounts.set(key, next);}-function releaseWorkspaceCaptureLease(sessionId: string): void {- const lease = workspaceCaptureLeasesBySession.get(sessionId);- if (!lease) return;- workspaceCaptureLeasesBySession.delete(sessionId);- lease.rejectReady(new Error('Turn change-set capture was cancelled.'));- lease.release();+function cancelPendingBegin(sessionId: string): void {+ beginEpochBySession.set(sessionId, (beginEpochBySession.get(sessionId) ?? 0) + 1);}/**- * Reserve the workspace synchronously before the first await in beginTurnChangeSet.- * This makes concurrent dispatches for one local workdir queue behind the prior- * turn's after-image capture instead of interleaving before/after snapshots.+ * Tracks in-flight after-image persistence per workspace. The next dispatch in the+ * same directory waits for prior snapshots to seal before its turn may mutate files.+ * This wait is bounded capture I/O — never the duration of a running turn.*/-function reserveWorkspaceCaptureLease(sessionId: string, cwd: string, anchorClientId: string): {- previous: Promise<void>;- lease: WorkspaceCaptureLease;-} {+function registerWorkspaceSeal(cwd: string, operation: Promise<unknown>): void {const key = normalizeTurnChangeSetWorkspaceKey(cwd);- const previous = workspaceCaptureChains.get(key) ?? Promise.resolve();- let resolveCurrent!: () => void;- const current = new Promise<void>((resolve) => {- resolveCurrent = resolve;+ const settled = operation.then(() => undefined, () => undefined);+ const previous = workspaceSealChains.get(key) ?? Promise.resolve();+ const current = previous.then(() => settled).finally(() => {+ if (workspaceSealChains.get(key) === current) workspaceSealChains.delete(key);});- workspaceCaptureChains.set(key, current);+ workspaceSealChains.set(key, current);+}- let resolveReady!: () => void;- let rejectReady!: (error: unknown) => void;- const ready = new Promise<void>((resolve, reject) => {- resolveReady = resolve;- rejectReady = reject;- });- // A rejected readiness promise is only an internal coordination signal. Keep- // it from becoming an unhandled rejection when no re-entrant caller awaits it.- void ready.catch(() => undefined);+async function waitForWorkspaceSeals(cwd: string): Promise<void> {+ const key = normalizeTurnChangeSetWorkspaceKey(cwd);+ for (;;) {+ const current = workspaceSealChains.get(key);+ if (!current) return;+ await current.catch(() => undefined);+ if (workspaceSealChains.get(key) === current) return;+ }+}- let released = false;- const lease: WorkspaceCaptureLease = {- key,- anchorClientId,- ready,- resolveReady,- rejectReady,- cancelled: false,- release: () => {- if (released) return;- released = true;- lease.cancelled = true;- resolveCurrent();- if (workspaceCaptureChains.get(key) === current) workspaceCaptureChains.delete(key);- },- };- workspaceCaptureLeasesBySession.set(sessionId, lease);- return { previous, lease };+/**+ * Optimistic concurrency for one shared workdir: overlapping turns are never+ * serialized (a turn has no bounded duration). Instead every capture that overlaps+ * another session's active capture is marked — the record stays reviewable, but an+ * after-image read during overlap may contain the other turn's writes, so both+ * sides become review-only (see isReversiblePatch).+ */+function markConcurrentWorkspaceCapture(sessionId: string): void {+ const key = pendingWorkspaceBySession.get(sessionId);+ const own = pendingBySession.get(sessionId);+ if (!key || !own) return;+ let overlapped = false;+ for (const [otherSessionId, otherKey] of pendingWorkspaceBySession) {+ if (otherSessionId === sessionId || otherKey !== key) continue;+ const other = pendingBySession.get(otherSessionId);+ if (!other) continue;+ addIncompleteReason(other, 'concurrent-workspace');+ overlapped = true;+ }+ if (overlapped) addIncompleteReason(own, 'concurrent-workspace');}async function waitForWorkspaceActions(cwd: string): Promise<void> {@@ -814,7 +805,7 @@ export async function beginTurnChangeSet(input: BeginTurnChangeSetInput): PromisclearPendingTurnChangeSets(input.sessionId);return;}- let existing = pendingBySession.get(input.sessionId);+ const existing = pendingBySession.get(input.sessionId);if (existing) {if (existing.anchorClientId === input.anchorClientId) return;log.warn('replacing unfinished turn change-set at dispatch boundary', {@@ -825,41 +816,21 @@ export async function beginTurnChangeSet(input: BeginTurnChangeSetInput): PromispendingBySession.delete(input.sessionId);unregisterPendingWorkspace(input.sessionId);}- const existingLease = workspaceCaptureLeasesBySession.get(input.sessionId);- if (existingLease) {- if (existingLease.anchorClientId === input.anchorClientId) {- await existingLease.ready;- return;- }- releaseWorkspaceCaptureLease(input.sessionId);- }- const { previous, lease } = reserveWorkspaceCaptureLease(- input.sessionId,- input.cwd,- input.anchorClientId,- );- try {- await previous.catch(() => undefined);- if (lease.cancelled || workspaceCaptureLeasesBySession.get(input.sessionId) !== lease) return;- await waitForWorkspaceActions(input.cwd);- if (lease.cancelled || workspaceCaptureLeasesBySession.get(input.sessionId) !== lease) return;- existing = pendingBySession.get(input.sessionId);- if (existing?.anchorClientId === input.anchorClientId) {- lease.resolveReady();- return;- }- if (existing) {- pendingBySession.delete(input.sessionId);- unregisterPendingWorkspace(input.sessionId);- }- const pending = ensurePending(input.sessionId, input.provider, input.cwd);- pending.anchorClientId = input.anchorClientId;- lease.resolveReady();- } catch (error) {- lease.rejectReady(error);- releaseWorkspaceCaptureLease(input.sessionId);- throw error;+ const epoch = beginEpochBySession.get(input.sessionId) ?? 0;+ // Bounded waits only: prior after-image seals and user-triggered undo/reapply in+ // this workspace. Dispatch never waits for another session's running turn — an+ // overlapping turn degrades both captures instead (markConcurrentWorkspaceCapture).+ await waitForWorkspaceSeals(input.cwd);+ await waitForWorkspaceActions(input.cwd);+ if ((beginEpochBySession.get(input.sessionId) ?? 0) !== epoch) return;+ const raced = pendingBySession.get(input.sessionId);+ if (raced && raced.anchorClientId !== null && raced.anchorClientId !== input.anchorClientId) {+ pendingBySession.delete(input.sessionId);+ unregisterPendingWorkspace(input.sessionId);}+ const pending = ensurePending(input.sessionId, input.provider, input.cwd);+ pending.anchorClientId = input.anchorClientId;+ markConcurrentWorkspaceCapture(input.sessionId);}function addIncompleteReason(@@ -1096,12 +1067,15 @@ async function persistPending(const files = diffs.length > 0 ? summarizeDiffs(diffs) : pending.nativeFiles;// An opaque tool with no known paths is still important turn metadata. Persist a// zero-file partial entry so the UI never silently represents it as fully tracked.- // 'turn-failed' alone is not such evidence: a turn that failed without any capture- // activity (no tools, no files) cannot have changed the workspace, so persisting- // an empty partial card would claim untracked changes that never existed.+ // 'turn-failed' and 'concurrent-workspace' alone are not such evidence: a turn+ // that failed or merely overlapped another session without any capture activity+ // (no tools, no files) has nothing to record, so persisting an empty partial card+ // would claim untracked changes that never existed.if (files.length === 0- && [...pending.incompleteReasons].every((reason) => reason === 'turn-failed')+ && [...pending.incompleteReasons].every(+ (reason) => reason === 'turn-failed' || reason === 'concurrent-workspace',+ )) return;const anchorClientId = pending.anchorClientId;if (!anchorClientId) {@@ -1148,12 +1122,15 @@ export function finalizeTurnChangeSet(const pending = pendingBySession.get(sessionId);if (!pending) return Promise.resolve();pendingBySession.delete(sessionId);- return enqueueSessionWrite(sessionId, () => persistPending(sessionId, pending, terminalState))+ const write = enqueueSessionWrite(sessionId, () => persistPending(sessionId, pending, terminalState)).catch((error) => log.warn('turn change-set persist failed', { sessionId, error })).finally(() => {unregisterPendingWorkspace(sessionId);- releaseWorkspaceCaptureLease(sessionId);});+ // The next dispatch in this workspace must not let its turn mutate files while+ // this after-image is still being read (registered synchronously on purpose).+ registerWorkspaceSeal(pending.cwd, write);+ return write;}/** Prevents the next product turn from mutating files before the prior after-image is sealed. */@@ -1427,7 +1404,7 @@ export function applyTurnChangeSetAction(export function clearPendingTurnChangeSets(sessionId: string): void {pendingBySession.delete(sessionId);unregisterPendingWorkspace(sessionId);- releaseWorkspaceCaptureLease(sessionId);+ cancelPendingBegin(sessionId);}async function validAnchorIds(sessionId: string, summaries: readonly TurnChangeSetSummary[]): Promise<Set<string>> {@@ -1495,7 +1472,7 @@ export async function getTurnChangeSets(export async function removeTurnChangeSetsForSession(sessionId: string): Promise<void> {pendingBySession.delete(sessionId);unregisterPendingWorkspace(sessionId);- releaseWorkspaceCaptureLease(sessionId);+ cancelPendingBegin(sessionId);await enqueueSessionWrite(sessionId, async () => {await fs.rm(sessionDir(sessionId), { recursive: true, force: true });});diff --git a/apps/desktop/src/shared/turnChangeSet.ts b/apps/desktop/src/shared/turnChangeSet.tsindex c67846cd11..97fd20b181 100644--- a/apps/desktop/src/shared/turnChangeSet.ts+++ b/apps/desktop/src/shared/turnChangeSet.ts@@ -16,7 +16,9 @@ export type TurnChangeIncompleteReason =| 'read-failed'| 'diff-too-large'| 'provider-diff-conflict'- | 'turn-failed';+ | 'turn-failed'+ /** Another session's turn overlapped in the same workspace; capture attribution is best-effort and never undoable. */+ | 'concurrent-workspace';export interface TurnChangeFileSummary {id: string;