Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): predict-prompt 派发紧前复查 agentKind 防切换竞态
Shinku7b98fdc0723f
diff --git a/apps/desktop/src/main/maker-host/__tests__/titleOneShot.test.ts b/apps/desktop/src/main/maker-host/__tests__/titleOneShot.test.tsindex f0a1e280b5..9d26123f92 100644--- a/apps/desktop/src/main/maker-host/__tests__/titleOneShot.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/titleOneShot.test.ts@@ -387,6 +387,70 @@ describe('generateTitleViaProviderResult — 手动重命名失败语义', () =>});+describe('generateTitleViaProviderResult — beforeDispatch 派发紧前复查', () => {+ it('beforeDispatch 返回 true → 照常派发,并收到 (sessionId, agentKind)', async () => {+ const fetchImpl = fakeFetch(() => ({+ json: { content: [{ type: 'text', text: '标题' }] },+ }));+ const beforeDispatch = vi.fn(async () => true);++ const result = await generateTitleViaProviderResult(+ { sessionId: 's-bd', agentKind: 'claude-code', prompt: 'x' },+ {+ fetchImpl,+ readSessionProviderId: async () => 'anthropic',+ listConnectedProviders: async () => [providerStub('anthropic')],+ readAnthropicOAuth: () => ({ accessToken: 'tok' }),+ beforeDispatch,+ },+ );++ expect(result).toEqual({ status: 'ok', title: '标题' });+ // 复查发生在凭证到手、请求发出的紧前,并收到本次 one-shot 的解析口径。+ expect(beforeDispatch).toHaveBeenCalledWith({ sessionId: 's-bd', agentKind: 'claude-code' });+ expect(fetchImpl).toHaveBeenCalledTimes(1);+ });++ it('beforeDispatch 返回 false → 派发紧前中止,不发付费请求', async () => {+ const fetchImpl = fakeFetch(() => ({+ json: { content: [{ type: 'text', text: '不应出现' }] },+ }));++ const result = await generateTitleViaProviderResult(+ { sessionId: 's-bd-fail', agentKind: 'claude-code', prompt: 'x' },+ {+ fetchImpl,+ readSessionProviderId: async () => 'anthropic',+ listConnectedProviders: async () => [providerStub('anthropic')],+ readAnthropicOAuth: () => ({ accessToken: 'tok' }),+ beforeDispatch: async () => false,+ },+ );++ expect(result).toEqual({ status: 'failed' });+ expect(fetchImpl).not.toHaveBeenCalled();+ });++ it('未注入 beforeDispatch(标题场景)→ 不复查,行为不变', async () => {+ const fetchImpl = fakeFetch(() => ({+ json: { content: [{ type: 'text', text: '标题' }] },+ }));++ const result = await generateTitleViaProviderResult(+ { sessionId: 's-no-bd', agentKind: 'claude-code', prompt: 'x' },+ {+ fetchImpl,+ readSessionProviderId: async () => 'anthropic',+ listConnectedProviders: async () => [providerStub('anthropic')],+ readAnthropicOAuth: () => ({ accessToken: 'tok' }),+ },+ );++ expect(result).toEqual({ status: 'ok', title: '标题' });+ expect(fetchImpl).toHaveBeenCalledTimes(1);+ });+});+// ── buildTitleTarget(锁定 catalog titleModel 配置)────────────────────────describe('buildTitleTarget(锁定 catalog titleModel 配置)', () => {diff --git a/apps/desktop/src/main/maker-host/title-one-shot.ts b/apps/desktop/src/main/maker-host/title-one-shot.tsindex df7287d6ab..44f4ab331c 100644--- a/apps/desktop/src/main/maker-host/title-one-shot.ts+++ b/apps/desktop/src/main/maker-host/title-one-shot.ts@@ -108,6 +108,13 @@ export interface TitleOneShotDeps {Promise<{ accessToken: string } | null> | { accessToken: string } | null;readCodexCreds?: () => { accessToken: string; accountId: string } | null;readGatewayKey?: () => string | null;+ /**+ * 派发紧前复查(异步):凭证到手、请求发出的紧前,回读会话归属 / agent 是否仍与本次+ * one-shot 的解析口径一致。返回 false 则中止本次 one-shot(回落失败,不发出付费请求)。+ * prompt prediction 用它防「等待期间会话被切换 agent,仍把转写路由到切换前的 provider /+ * 账号」的 TOCTOU 竞态;标题场景无此竞态,缺省不复查。+ */+ beforeDispatch?: (args: { sessionId: string; agentKind: AgentKind }) => Promise<boolean>;}const EFFORT_RANK: Record<Effort, number> = {@@ -553,6 +560,24 @@ export async function generateTitleViaProviderResult(});return false;};+ // 派发紧前复查:同步的 route 可用性(canDispatchNow)之外,再叠加可选的异步会话归属+ // 复查(beforeDispatch)。凭证获取是可能数秒的 await,期间会话可能被切换 agent / 转远程,+ // 仅在发出付费请求的紧前复查才能把窗口缩到最小。+ const preDispatchEligible = async (stage: string): Promise<boolean> => {+ if (!canDispatchNow(stage)) return false;+ if (+ deps.beforeDispatch &&+ !(await deps.beforeDispatch({ sessionId: args.sessionId, agentKind: args.agentKind }))+ ) {+ log.debug('title oneShot skipped: pre-dispatch eligibility check failed', {+ providerId,+ model: target.model,+ stage,+ });+ return false;+ }+ return true;+ };// 非标题场景(如 prompt prediction)可覆盖 token 数/校验规则。const maxTokens = opts?.maxTokens ?? TITLE_MAX_TOKENS;const codexInstructions = opts?.codexInstructions ?? CODEX_TITLE_INSTRUCTIONS;@@ -567,7 +592,7 @@ export async function generateTitleViaProviderResult(log.debug('title oneShot skipped: no anthropic OAuth', { providerId });return { status: 'failed' };}- if (!canDispatchNow('after-credential-refresh')) {+ if (!(await preDispatchEligible('after-credential-refresh'))) {return { status: 'failed' };}text = await fetchAnthropicTitle(@@ -588,7 +613,7 @@ export async function generateTitleViaProviderResult(log.debug('title oneShot skipped: no codex creds', { providerId });return { status: 'failed' };}- if (!canDispatchNow('after-credential-read')) {+ if (!(await preDispatchEligible('after-credential-read'))) {return { status: 'failed' };}text = await fetchCodexTitle(@@ -610,7 +635,7 @@ export async function generateTitleViaProviderResult(log.debug('title oneShot skipped: no gateway key', { providerId });return { status: 'failed' };}- if (!canDispatchNow('after-credential-read')) {+ if (!(await preDispatchEligible('after-credential-read'))) {return { status: 'failed' };}text = await fetchGatewayTitle(diff --git a/apps/desktop/src/main/maker-ipc/promptPrediction.ts b/apps/desktop/src/main/maker-ipc/promptPrediction.tsindex ef05c7b262..ad95dcc3c1 100644--- a/apps/desktop/src/main/maker-ipc/promptPrediction.ts+++ b/apps/desktop/src/main/maker-ipc/promptPrediction.ts@@ -14,6 +14,7 @@import type { AgentKind } from '@cindy/maker-core';+import { dbToMakerAgentKind } from '../../shared/agentKindConversion.js';import { getResolvedMainLocale } from '../i18n.js';import { getDesktopProviderService } from '../maker-host/createDesktopProviderService.js';import { generateTitleViaProviderResult } from '../maker-host/title-one-shot.js';@@ -197,6 +198,25 @@ export async function generatePromptPrediction({readSessionProviderId: readSessionProviderIdFromDb,listConnectedProviders: listConnectedProvidersForAgent,+ // 派发紧前复查:会话在 drain 与 provider/凭证解析期间可能被切换 agent+ // (sessionAgentSwitchHandler 会提交 agentKind 变更),上方 title.ts handler 里 drain 后的+ // agentKind 复核到 provider 实际发出 HTTP 之间仍有一段异步窗口。这里在发出付费请求的紧前+ // 再回读一次 DB agentKind,与本次预测所用 agentKind 不一致时中止,避免把新 agent 的转写+ // 路由到切换前的 provider/账号触发付费调用。+ beforeDispatch: async ({ sessionId, agentKind }) => {+ try {+ const [row] = await getDbClient()+ .drizzle.select({ agentKind: sessions.agentKind })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ if (!row) return false;+ return dbToMakerAgentKind(row.agentKind) === agentKind;+ } catch {+ // 复查失败按 fail-closed 处理:宁可漏掉一次推荐,也不在归属不确定时外发付费调用。+ return false;+ }+ },},{maxTokens: 96,