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): 修复推荐指令偶发消失及草稿清空后不恢复 (#5297)

DavidShenXD297c8577f7fc
diff --git a/apps/desktop/src/main/cindy-make/__tests__/versionStartup.test.ts b/apps/desktop/src/main/cindy-make/__tests__/versionStartup.test.ts
index 89abfd5945..dd13535dc7 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/versionStartup.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/versionStartup.test.ts
@@ -6,6 +6,13 @@ import fs from 'node:fs';
import { createHash, randomUUID } from 'node:crypto';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { CINDY_VERSION_PROTOCOL } from '../../../shared/cindyVersions';
+// These checkpoints include real filesystem I/O, not a one-second performance contract.
+// Use the existing platform test budget; vi.waitFor otherwise defaults to only 1000 ms.
+let ioTimeout: number;
+function waitForIo(assertion: () => unknown) {
+ return vi.waitFor(assertion, { timeout: ioTimeout });
+}
+
const h = vi.hoisted(() => ({
profile: '',
appPath: '',
@@ -66,7 +73,8 @@ let root = '';
let startup: typeof import('../versionStartup');
let store: typeof import('../versionStore');
let original: import('../versionStore').OriginalVersion;
-beforeEach(async () => {
+beforeEach(async ({ task }) => {
+ ioTimeout = task.timeout;
vi.resetModules();
vi.clearAllMocks();
root = await mkdtemp(path.join(os.tmpdir(), 'cindy-version-startup-'));
@@ -419,7 +427,7 @@ describe('one original version type for Dev and installed Cindy', () => {
});
startup.prepareCindyVersionStartup();
const result = startup.dispatchCindyVersionStartup();
- await vi.waitFor(() => expect(h.pty).toHaveBeenCalledOnce());
+ await waitForIo(() => expect(h.pty).toHaveBeenCalledOnce());
expect(h.pty.mock.calls[0].slice(0, 2)).toEqual([
originalExec,
[path.join(root, 'checkout/scripts/desktop-dev-runner.mjs'), 'remote'],
@@ -457,7 +465,7 @@ describe('startup dispatch stays ahead of Electron ready', () => {
expect(h.exit).not.toHaveBeenCalled();
expect(store.readOriginalVersion(h.profile)?.migrationHash).toBe(original.migrationHash);
startup.finishCindyVersionStartup();
- await vi.waitFor(() => {
+ await waitForIo(() => {
expect(store.selectedVersion(h.profile)).toBe('original');
expect(store.readOriginalVersion(h.profile)?.migrationHash).toBe(
store.migrationIdentity(path.join(h.appPath, 'drizzle')),
@@ -472,7 +480,7 @@ describe('startup dispatch stays ahead of Electron ready', () => {
expect(ready).not.toHaveBeenCalled();
expect(store.readOriginalVersion(h.profile)?.version).toBeUndefined();
startup.finishCindyVersionStartup();
- await vi.waitFor(() => expect(store.readOriginalVersion(h.profile)?.version).toBe('0.1.99'));
+ await waitForIo(() => expect(store.readOriginalVersion(h.profile)?.version).toBe('0.1.99'));
expect(
store.readVersionJson(path.join(store.versionsRoot(h.profile), 'active.json')),
).toMatchObject({ pid: process.pid, id: 'original' });
@@ -489,7 +497,7 @@ describe('startup dispatch stays ahead of Electron ready', () => {
expect(h.spawn).not.toHaveBeenCalled();
expect(store.selectedVersion(h.profile)).toBe(personal.id);
startup.finishCindyVersionStartup();
- await vi.waitFor(() => expect(store.selectedVersion(h.profile)).toBe('original'));
+ await waitForIo(() => expect(store.selectedVersion(h.profile)).toBe('original'));
});
it('opens the original in-process when the selected version fails before any real I/O', async () => {
saveOriginal();
@@ -500,7 +508,7 @@ describe('startup dispatch stays ahead of Electron ready', () => {
expect(h.exit).not.toHaveBeenCalled();
expect(h.relaunch).not.toHaveBeenCalled();
startup.finishCindyVersionStartup();
- await vi.waitFor(() => expect(store.selectedVersion(h.profile)).toBe('original'));
+ await waitForIo(() => expect(store.selectedVersion(h.profile)).toBe('original'));
});
it.each([
['packaged', true],
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botInvitation.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botInvitation.test.ts
index c426e24f1e..08ec56ca3e 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botInvitation.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botInvitation.test.ts
@@ -5,6 +5,13 @@ import Database from 'better-sqlite3';
import { drizzle } from 'drizzle-orm/better-sqlite3';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+// These checkpoints include real filesystem I/O, not a one-second performance contract.
+// Use the existing platform test budget; vi.waitFor otherwise defaults to only 1000 ms.
+let ioTimeout: number;
+function waitForIo(assertion: () => unknown) {
+ return vi.waitFor(assertion, { timeout: ioTimeout });
+}
+
const h = vi.hoisted(() => ({
client: {} as { drizzle: unknown; tx: unknown },
root: '',
@@ -93,7 +100,8 @@ function seed(invitation: Record<string, unknown> = {}, config: Record<string, u
}),
);
}
-beforeEach(async () => {
+beforeEach(async ({ task }) => {
+ ioTimeout = task.timeout;
vi.clearAllMocks();
h.owner = 'owner-a';
h.root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-invitation-'));
@@ -131,13 +139,13 @@ describe('companion invitation with SQLite and real skill files', () => {
const createCanonicalSession = vi.fn(async () => ({ canonicalSessionId: 'chat-1' }));
const canStartWelcome = vi.fn(async () => Boolean(getSelectedNewMakerRoute(h.owner)));
enqueueBotInvitation('bot-1', { canStartWelcome, createCanonicalSession, broadcastProfileChanged: h.broadcast });
- await vi.waitFor(() => expect(canStartWelcome).toHaveBeenCalledOnce());
+ await waitForIo(() => expect(canStartWelcome).toHaveBeenCalledOnce());
expect(state().stage).toBe('welcome');
expect(createCanonicalSession).not.toHaveBeenCalled();
expect(h.welcome).not.toHaveBeenCalled();
const selected = { harness: 'codex' as const, providerId: 'user-provider', model: 'user-selected-model', effort: 'low', fastMode: true };
mirror(selected);
- await vi.waitFor(() => expect(state().stage).toBe('ready'));
+ await waitForIo(() => expect(state().stage).toBe('ready'));
mirror(selected);
expect(getSelectedNewMakerRoute(h.owner)).toEqual(selected);
expect(createCanonicalSession).toHaveBeenCalledOnce();
@@ -240,7 +248,7 @@ describe('companion invitation with SQLite and real skill files', () => {
expect(state().stage).toBe('welcome');
expect(createCanonicalSession).not.toHaveBeenCalled();
cold.setBotInvitationWelcomeDispatch(h.welcome);
- await vi.waitFor(() => expect(state().stage).toBe('ready'));
+ await waitForIo(() => expect(state().stage).toBe('ready'));
expect(createCanonicalSession).toHaveBeenCalledOnce();
expect(h.welcome).toHaveBeenCalledOnce();
});
@@ -252,7 +260,7 @@ describe('companion invitation with SQLite and real skill files', () => {
])('greets in invitation locale %s without a separate generation step', async (locale, expectedLocale) => {
seed({ locale });
queueBotInvitation('bot-1');
- await vi.waitFor(() => expect(state().stage).toBe('ready'));
+ await waitForIo(() => expect(state().stage).toBe('ready'));
expect(h.welcome).toHaveBeenCalledOnce();
expect(h.generate).not.toHaveBeenCalled();
const { message, persistedContent } = h.welcome.mock.calls[0]![0];
@@ -269,7 +277,7 @@ describe('companion invitation with SQLite and real skill files', () => {
const welcomeContext = { projects: ['Puzzle Studio'], tasks: ['Build a game editor'], automations: ['Daily issue triage'] };
seed({ welcomeContext });
queueBotInvitation('bot-1');
- await vi.waitFor(() => expect(state().stage).toBe('ready'));
+ await waitForIo(() => expect(state().stage).toBe('ready'));
expect(h.welcome).toHaveBeenCalledOnce();
expect(h.generate).not.toHaveBeenCalled();
const { message } = h.welcome.mock.calls[0]![0];
@@ -286,7 +294,7 @@ describe('companion invitation with SQLite and real skill files', () => {
const welcomeContext = { projects: [], tasks: [], automations: [], [field]: [attack] };
seed({ welcomeContext });
queueBotInvitation('bot-1');
- await vi.waitFor(() => expect(state().stage).toBe('ready'));
+ await waitForIo(() => expect(state().stage).toBe('ready'));
expect(h.welcome).toHaveBeenCalledOnce();
expect(h.generate).not.toHaveBeenCalled();
const { message, persistedContent } = h.welcome.mock.calls[0]![0];
@@ -309,7 +317,7 @@ describe('companion invitation with SQLite and real skill files', () => {
seed({ draft });
queueBotInvitation('bot-1');
queueBotInvitation('bot-1');
- await vi.waitFor(() => expect(state().stage).toBe('ready'));
+ await waitForIo(() => expect(state().stage).toBe('ready'));
expect(h.generate).not.toHaveBeenCalled();
expect(await readBotSkill(h.root, 'bot-1', 'develop-characters')).toMatchObject(
draft.skills[0],
@@ -331,7 +339,7 @@ describe('companion invitation with SQLite and real skill files', () => {
seed({ stage: 'skills', draft });
await seedBotSkillIfMissing(h.root, 'bot-1', { ...draft.skills[0]!, body: '用户自己的方法' });
queueBotInvitation('bot-1');
- await vi.waitFor(() => expect(state().stage).toBe('ready'));
+ await waitForIo(() => expect(state().stage).toBe('ready'));
expect(h.generate).not.toHaveBeenCalled();
expect((await readBotSkill(h.root, 'bot-1', 'develop-characters'))?.body).toBe(
'用户自己的方法',
@@ -350,17 +358,17 @@ describe('companion invitation with SQLite and real skill files', () => {
return { ok: await receipts.dispatch(input.targetSessionId, clientId, enqueued) };
});
queueBotInvitation('bot-1');
- await vi.waitFor(() => expect(enqueued).toHaveBeenCalledOnce());
+ await waitForIo(() => expect(enqueued).toHaveBeenCalledOnce());
expect(state()).toMatchObject({ stage: 'welcome', draft, welcomeContext, welcomeClientId: 'welcome-attempt-1' });
receipts.settle('chat-1', 'welcome-attempt-1', false);
- await vi.waitFor(() => expect(state().stage).toBe('failed'));
+ await waitForIo(() => expect(state().stage).toBe('failed'));
expect(state()).toMatchObject({ draft, welcomeContext, welcomeClientId: 'welcome-attempt-1' });
queueBotInvitation('bot-1', true);
- await vi.waitFor(() => expect(enqueued).toHaveBeenCalledTimes(2));
+ await waitForIo(() => expect(enqueued).toHaveBeenCalledTimes(2));
expect(h.welcome.mock.calls[1][0]).toMatchObject({ clientId: 'welcome-attempt-1', retry: true });
receipts.settle('chat-1', 'welcome-attempt-2', true);
- await vi.waitFor(() => expect(state().stage).toBe('ready'));
+ await waitForIo(() => expect(state().stage).toBe('ready'));
expect(state().draft).toBeUndefined();
expect(state().welcomeContext).toBeUndefined();
expect(state().welcomeClientId).toBeUndefined();
@@ -371,10 +379,10 @@ describe('companion invitation with SQLite and real skill files', () => {
seed();
h.welcome.mockResolvedValueOnce({ ok: false });
queueBotInvitation('bot-1');
- await vi.waitFor(() => expect(state().stage).toBe('failed'));
+ await waitForIo(() => expect(state().stage).toBe('failed'));
expect(h.welcome).toHaveBeenCalledTimes(1);
queueBotInvitation('bot-1', true);
- await vi.waitFor(() => expect(state().stage).toBe('ready'));
+ await waitForIo(() => expect(state().stage).toBe('ready'));
expect(sqlite.prepare('SELECT count(*) AS n FROM bot_profiles').get()).toEqual({ n: 1 });
});
@@ -384,7 +392,7 @@ describe('companion invitation with SQLite and real skill files', () => {
seed({}, { templateId });
sqlite.prepare('UPDATE bot_profile_versions SET identity_source = ?').run('用户已经修改的人设');
queueBotInvitation('bot-1');
- await vi.waitFor(() => expect(state().stage).toBe('ready'));
+ await waitForIo(() => expect(state().stage).toBe('ready'));
expect(h.generate).not.toHaveBeenCalled();
const folder = await readBotProfileFolder(h.root, 'bot-1');
expect(folder.identitySource).toBe('用户已经修改的人设');
@@ -395,7 +403,7 @@ describe('companion invitation with SQLite and real skill files', () => {
it('does not lose a prepared character when optional image generation is unavailable', async () => {
seed({ avatarRequested: true, avatarPrompt: draft.avatarPrompt });
queueBotInvitation('bot-1');
- await vi.waitFor(() => expect(state()).toMatchObject({ stage: 'ready', avatarSkipped: true }));
+ await waitForIo(() => expect(state()).toMatchObject({ stage: 'ready', avatarSkipped: true }));
expect(sqlite.prepare('SELECT avatar FROM bot_profiles').get()).toEqual({ avatar: '✦' });
expect(h.welcome).toHaveBeenCalledTimes(1);
});
@@ -403,11 +411,11 @@ describe('companion invitation with SQLite and real skill files', () => {
it('retries an optional portrait without regenerating the character or greeting again', async () => {
seed({ avatarRequested: true, avatarPrompt: draft.avatarPrompt });
queueBotInvitation('bot-1');
- await vi.waitFor(() => expect(state().stage).toBe('ready'));
+ await waitForIo(() => expect(state().stage).toBe('ready'));
expect(state().avatarSkipped).toBe(true);
queueBotInvitation('bot-1', true);
- await vi.waitFor(() => expect(h.prepareAvatar).toHaveBeenCalledTimes(2));
- await vi.waitFor(() => expect(state().stage).toBe('ready'));
+ await waitForIo(() => expect(h.prepareAvatar).toHaveBeenCalledTimes(2));
+ await waitForIo(() => expect(state().stage).toBe('ready'));
expect(h.generate).not.toHaveBeenCalled();
expect(h.welcome).toHaveBeenCalledTimes(1);
});
@@ -416,7 +424,7 @@ describe('companion invitation with SQLite and real skill files', () => {
seed({ stage: 'avatar', avatarRequested: true, avatarPrompt: draft.avatarPrompt });
sqlite.prepare("UPDATE bot_profiles SET canonical_session_id = 'chat-1' WHERE id = 'bot-1'").run();
queueBotInvitation('bot-1');
- await vi.waitFor(() => expect(state().stage).toBe('ready'));
+ await waitForIo(() => expect(state().stage).toBe('ready'));
expect(h.generate).not.toHaveBeenCalled();
expect(h.welcome).not.toHaveBeenCalled();
expect(state().avatarSkipped).toBe(true);
@@ -430,7 +438,7 @@ describe('companion invitation with SQLite and real skill files', () => {
return { url: 'ai-portrait', hash: 'a'.repeat(64) };
});
queueBotInvitation('bot-1');
- await vi.waitFor(() => expect(state().stage).toBe('ready'));
+ await waitForIo(() => expect(state().stage).toBe('ready'));
expect(sqlite.prepare('SELECT avatar FROM bot_profiles').get()).toEqual({
avatar: 'user-upload',
});
@@ -445,7 +453,7 @@ describe('companion invitation with SQLite and real skill files', () => {
});
h.finishAvatar.mockRejectedValueOnce(new Error('outcome unknown'));
queueBotInvitation('bot-1');
- await vi.waitFor(() => expect(state().stage).toBe('ready'));
+ await waitForIo(() => expect(state().stage).toBe('ready'));
expect(h.prepareAvatar).not.toHaveBeenCalled();
expect(h.finishAvatar).toHaveBeenCalledWith(
'image-1',
@@ -458,7 +466,7 @@ describe('companion invitation with SQLite and real skill files', () => {
it('creates from a name without generating a profile or padding Skills', async () => {
seed();
queueBotInvitation('bot-1');
- await vi.waitFor(() => expect(state().stage).toBe('ready'));
+ await waitForIo(() => expect(state().stage).toBe('ready'));
expect(h.generate).not.toHaveBeenCalled();
expect(await readBotSkill(h.root, 'bot-1', 'develop-characters')).toBeNull();
expect((await readBotProfileFolder(h.root, 'bot-1')).identitySource).toContain('original');
@@ -470,7 +478,7 @@ describe('companion invitation with SQLite and real skill files', () => {
let finish!: (value: unknown) => void;
h.finishAvatar.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
queueBotInvitation('bot-1');
- await vi.waitFor(() => expect(h.finishAvatar).toHaveBeenCalled());
+ await waitForIo(() => expect(h.finishAvatar).toHaveBeenCalled());
h.owner = 'owner-b';
finish({ url: 'ai-portrait', hash: 'a'.repeat(64) });
await new Promise(resolve => setTimeout(resolve, 20));
@@ -481,8 +489,7 @@ describe('companion invitation with SQLite and real skill files', () => {
describe('generated character validation', () => {
it.each([{ skills: [] }, { skills: [draft.skills[0]] }])('accepts only the methods the character needs', ({ skills }) => {
- const { greeting, ...withoutGreeting } = draft;
- expect(parseBotInvitationDraft(JSON.stringify({ ...withoutGreeting, skills })).skills).toEqual(skills);
+ expect(parseBotInvitationDraft(JSON.stringify({ ...draft, greeting: undefined, skills })).skills).toEqual(skills);
});
it('keeps the sketch as quoted input and accepts a complete role-specific draft', () => {
expect(botInvitationPrompt('阿橙', '一个热爱写网文的小说家', 'zh-CN')).toContain(
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 a85adef2a4..975581f23f 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/predictPromptIpcBoundary.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/predictPromptIpcBoundary.test.ts
@@ -365,6 +365,40 @@ describe('maker:predict-prompt — sender 断言', () => {
});
describe('maker:predict-prompt — payload 运行期校验', () => {
+ it.each([undefined, 0, -1, 1.5, '2'])('取消请求拒绝无效完成轮次 %s', async (completionRevision) => {
+ await expect(invokePredict({ sessionId: 'session-1', cancel: true, completionRevision })).rejects.toThrow(/INVALID_PARAMS/);
+ expect(h.predict).not.toHaveBeenCalled();
+ });
+
+ it('取消仍校验来源,且取消本身不读取素材或调用模型', async () => {
+ const request = { sessionId: 'session-1', completionRevision: 2, cancel: true };
+ h.trusted = false;
+ await expect(invokePredict(request)).rejects.toThrow(/PERMISSION_DENIED/);
+ h.trusted = true;
+ await expect(invokePredict(request)).resolves.toEqual({ prompt: null });
+ expect(h.predict).not.toHaveBeenCalled();
+ expect(h.regenerateMaterial).not.toHaveBeenCalled();
+ await expect(invokePredict(VALID_REQUEST)).resolves.toEqual({ prompt: null });
+ expect(h.predict).not.toHaveBeenCalled();
+ });
+
+ it('远控取消沿原通道执行,迟到的旧轮取消不阻塞下一完成轮', async () => {
+ h.trusted = false;
+ await runDeviceLinkInvokeContext({
+ controllerDeviceId: 'controller-a', controllerPlatform: 'win32', channel: 'maker:predict-prompt',
+ }, () => invokePredict({ sessionId: 'session-1', completionRevision: 1, cancel: true }));
+ h.trusted = true;
+ await expect(invokePredict(VALID_REQUEST)).resolves.toEqual({ prompt: '下一步做什么' });
+ expect(h.predict).toHaveBeenCalledTimes(1);
+ });
+
+ it('取消当前轮后不再复用已缓存的成功结果', async () => {
+ await invokePredict(VALID_REQUEST);
+ await invokePredict({ sessionId: 'session-1', completionRevision: 2, cancel: true });
+ await expect(invokePredict(VALID_REQUEST)).resolves.toEqual({ prompt: null });
+ expect(h.predict).toHaveBeenCalledTimes(1);
+ });
+
it.each([
['非对象', null],
['数组', []],
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/promptPredictionRevision.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/promptPredictionRevision.test.ts
index 6121a31c5c..57fd17255c 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/promptPredictionRevision.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/promptPredictionRevision.test.ts
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const h = vi.hoisted(() => ({
rows: [] as Array<{
@@ -15,6 +15,8 @@ const h = vi.hoisted(() => ({
dbReads: 0,
beforeDispatchCalls: 0,
models: [] as string[],
+ owner: 'owner-a:1',
+ boundaryPending: false,
afterDispatch: null as null | (() => void),
requestUtilityText: vi.fn(),
}));
@@ -23,6 +25,11 @@ vi.mock('../../logger.js', () => ({
createLogger: () => ({ debug: vi.fn(), warn: vi.fn(), error: vi.fn() }),
}));
+vi.mock('../../appSessionState.js', () => ({
+ activeOwnerScopeKey: () => h.owner,
+ isAppSessionBoundaryPending: () => h.boundaryPending,
+}));
+
vi.mock('../../i18n.js', () => ({
getResolvedMainLocale: () => 'zh-CN',
}));
@@ -59,6 +66,7 @@ vi.mock('../../maker-host/index.js', () => ({
import { generatePromptPrediction } from '../promptPrediction.js';
import {
+ notePromptPredictionSessionCancelled,
notePromptPredictionSessionStopped,
resetPromptPredictionStopLedgerForTests,
} from '../promptPredictionStopLedger.js';
@@ -90,11 +98,14 @@ function predict(): Promise<string | null> {
}
beforeEach(() => {
+ vi.useFakeTimers();
vi.clearAllMocks();
h.dbReads = 0;
h.beforeDispatchCalls = 0;
h.afterDispatch = null;
h.models = [];
+ h.owner = 'owner-a:1';
+ h.boundaryPending = false;
h.rows = [{ ...VALID_ROW }, { ...VALID_ROW }];
h.requestUtilityText.mockImplementation(
async (_maker: unknown, _prompt: string, options: Record<string, unknown>) => {
@@ -121,7 +132,97 @@ beforeEach(() => {
resetPromptPredictionStopLedgerForTests();
});
+afterEach(() => vi.useRealTimers());
+
describe('prompt prediction completion revision guard', () => {
+ const timeout = {
+ ok: false,
+ reason: 'timeout',
+ attempts: [{ status: 'failed', reason: 'timeout' }],
+ };
+
+ it('临时超时后在同一请求中补试一次并返回推荐', async () => {
+ h.requestUtilityText.mockResolvedValueOnce(timeout);
+ const pending = predict();
+ await vi.advanceTimersByTimeAsync(1_499);
+ expect(h.requestUtilityText).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1);
+ await expect(pending).resolves.toBe('继续补测试');
+ expect(h.requestUtilityText).toHaveBeenCalledTimes(2);
+ });
+
+ it('连续临时失败最多补试一次,不无限重试', async () => {
+ h.requestUtilityText.mockResolvedValue(timeout);
+ const pending = predict();
+ await vi.runAllTimersAsync();
+ await expect(pending).resolves.toBeNull();
+ expect(h.requestUtilityText).toHaveBeenCalledTimes(2);
+ });
+
+ it.each([400, 401, 403, 422])('HTTP %i 与超时混合失败时不重跑整条链', async (httpStatus) => {
+ for (const permanentFirst of [true, false]) {
+ h.requestUtilityText.mockClear();
+ const permanent = { status: 'failed', reason: 'http_error', httpStatus };
+ const transient = timeout.attempts[0];
+ h.requestUtilityText.mockResolvedValueOnce({
+ ok: false,
+ reason: 'all_candidates_failed',
+ attempts: permanentFirst ? [permanent, transient] : [transient, permanent],
+ });
+ const pending = predict();
+ await vi.runAllTimersAsync();
+ await expect(pending).resolves.toBeNull();
+ expect(h.requestUtilityText).toHaveBeenCalledTimes(1);
+ }
+ });
+
+ it('全部实际失败均为临时错误时仍可补试,跳过的候选不算执行失败', async () => {
+ h.requestUtilityText.mockResolvedValueOnce({
+ ok: false,
+ reason: 'all_candidates_failed',
+ attempts: [
+ { status: 'skipped', reason: 'api_key_missing' },
+ timeout.attempts[0],
+ { status: 'failed', reason: 'http_error', httpStatus: 429 },
+ { status: 'failed', reason: 'http_error', httpStatus: 503 },
+ ],
+ });
+ const pending = predict();
+ await vi.runAllTimersAsync();
+ await expect(pending).resolves.toBe('继续补测试');
+ expect(h.requestUtilityText).toHaveBeenCalledTimes(2);
+ });
+
+ it.each([
+ { ok: false, reason: 'no_candidate', attempts: [] },
+ { ok: false, reason: 'all_candidates_failed', attempts: [{ status: 'failed', reason: 'http_error', httpStatus: 401 }] },
+ { ok: true, text: 'invalid\nmultiline' },
+ ])('不可用配置或不合格输出不触发重复付费: %j', async (result) => {
+ h.requestUtilityText.mockResolvedValueOnce(result);
+ await expect(predict()).resolves.toBeNull();
+ expect(h.requestUtilityText).toHaveBeenCalledTimes(1);
+ });
+
+ it.each(['stop', 'new-turn', 'owner', 'boundary', 'models', 'disabled'])(
+ '重试等待期间发生 %s 时不会派发旧请求', async (change) => {
+ h.requestUtilityText.mockResolvedValueOnce(timeout);
+ const paidDispatch = vi.fn();
+ h.afterDispatch = paidDispatch;
+ const pending = predict();
+ await vi.advanceTimersByTimeAsync(1);
+ if (change === 'stop') notePromptPredictionSessionStopped('session-1');
+ if (change === 'new-turn') h.rows = [{ ...VALID_ROW, activeTurnStartedAt: 300 }];
+ if (change === 'owner') h.owner = 'owner-b:2';
+ if (change === 'boundary') h.boundaryPending = true;
+ if (change === 'models') h.models = ['changed-model'];
+ if (change === 'disabled') notePromptPredictionSessionCancelled('session-1', 200, h.owner);
+ await vi.runAllTimersAsync();
+ await expect(pending).resolves.toBeNull();
+ expect(paidDispatch).not.toHaveBeenCalled();
+ if (change === 'disabled') expect(h.requestUtilityText).toHaveBeenCalledTimes(1);
+ },
+ );
+
it('provider 派发紧前两次复核都匹配时允许预测', async () => {
await expect(predict()).resolves.toBe('继续补测试');
expect(h.beforeDispatchCalls).toBe(1);
@@ -164,6 +265,31 @@ describe('prompt prediction completion revision guard', () => {
expect(h.dbReads).toBe(2);
});
+ it('请求准备期间关闭推荐时拦截首次付费派发', async () => {
+ const paidDispatch = vi.fn();
+ h.afterDispatch = paidDispatch;
+ notePromptPredictionSessionCancelled('session-1', 200, h.owner);
+ await expect(predict()).resolves.toBeNull();
+ expect(paidDispatch).not.toHaveBeenCalled();
+ });
+
+ it('请求发出后关闭推荐时丢弃迟到结果', async () => {
+ h.afterDispatch = () => notePromptPredictionSessionCancelled('session-1', 200, h.owner);
+ await expect(predict()).resolves.toBeNull();
+ });
+
+ it('旧完成轮和旧账号的取消不影响当前推荐', async () => {
+ notePromptPredictionSessionCancelled('session-1', 199, h.owner);
+ await expect(predict()).resolves.toBe('继续补测试');
+ notePromptPredictionSessionCancelled('session-1', 200, 'owner-other');
+ await expect(predict()).resolves.toBe('继续补测试');
+ });
+
+ it('provider 请求已发出后切换 owner 时丢弃返回值', async () => {
+ h.afterDispatch = () => { h.owner = 'owner-b:2'; };
+ await expect(predict()).resolves.toBeNull();
+ });
+
it('首次复核发现 completion revision 已变化时中止付费派发', async () => {
h.rows = [{ ...VALID_ROW, lastTurnEndedAt: 201 }];
diff --git a/apps/desktop/src/main/maker-ipc/promptPrediction.ts b/apps/desktop/src/main/maker-ipc/promptPrediction.ts
index 394fb1c6b6..ee30316e1b 100644
--- a/apps/desktop/src/main/maker-ipc/promptPrediction.ts
+++ b/apps/desktop/src/main/maker-ipc/promptPrediction.ts
@@ -11,13 +11,18 @@ import { dbToMakerAgentKind } from '../../shared/agentKindConversion.js';
import { getResolvedMainLocale } from '../i18n.js';
import { getMaker } from '../maker-host/index.js';
import { validateTitleOutput } from '../maker-host/title-output-validation.js';
-import { requestUtilityText } from '../utility-model/oneShotCandidates.js';
+import { requestUtilityText, type UtilityTextRequestOptions } from '../utility-model/oneShotCandidates.js';
+import type { UtilityTextFailure } from '../../shared/utilityTextResult.js';
import { readAuxiliaryModelSettings } from '../utility-model/auxiliary-model-settings-store.js';
import { eq } from 'drizzle-orm';
import { getDbClient } from '../localDb/client/current.js';
import { sessions } from '../localDb/schema.js';
import { createLogger } from '../logger.js';
-import { wasPromptPredictionSessionStopped } from './promptPredictionStopLedger.js';
+import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';
+import {
+ wasPromptPredictionSessionCancelled,
+ wasPromptPredictionSessionStopped,
+} from './promptPredictionStopLedger.js';
const log = createLogger('maker-ipc/prompt-prediction');
@@ -28,6 +33,18 @@ const PREDICTION_USER_MSG_MAX = 400;
const PREDICTION_ASSISTANT_MSG_MAX = 600;
/** 最近 N 轮 user↔assistant 配对数。 */
const PREDICTION_RECENT_PAIRS = 3;
+const PREDICTION_RETRY_DELAY_MS = 1_500;
+
+function isTransientPredictionFailure(result: UtilityTextFailure): boolean {
+ const failures = result.attempts.filter((attempt) => attempt.status === 'failed');
+ // 补试会重跑整条链,只有实际失败全部为临时错误时才允许,避免重复明确失败的请求。
+ return failures.length > 0 && failures.every((attempt) => (
+ attempt.reason === 'timeout' ||
+ attempt.reason === 'request_failed' ||
+ attempt.reason === 'empty_response' ||
+ (attempt.reason === 'http_error' && (attempt.httpStatus === 429 || attempt.httpStatus >= 500))
+ ));
+}
type SlimMessage = { role: string; content: string };
@@ -182,6 +199,10 @@ export interface PromptPredictionParams {
export async function generatePromptPrediction(
params: PromptPredictionParams,
): Promise<string | null> {
+ const requestOwnerScopeKey = activeOwnerScopeKey();
+ const isCancelled = () => wasPromptPredictionSessionCancelled(
+ params.sessionId, params.completionRevision, requestOwnerScopeKey,
+ );
const context = buildConversationContext(params.messages, PREDICTION_RECENT_PAIRS);
if (!context) {
log.debug('prompt prediction skipped: no conversational context');
@@ -226,7 +247,7 @@ export async function generatePromptPrediction(
const modelsSnapshot = JSON.stringify(readAuxiliaryModelSettings().models);
- const result = await requestUtilityText(getMaker(), truncated, {
+ const requestOptions: UtilityTextRequestOptions = {
maxTokens: 96,
timeoutMs: 12_000,
disableReasoning: true,
@@ -236,6 +257,10 @@ export async function generatePromptPrediction(
'Output only the predicted next user message — no quotes, markdown, or commentary.',
beforeDispatch: async () => {
try {
+ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== requestOwnerScopeKey) {
+ return false;
+ }
+ if (isCancelled()) return false;
if (JSON.stringify(readAuxiliaryModelSettings().models) !== modelsSnapshot) {
return false;
}
@@ -257,16 +282,35 @@ export async function generatePromptPrediction(
beforeDispatchDrainUpdatedAt
&& finalRow.updatedAt !== beforeDispatchDrainUpdatedAt
) return false;
- return JSON.stringify(readAuxiliaryModelSettings().models) === modelsSnapshot;
+ return !isAppSessionBoundaryPending()
+ && !isCancelled()
+ && activeOwnerScopeKey() === requestOwnerScopeKey
+ && JSON.stringify(readAuxiliaryModelSettings().models) === modelsSnapshot;
} catch {
return false;
}
},
- });
+ };
+
+ // 重试包含在 Main 已去重的同一笔 Promise 内:跨窗口、远程读取不会各自重试。
+ // 只补试一次临时传输失败;无可用模型、鉴权失败、输出格式不合格不重试。
+ let result = await requestUtilityText(getMaker(), truncated, requestOptions);
+ if (!result.ok && isTransientPredictionFailure(result)) {
+ await new Promise<void>((resolve) => setTimeout(resolve, PREDICTION_RETRY_DELAY_MS));
+ // beforeDispatch 保留首次 owner,并复核配置、Stop、完成代次及素材。
+ if (!isCancelled()) {
+ result = await requestUtilityText(getMaker(), truncated, requestOptions);
+ }
+ }
// HTTP 已经发出后仍可能收到其它窗口 / Device Link 的 Stop。费用无法撤回,但返回值
// 必须丢弃,不能在用户明确停止后把推荐重新显示到输入框。
- if (wasPromptPredictionSessionStopped(params.sessionId)) return null;
+ if (
+ wasPromptPredictionSessionStopped(params.sessionId) ||
+ isCancelled() ||
+ isAppSessionBoundaryPending() ||
+ activeOwnerScopeKey() !== requestOwnerScopeKey
+ ) return null;
if (!result.ok) return null;
const normalized = validateTitleOutput(result.text, 512);
return normalized ? Array.from(normalized).slice(0, 140).join('') : null;
diff --git a/apps/desktop/src/main/maker-ipc/promptPredictionStopLedger.ts b/apps/desktop/src/main/maker-ipc/promptPredictionStopLedger.ts
index 859cf070ab..a41e35a69e 100644
--- a/apps/desktop/src/main/maker-ipc/promptPredictionStopLedger.ts
+++ b/apps/desktop/src/main/maker-ipc/promptPredictionStopLedger.ts
@@ -6,6 +6,7 @@
* maker-core turn-start boundary. Nothing is persisted across app restarts.
*/
const explicitlyStoppedSessions = new Set<string>();
+const cancelledRevisions = new Map<string, { revision: number; ownerScope: string }>();
export function notePromptPredictionSessionStopped(sessionId: string): void {
if (sessionId) explicitlyStoppedSessions.add(sessionId);
@@ -19,6 +20,23 @@ export function wasPromptPredictionSessionStopped(sessionId: string): boolean {
return explicitlyStoppedSessions.has(sessionId);
}
+/** Preference changes cancel an in-flight prediction without pretending the user stopped a turn. */
+export function notePromptPredictionSessionCancelled(
+ sessionId: string, revision: number, ownerScope: string,
+): void {
+ const previous = cancelledRevisions.get(sessionId);
+ if (previous?.ownerScope === ownerScope && previous.revision > revision) return;
+ cancelledRevisions.set(sessionId, { revision, ownerScope });
+}
+
+export function wasPromptPredictionSessionCancelled(
+ sessionId: string, revision: number, ownerScope: string,
+): boolean {
+ const cancelled = cancelledRevisions.get(sessionId);
+ return cancelled?.ownerScope === ownerScope && revision <= cancelled.revision;
+}
+
export function resetPromptPredictionStopLedgerForTests(): void {
explicitlyStoppedSessions.clear();
+ cancelledRevisions.clear();
}
diff --git a/apps/desktop/src/main/maker-ipc/title.ts b/apps/desktop/src/main/maker-ipc/title.ts
index 85d5d58509..bd39895e64 100644
--- a/apps/desktop/src/main/maker-ipc/title.ts
+++ b/apps/desktop/src/main/maker-ipc/title.ts
@@ -14,6 +14,7 @@
*/
import { ipcMain } from 'electron';
+import { activeOwnerScopeKey } from '../appSessionState.js';
import { dbToMakerAgentKind } from '../../shared/agentKindConversion.js';
import { eq } from 'drizzle-orm';
@@ -49,7 +50,11 @@ import {
type SessionAutoTitleResult,
} from './sessionAutoTitle.js';
import { generatePromptPrediction } from './promptPrediction.js';
-import { wasPromptPredictionSessionStopped } from './promptPredictionStopLedger.js';
+import {
+ notePromptPredictionSessionCancelled,
+ wasPromptPredictionSessionCancelled,
+ wasPromptPredictionSessionStopped,
+} from './promptPredictionStopLedger.js';
const log = createLogger('maker-ipc/title');
@@ -356,7 +361,9 @@ interface PredictPromptRequest {
turnGen: number;
completionRevision: number;
cacheOnly?: boolean;
+ cancel?: false;
}
+type CancelPromptRequest = { sessionId: string; completionRevision: number; cancel: true };
interface PromptPredictionCacheEntry {
revision: number;
@@ -367,17 +374,26 @@ interface PromptPredictionCacheEntry {
/** 每个 session 只保留最新完成轮的一笔 Promise/结果,进程重启自然清空。 */
const _promptPredictionCache = new Map<string, PromptPredictionCacheEntry>();
-function parsePredictPromptRequest(raw: unknown): PredictPromptRequest {
+function parsePredictPromptRequest(raw: unknown): PredictPromptRequest | CancelPromptRequest {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
throwIpcError('INVALID_PARAMS', 'predict-prompt request must be a non-null object');
}
- const { sessionId, agentKind, turnGen, completionRevision, cacheOnly } = raw as Record<string, unknown>;
+ const { sessionId, agentKind, turnGen, completionRevision, cacheOnly, cancel } = raw as Record<string, unknown>;
if (cacheOnly !== undefined && typeof cacheOnly !== 'boolean') {
throwIpcError('INVALID_PARAMS', 'cacheOnly must be a boolean');
}
+ if (cancel !== undefined && typeof cancel !== 'boolean') {
+ throwIpcError('INVALID_PARAMS', 'cancel must be a boolean');
+ }
if (typeof sessionId !== 'string' || !sessionId || sessionId.length > SESSION_ID_MAX) {
throwIpcError('INVALID_PARAMS', 'invalid or missing sessionId for predict-prompt');
}
+ if (cancel === true) {
+ if (typeof completionRevision !== 'number' || !Number.isSafeInteger(completionRevision) || completionRevision <= 0) {
+ throwIpcError('INVALID_PARAMS', 'invalid completionRevision for cancellation');
+ }
+ return { sessionId, completionRevision, cancel: true };
+ }
if (!TITLE_AGENT_KINDS.includes(agentKind as AgentKind)) {
throwIpcError('INVALID_PARAMS', `invalid agentKind for predict-prompt: ${String(agentKind)}`);
}
@@ -404,6 +420,7 @@ function parsePredictPromptRequest(raw: unknown): PredictPromptRequest {
turnGen,
completionRevision,
cacheOnly,
+ cancel: false,
};
}
@@ -422,6 +439,7 @@ async function predictPromptForCompletedRevision(
options: RegisterMakerTitleIpcOptions,
): Promise<string | null> {
const { sessionId, agentKind, completionRevision } = request;
+ if (wasPromptPredictionSessionCancelled(sessionId, completionRevision, activeOwnerScopeKey())) return null;
// 防御纵深:身份、来源、完成轮次都以 DB 为准。activeTurnStartedAt 不早于完成
// revision 表示下一轮已经启动(含同毫秒),即使命中缓存也不能返回上一轮推荐。
const [sessionRow] = await getDbClient()
@@ -462,6 +480,7 @@ async function predictPromptForCompletedRevision(
}
const cached = _promptPredictionCache.get(sessionId);
+ if (wasPromptPredictionSessionCancelled(sessionId, completionRevision, activeOwnerScopeKey())) return null;
if (cached?.revision === completionRevision) {
// workingDir 会进入模型 prompt;同轮改过目录后不能复用旧目录上下文的结果。
if (cached.workingDir !== (sessionRow.workingDir ?? null)) return null;
@@ -645,6 +664,10 @@ export function registerMakerTitleIpc(options: RegisterMakerTitleIpcOptions = {}
assertTitleIpcCaller(event);
const parsed = parsePredictPromptRequest(request);
try {
+ if (parsed.cancel) {
+ notePromptPredictionSessionCancelled(parsed.sessionId, parsed.completionRevision, activeOwnerScopeKey());
+ return { prompt: null };
+ }
return {
prompt: await predictPromptForCompletedRevision(parsed, options),
};
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 21549f7cbe..f6d6974a0d 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -7458,6 +7458,11 @@ contextBridge.exposeInMainWorld('electronAPI', {
workingDir?: string;
turnGen: number;
completionRevision: number;
+ cancel?: false;
+ } | {
+ sessionId: string;
+ completionRevision: number;
+ cancel: true;
}): Promise<{ prompt: string | null }> => ipcRenderer.invoke('maker:predict-prompt', request),
helpAsk: (
request: import('../shared/helpTypes').HelpAskRequest,
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index eb1c6eaa32..a3b79b4edf 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -294,10 +294,10 @@ import {
useComposerSendShortcutPreference,
} from '@/hooks/useComposerSendShortcutPreference';
import { usePromptRecommendationPreference } from '@/hooks/usePromptRecommendationPreference';
+import { usePromptRecommendationPrediction } from '@/hooks/usePromptRecommendationPrediction';
+import { predictPromptUntilDisabled } from '@/lib/predictPromptUntilDisabled';
import {
- beginPromptRecommendationPrediction,
dismissPromptRecommendation,
- resolvePromptRecommendationPrediction,
usePromptRecommendation,
} from '@/lib/promptRecommendationStore';
import { createLogger } from '@/lib/logger';
@@ -308,7 +308,10 @@ import {
shouldRefreshComposerRender,
type ComposerRenderSnapshot,
} from './composerRenderGate';
-import { shouldShowComposerPromptRecommendation } from './composerPromptRecommendation';
+import {
+ isComposerReadyForPromptRecommendation,
+ shouldShowComposerPromptRecommendation,
+} from './composerPromptRecommendation';
import { createComposerFrameScheduler } from './composerFrameScheduler';
import {
serializeEditorContent,
@@ -1213,7 +1216,7 @@ export function ChatInput({
const promptPreviewInputGuardRef = useRef<() => boolean>(() => false);
const acceptPromptRecommendationRef = useRef<() => boolean>(() => false);
// session 切换时 ChatInput/Editor 会复用;推荐资格必须等目标草稿完成水合后再判断。
- const [composerHydrationGeneration, setComposerHydrationGeneration] = useState(0);
+ const [, setComposerHydrationGeneration] = useState(0);
// 完整输入框空判断:不仅检查 ProseMirror 文档是否为空,还检查附件、浏览器评论和语音稿。
// 避免在用户放好了附件/评论/语音稿但正文为空时,仍发起付费的 predictNextPrompt 调用。
const voiceDraftTextRef = useRef('');
@@ -1351,90 +1354,7 @@ export function ChatInput({
}
}, [recommendationEnabled, sessionId]);
- // messages 是可选 prop。只把「是否已有历史」放进 deps,避免流式 delta 让预测 effect
- // 每个 token 都重跑;真正素材仍由 main 从 DB 读取,renderer payload 不作为信任来源。
- const messagesRef = useRef(messages ?? []);
- messagesRef.current = messages ?? [];
const hasPredictionMessages = (messages?.length ?? 0) > 0;
- useEffect(() => {
- if (!sessionId || recommendation?.phase !== 'candidate') return;
- if (!recommendationEnabled) {
- dismissPromptRecommendation(sessionId, recommendation.revision);
- return;
- }
- // deviceLinkDeviceId=undefined 是归属尚未解析的暂态,先保留 candidate;
- // 远程推荐通过被控端 maker 隧道生成,避免在控制端读取不到会话素材。
- if (deviceLinkDeviceId === undefined || runtimeAgentKind == null || !hasPredictionMessages) {
- return;
- }
- if (remoteHostId || disabled) {
- dismissPromptRecommendation(sessionId, recommendation.revision);
- return;
- }
- const ed = editorRef.current;
- if (!ed || ed.isDestroyed) return;
- // ChatInput/Editor 在 session 间复用。目标 storageKey 的草稿尚未水合时,editor 里仍是
- // 上一 session 的正文;此时判非空会误删目标 session candidate。等水合代次推进后重试。
- if (
- !hasHydratedRef.current ||
- storageKeyForDraftRef.current !== storageKey ||
- isRestoringRef.current
- ) {
- return;
- }
- // candidate 首次进入前台时已有草稿/附件/评论/语音稿,沿用旧逻辑:不发付费调用。
- if (!composerFullyEmptyRef.current()) {
- dismissPromptRecommendation(sessionId, recommendation.revision);
- return;
- }
-
- const requestSeq = beginPromptRecommendationPrediction(sessionId, recommendation.revision);
- if (requestSeq == null) return;
- const requestSessionId = sessionId;
- const requestRevision = recommendation.revision;
- const requestTurnGen = turnGenRef.current;
- const contextMsgs = messagesRef.current.slice(-20).map((message) => ({
- role: message.role,
- content: message.content,
- }));
-
- makerApiForSticky(requestSessionId)
- .predictNextPrompt({
- sessionId: requestSessionId,
- agentKind: runtimeAgentKind,
- messages: contextMsgs,
- workingDir: workingDirRef.current ?? undefined,
- turnGen: requestTurnGen,
- completionRevision: requestRevision,
- })
- .then((result) => {
- // 结果按原 session + completion revision 落入 Store;即使用户已切到其它
- // session,也只更新原 session,切回时再展示,不污染当前输入框。
- resolvePromptRecommendationPrediction(
- requestSessionId,
- requestRevision,
- requestSeq,
- result?.prompt ?? null,
- );
- })
- .catch(() => {
- resolvePromptRecommendationPrediction(requestSessionId, requestRevision, requestSeq, null);
- // 预测失败静默处理:不显示推荐,也不回落任何默认文案。
- });
- }, [
- composerHydrationGeneration,
- deviceLinkDeviceId,
- disabled,
- hasPredictionMessages,
- recommendation?.phase,
- recommendation?.revision,
- recommendationEnabled,
- remoteHostId,
- runtimeAgentKind,
- sessionId,
- storageKey,
- ]);
-
// F-QUEUE-DEFER: when the queue panel is expanded, esc collapses it
// BEFORE falling through to the existing stop / history shortcuts. That
// way the user's mental model stays consistent: esc = "back out of the
@@ -3212,30 +3132,6 @@ export function ChatInput({
editor?.setEditable(!composerTypingLocked);
}, [composerTypingLocked, editor]);
- // 附件/浏览器评论/语音/锁定保持原有「失效」语义(不同于普通文字输入的暂时隐藏)。
- // 同步清 ref,避免稳定闭包里的 Tab 在 React 重渲染前填入已隐藏推荐。
- useEffect(() => {
- const activeRecommendation = recommendationRef.current;
- if (
- sessionId &&
- activeRecommendation &&
- (attachments.length > 0 ||
- browserComments.length > 0 ||
- composerMutationLocked ||
- (voiceBusyOnCurrentComposer && voiceInput.draftText.trim().length > 0))
- ) {
- showRecommendationRef.current = false;
- dismissPromptRecommendation(sessionId, activeRecommendation.revision);
- }
- }, [
- attachments.length,
- browserComments.length,
- composerMutationLocked,
- sessionId,
- voiceBusyOnCurrentComposer,
- voiceInput.draftText,
- ]);
-
const captureSendFocusForRestore = useComposerSendFocusRestore(editor, composerTypingLocked);
const { settings: voiceInputSettings } = useVoiceInputSettings();
const voiceInputShortcutLabel = useMemo(
@@ -8380,20 +8276,45 @@ export function ChatInput({
renderSnapshotRef.current = composerRenderSnapshot(trigger, hasMessage);
const hasComposerPayload = hasMessage || hasAttachments || browserComments.length > 0;
const hasVoiceDraftText = voiceBusyOnCurrentComposer && voiceInput.draftText.trim().length > 0;
- // 推荐 overlay 的可见判据:开关开启 + 有推荐词 + 输入框空 + 无附件/浏览器评论/语音草稿 + 输入框未锁定。
- // composerMutationLocked 涵盖 disabled、sendDispatchInFlight、当前输入框所属语音及远程只读/锁定状态。
- const showRecommendationOverlay = shouldShowComposerPromptRecommendation({
+ const recommendationComposerState = {
enabled: recommendationEnabled,
hydrated:
hasHydratedRef.current &&
storageKeyForDraftRef.current === storageKey &&
!isRestoringRef.current,
- prompt: recommendedPrompt,
hasMessage,
hasAttachments,
hasBrowserComments: browserComments.length > 0,
hasVoiceDraftText,
mutationLocked: composerMutationLocked,
+ };
+ const recommendationComposerReady = isComposerReadyForPromptRecommendation(recommendationComposerState);
+ usePromptRecommendationPrediction({
+ sessionId,
+ recommendation,
+ canPredict:
+ recommendationComposerReady && !!editor && !editor.isDestroyed &&
+ deviceLinkDeviceId !== undefined && runtimeAgentKind != null &&
+ hasPredictionMessages && !remoteHostId,
+ predict: async (revision) => {
+ if (!sessionId || runtimeAgentKind == null) return null;
+ // 素材仍由 Main 从 DB 读取;远程任务经 sticky 路由交给被控电脑。
+ const result = await predictPromptUntilDisabled(makerApiForSticky(sessionId), {
+ sessionId,
+ agentKind: runtimeAgentKind,
+ messages: (messages ?? []).slice(-20).map(({ role, content }) => ({ role, content })),
+ workingDir: workingDirRef.current ?? undefined,
+ turnGen: turnGenRef.current,
+ completionRevision: revision,
+ });
+ return result?.prompt ?? null;
+ },
+ });
+ // 推荐 overlay 的可见判据:开关开启 + 有推荐词 + 输入框空 + 无附件/浏览器评论/语音草稿 + 输入框未锁定。
+ // composerMutationLocked 涵盖 disabled、sendDispatchInFlight、当前输入框所属语音及远程只读/锁定状态。
+ const showRecommendationOverlay = shouldShowComposerPromptRecommendation({
+ ...recommendationComposerState,
+ prompt: recommendedPrompt,
});
// handleKeyDown 的稳定闭包只按真实可见性接受 Tab,避免隐藏推荐被误填入。
showRecommendationRef.current = showRecommendationOverlay;
diff --git a/apps/desktop/src/renderer/components/new-chat/__tests__/composerPromptRecommendation.test.ts b/apps/desktop/src/renderer/components/new-chat/__tests__/composerPromptRecommendation.test.ts
index 82d194bf19..45dea5f7f7 100644
--- a/apps/desktop/src/renderer/components/new-chat/__tests__/composerPromptRecommendation.test.ts
+++ b/apps/desktop/src/renderer/components/new-chat/__tests__/composerPromptRecommendation.test.ts
@@ -115,15 +115,15 @@ describe('shouldShowComposerPromptRecommendation', () => {
});
it('等待目标 session 草稿水合后才判断 candidate 是否为空输入', () => {
- expect(CHAT_INPUT_SOURCE).toContain('storageKeyForDraftRef.current !== storageKey');
+ expect(CHAT_INPUT_SOURCE).toContain('storageKeyForDraftRef.current === storageKey');
expect(CHAT_INPUT_SOURCE).toContain(
'setComposerHydrationGeneration((generation) => generation + 1);',
);
});
- it('只让当前 session 拥有的语音草稿消费推荐', () => {
+ it('只让当前 session 拥有的语音草稿暂停推荐', () => {
expect(CHAT_INPUT_SOURCE).toContain(
- '(voiceBusyOnCurrentComposer && voiceInput.draftText.trim().length > 0)',
+ 'voiceBusyOnCurrentComposer && voiceInput.draftText.trim().length > 0',
);
});
diff --git a/apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts b/apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts
index cb3f1c5321..13521f68b1 100644
--- a/apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts
+++ b/apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts
@@ -9,14 +9,13 @@ export interface ComposerPromptRecommendationVisibilityInput {
mutationLocked: boolean;
}
-/** Overlay 与 Tab 接受共用的唯一可见性判据。 */
-export function shouldShowComposerPromptRecommendation(
- input: ComposerPromptRecommendationVisibilityInput,
+/** 生成、Overlay 与 Tab 接受共用输入框资格;草稿和临时锁定不消费候选。 */
+export function isComposerReadyForPromptRecommendation(
+ input: Omit<ComposerPromptRecommendationVisibilityInput, 'prompt'>,
): boolean {
return (
input.enabled &&
input.hydrated &&
- !!input.prompt &&
!input.hasMessage &&
!input.hasAttachments &&
!input.hasBrowserComments &&
@@ -24,3 +23,9 @@ export function shouldShowComposerPromptRecommendation(
!input.mutationLocked
);
}
+
+export function shouldShowComposerPromptRecommendation(
+ input: ComposerPromptRecommendationVisibilityInput,
+): boolean {
+ return !!input.prompt && isComposerReadyForPromptRecommendation(input);
+}
diff --git a/apps/desktop/src/renderer/hooks/__tests__/usePromptRecommendationPrediction.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/usePromptRecommendationPrediction.test.tsx
new file mode 100644
index 0000000000..cb69566644
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/__tests__/usePromptRecommendationPrediction.test.tsx
@@ -0,0 +1,107 @@
+// @vitest-environment jsdom
+import { act, cleanup, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/hooks/usePromptRecommendationPreference', () => ({
+ PROMPT_RECOMMENDATION_KEY: 'prompt-recommendation-enabled',
+ getPromptRecommendationPreference: () => true,
+ subscribePromptRecommendationPreference: () => () => undefined,
+ syncPromptRecommendationPreferenceFromStorageValue: () => true,
+}));
+vi.mock('@/lib/makerChatStore', () => ({
+ makerChatStore: {
+ getPromptRecommendationRunStartedAt: () => 100,
+ getPromptRecommendationCompletionStatus: () => ({
+ turnStoppedByUser: false, hasTerminalError: false, sideTask: false,
+ hasBackgroundAgentWork: false, hasAutoDrainingQueue: false,
+ }),
+ },
+}));
+
+import {
+ __testing,
+ dismissPromptRecommendation,
+ usePromptRecommendation,
+} from '@/lib/promptRecommendationStore';
+import { isComposerReadyForPromptRecommendation } from '@/components/new-chat/composerPromptRecommendation';
+import { usePromptRecommendationPrediction } from '../usePromptRecommendationPrediction';
+
+const READY = {
+ enabled: true, hydrated: true, hasMessage: false, hasAttachments: false,
+ hasBrowserComments: false, hasVoiceDraftText: false, mutationLocked: false,
+};
+
+function complete(): void {
+ __testing.applyRunningSnapshot(new Map([['a', { isRunning: true }]]));
+ __testing.noteTurnEnded('a', 200);
+ __testing.applyRunningSnapshot(new Map());
+ vi.advanceTimersByTime(500);
+}
+
+function useHarness(sessionId: string, ready: typeof READY, predict: () => Promise<string | null>) {
+ const recommendation = usePromptRecommendation(sessionId);
+ usePromptRecommendationPrediction({
+ sessionId, recommendation, canPredict: isComposerReadyForPromptRecommendation(ready), predict,
+ });
+ return recommendation;
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ __testing.reset();
+});
+afterEach(() => {
+ cleanup();
+ __testing.reset();
+ vi.useRealTimers();
+});
+
+describe('composer prediction lifecycle', () => {
+ it.each([
+ { hasMessage: true }, { hasAttachments: true }, { hasBrowserComments: true },
+ { hasVoiceDraftText: true }, { mutationLocked: true }, { hydrated: false },
+ ])('暂态 %j 期间保留候选,恢复后只生成一次', async (blocked) => {
+ const predict = vi.fn(async () => '继续测试');
+ const hook = renderHook(({ ready }) => useHarness('a', ready, predict), {
+ initialProps: { ready: { ...READY, ...blocked } },
+ });
+ act(complete);
+ expect(hook.result.current?.phase).toBe('candidate');
+ expect(predict).not.toHaveBeenCalled();
+ await act(async () => hook.rerender({ ready: READY }));
+ expect(hook.result.current?.prompt).toBe('继续测试');
+ await act(async () => {
+ hook.rerender({ ready: { ...READY, ...blocked } });
+ });
+ await act(async () => hook.rerender({ ready: READY }));
+ expect(hook.result.current?.prompt).toBe('继续测试');
+ expect(predict).toHaveBeenCalledTimes(1);
+ });
+
+ it('分屏共享同一笔预测,切换任务不丢掉原任务结果', async () => {
+ let resolve!: (prompt: string) => void;
+ const predict = vi.fn(() => new Promise<string>((r) => { resolve = r; }));
+ const first = renderHook(({ id }) => useHarness(id, READY, predict), { initialProps: { id: 'a' } });
+ const second = renderHook(() => useHarness('a', READY, predict));
+ act(complete);
+ expect(predict).toHaveBeenCalledTimes(1);
+ first.rerender({ id: 'b' });
+ await act(async () => resolve('原任务推荐'));
+ expect(first.result.current).toBeUndefined();
+ expect(second.result.current?.prompt).toBe('原任务推荐');
+ first.rerender({ id: 'a' });
+ expect(first.result.current?.prompt).toBe('原任务推荐');
+ });
+
+ it('候选被发送消费后,清空草稿不能重新发起预测', async () => {
+ const predict = vi.fn(async () => '不应生成');
+ const hook = renderHook(({ ready }) => useHarness('a', ready, predict), {
+ initialProps: { ready: { ...READY, hasMessage: true } },
+ });
+ act(complete);
+ act(() => dismissPromptRecommendation('a'));
+ await act(async () => hook.rerender({ ready: READY }));
+ expect(hook.result.current).toBeUndefined();
+ expect(predict).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/renderer/hooks/usePromptRecommendationPrediction.ts b/apps/desktop/src/renderer/hooks/usePromptRecommendationPrediction.ts
new file mode 100644
index 0000000000..fd472ecaf5
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/usePromptRecommendationPrediction.ts
@@ -0,0 +1,35 @@
+import { useEffect, useRef } from 'react';
+
+import {
+ beginPromptRecommendationPrediction,
+ resolvePromptRecommendationPrediction,
+ type PromptRecommendationSnapshot,
+} from '@/lib/promptRecommendationStore';
+
+/** 草稿、水合、临时锁定只暂停候选;恢复可用后仍按 session + revision 去重生成。 */
+export function usePromptRecommendationPrediction({
+ sessionId,
+ recommendation,
+ canPredict,
+ predict,
+}: {
+ sessionId: string | undefined;
+ recommendation: PromptRecommendationSnapshot | undefined;
+ canPredict: boolean;
+ predict: (revision: number) => Promise<string | null>;
+}): void {
+ const predictRef = useRef(predict);
+ predictRef.current = predict;
+
+ useEffect(() => {
+ if (!sessionId || !canPredict || recommendation?.phase !== 'candidate') return;
+ const revision = recommendation.revision;
+ const requestSeq = beginPromptRecommendationPrediction(sessionId, revision);
+ if (requestSeq == null) return;
+ // 切换任务或暂时输入文字不取消在途请求;结果仍落到原 session,重新打开可复用。
+ void predictRef.current(revision).then(
+ (prompt) => resolvePromptRecommendationPrediction(sessionId, revision, requestSeq, prompt),
+ () => resolvePromptRecommendationPrediction(sessionId, revision, requestSeq, null),
+ );
+ }, [canPredict, recommendation?.phase, recommendation?.revision, sessionId]);
+}
diff --git a/apps/desktop/src/renderer/lib/__tests__/predictPromptUntilDisabled.test.ts b/apps/desktop/src/renderer/lib/__tests__/predictPromptUntilDisabled.test.ts
new file mode 100644
index 0000000000..14eb6f4f73
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/__tests__/predictPromptUntilDisabled.test.ts
@@ -0,0 +1,67 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ _resetPromptRecommendationPreferenceForTests,
+ syncPromptRecommendationPreferenceFromStorageValue,
+} from '@/hooks/usePromptRecommendationPreference';
+import { predictPromptUntilDisabled } from '../predictPromptUntilDisabled';
+
+const request = {
+ sessionId: 'original-session', agentKind: 'codex' as const, messages: [],
+ turnGen: 0, completionRevision: 200,
+};
+
+beforeEach(() => {
+ _resetPromptRecommendationPreferenceForTests();
+ syncPromptRecommendationPreferenceFromStorageValue('true');
+});
+
+describe('request-owned prediction cancellation', () => {
+ it('关闭开关后只向最初捕获的路由取消一次,重新打开也不恢复旧结果', async () => {
+ let resolve!: (result: { prompt: string }) => void;
+ const api = { predictNextPrompt: vi.fn()
+ .mockImplementationOnce(() => new Promise(done => { resolve = done; }))
+ .mockResolvedValue({ prompt: null }) };
+ const pending = predictPromptUntilDisabled(api, request);
+ syncPromptRecommendationPreferenceFromStorageValue('false');
+ syncPromptRecommendationPreferenceFromStorageValue('true');
+ syncPromptRecommendationPreferenceFromStorageValue('false');
+ expect(api.predictNextPrompt).toHaveBeenCalledTimes(2);
+ expect(api.predictNextPrompt).toHaveBeenLastCalledWith({
+ sessionId: 'original-session', completionRevision: 200, cancel: true,
+ });
+ resolve({ prompt: 'late result' });
+ await expect(pending).resolves.toEqual({ prompt: null });
+ });
+
+ it('已关闭时不生成,已完成后释放订阅,下一轮仍能生成', async () => {
+ const api = { predictNextPrompt: vi.fn().mockResolvedValue({ prompt: 'next' }) };
+ await expect(predictPromptUntilDisabled(api, request)).resolves.toEqual({ prompt: 'next' });
+ syncPromptRecommendationPreferenceFromStorageValue('false');
+ await expect(predictPromptUntilDisabled(api, request)).resolves.toEqual({ prompt: null });
+ expect(api.predictNextPrompt).toHaveBeenCalledTimes(1);
+ syncPromptRecommendationPreferenceFromStorageValue('true');
+ await predictPromptUntilDisabled(api, { ...request, completionRevision: 300 });
+ expect(api.predictNextPrompt).toHaveBeenCalledTimes(2);
+ });
+
+ it('旧主机拒绝取消时也丢弃结果,取消载荷不带生成所需字段', async () => {
+ let resolve!: (result: { prompt: string }) => void;
+ const api = { predictNextPrompt: vi.fn()
+ .mockImplementationOnce(() => new Promise(done => { resolve = done; }))
+ .mockRejectedValue(new Error('[INVALID_PARAMS] legacy host')) };
+ const pending = predictPromptUntilDisabled(api, request);
+ syncPromptRecommendationPreferenceFromStorageValue('false');
+ const cancellation = api.predictNextPrompt.mock.calls[1][0];
+ expect(cancellation).not.toHaveProperty('agentKind');
+ expect(cancellation).not.toHaveProperty('turnGen');
+ resolve({ prompt: 'late result' });
+ await expect(pending).resolves.toEqual({ prompt: null });
+ });
+
+ it('生成失败后释放订阅', async () => {
+ const api = { predictNextPrompt: vi.fn().mockRejectedValue(new Error('failed')) };
+ await expect(predictPromptUntilDisabled(api, request)).rejects.toThrow('failed');
+ syncPromptRecommendationPreferenceFromStorageValue('false');
+ expect(api.predictNextPrompt).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/desktop/src/renderer/lib/__tests__/promptRecommendationStore.test.ts b/apps/desktop/src/renderer/lib/__tests__/promptRecommendationStore.test.ts
index 6f38dc4c4a..beb63fdb2e 100644
--- a/apps/desktop/src/renderer/lib/__tests__/promptRecommendationStore.test.ts
+++ b/apps/desktop/src/renderer/lib/__tests__/promptRecommendationStore.test.ts
@@ -74,6 +74,71 @@ afterEach(() => {
});
describe('promptRecommendationStore', () => {
+ it.each([400, 600, 5_000])('最终 done 晚于 status:false %dms 时仍能生成推荐', (delay) => {
+ h.statusBySession.set('session-a', ELIGIBLE);
+ h.startedAtBySession.set('session-a', 100);
+ __testing.applyRunningSnapshot(new Map([['session-a', { isRunning: true }]]));
+ __testing.applyRunningSnapshot(new Map());
+ __testing.noteTurnEnded('session-a', 200);
+ vi.advanceTimersByTime(delay);
+
+ const early = __testing.getSessionSnapshot('session-a');
+ if (early) {
+ const seq = beginPromptRecommendationPrediction('session-a', early.revision)!;
+ // Main 的 dispatch boundary 尚未释放,本次没有调用模型。
+ resolvePromptRecommendationPrediction('session-a', early.revision, seq, null);
+ }
+ __testing.noteTurnEnded('session-a', 200 + delay);
+ vi.advanceTimersByTime(500);
+ expect(__testing.getSessionSnapshot('session-a')?.revision).toBe(200 + delay);
+ });
+
+ it('更新的完成通知立即作废旧预测,不让旧 Promise 抢先消费最终完成', () => {
+ h.statusBySession.set('session-a', ELIGIBLE);
+ complete('session-a', 200);
+ const seq = beginPromptRecommendationPrediction('session-a', 200)!;
+ __testing.noteTurnEnded('session-a', 800);
+ resolvePromptRecommendationPrediction('session-a', 200, seq, '旧结果');
+ expect(__testing.getSessionSnapshot('session-a')?.prompt).not.toBe('旧结果');
+ vi.advanceTimersByTime(500);
+ expect(__testing.getSessionSnapshot('session-a')?.revision).toBe(800);
+ });
+
+ it.each(['accepted', 'dismissed'])('%s 后迟到的结束 patch 不会重新生成推荐', (outcome) => {
+ h.statusBySession.set('session-a', ELIGIBLE);
+ complete('session-a', 200);
+ const seq = beginPromptRecommendationPrediction('session-a', 200)!;
+ if (outcome === 'accepted') {
+ resolvePromptRecommendationPrediction('session-a', 200, seq, '继续测试');
+ }
+ dismissPromptRecommendation('session-a', 200);
+ __testing.noteTurnEnded('session-a', 800);
+ vi.advanceTimersByTime(500);
+ expect(__testing.getSessionSnapshot('session-a')).toBeUndefined();
+ });
+
+ it('等待最终 done 时即使没有 entry,显式发送也取消这份等待', () => {
+ h.statusBySession.set('session-a', ELIGIBLE);
+ complete('session-a', 200);
+ const seq = beginPromptRecommendationPrediction('session-a', 200)!;
+ resolvePromptRecommendationPrediction('session-a', 200, seq, null);
+ dismissPromptRecommendation('session-a');
+ __testing.noteTurnEnded('session-a', 800);
+ vi.advanceTimersByTime(500);
+ expect(__testing.getSessionSnapshot('session-a')).toBeUndefined();
+ });
+
+ it('新 running 后输入框的同步失效不会误删新轮完成资格', () => {
+ h.statusBySession.set('session-a', ELIGIBLE);
+ h.startedAtBySession.set('session-a', 100);
+ __testing.applyRunningSnapshot(new Map([['session-a', { isRunning: true }]]));
+ dismissPromptRecommendation('session-a');
+ __testing.noteTurnEnded('session-a', 200);
+ __testing.applyRunningSnapshot(new Map());
+ vi.advanceTimersByTime(500);
+ expect(__testing.getSessionSnapshot('session-a')?.revision).toBe(200);
+ });
+
it('不会为本次运行期间未观察到 running 的历史 session 创建候选', () => {
h.statusBySession.set('old-session', ELIGIBLE);
diff --git a/apps/desktop/src/renderer/lib/predictPromptUntilDisabled.ts b/apps/desktop/src/renderer/lib/predictPromptUntilDisabled.ts
new file mode 100644
index 0000000000..a1e72540c3
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/predictPromptUntilDisabled.ts
@@ -0,0 +1,29 @@
+import {
+ getPromptRecommendationPreference,
+ subscribePromptRecommendationPreference,
+} from '@/hooks/usePromptRecommendationPreference';
+
+type PredictionApi = Pick<typeof window.electronAPI.maker, 'predictNextPrompt'>;
+type PredictionRequest = Exclude<Parameters<PredictionApi['predictNextPrompt']>[0], { cancel: true }>;
+
+/** Keep cancellation attached to the request, even after its composer has unmounted. */
+export async function predictPromptUntilDisabled(api: PredictionApi, request: PredictionRequest) {
+ if (!getPromptRecommendationPreference()) return { prompt: null };
+ let cancelled = false;
+ const unsubscribe = subscribePromptRecommendationPreference((enabled) => {
+ if (enabled || cancelled) return;
+ cancelled = true;
+ // Deliberately omit generation fields: old hosts reject instead of generating another prompt.
+ void api.predictNextPrompt({
+ sessionId: request.sessionId,
+ completionRevision: request.completionRevision,
+ cancel: true,
+ }).catch(() => undefined);
+ });
+ try {
+ const result = await api.predictNextPrompt(request);
+ return cancelled ? { prompt: null } : result;
+ } finally {
+ unsubscribe();
+ }
+}
diff --git a/apps/desktop/src/renderer/lib/promptRecommendationStore.ts b/apps/desktop/src/renderer/lib/promptRecommendationStore.ts
index 1eaf053340..b4169658ea 100644
--- a/apps/desktop/src/renderer/lib/promptRecommendationStore.ts
+++ b/apps/desktop/src/renderer/lib/promptRecommendationStore.ts
@@ -75,7 +75,7 @@ function handlePreferenceChanged(enabled: boolean): void {
entries.clear();
pendingCompletionRevisions.clear();
sawRunningSessionIds.clear();
- runStartedAtBySession.clear();
+ runStartedAtBySession.clear();
for (const timer of settleTimers.values()) clearTimeout(timer);
settleTimers.clear();
for (const sessionId of changedSessionIds) emitSession(sessionId);
@@ -104,8 +104,8 @@ function settleCompletion(sessionId: string): void {
if (revision == null || !sawRunningSessionIds.has(sessionId)) return;
pendingCompletionRevisions.delete(sessionId);
- sawRunningSessionIds.delete(sessionId);
- runStartedAtBySession.delete(sessionId);
+ // status:false 与最终 done 都可能写 ended revision。500ms 只是合并窗口,
+ // 不是终末证明:保留本轮观察资格,Main 暂时返回 null 后仍能接住迟到的 done。
const previousHandled = handledCompletionRevisions.get(sessionId) ?? 0;
if (revision <= previousHandled) return;
handledCompletionRevisions.set(sessionId, revision);
@@ -121,6 +121,8 @@ function settleCompletion(sessionId: string): void {
!status.hasAutoDrainingQueue;
if (!eligible) {
+ sawRunningSessionIds.delete(sessionId);
+ runStartedAtBySession.delete(sessionId);
deleteEntry(sessionId);
return;
}
@@ -194,6 +196,8 @@ function noteTurnEnded(sessionId: string, revision: number): void {
const pending = pendingCompletionRevisions.get(sessionId) ?? 0;
if (revision <= handled || revision <= pending) return;
pendingCompletionRevisions.set(sessionId, revision);
+ // 新 revision 已到达时立即隔离旧 Promise,不能等 settle timer 才作废。
+ deleteEntry(sessionId);
scheduleCompletionSettle(sessionId);
}
@@ -325,6 +329,8 @@ export function resolvePromptRecommendationPrediction(
deleteEntry(sessionId);
return;
}
+ sawRunningSessionIds.delete(sessionId);
+ runStartedAtBySession.delete(sessionId);
entries.set(sessionId, {
...current,
phase: 'ready',
@@ -333,10 +339,18 @@ export function resolvePromptRecommendationPrediction(
emitSession(sessionId);
}
-/** Tab / 发送 / workingDir / 附件等消费路径同步作废当前推荐。 */
+/** Tab / 发送 / workingDir 等显式消费路径同步作废当前推荐和迟到的完成通知。 */
export function dismissPromptRecommendation(sessionId: string, revision?: number): void {
const current = entries.get(sessionId);
- if (!current || (revision != null && current.revision !== revision)) return;
+ if (revision != null && current?.revision !== revision) return;
+ // 无 entry 也可能仍在等待最终 done;显式发送/换目录应取消这份等待。
+ // 新 running 的 layout effect 也会调用本函数,不能清掉刚开始的新轮资格。
+ if (!runningSessionIds.has(sessionId)) {
+ clearSettleTimer(sessionId);
+ pendingCompletionRevisions.delete(sessionId);
+ sawRunningSessionIds.delete(sessionId);
+ runStartedAtBySession.delete(sessionId);
+ }
deleteEntry(sessionId);
}
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 6ea3cf0433..f845220141 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -6594,6 +6594,11 @@ interface ElectronAPI {
workingDir?: string;
turnGen: number;
completionRevision: number;
+ cancel?: false;
+ } | {
+ sessionId: string;
+ completionRevision: number;
+ cancel: true;
}) => Promise<{ prompt: string | null }>;
helpAsk: (
request: import('../shared/helpTypes').HelpAskRequest,