Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 跨窗口去重改为 DB 权威 updatedAt + beforeDispatch 后凭证终末复查

Shinkuff37dde45efe
diff --git a/apps/desktop/src/main/maker-host/title-one-shot.ts b/apps/desktop/src/main/maker-host/title-one-shot.ts
index 5a4f377e80..a760505eee 100644
--- a/apps/desktop/src/main/maker-host/title-one-shot.ts
+++ b/apps/desktop/src/main/maker-host/title-one-shot.ts
@@ -627,9 +627,10 @@ export async function generateTitleViaProviderResult(
return { status: 'failed' };
}
// readAnthropicOAuth 是异步操作,期间 session 可能被删除/切换 agent/
- // 转远程/改工作目录。在最后一个 await 之后再做一次 session 归属复核
- // (仅 DB 查询,不做 provider/credential 状态读取),避免用过期
- // session 上下文外发付费调用。
+ // 转远程/改工作目录。在最后一个 await 之后再做一次 session 归属复核,
+ // 避免用过期 session 上下文外发付费调用。
+ // 注:deps.beforeDispatch 内部会调用 listConnectedProvidersForAgent(),
+ // 该异步操作期间凭证可能变更,在 beforeDispatch 返回后还有一轮凭证终末复查。
if (
deps.beforeDispatch &&
!(await deps.beforeDispatch({
@@ -643,6 +644,17 @@ export async function generateTitleViaProviderResult(
});
return { status: 'failed' };
}
+ // deps.beforeDispatch 内部调用 listConnectedProvidersForAgent() 是异步操作
+ // 且允许凭证相关副作用。期间用户可能切换账号/轮换 OAuth token。在最后一个
+ // await 之后重新读取并比对,捕获 beforeDispatch 期间的凭证变更,避免向
+ // 旧账号外发付费调用。
+ const oauthPostDispatch = await readAnthropicOAuth();
+ if (oauthPostDispatch?.accessToken !== oauth.accessToken) {
+ log.debug('oneShot skipped: credential changed during beforeDispatch', {
+ providerId,
+ });
+ return { status: 'failed' };
+ }
text = await fetchAnthropicTitle(
target.upstream,
target.model,
@@ -693,9 +705,9 @@ export async function generateTitleViaProviderResult(
return { status: 'failed' };
}
// readCodexCreds 是同步操作,但 preDispatchEligible 内部有异步 provider
- // 状态读取,期间 session 可能被删除/切换 agent/转远程。在最后一个 await
- // 之后再做一次 session 归属复核(仅 DB 查询),避免用过期 session 上下文
- // 外发付费调用。
+ // 状态读取,期间 session 可能被删除/切换 agent/转远程/改工作目录。
+ // 在最后一个 await 之后再做一次 session 归属复核(仅 DB 查询),
+ // 避免用过期 session 上下文外发付费调用。
if (
deps.beforeDispatch &&
!(await deps.beforeDispatch({
@@ -709,6 +721,21 @@ export async function generateTitleViaProviderResult(
});
return { status: 'failed' };
}
+ // deps.beforeDispatch 内部调用 listConnectedProvidersForAgent() 是异步操作
+ // 且允许凭证相关副作用。期间用户可能切换 workspace/轮换 token。在最后一个
+ // await 之后重新读取并比对,捕获 beforeDispatch 期间的凭证变更,避免向
+ // 旧账号外发付费调用。
+ const credsPostDispatch = readCodexCreds();
+ if (
+ !credsPostDispatch ||
+ credsPostDispatch.accountId !== creds.accountId ||
+ credsPostDispatch.accessToken !== creds.accessToken
+ ) {
+ log.debug('oneShot skipped: credential changed during beforeDispatch', {
+ providerId,
+ });
+ return { status: 'failed' };
+ }
text = await fetchCodexTitle(
target.upstream,
target.model,
@@ -751,9 +778,9 @@ export async function generateTitleViaProviderResult(
return { status: 'failed' };
}
// readGatewayKey 是同步操作,但 preDispatchEligible 内部有异步 provider
- // 状态读取,期间 session 可能被删除/切换 agent/转远程。在最后一个 await
- // 之后再做一次 session 归属复核(仅 DB 查询),避免用过期 session 上下文
- // 外发付费调用。
+ // 状态读取,期间 session 可能被删除/切换 agent/转远程/改工作目录。
+ // 在最后一个 await 之后再做一次 session 归属复核(仅 DB 查询),
+ // 避免用过期 session 上下文外发付费调用。
if (
deps.beforeDispatch &&
!(await deps.beforeDispatch({
@@ -767,6 +794,16 @@ export async function generateTitleViaProviderResult(
});
return { status: 'failed' };
}
+ // deps.beforeDispatch 内部调用 listConnectedProvidersForAgent() 是异步操作
+ // 且允许凭证相关副作用。期间用户可能轮换网关 key。在最后一个 await 之后
+ // 重新读取并比对,捕获 beforeDispatch 期间的凭证变更,避免用旧 key 外发
+ // 付费调用。
+ if (readGatewayKey() !== key) {
+ log.debug('oneShot skipped: gateway key changed during beforeDispatch', {
+ providerId,
+ });
+ return { status: 'failed' };
+ }
text = await fetchGatewayTitle(
target.upstream,
target.model,
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/predictPromptIpcBoundary.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/predictPromptIpcBoundary.test.ts
index 074d13c49e..c1ff2b4f76 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/predictPromptIpcBoundary.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/predictPromptIpcBoundary.test.ts
@@ -28,9 +28,9 @@ const h = vi.hoisted(() => ({
},
),
/** 模拟 DB 返回的 session row */
- sessionRow: { remoteHostId: null, agentKind: null } as { remoteHostId: string | null; source?: string | null; agentKind: string | null; workingDir?: string | null; status?: string | null } | undefined,
+ sessionRow: { remoteHostId: null, agentKind: null, updatedAt: 1 } as { remoteHostId: string | null; source?: string | null; agentKind: string | null; workingDir?: string | null; status?: string | null; updatedAt?: number } | undefined,
/** 模拟 DB 第二次读取(排空落盘队列之后)返回的 session row;用于「drain 期间被删除」竞态测试。 */
- sessionRowAfterDrain: undefined as { remoteHostId: string | null; source?: string | null; agentKind: string | null; workingDir?: string | null; status?: string | null } | undefined,
+ sessionRowAfterDrain: undefined as { remoteHostId: string | null; source?: string | null; agentKind: string | null; workingDir?: string | null; status?: string | null; updatedAt?: number } | undefined,
/** DB 读取次数计数(区分 drain 前后的两次读取)。 */
dbReads: 0,
}));
@@ -223,7 +223,7 @@ beforeEach(() => {
vi.clearAllMocks();
h.handlers.clear();
h.trusted = true;
- h.sessionRow = { remoteHostId: null, agentKind: 'cc' };
+ h.sessionRow = { remoteHostId: null, agentKind: 'cc', updatedAt: 1 };
h.sessionRowAfterDrain = undefined;
h.dbReads = 0;
h.predict.mockResolvedValue('下一步做什么');
@@ -268,7 +268,7 @@ describe('maker:predict-prompt — payload 运行期校验', () => {
});
it('素材从 DB 读取,不采用 renderer 上报的 messages / workingDir', async () => {
- h.sessionRow = { remoteHostId: null, agentKind: 'pi', workingDir: '/db/workdir' };
+ h.sessionRow = { remoteHostId: null, agentKind: 'pi', workingDir: '/db/workdir', updatedAt: 1 };
await invokePredict({
sessionId: 'session-1',
agentKind: 'pi',
@@ -302,14 +302,14 @@ describe('maker:predict-prompt — DB 防御纵深(远程会话拒绝)', () => {
});
it('session 为远程会话(remoteHostId 非空)时静默返回 null', async () => {
- h.sessionRow = { remoteHostId: 'ssh-host-1', agentKind: 'cc' };
+ h.sessionRow = { remoteHostId: 'ssh-host-1', agentKind: 'cc', updatedAt: 1 };
await expect(invokePredict(VALID_REQUEST)).resolves.toEqual({ prompt: null });
expect(h.predict).not.toHaveBeenCalled();
});
it('本地 session(remoteHostId=null, agentKind 匹配)正常执行预测', async () => {
- h.sessionRow = { remoteHostId: null, agentKind: 'cc' };
+ h.sessionRow = { remoteHostId: null, agentKind: 'cc', updatedAt: 1 };
await expect(invokePredict(VALID_REQUEST)).resolves.toEqual({ prompt: '下一步做什么' });
expect(h.predict).toHaveBeenCalledTimes(1);
@@ -317,14 +317,14 @@ describe('maker:predict-prompt — DB 防御纵深(远程会话拒绝)', () => {
it('agentKind 不匹配时静默返回 null,不触发付费调用', async () => {
// renderer 上报 claude-code,DB 存的是 codex
- h.sessionRow = { remoteHostId: null, agentKind: 'codex' };
+ h.sessionRow = { remoteHostId: null, agentKind: 'codex', updatedAt: 1 };
await expect(invokePredict(VALID_REQUEST)).resolves.toEqual({ prompt: null });
expect(h.predict).not.toHaveBeenCalled();
});
it('session 为已删除(soft-deleted)时静默返回 null,不触发付费调用', async () => {
- h.sessionRow = { remoteHostId: null, agentKind: 'cc', status: 'deleted' };
+ h.sessionRow = { remoteHostId: null, agentKind: 'cc', status: 'deleted', updatedAt: 1 };
await expect(invokePredict(VALID_REQUEST)).resolves.toEqual({ prompt: null });
expect(h.predict).not.toHaveBeenCalled();
@@ -333,8 +333,8 @@ describe('maker:predict-prompt — DB 防御纵深(远程会话拒绝)', () => {
it('drain 等待期间 session 被软删除时,排空后重新校验并静默返回 null', async () => {
// 第一次读取(drain 前)返回合法本地 session;排空落盘队列后第二次读取返回已删除状态,
// 覆盖 TOCTOU 竞态:drain 前的 status 检查过期后,必须在素材物化/调用 provider 前重新校验。
- h.sessionRow = { remoteHostId: null, agentKind: 'cc' };
- h.sessionRowAfterDrain = { remoteHostId: null, agentKind: 'cc', status: 'deleted' };
+ h.sessionRow = { remoteHostId: null, agentKind: 'cc', updatedAt: 1 };
+ h.sessionRowAfterDrain = { remoteHostId: null, agentKind: 'cc', status: 'deleted', updatedAt: 1 };
await expect(invokePredict(VALID_REQUEST)).resolves.toEqual({ prompt: null });
expect(h.predict).not.toHaveBeenCalled();
@@ -345,8 +345,8 @@ describe('maker:predict-prompt — DB 防御纵深(远程会话拒绝)', () => {
// agentKind='codex'。sessionAgentSwitchHandler 会在会话切换时提交 agentKind 变更,因此
// drain 前的 agentKind 校验已过期:必须在调用 provider 前用 drain 后的 DB agentKind 复核,
// 与 renderer 上报(claude-code)不一致时拒绝,避免把转写路由到切换前的 provider/账号。
- h.sessionRow = { remoteHostId: null, agentKind: 'cc' };
- h.sessionRowAfterDrain = { remoteHostId: null, agentKind: 'codex' };
+ h.sessionRow = { remoteHostId: null, agentKind: 'cc', updatedAt: 1 };
+ h.sessionRowAfterDrain = { remoteHostId: null, agentKind: 'codex', updatedAt: 1 };
await expect(invokePredict(VALID_REQUEST)).resolves.toEqual({ prompt: null });
expect(h.predict).not.toHaveBeenCalled();
@@ -354,7 +354,7 @@ describe('maker:predict-prompt — DB 防御纵深(远程会话拒绝)', () => {
});
describe('maker:predict-prompt — 多窗口去重', () => {
- it('同一 session 同一 turnGen 并发调用时第二个请求直接返回 null,避免重复付费', async () => {
+ it('同一 session 同一 turn(DB updatedAt 不变)并发调用时第二个请求直接返回 null,避免重复付费', async () => {
// 让第一次预测暂挂,模拟并发
let resolveFirst!: (value: string) => void;
h.predict.mockImplementationOnce(
@@ -374,7 +374,7 @@ describe('maker:predict-prompt — 多窗口去重', () => {
await expect(first).resolves.toEqual({ prompt: '预测结果' });
});
- it('同一 session 新 turnGen 的预测可以替换旧 turnGen 的进行中请求', async () => {
+ it('同一 session 新 turn(DB updatedAt 变化)的预测可以替换旧条目的进行中请求', async () => {
let resolveFirst!: (value: string) => void;
let resolveSecond!: (value: string) => void;
h.predict
@@ -385,23 +385,23 @@ describe('maker:predict-prompt — 多窗口去重', () => {
() => new Promise<string>((resolve) => { resolveSecond = resolve; }),
);
- // 发起 turnGen=0 的预测并暂挂
+ // 发起 updatedAt=1 的预测并暂挂
+ h.sessionRow = { remoteHostId: null, agentKind: 'cc', updatedAt: 1 };
const first = invokePredict(VALID_REQUEST);
await vi.waitFor(() => expect(h.predict).toHaveBeenCalledTimes(1));
- // 同一 session 发起 turnGen=1 的新预测,应能通过(替换旧条目)
- const second = invokePredict({
- ...VALID_REQUEST,
- turnGen: 1,
- });
+ // 同一 session DB updatedAt 变为 2(新 turn),应能通过(替换旧条目)
+ h.sessionRow = { remoteHostId: null, agentKind: 'cc', updatedAt: 2 };
+ const second = invokePredict(VALID_REQUEST);
await vi.waitFor(() => expect(h.predict).toHaveBeenCalledTimes(2));
- // 旧预测完成,因 turnGen 不匹配,不应删除去重条目
+ // 旧预测完成,因 updatedAt 不匹配,不应删除去重条目
resolveFirst('旧轮预测');
await expect(first).resolves.toEqual({ prompt: '旧轮预测' });
- // 新预测仍在途,去重条目应仍为 turnGen=1
- const third = invokePredict({ ...VALID_REQUEST, turnGen: 1 });
+ // 新预测仍在途,去重条目应仍为 updatedAt=2
+ h.sessionRow = { remoteHostId: null, agentKind: 'cc', updatedAt: 2 };
+ const third = invokePredict(VALID_REQUEST);
await expect(third).resolves.toEqual({ prompt: null });
// 新预测完成
@@ -428,18 +428,21 @@ describe('maker:predict-prompt — 多窗口去重', () => {
await expect(first).resolves.toEqual({ prompt: '预测结果A' });
});
- it('同一 session 更低 turnGen 的请求被拒绝(跨窗口旧窗口场景)', async () => {
+ it('同一 session DB updatedAt 不变时拒绝重复请求,避免跨窗口重复付费', async () => {
let resolveFirst!: (value: string) => void;
h.predict.mockImplementationOnce(
() => new Promise<string>((resolve) => { resolveFirst = resolve; }),
);
- // 窗口 A 发起 turnGen=5 的预测并暂挂
- const first = invokePredict({ ...VALID_REQUEST, turnGen: 5 });
+ // 窗口 A 发起预测(DB updatedAt=1)并暂挂
+ h.sessionRow = { remoteHostId: null, agentKind: 'cc', updatedAt: 1 };
+ const first = invokePredict(VALID_REQUEST);
await vi.waitFor(() => expect(h.predict).toHaveBeenCalledTimes(1));
- // 窗口 B 发起 turnGen=3 的预测(因挂载/会话切换历史不同,turnGen 更低),应被拒绝
- const second = invokePredict({ ...VALID_REQUEST, turnGen: 3 });
+ // 窗口 B 同时发起预测,DB updatedAt 仍为 1(同一 turn),应被拒绝
+ // (无论窗口 B 的局部 turnGen 是多少,DB 记录才是权威去重依据)
+ h.sessionRow = { remoteHostId: null, agentKind: 'cc', updatedAt: 1 };
+ const second = invokePredict({ ...VALID_REQUEST, turnGen: 5 });
await expect(second).resolves.toEqual({ prompt: null });
// 窗口 A 的预测完成
diff --git a/apps/desktop/src/main/maker-ipc/title.ts b/apps/desktop/src/main/maker-ipc/title.ts
index 2e22b6ae8a..a4dc2ce00d 100644
--- a/apps/desktop/src/main/maker-ipc/title.ts
+++ b/apps/desktop/src/main/maker-ipc/title.ts
@@ -346,17 +346,19 @@ const PREDICTION_RECENT_MESSAGE_LIMIT = 6;
/** 预测请求:仅 sessionId + agentKind + turnGen。素材(messages / workingDir)一律由 main 从 DB 读取,
* 不信任 renderer 上报内容——受信 renderer 或 stale UI 可能携带其它会话转写 / 伪造 workdir,
- * 把非本会话内容送到本地 provider 触发付费调用。turnGen 用于主进程级去重:同一 session
- * 新 turn 的预测(更高 turnGen)可以替换旧 turn 的进行中请求,避免旧请求阻塞新轮预测。 */
+ * 把非本会话内容送到本地 provider 触发付费调用。turnGen 用于 IPC 参数校验与 renderer 侧去重;
+ * 主进程级去重使用 DB 的权威 updatedAt(见 _predictingPromptSessions)。 */
interface PredictPromptRequest {
sessionId: string;
agentKind: AgentKind;
turnGen: number;
}
-/** 主进程级去重:同一 session 同一 turnGen 同时只能有一笔预测在途,
+/** 主进程级去重:同一 session 同时只能有一笔预测在途,
* 避免多窗口重复付费调用。与 renderer 侧 _predictingSessions 同模式:
- * Map<sessionId, turnGen>——新 turn 的更高 turnGen 会替换旧条目,不阻塞新轮预测。 */
+ * Map<sessionId, updatedAt(DB 权威值)>——新 turn 的 DB updatedAt 变化时替换旧条目。
+ * 使用 DB 的权威 updatedAt 而非 renderer 的局部 turnGen:同一 session 的
+ * 任意窗口都读到相同的 DB 记录,避免跨窗口代次顺序失真。 */
const _predictingPromptSessions = new Map<string, number>();
function parsePredictPromptRequest(raw: unknown): PredictPromptRequest {
@@ -478,15 +480,15 @@ export function registerMakerTitleIpc(options: RegisterMakerTitleIpcOptions = {}
return { prompt: null };
}
// 多窗口去重:同一 session 同时只能有一笔预测在途,避免 openSessionInNewWindow
- // 等多窗口场景下重复触发付费 provider 调用。与 renderer 侧 _predictingSessions 同模式:
- // 新 turn 的更高 turnGen 会替换旧条目,允许新轮预测通过。
- // 使用 <= 比较而非 ===:两个窗口的 ChatInput 因各自的挂载/会话切换/turn 历史
- // 持有不同的 turnGen 时,低 turnGen 的旧请求被拒绝,高 turnGen 的新请求替换旧条目。
- const existingTurnGen = _predictingPromptSessions.get(sessionId);
- if (existingTurnGen != null && turnGen <= existingTurnGen) {
+ // 等多窗口场景下重复触发付费 provider 调用。使用 DB 的权威 updatedAt 而非
+ // renderer 的局部 turnGen 作为去重键:同一 session 的任意窗口都读到相同的 DB
+ // 记录,避免跨窗口代次顺序失真。若 DB 状态未变(同一轮),拒绝重复请求;若 DB
+ // 状态已变(新轮),允许新请求替换旧条目。
+ const existingUpdatedAt = _predictingPromptSessions.get(sessionId);
+ if (existingUpdatedAt != null && sessionRow.updatedAt === existingUpdatedAt) {
return { prompt: null };
}
- _predictingPromptSessions.set(sessionId, turnGen);
+ _predictingPromptSessions.set(sessionId, sessionRow.updatedAt);
try {
// 素材只从 DB 读取,不信任 renderer 上报的 messages / workingDir:受信 renderer 或
// stale UI 可能携带其它会话转写或伪造 workdir,把非本会话内容送到本地 provider 触发
@@ -547,9 +549,9 @@ export function registerMakerTitleIpc(options: RegisterMakerTitleIpcOptions = {}
}),
};
} finally {
- // 仅在 Map 条目仍为请求时刻的 turnGen 时才删除,防止旧轮预测结束时
+ // 仅在 Map 条目仍为请求时刻的 updatedAt 时才删除,防止旧轮预测结束时
// 清除新轮预测的去重保护(与 renderer 侧 _predictingSessions 同模式)。
- if (_predictingPromptSessions.get(sessionId) === turnGen) {
+ if (_predictingPromptSessions.get(sessionId) === sessionRow.updatedAt) {
_predictingPromptSessions.delete(sessionId);
}
}