Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): fence authorization creation and continuation against history changes
zqchrisb3b99c60b702
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationService.test.tsindex 7165857788..271590ffd0 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationService.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationService.test.ts@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import {BotAuthorizationService,buildBotAuthorizationContinuation,+ commitBotAuthorizationInput,type BotAuthorizationAdapter,} from '../botAuthorizationService';import type { BotAuthorizationCard } from '../../../shared/botAuthorization';@@ -439,3 +440,58 @@ it('retires an OAuth waiter when the card is rewound during completion persistenexpect(h.deps.resume).not.toHaveBeenCalled();await h.service.dispose();});++describe('authorization input CAS', () => {+ it('does not enqueue when clear wins during the visibility query', async () => {+ let generation = 1;+ const captured = generation;+ let finish!: () => void;+ const enqueue = vi.fn();+ const committing = commitBotAuthorizationInput(+ {+ validate: () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ }),+ assertCurrent: () => {+ if (generation !== captured) throw new Error('cleared');+ },+ },+ enqueue,+ );+ const rejected = expect(committing).rejects.toThrow('cleared');+ generation++;+ finish();+ await rejected;+ expect(enqueue).not.toHaveBeenCalled();+ });+ it('checks the generation and enqueues in one synchronous boundary', async () => {+ const events: string[] = [];+ await commitBotAuthorizationInput(+ {+ validate: async () => {+ events.push('visible');+ },+ assertCurrent: () => {+ events.push('guard');+ queueMicrotask(() => events.push('clear'));+ },+ },+ () => {+ events.push('enqueue');+ },+ );+ expect(events).toEqual(['visible', 'guard', 'enqueue', 'clear']);+ });+ it('retires the card entry when creation loses the durable clear-boundary CAS', async () => {+ const h = harness();+ h.deps.save.mockRejectedValueOnce(+ Object.assign(new Error('clear won'), { code: 'REMOTE_OPTIMISTIC_INPUT_CLEARED' }),+ );+ await expect(h.service.request('s', { kind: 'host', id: 'grok' })).rejects.toThrow('clear won');+ expect(h.listeners.size).toBe(0);+ expect(h.stored.size).toBe(0);+ expect(h.adapter.execute).not.toHaveBeenCalled();+ await h.service.dispose();+ });+});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 248b53ac29..e298065b3f 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@@ -63,6 +63,7 @@ vi.mock('../../logger.js', () => ({import { MAKER_INVOKE } from '../channels.js';import { registerMakerRewindIpc } from '../rewind.js';+import { acquireSendToSessionLock } from '../sendToSessionLock.js';function sessionRunningError(): Error & { code: 'SESSION_RUNNING' } {return Object.assign(new Error('session running'), { code: 'SESSION_RUNNING' as const });@@ -84,6 +85,21 @@ describe('maker rewind IPC stop-then-rewind', () => {registerMakerRewindIpc();});+ it('does not commit rewind while authorization owns the session send boundary', async () => {+ const release = await acquireSendToSessionLock('session-1');+ mocks.commitRewindAtMessage.mockResolvedValue({ id: 'session-1' });+ const handler = mocks.handlers.get(MAKER_INVOKE.REWIND_COMMIT)!;+ const rewinding = handler({}, 'session-1', 'message-1', { stopIfRunning: true });+ try {+ for (let i = 0; i < 20; i++) await Promise.resolve();+ expect(mocks.commitRewindAtMessage).not.toHaveBeenCalled();+ } finally {+ release();+ }+ await rewinding;+ expect(mocks.commitRewindAtMessage).toHaveBeenCalledOnce();+ });+it('runs normal rewind inside the stopped input boundary when requested', async () => {const session = { id: 'session-1' };const visibleBefore = [{ provider: 'claude-code', identities: ['before'] }];diff --git a/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts b/apps/desktop/src/main/maker-ipc/botAuthorizationHost.tsindex 173e7650ca..86ee627a3c 100644--- a/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts+++ b/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts@@ -62,7 +62,7 @@ export async function isBotAuthorizationSession(sessionId: string): Promise<bool/** Adapts existing Host credentials and plugin configuration into the same card lifecycle. */export function initializeBotAuthorizationHost(- resume: (card: BotAuthorizationCard) => Promise<void>,+ resume: (card: BotAuthorizationCard, validate: () => Promise<void>) => Promise<void>,) {const ownerScopes = new Map<string, ReturnType<typeof captureDataOwnerBroadcastScope>>();const assertSession = async (sessionId: string) => {@@ -250,7 +250,10 @@ export function initializeBotAuthorizationHost(agentMeta: { botAuthorization: card },createdAt: card.createdAt,},- { broadcastOwnerScope: ownerScopes.get(card.sessionId) },+ {+ broadcastOwnerScope: ownerScopes.get(card.sessionId),+ expectedClearBoundaryMs: row.clearedAt,+ },);await assertSession(card.sessionId);await updateMessageContent(card.sessionId, clientId, fallback);@@ -307,23 +310,24 @@ export function initializeBotAuthorizationHost(return null;},async resume(card) {- await assertSession(card.sessionId);- const [row] = await getDbClient()- .drizzle.select({ id: messages.id })- .from(messages)- .innerJoin(sessions, eq(sessions.id, messages.sessionId))- .where(- and(- eq(messages.sessionId, card.sessionId),- eq(messages.clientId, `bot-authorization:${card.snapshot.requestId}`),- isNull(messages.rewindAt),- or(isNull(sessions.clearedAt), gt(messages.createdAt, sessions.clearedAt)),- ),- )- .limit(1);- if (!row) throw new Error('Authorization card is no longer visible');- await assertSession(card.sessionId);- await resume(card);+ await resume(card, async () => {+ await assertSession(card.sessionId);+ const [row] = await getDbClient()+ .drizzle.select({ id: messages.id })+ .from(messages)+ .innerJoin(sessions, eq(sessions.id, messages.sessionId))+ .where(+ and(+ eq(messages.sessionId, card.sessionId),+ eq(messages.clientId, `bot-authorization:${card.snapshot.requestId}`),+ isNull(messages.rewindAt),+ or(isNull(sessions.clearedAt), gt(messages.createdAt, sessions.clearedAt)),+ ),+ )+ .limit(1);+ if (!row) throw new Error('Authorization card is no longer visible');+ await assertSession(card.sessionId);+ });},onDisposing: () => cancelGrokOAuthLogin(),onDispose: () => ownerScopes.clear(),diff --git a/apps/desktop/src/main/maker-ipc/botAuthorizationService.ts b/apps/desktop/src/main/maker-ipc/botAuthorizationService.tsindex ff15da0713..bb6866a9f8 100644--- a/apps/desktop/src/main/maker-ipc/botAuthorizationService.ts+++ b/apps/desktop/src/main/maker-ipc/botAuthorizationService.ts@@ -29,6 +29,22 @@ export function buildBotAuthorizationContinuation(card: BotAuthorizationCard) {};}+export interface BotAuthorizationInputGuard {+ validate(): Promise<void>;+ assertCurrent(): void;+}++/** Called while the existing session send lock is held. No await may separate+ * the synchronous clear-generation check from enqueue. */+export async function commitBotAuthorizationInput(+ guard: BotAuthorizationInputGuard,+ enqueue: () => void,+) {+ await guard.validate();+ guard.assertCurrent();+ enqueue();+}+export interface BotAuthorizationAdapter {identity: { id: string; name: string; iconDataUrl?: string };assess(): Promise<GhostSetupAssessment>;@@ -191,9 +207,15 @@ export class BotAuthorizationService {}private save(entry: Entry): Promise<void> {const card = structuredClone(entry.card);- const write = entry.writes.then(() => {- if (!entry.closed) return this.deps.save(card);- });+ const write = entry.writes+ .then(() => {+ if (!entry.closed) return this.deps.save(card);+ })+ .catch((error: unknown) => {+ if ((error as { code?: string } | null)?.code === 'REMOTE_OPTIMISTIC_INPUT_CLEARED')+ this.close(entry);+ throw error;+ });entry.writes = write.catch(this.deps.warn);return write;}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 8d13ddfdb4..7fe73850f7 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -1,5 +1,5 @@import { initializeBotAuthorizationHost } from './botAuthorizationHost.js';-import { buildBotAuthorizationContinuation, getBotAuthorizationService } from './botAuthorizationService.js';+import { buildBotAuthorizationContinuation, commitBotAuthorizationInput, type BotAuthorizationInputGuard, getBotAuthorizationService } from './botAuthorizationService.js';import { registerSessionSetModelHandler } from './sessionSetModelHandler.js';import { projectRemoteBotDelegations } from './remoteBotDelegations.js';/**@@ -8184,6 +8184,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)onAcceptedRollback?: () => void | Promise<void>;onAcceptedCommit?: () => void | Promise<void>;origin?: AgentInputQueuedMessage['origin'];+ authorizationGuard?: BotAuthorizationInputGuard;createDefaults?: SendToSessionCreateDefaults;/** 安全调用方可要求新会话不比来源会话拥有更高的权限。 */inheritSourcePermissionMode?: boolean;@@ -8551,6 +8552,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)onAcceptedRollback,onAcceptedCommit,origin: queuedOrigin,+ authorizationGuard: params.authorizationGuard,});return {ok: true as const,@@ -8880,6 +8882,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const dispatchBotSessionMessage = async (params: {targetSessionId: string;+ authorizationGuard?: BotAuthorizationInputGuard;message: string;persistedContent?: string;clientId?: string;@@ -8950,9 +8953,20 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)return sendToSessionInternal(params);};- initializeBotAuthorizationHost(async (card) => {+ initializeBotAuthorizationHost(async (card, validate) => {await inputCoordinator.ensureQueueRestored(card.sessionId);- const result = await dispatchBotSessionMessage(buildBotAuthorizationContinuation(card));+ const generation = inputCoordinator.getGeneration(card.sessionId);+ const authorizationGuard: BotAuthorizationInputGuard = {+ validate,+ assertCurrent: () => {+ assertRemoteInputClearNotInFlight(card.sessionId, true);+ if (rewindInputSessions.has(card.sessionId) || !inputCoordinator.isGenerationCurrent(card.sessionId, generation)) {+ throw new Error('Authorization input boundary changed');+ }+ },+ };+ authorizationGuard.assertCurrent();+ const result = await dispatchBotSessionMessage({ ...buildBotAuthorizationContinuation(card), authorizationGuard });if (!result.ok) throw new Error('Authorization continuation not accepted');await awaitAgentInputQueueSnapshotPersistence(card.sessionId);});@@ -9427,6 +9441,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)onAcceptedRollback?: () => void | Promise<void>;onAcceptedCommit?: () => void | Promise<void>;origin?: AgentInputQueuedMessage['origin'];+ authorizationGuard?: BotAuthorizationInputGuard;}): Promise<void> {const queued = await buildSessionControlInputItem(params);if (params.onAccepted) {@@ -9440,7 +9455,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 崩溃恢复排序:确保先读回持久化队列再追加本条(见 ensureQueueRestored)。// 失败时 enqueue 照常入队(shouldQueueNewTurn 已守住不会直发)。await inputCoordinator.ensureQueueRestored(params.targetSessionId).catch(() => undefined);- inputCoordinator.enqueue(params.targetSessionId, queued);+ if (params.authorizationGuard) {+ await commitBotAuthorizationInput(params.authorizationGuard, () => {+ inputCoordinator.enqueue(params.targetSessionId, queued);+ });+ } else {+ inputCoordinator.enqueue(params.targetSessionId, queued);+ }log.info('send_to_session queued while target busy', {targetSessionId: params.targetSessionId,clientId: params.clientId,diff --git a/apps/desktop/src/main/maker-ipc/rewind.ts b/apps/desktop/src/main/maker-ipc/rewind.tsindex 50ee7698e2..9e748e963d 100644--- a/apps/desktop/src/main/maker-ipc/rewind.ts+++ b/apps/desktop/src/main/maker-ipc/rewind.ts@@ -1,3 +1,4 @@+import { withSendToSessionLock } from './sendToSessionLock.js';/*** registerMakerRewindIpc — maker:rewind:preview / maker:rewind:commit*@@ -66,7 +67,7 @@ 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 commitRewindAtMessage(sessionId, clientId, opts);+ return withSendToSessionLock(sessionId, () => commitRewindAtMessage(sessionId, clientId, opts));}function wrapErr(err: unknown): never {diff --git a/docs/product-rules/bot-authorization-cards.md b/docs/product-rules/bot-authorization-cards.mdindex fa6abf1ef6..ee683ba991 100644--- a/docs/product-rules/bot-authorization-cards.md+++ b/docs/product-rules/bot-authorization-cards.md@@ -51,3 +51,7 @@ Grok 的 MCP 后端 state TTL 不能直接套给 Grok 订阅登录或所有插卡片去重以未清空、未回退的持久消息为准;内存观察器到期不失去该关系。清空后重新请求生成新卡,观察器到期后重新请求复用旧卡,同一账号的并发请求共用一次创建。++创建卡片使用现有 expectedClearBoundaryMs CAS;边界变化即拒绝保存并退役观察器。+续接的可见性查询移入发送锁内,rewind 提交共用该锁;查询之后以同步代次检查及入队+封住 /clear 并发窗口,不在检查与入队之间让出执行。