Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): preserve reauthorization intent and fence rewound card creation
zqchrisc079fe3399bc
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationHost.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationHost.test.tsindex c930c58ba8..d951648c8d 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationHost.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationHost.test.ts@@ -1,3 +1,4 @@+import { advanceSessionRewindGeneration, withSendToSessionLock } from '../sendToSessionLock';import { beforeEach, describe, expect, it, vi } from 'vitest';import type { GhostSetupAssessment } from '../../../shared/ghost';import type { BotAuthorizationCard } from '../../../shared/botAuthorization';@@ -75,6 +76,25 @@ describe('authorization Host frozen plugin policy', () => {});});+ it('rejects a prepared card when rewind wins the shared write boundary', async () => {+ await state.deps.adapter('session', target);+ const assertCurrent = state.deps.captureRequestGuard!('session');+ let release!: () => void;+ const rewind = withSendToSessionLock('session', async () => {+ await new Promise<void>((resolve) => { release = resolve; });+ advanceSessionRewindGeneration('session');+ });+ await vi.waitFor(() => expect(release).toBeTypeOf('function'));+ const saving = state.deps.save({ v: 1, sessionId: 'session', target, createdAt: 1,+ snapshot: { kind: 'plugin_setup', requestId: 'stale', revision: 1,+ ghost: { id: 'art', name: 'Art' }, steps: [] } }, assertCurrent);+ const rejected = expect(saving).rejects.toThrow('Authorization request was rewound');+ release();+ await rewind;+ await rejected;+ expect(state.save).not.toHaveBeenCalled();+ });+it('keeps credential A pending after credential B completes until A reauth is resolved', async () => {const ready: GhostSetupAssessment = { state: 'ready', revision: 1, groups: [] };state.assessment.mockReturnValue({ ...ready, reauthSuggest: {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationService.test.tsindex 4c3b0d0e5f..6718eab9ec 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationService.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationService.test.ts@@ -56,6 +56,7 @@ function harness() {card.sessionId === sessionId &&card.target.kind === target.kind &&card.target.id === target.id &&+ !!card.target.reauthorize === !!target.reauthorize &&!card.snapshot.terminal,) ?? null,),@@ -485,6 +486,17 @@ describe('authorization durable completion boundary', () => {});describe('durable authorization card deduplication', () => {+ it.each([false, true])('preserves explicit reauthorization when an ordinary card exists (expired=%s)', async (expired) => {+ const h = harness();+ const original = await h.service.request('s', { kind: 'plugin', id: 'p', reauthorize: false });+ if (expired) await vi.advanceTimersByTimeAsync(61 * 60_000);+ const reauth = await h.service.request('s', { kind: 'plugin', id: 'p', reauthorize: true });+ expect(reauth).not.toEqual(original);+ expect([...h.stored.values()].at(-1)?.target.reauthorize).toBe(true);+ expect(await h.service.request('s', { kind: 'plugin', id: 'p', reauthorize: true })).toEqual(reauth);+ await h.service.dispose();+ });+it('replaces an in-memory card whose persisted message was cleared', async () => {const h = harness();await h.service.request('s', { kind: 'plugin', id: 'p' });diff --git a/apps/desktop/src/main/maker-ipc/__tests__/rewind-ipc.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/rewind-ipc.test.tsindex e298065b3f..b739b42593 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/rewind-ipc.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/rewind-ipc.test.ts@@ -1,3 +1,4 @@+import { getSessionRewindGeneration } from '../sendToSessionLock';import { beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({@@ -111,9 +112,11 @@ describe('maker rewind IPC stop-then-rewind', () => {const handler = mocks.handlers.get(MAKER_INVOKE.REWIND_COMMIT);if (!handler) throw new Error('rewind commit handler not registered');+ const generation = getSessionRewindGeneration('session-1');await expect(handler({}, 'session-1', 'message-1', { stopIfRunning: true })).resolves.toBe(session,);+ expect(getSessionRewindGeneration('session-1')).toBe(generation + 1);expect(mocks.withSessionInputStoppedForRewind).toHaveBeenCalledWith('session-1',diff --git a/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts b/apps/desktop/src/main/maker-ipc/botAuthorizationHost.tsindex 1dd66a1803..ee79e73b4c 100644--- a/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts+++ b/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts@@ -1,3 +1,4 @@+import { getSessionRewindGeneration, withSendToSessionLock } from './sendToSessionLock.js';import { shell } from 'electron';import { t } from '../i18n.js';import { and, eq, isNull, ne, or, gt, like, desc, inArray } from 'drizzle-orm';@@ -250,48 +251,58 @@ export function initializeBotAuthorizationHost(},};},- async save(card) {- await assertSession(card.sessionId);- const [row] = await getDbClient()- .drizzle.select({ clearedAt: sessions.clearedAt })- .from(sessions)- .where(eq(sessions.id, card.sessionId))- .limit(1);- if (!row || (row.clearedAt !== null && row.clearedAt >= card.createdAt))- throw new Error('Authorization card was cleared');- card = {- ...card,- snapshot: {- ...sanitizeGhostSetupSnapshotForDesktop(card.snapshot),- ...(card.snapshot.reopenActionId ? { reopenActionId: card.snapshot.reopenActionId } : {}),- },+ captureRequestGuard(sessionId) {+ const generation = getSessionRewindGeneration(sessionId);+ return () => {+ if (getSessionRewindGeneration(sessionId) !== generation)+ throw new Error('Authorization request was rewound');};- const clientId = `bot-authorization:${card.snapshot.requestId}`;- const phase = card.snapshot.steps.find((s) => s.phase !== 'satisfied')?.phase ?? 'satisfied';- const fallback = `${card.snapshot.ghost.name} · ${t(`newChat.pluginSetup.phase.${phase}`)}${card.snapshot.terminal ? '' : ` · ${t('newChat.pluginSetup.completeOnDesktop')}`}`;- // Only the presentation is stored. Current assessment/actions are re-read on every click.- await createMessage(- card.sessionId,- {+ },+ async save(card, assertCurrent) {+ return withSendToSessionLock(card.sessionId, async () => {+ assertCurrent?.();+ await assertSession(card.sessionId);+ const [row] = await getDbClient()+ .drizzle.select({ clearedAt: sessions.clearedAt })+ .from(sessions)+ .where(eq(sessions.id, card.sessionId))+ .limit(1);+ if (!row || (row.clearedAt !== null && row.clearedAt >= card.createdAt))+ throw new Error('Authorization card was cleared');+ card = {+ ...card,+ snapshot: {+ ...sanitizeGhostSetupSnapshotForDesktop(card.snapshot),+ ...(card.snapshot.reopenActionId ? { reopenActionId: card.snapshot.reopenActionId } : {}),+ },+ };+ const clientId = `bot-authorization:${card.snapshot.requestId}`;+ const phase = card.snapshot.steps.find((s) => s.phase !== 'satisfied')?.phase ?? 'satisfied';+ const fallback = `${card.snapshot.ghost.name} · ${t(`newChat.pluginSetup.phase.${phase}`)}${card.snapshot.terminal ? '' : ` · ${t('newChat.pluginSetup.completeOnDesktop')}`}`;+ // Only the presentation is stored. Current assessment/actions are re-read on every click.+ await createMessage(+ card.sessionId,+ {+ clientId,+ role: 'assistant',+ content: fallback,+ agentMeta: { botAuthorization: card },+ createdAt: card.createdAt,+ },+ {+ broadcastOwnerScope: ownerScopes.get(card.sessionId),+ expectedClearBoundaryMs: row.clearedAt,+ },+ );+ await assertSession(card.sessionId);+ await updateMessageContent(card.sessionId, clientId, fallback);+ await patchMessageAgentMeta(card.sessionId, clientId, { botAuthorization: card });+ await broadcastMessageAgentMetaUpdate(+ card.sessionId,clientId,- role: 'assistant',- content: fallback,- agentMeta: { botAuthorization: card },- createdAt: card.createdAt,- },- {- broadcastOwnerScope: ownerScopes.get(card.sessionId),- expectedClearBoundaryMs: row.clearedAt,- },- );- await assertSession(card.sessionId);- await updateMessageContent(card.sessionId, clientId, fallback);- await patchMessageAgentMeta(card.sessionId, clientId, { botAuthorization: card });- await broadcastMessageAgentMetaUpdate(- card.sessionId,- clientId,- ownerScopes.get(card.sessionId),- );+ ownerScopes.get(card.sessionId),+ );+ });},async load(requestId) {const [row] = await getDbClient()@@ -332,7 +343,8 @@ export function initializeBotAuthorizationHost(card &&!card.snapshot.terminal &&card.target.kind === target.kind &&- card.target.id === target.id+ card.target.id === target.id &&+ !!card.target.reauthorize === !!target.reauthorize)return card;}diff --git a/apps/desktop/src/main/maker-ipc/botAuthorizationService.ts b/apps/desktop/src/main/maker-ipc/botAuthorizationService.tsindex 88ca68af94..452ec27d76 100644--- a/apps/desktop/src/main/maker-ipc/botAuthorizationService.ts+++ b/apps/desktop/src/main/maker-ipc/botAuthorizationService.ts@@ -58,7 +58,8 @@ export interface BotAuthorizationAdapter {}export interface BotAuthorizationDeps {adapter(sessionId: string, target: BotAuthorizationTarget): Promise<BotAuthorizationAdapter>;- save(card: BotAuthorizationCard): Promise<void>;+ captureRequestGuard?(sessionId: string): () => void;+ save(card: BotAuthorizationCard, assertCurrent?: () => void): Promise<void>;load(requestId: string): Promise<BotAuthorizationCard | null>;findPending(sessionId: string,@@ -105,7 +106,7 @@ export class BotAuthorizationService {private requests = new Map<string, ReturnType<BotAuthorizationService['requestCard']>>();request(sessionId: string, target: BotAuthorizationTarget, plan?: GhostSetupPlan) {- const key = `${this.epoch}:${sessionId}:${target.kind}:${target.id}`;+ const key = `${this.epoch}:${sessionId}:${target.kind}:${target.id}:${!!target.reauthorize}`;const existing = this.requests.get(key);if (existing) return existing;const pending = this.requestCard(sessionId, target, plan).finally(() =>@@ -121,6 +122,7 @@ export class BotAuthorizationService {plan?: GhostSetupPlan,) {const epoch = this.epoch;+ const assertCurrent = this.deps.captureRequestGuard?.(sessionId);const adapter = await this.deps.adapter(sessionId, target);const assessment = await adapter.assess();if (epoch !== this.epoch) throw new Error('Authorization context changed');@@ -131,7 +133,8 @@ export class BotAuthorizationService {!e.closed &&e.card.sessionId === sessionId &&e.card.target.kind === target.kind &&- e.card.target.id === target.id,+ e.card.target.id === target.id &&+ !!e.card.target.reauthorize === !!target.reauthorize,);if (existing) {await existing.writes;@@ -160,7 +163,7 @@ export class BotAuthorizationService {const entry = this.attach(card, adapter);entry.assessmentFingerprint = JSON.stringify(assessment);try {- await this.save(entry);+ await this.save(entry, assertCurrent);} catch (error) {this.close(entry);throw error;@@ -205,11 +208,11 @@ export class BotAuthorizationService {);entry.expiry.unref?.();}- private save(entry: Entry): Promise<void> {+ private save(entry: Entry, assertCurrent?: () => void): Promise<void> {const card = structuredClone(entry.card);const write = entry.writes.then(() => {- if (!entry.closed) return this.deps.save(card);+ if (!entry.closed) return this.deps.save(card, assertCurrent);}).catch((error: unknown) => {if ((error as { code?: string } | null)?.code === 'REMOTE_OPTIMISTIC_INPUT_CLEARED')diff --git a/apps/desktop/src/main/maker-ipc/rewind.ts b/apps/desktop/src/main/maker-ipc/rewind.tsindex 9e748e963d..c9b0b32d2c 100644--- a/apps/desktop/src/main/maker-ipc/rewind.ts+++ b/apps/desktop/src/main/maker-ipc/rewind.ts@@ -1,4 +1,4 @@-import { withSendToSessionLock } from './sendToSessionLock.js';+import { withSendToSessionLock, advanceSessionRewindGeneration } from './sendToSessionLock.js';/*** registerMakerRewindIpc — maker:rewind:preview / maker:rewind:commit*@@ -67,7 +67,11 @@ async function commitAfterPersistBarrier(// withdrawn work visible again. Drain first, then let commitRewindAtMessage// reload its target and transaction boundary from the durable store.await drainPersistQueue();- return withSendToSessionLock(sessionId, () => commitRewindAtMessage(sessionId, clientId, opts));+ return withSendToSessionLock(sessionId, async () => {+ const result = await commitRewindAtMessage(sessionId, clientId, opts);+ advanceSessionRewindGeneration(sessionId);+ return result;+ });}function wrapErr(err: unknown): never {diff --git a/apps/desktop/src/main/maker-ipc/sendToSessionLock.ts b/apps/desktop/src/main/maker-ipc/sendToSessionLock.tsindex 0e6e8801e7..5ebe0b6ed1 100644--- a/apps/desktop/src/main/maker-ipc/sendToSessionLock.ts+++ b/apps/desktop/src/main/maker-ipc/sendToSessionLock.ts@@ -154,3 +154,13 @@ export function trackSendToSessionLockRun<T>(installSendToSessionLockEntry(sessionId, run as Promise<unknown>, getStage);return run;}++// A request may start before rewind and acquire the write lock only afterwards.+// Capture this generation before async preparation and validate inside the lock.+const rewindGenerations = new Map<string, number>();+export function getSessionRewindGeneration(sessionId: string): number {+ return rewindGenerations.get(sessionId) ?? 0;+}+export function advanceSessionRewindGeneration(sessionId: string): void {+ rewindGenerations.set(sessionId, getSessionRewindGeneration(sessionId) + 1);+}