Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(chat): serialize PR reference corrections with publication
xda37842cde6ed
diff --git a/apps/desktop/src/main/git-context/prRefsStore.ts b/apps/desktop/src/main/git-context/prRefsStore.tsindex ec9d65a56c..5471e890e3 100644--- a/apps/desktop/src/main/git-context/prRefsStore.ts+++ b/apps/desktop/src/main/git-context/prRefsStore.ts@@ -133,13 +133,55 @@ interface PrRefsRecomputeScope {isCurrent: () => boolean;}+// Recompute and publication share a per-DB/session queue so an old history+// snapshot cannot prune a concurrently published PR. Other sessions are independent.+const pendingPrWrites = new WeakMap<DbClient, Map<string, Promise<void>>>();++async function acquirePrWrite(dbClient: DbClient, sessionId: string): Promise<() => void> {+ let sessions = pendingPrWrites.get(dbClient);+ if (!sessions) {+ sessions = new Map();+ pendingPrWrites.set(dbClient, sessions);+ }+ const previous = sessions.get(sessionId) ?? Promise.resolve();+ let release!: () => void;+ const held = new Promise<void>((resolve) => { release = resolve; });+ // Queue promises only represent lock release and never reject. Each caller+ // releases in finally, so a failed write cannot block subsequent publications.+ const pending = previous.then(() => held);+ sessions.set(sessionId, pending);+ const queue = sessions;+ void pending.then(() => {+ if (queue.get(sessionId) === pending) queue.delete(sessionId);+ });+ await previous;+ return release;+}+async function upsertPrRefs(sessionId: string,refs: PrRef[],atMs?: number,opts?: { authoritative?: boolean; scope?: PrRefsRecomputeScope },): Promise<void> {- const db = (opts?.scope?.dbClient ?? getDbClient()).drizzle;+ const dbClient = opts?.scope?.dbClient ?? getDbClient();+ const release = await acquirePrWrite(dbClient, sessionId);+ try {+ await upsertPrRefsWithinWrite(dbClient, sessionId, refs, atMs, opts);+ } finally {+ release();+ }+}++/** Caller holds the session's PR write queue, including during recomputation. */+async function upsertPrRefsWithinWrite(+ dbClient: DbClient,+ sessionId: string,+ refs: PrRef[],+ atMs?: number,+ opts?: { authoritative?: boolean; scope?: PrRefsRecomputeScope },+): Promise<void> {+ const db = dbClient.drizzle;const ts = atMs ?? Date.now();for (const ref of refs) {if (opts?.scope && !opts.scope.isCurrent()) return;@@ -255,16 +297,20 @@ export async function ensurePrRefsBackfill(): Promise<void> {* 重算某 session 的 PR 引用,只统计"对用户可见"的消息——rewind(rewind_at* 置位软删)与 /clear(clearedAt 边界之前隐藏)之后调用,只出现在被回滚/被* clear 段里的 PR 不该再挂在会话上(Codex review P2 ×2)。- * 做法:删全量后按存活消息重提取,时间戳用消息原始 createdAt;完成广播刷新。- * rewind / clear 都是低频操作,全量重算可接受。+ * 按存活消息 upsert 后剪除过期引用,时间戳用消息原始 createdAt;完成广播刷新。+ * 与同任务的 PR 写入串行,避免迟到全文校准用旧快照剪除并发新消息的引用。*/export async function recomputePrRefsForSession(sessionId: string,scope?: PrRefsRecomputeScope,): Promise<void> {+ let release: (() => void) | undefined;try {if (scope && !scope.isCurrent()) return;- const db = (scope?.dbClient ?? getDbClient()).drizzle;+ const dbClient = scope?.dbClient ?? getDbClient();+ release = await acquirePrWrite(dbClient, sessionId);+ if (scope && !scope.isCurrent()) return;+ const db = dbClient.drizzle;const [sessionRow] = await db.select({ clearedAt: sessions.clearedAt }).from(sessions)@@ -298,7 +344,7 @@ export async function recomputePrRefsForSession(const refs = extractPrRefs(row.content);if (refs.length === 0) continue;for (const ref of refs) keep.add(`${ref.owner}/${ref.repo}#${ref.prNumber}`);- await upsertPrRefs(sessionId, refs, row.createdAt, { authoritative: true, scope });+ await upsertPrRefsWithinWrite(dbClient, sessionId, refs, row.createdAt, { authoritative: true, scope });}if (scope && !scope.isCurrent()) return;@@ -324,6 +370,8 @@ export async function recomputePrRefsForSession(sessionId,err: err instanceof Error ? err.message : String(err),});+ } finally {+ release?.();}}diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/assistantFinalRetraction.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/assistantFinalRetraction.test.tsindex 23a1cc2af2..ad12ce065b 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/assistantFinalRetraction.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/assistantFinalRetraction.test.ts@@ -4,7 +4,7 @@ import { drizzle } from 'drizzle-orm/better-sqlite3';import { afterEach, beforeEach, expect, it, vi } from 'vitest';import { messages, sessions } from '../../schema';import { tx } from '../../worker/opHandlers/tx';-import { discardPersistedAssistantMessage, updateMessageContent } from '../messages';+import { createMessage, discardPersistedAssistantMessage, updateMessageContent } from '../messages';import * as prRefsStore from '../../../git-context/prRefsStore';import * as previewRows from '../../latestMessageText';import { commitMessageMediaRefs } from '../../../cindy-media/chatAttachments';@@ -247,9 +247,10 @@ it('does not restore pre-clear PR references when retraction cleanup resumes aftconst boundary = Date.now() + 1000;h.sqlite!.prepare('UPDATE sessions SET cleared_at = ? WHERE id = ?').run(boundary, 's1');noteSessionClearBoundary('s1', boundary);- await prRefsStore.recomputePrRefsForSession('s1');- expect(await prRefsStore.listPrRefs('s1')).toHaveLength(0);+ const clearedRefs = prRefsStore.recomputePrRefsForSession('s1');release();+ await clearedRefs;+ expect(await prRefsStore.listPrRefs('s1')).toHaveLength(0);await drainPersistQueue();expect(await prRefsStore.listPrRefs('s1')).toHaveLength(0);} finally { release(); spy.mockRestore(); }@@ -478,3 +479,61 @@ it('does not republish a rewritten message at the session clear boundary', asyncexpect(h.broadcast.mock.calls.filter(([channel]) => channel === 'local-db:sessions:patched')).toHaveLength(0);});++it.each(['correction', 'retraction'])('preserves concurrent new-message PR refs during final %s', async (mode) => {+ onAssistantTextEvent('s1', { text: 'https://github.com/o/r/pull/1', agentMessageId: 'a' }, null);+ flushAssistantBlock('s1'); await drainPersistQueue();+ let release!: () => void, captured!: () => void;+ const resume = new Promise<void>(resolve => { release = resolve; });+ const snapshotTaken = new Promise<void>(resolve => { captured = resolve; });+ const db = h.client!.drizzle, select = db.select.bind(db);+ let paused = false;+ const spy = vi.spyOn(db, 'select').mockImplementation((fields) => {+ const query = select(fields);+ if (!fields || Object.keys(fields).sort().join(',') !== 'content,createdAt') return query;+ const from = query.from.bind(query);+ vi.spyOn(query, 'from').mockImplementation((table) => {+ const builder = from(table);+ if (table === messages && !paused) {+ const orderBy = builder.orderBy.bind(builder);+ vi.spyOn(builder, 'orderBy').mockImplementationOnce((...columns) => {+ paused = true; const snapshot = orderBy(...columns).all(); captured();+ return resume.then(() => snapshot) as unknown as ReturnType<typeof orderBy>;+ });+ }+ return builder;+ }); return query;+ });+ const hook = vi.spyOn(prRefsStore, 'recordPrRefsForMessage');+ try {+ onAssistantTextEvent('s1', { text: mode === 'retraction' ? '' : 'Corrected final without a link', agentMessageId: 'a', isFinal: true, isFullText: true }, null);+ await snapshotTaken;+ await createMessage('s1', { clientId: 'new-user', role: 'user', content: 'https://github.com/o/r/pull/2' });+ const newMessagePrWrite = hook.mock.results.at(-1)!.value;+ // A blocked recompute in s1 must not block another task's publication.+ await prRefsStore.recordPrRefsForMessage({ sessionId: 's2', role: 'user',+ content: 'https://github.com/o/r/pull/3', createdAt: Date.now() });+ expect((await prRefsStore.listPrRefs('s2')).map(ref => ref.prNumber)).toEqual([3]);+ // Let a non-serialized publication finish; a correctly queued hook waits+ // for the recompute. Do not await that hook while holding its predecessor.+ await new Promise<void>((resolve) => setImmediate(resolve));+ release();+ await newMessagePrWrite;+ await drainPersistQueue();+ expect(h.sqlite!.prepare("SELECT client_id FROM messages WHERE client_id='new-user'").get()).toBeTruthy();+ expect((await prRefsStore.listPrRefs('s1')).map(ref => ref.prNumber)).toContain(2);+ } finally { release(); spy.mockRestore(); hook.mockRestore(); }+});++it('releases the PR write queue after a failed publication', async () => {+ const insert = vi.spyOn(h.client!.drizzle, 'insert').mockImplementationOnce(() => {+ throw new Error('simulated PR write failure');+ });+ try {+ await prRefsStore.recordPrRefsForMessage({ sessionId: 's1', role: 'user',+ content: 'https://github.com/o/r/pull/1', createdAt: Date.now() });+ await prRefsStore.recordPrRefsForMessage({ sessionId: 's1', role: 'user',+ content: 'https://github.com/o/r/pull/2', createdAt: Date.now() });+ expect((await prRefsStore.listPrRefs('s1')).map(ref => ref.prNumber)).toEqual([2]);+ } finally { insert.mockRestore(); }+});