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(goal): 目标不在运行时提醒模型停止输出裁决块、不承诺自动续跑 (#5463)

Dash011d9398a9f3
diff --git a/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts b/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts
index b2dfa82825..47cbd51679 100644
--- a/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts
+++ b/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts
@@ -233,8 +233,8 @@ describe('注入接线(源码级守卫)', () => {
expect(source).toContain(
'deps.isMobileClientInvoke?.() === true || so.fromMobileClient === true',
);
- // 注入链:normalized → withHandoff → withPlanReconcile → mobile note(最外层)。
- expect(source).toContain('prependNoteToWireUserMessage(withPlanReconcile as HandoffWireMessage, mobileClientNote)');
+ // 注入链:normalized → withHandoff → withPlanReconcile → withGoalInactiveNote → mobile note(最外层)。
+ expect(source).toContain('prependNoteToWireUserMessage(withGoalInactiveNote as HandoffWireMessage, mobileClientNote)');
expect(source).toContain('shouldPrependMobileClientPromptNote(normalized, sess.agentKind)');
// 落库内容必须仍取 persistUserMessage.content —— 若改成 outgoing,提示语会写进
// 用户消息、污染界面显示的原话。
diff --git a/apps/desktop/src/main/goal-host/__tests__/inactiveNote.test.ts b/apps/desktop/src/main/goal-host/__tests__/inactiveNote.test.ts
new file mode 100644
index 0000000000..980ce216ac
--- /dev/null
+++ b/apps/desktop/src/main/goal-host/__tests__/inactiveNote.test.ts
@@ -0,0 +1,103 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const goalRows = vi.hoisted(() => ({
+ value: [] as Array<{ status: string; usageResetAt: number | null }>,
+}));
+const latestAssistant = vi.hoisted(() => ({ value: '' }));
+
+vi.mock('../../localDb/client/current.js', () => {
+ const query = {
+ select: () => query,
+ from: () => query,
+ where: () => query,
+ limit: async () => goalRows.value,
+ };
+ return { getDbClient: () => ({ drizzle: query }) };
+});
+
+vi.mock('../../localDb/latestMessageText.js', () => ({
+ latestNonEmptyMessageText: vi.fn(async () => latestAssistant.value),
+}));
+
+import {
+ buildGoalInactiveNote,
+ hasTrailingGoalVerdictBlock,
+ peekGoalInactiveNote,
+ shouldPrependGoalInactiveNote,
+} from '../inactiveNote';
+
+const REPLY_WITH_VERDICT =
+ '资源正在上传。\n\n```json\n{"goal_status":"continue","reason":"仍在上传"}\n```';
+
+describe('goal inactive note', () => {
+ beforeEach(() => {
+ goalRows.value = [];
+ latestAssistant.value = '';
+ });
+
+ it('只认回复末尾的裁决块', () => {
+ expect(hasTrailingGoalVerdictBlock(REPLY_WITH_VERDICT)).toBe(true);
+ expect(hasTrailingGoalVerdictBlock('结论\n{"goal_status":"complete","reason":"done"}')).toBe(
+ true,
+ );
+ expect(hasTrailingGoalVerdictBlock('协议里有 "goal_status" 字段,用来裁决续跑。')).toBe(false);
+ expect(hasTrailingGoalVerdictBlock('')).toBe(false);
+ });
+
+ it('末尾围栏块的 reason 含花括号时也能认出', () => {
+ expect(
+ hasTrailingGoalVerdictBlock(
+ '已改好。\n\n```json\n{"goal_status":"continue","reason":"还要处理 {config} 段"}\n```\n',
+ ),
+ ).toBe(true);
+ expect(
+ hasTrailingGoalVerdictBlock(
+ '```json\n{"goal_status":"continue"}\n```\n\n示例:\n```ts\nconst a = {};\n```',
+ ),
+ ).toBe(false);
+ });
+
+ it('目标不再续跑且上一条回复带裁决块时才注入', () => {
+ const goal = (status: string, usageResetAt: number | null = null) => ({ status, usageResetAt });
+ for (const g of [
+ null,
+ goal('paused'),
+ goal('blocked'),
+ goal('budgetLimited'),
+ // 没有重置时刻的 usageLimited 不会自动恢复,停着等手动 resume。
+ goal('usageLimited'),
+ ]) {
+ expect(
+ shouldPrependGoalInactiveNote({ goal: g, latestAssistantText: REPLY_WITH_VERDICT }),
+ ).toBe(true);
+ }
+ // active 正在续跑;带重置时刻的 usageLimited 会到点自动恢复,都不能说"不会自动继续"。
+ for (const g of [goal('active'), goal('usageLimited', 1_800_000_000_000)]) {
+ expect(
+ shouldPrependGoalInactiveNote({ goal: g, latestAssistantText: REPLY_WITH_VERDICT }),
+ ).toBe(false);
+ }
+ expect(shouldPrependGoalInactiveNote({ goal: null, latestAssistantText: '普通回复' })).toBe(
+ false,
+ );
+ });
+
+ it('说明要求停吐裁决块、不承诺自动续跑,并以用户消息边界收尾', () => {
+ const note = buildGoalInactiveNote();
+ expect(note).toContain('不要再输出 goal_status 裁决块');
+ expect(note).toContain('不要承诺会自己接着推进');
+ expect(note.endsWith('== 状态说明结束,以下是用户的新消息 ==')).toBe(true);
+ });
+
+ it('peek 按库内目标状态与最新回复现查', async () => {
+ latestAssistant.value = REPLY_WITH_VERDICT;
+ expect(await peekGoalInactiveNote('s1')).toBe(buildGoalInactiveNote());
+
+ goalRows.value = [{ status: 'active', usageResetAt: null }];
+ expect(await peekGoalInactiveNote('s1')).toBeNull();
+
+ goalRows.value = [{ status: 'paused', usageResetAt: null }];
+ latestAssistant.value = '模型已不再输出裁决块。';
+ expect(await peekGoalInactiveNote('s1')).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/goal-host/inactiveNote.ts b/apps/desktop/src/main/goal-host/inactiveNote.ts
new file mode 100644
index 0000000000..2e8d49c241
--- /dev/null
+++ b/apps/desktop/src/main/goal-host/inactiveNote.ts
@@ -0,0 +1,102 @@
+/**
+ * 目标模式已不在运行时的状态说明(goal inactive note)。
+ *
+ * 目标运行期间,每个续跑轮都在 user message 后缀里要求模型"每轮末尾吐 goal_status
+ * 裁决块"(见 directive.ts)。目标清除 / 完成 / 暂停 / 受阻后不再追加该指令,但历史
+ * 轮次仍留在 agent 原生上下文里,模型会照着自己前面的回复继续吐裁决块,还会以为自己
+ * 会被自动续跑,向用户承诺"剩下由我继续处理"。
+ *
+ * 机制与计划对账(maker-ipc/planReconcile.ts)同一条搭车通道:每次普通发送时现查,
+ * 若会话没有仍会续跑的目标、而上一条 assistant 回复末尾仍带裁决块,就在 wire payload
+ * 前插一段说明。不落库、不新增状态:模型一旦不再吐块,条件自然失效;重启后照样生效。
+ * goal controller 自己发起的续跑轮直接走 session.send,不经过这些入口。
+ */
+
+import { eq } from 'drizzle-orm';
+
+import { stripGoalVerdictBlock } from '@cindy/maker-shared/goal-verdict';
+
+import { getDbClient } from '../localDb/client/current.js';
+import { latestNonEmptyMessageText } from '../localDb/latestMessageText.js';
+import { sessionGoals } from '../localDb/schema.js';
+
+/** 末尾围栏块的内文;回复不以围栏收尾时为 null。 */
+function trailingFenceBody(text: string): string | null {
+ const trimmed = text.trimEnd();
+ if (!trimmed.endsWith('```')) return null;
+ const body = trimmed.slice(0, -3);
+ const open = body.lastIndexOf('```');
+ if (open < 0) return null;
+ return body.slice(open + 3).replace(/^(?:jsonc?)?\s*/i, '');
+}
+
+function isGoalProtocolObject(raw: string): boolean {
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ return (
+ typeof parsed === 'object' &&
+ parsed !== null &&
+ ('goal_status' in parsed || 'goal_setup' in parsed)
+ );
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * 回复**末尾**是否带 goal_status / goal_setup 块。末尾围栏块按 JSON 解析(reason 含花括号
+ * 也能认出),其余形态沿用显示层剥离的判据。
+ */
+export function hasTrailingGoalVerdictBlock(text: string): boolean {
+ if (text === '') return false;
+ const fenced = trailingFenceBody(text);
+ if (fenced !== null && isGoalProtocolObject(fenced)) return true;
+ return stripGoalVerdictBlock(text) !== text;
+}
+
+export interface GoalContinuationState {
+ status: string;
+ usageResetAt: number | null;
+}
+
+/** 目标仍会续跑:active 正在跑;usageLimited 且有重置时刻会到点自动恢复(controller 排的 timer)。 */
+function goalStillContinues(goal: GoalContinuationState | null): boolean {
+ if (!goal) return false;
+ return goal.status === 'active' || (goal.status === 'usageLimited' && goal.usageResetAt != null);
+}
+
+export function shouldPrependGoalInactiveNote(input: {
+ goal: GoalContinuationState | null;
+ latestAssistantText: string;
+}): boolean {
+ return !goalStillContinues(input.goal) && hasTrailingGoalVerdictBlock(input.latestAssistantText);
+}
+
+export function buildGoalInactiveNote(): string {
+ return [
+ '[目标状态]本任务当前没有运行中的目标,之前回复末尾的 goal_status 裁决块只属于目标模式。',
+ '本轮回复末尾不要再输出 goal_status 裁决块。',
+ '这一轮结束后不会因目标模式被自动唤起继续:可以说明仍在后台运行的进程,但不要承诺会自己接着推进;',
+ '需要持续推进时,建议用户开启目标模式或设置自动任务。',
+ '== 状态说明结束,以下是用户的新消息 ==',
+ ].join('\n');
+}
+
+/** 发送入口调用:命中条件返回说明文本,否则 null。读库失败由调用方静默跳过。 */
+export async function peekGoalInactiveNote(sessionId: string): Promise<string | null> {
+ const [goalRows, latestAssistantText] = await Promise.all([
+ getDbClient()
+ .drizzle.select({ status: sessionGoals.status, usageResetAt: sessionGoals.usageResetAt })
+ .from(sessionGoals)
+ .where(eq(sessionGoals.sessionId, sessionId))
+ .limit(1),
+ // 目标达成 / 用量恢复会落空正文的 assistant 记录,要跳过它们看真正的上一条回复。
+ latestNonEmptyMessageText(sessionId, 'assistant'),
+ ]);
+ return shouldPrependGoalInactiveNote({
+ goal: goalRows[0] ?? null,
+ latestAssistantText,
+ })
+ ? buildGoalInactiveNote()
+ : null;
+}
diff --git a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
index bf578e7a19..3db925930c 100644
--- a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
+++ b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
@@ -60,6 +60,7 @@ const h = vi.hoisted(() => {
createSessionRow: vi.fn(async () => undefined),
peekPendingHandoff: vi.fn(async () => null as string | null),
consumePendingHandoff: vi.fn(),
+ peekGoalInactiveNote: vi.fn(async () => null as string | null),
listProviders: vi.fn(async (): Promise<unknown[]> => []),
getModelVisibilityOverride: vi.fn(() => undefined),
readImDefaultSettings: vi.fn(),
@@ -155,6 +156,9 @@ vi.mock('../../maker-ipc/agentHandoffPendingSingleton.js', () => ({
consume: h.consumePendingHandoff,
},
}));
+vi.mock('../../goal-host/inactiveNote.js', () => ({
+ peekGoalInactiveNote: h.peekGoalInactiveNote,
+}));
vi.mock('../../imageCacheStore.js', () => ({
resolveSafe: vi.fn(),
}));
@@ -1065,6 +1069,34 @@ describe('hook session-runner 的 userSendAt 时序(未分类误判回归)', ()
expect(h.consumePendingHandoff).toHaveBeenCalledWith('sess-new');
});
+ it('目标状态说明只注入 agent wire 内容,排在交接段外层', async () => {
+ h.peekPendingHandoff.mockResolvedValueOnce('HANDOFF');
+ h.peekGoalInactiveNote.mockResolvedValueOnce('GOAL-NOTE');
+ const runner = createMakerHookSessionRunner({ log });
+ const outcome = await runner.run(baseReq({}));
+
+ expect(outcome.status).toBe('ok');
+ expect(h.peekGoalInactiveNote).toHaveBeenCalledWith('sess-new');
+ const session = await fakeMaker.createSession.mock.results[0].value;
+ expect(session.send.mock.calls[0][0]).toMatchObject({
+ content: `GOAL-NOTE\n\nHANDOFF\n\n${HELLO_WITH_NOTE}`,
+ });
+ const createCalls = h.createMessage.mock.calls as unknown as Array<
+ [string, { content: unknown }]
+ >;
+ expect(createCalls[0][1].content).toBe('hello');
+ });
+
+ it('目标状态说明读取抛错时静默跳过,不挡发送', async () => {
+ h.peekGoalInactiveNote.mockRejectedValueOnce(new Error('db unavailable'));
+ const runner = createMakerHookSessionRunner({ log });
+ const outcome = await runner.run(baseReq({}));
+
+ expect(outcome.status).toBe('ok');
+ const session = await fakeMaker.createSession.mock.results[0].value;
+ expect(session.send.mock.calls[0][0]).toMatchObject({ content: HELLO_WITH_NOTE });
+ });
+
it('复用/接管(isNew=false):createSession 不带 vendorOptions,不给可能的桌面会话打 Slack 标', async () => {
const runner = createMakerHookSessionRunner({ log });
const outcome = await runner.run(baseReq({ sessionId: 'sess-old', isNew: false }));
diff --git a/apps/desktop/src/main/hook-control/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.ts
index 0a1759bd7b..4adeb3202a 100644
--- a/apps/desktop/src/main/hook-control/session-runner.ts
+++ b/apps/desktop/src/main/hook-control/session-runner.ts
@@ -75,6 +75,7 @@ import {
} from '../maker-ipc/agentHandoff.js';
import { agentHandoffPending } from '../maker-ipc/agentHandoffPendingSingleton.js';
import { summarizeOpenPlan, buildPlanReconcileNote } from '../maker-ipc/planReconcile.js';
+import { peekGoalInactiveNote } from '../goal-host/inactiveNote.js';
import { listMessagesForAgentHandoff } from '../localDb/ipc/messages.js';
import { enqueueDurableWrite } from '../messagePersistBroadcaster.js';
import { toDesktopSessionDispatchOutcome } from '../maker-host/send-outcome.js';
@@ -1164,9 +1165,16 @@ export function createMakerHookSessionRunner(deps: {
return null;
}
})() : null;
- const outgoingMessage: UserMessage = planReconcileNote
+ const withPlanReconcile: UserMessage = planReconcileNote
? (prependNoteToWireUserMessage(withHandoff, planReconcileNote) as UserMessage)
: withHandoff;
+ // 目标状态说明:与 makerSendTransaction 同语义,读库失败静默跳过。
+ const goalInactiveNote = await enqueueDurableWrite(`goal-inactive-read:${session.id}`, () =>
+ peekGoalInactiveNote(session.id),
+ ).catch(() => null);
+ const outgoingMessage: UserMessage = goalInactiveNote
+ ? (prependNoteToWireUserMessage(withPlanReconcile, goalInactiveNote) as UserMessage)
+ : withPlanReconcile;
const trustedChannelOrigin = mainOwnedChannelOrigin(req.source?.im);
const sendResult = await session.send(outgoingMessage, {
origin,
diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
index 11de28e405..e1469db356 100644
--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
@@ -82,6 +82,7 @@ const mocks = vi.hoisted(() => ({
generateAndPersistFbotTitle: vi.fn(),
desktopSessionRows: vi.fn(),
materializeLocalMarkdownImages: vi.fn(),
+ peekGoalInactiveNote: vi.fn(async (): Promise<string | null> => null),
}));
vi.mock('../../../logger', () => ({
@@ -119,6 +120,10 @@ vi.mock('../../../localDb/schema', () => ({
sessions: {},
}));
+vi.mock('../../../goal-host/inactiveNote', () => ({
+ peekGoalInactiveNote: mocks.peekGoalInactiveNote,
+}));
+
vi.mock('../../../imageCacheStore', () => ({
resolveSafe: mocks.resolveXdtImageUrl,
}));
@@ -798,6 +803,25 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
});
});
+ it('prepends the goal inactive note to the agent wire message only', async () => {
+ mocks.peekGoalInactiveNote.mockResolvedValueOnce('GOAL-NOTE');
+ const h = setupSession(async () => ({ accepted: true }));
+
+ await runDefaultTurn(vi.fn(), { text: 'hello', agentText: 'hello' });
+
+ expect(mocks.peekGoalInactiveNote).toHaveBeenCalledTimes(1);
+ expect(h.send.mock.calls[0]?.[0]).toMatchObject({ content: 'GOAL-NOTE\n\nhello' });
+ });
+
+ it('sends unchanged when reading the goal inactive note fails', async () => {
+ mocks.peekGoalInactiveNote.mockRejectedValueOnce(new Error('db unavailable'));
+ const h = setupSession(async () => ({ accepted: true }));
+
+ await runDefaultTurn(vi.fn(), { text: 'hello', agentText: 'hello' });
+
+ expect(h.send.mock.calls[0]?.[0]).toMatchObject({ content: 'hello' });
+ });
+
it('marks only an accepted attached IM turn headless and releases it on done', async () => {
const sendGate = deferred<SessionSendResult>();
const h = setupAttachedSession(async () => sendGate.promise);
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts
index f722c3955a..cc0e211ffb 100644
--- a/apps/desktop/src/main/im/shared/turnRunner.ts
+++ b/apps/desktop/src/main/im/shared/turnRunner.ts
@@ -116,6 +116,7 @@ import { beginGroupHistoryAccess, type GroupHistoryAccessScope } from './groupHi
import { agentHandoffPending } from '../../maker-ipc/agentHandoffPendingSingleton';
import { prependHandoffToUserMessage, prependNoteToWireUserMessage } from '../../maker-ipc/agentHandoff';
import { buildPlanReconcileNote, summarizeOpenPlan } from '../../maker-ipc/planReconcile';
+import { peekGoalInactiveNote } from '../../goal-host/inactiveNote';
import { listMessagesForAgentHandoff } from '../../localDb/ipc/messages';
import {
enqueueDurableWrite,
@@ -1275,12 +1276,23 @@ export function createTurnRunner(
return null;
}
})();
- const outgoingMessage = planReconcileNote
+ const withPlanReconcile = planReconcileNote
? prependNoteToWireUserMessage(
withHandoff as Parameters<typeof prependNoteToWireUserMessage>[0],
planReconcileNote,
)
: withHandoff;
+ // 目标状态说明:与 makerSendTransaction 同语义,目标已不在运行时提醒模型别再
+ // 吐裁决块、别承诺自动续跑。读库失败静默跳过。
+ const goalInactiveNote = await enqueueDurableWrite(`goal-inactive-read:${rowId}`, () =>
+ peekGoalInactiveNote(rowId),
+ ).catch(() => null);
+ const outgoingMessage = goalInactiveNote
+ ? prependNoteToWireUserMessage(
+ withPlanReconcile as Parameters<typeof prependNoteToWireUserMessage>[0],
+ goalInactiveNote,
+ )
+ : withPlanReconcile;
// 群护栏取缔: 按会话当前权限档决定是否真正挂强确认策略, 见
// resolveEffectiveTurnPolicy。不挂时走与 DM 轮次相同的无策略路径。
diff --git a/apps/desktop/src/main/localDb/__tests__/latestMessageText.test.ts b/apps/desktop/src/main/localDb/__tests__/latestMessageText.test.ts
index ce87e46455..fdb8fdc7e2 100644
--- a/apps/desktop/src/main/localDb/__tests__/latestMessageText.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/latestMessageText.test.ts
@@ -4,7 +4,7 @@ import { drizzle } from 'drizzle-orm/better-sqlite3';
import type { DbClient } from '../client/DbClient.js';
import { clearCurrentDbClient, setCurrentDbClient } from '../client/current.js';
-import { regenerateTitleMaterial } from '../latestMessageText.js';
+import { latestNonEmptyMessageText, regenerateTitleMaterial } from '../latestMessageText.js';
import * as schema from '../schema.js';
interface Harness {
@@ -256,3 +256,34 @@ describe('regenerateTitleMaterial hook user text', () => {
expect(material.recent.map((m) => m.text)).toEqual(['原始用户正文']);
});
});
+
+describe('latestNonEmptyMessageText', () => {
+ it('skips empty-body records and respects rewind and clear boundaries', async () => {
+ const { sqlite } = createHarness();
+ sqlite.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, ?)').run('s1', 1500);
+ const insert = sqlite.prepare(`
+ INSERT INTO messages (
+ id, client_id, session_id, role, content, tool_use_id, agent_meta, created_at, rewind_at
+ ) VALUES (?, ?, 's1', 'assistant', ?, NULL, ?, ?, ?)
+ `);
+ insert.run('m1', 'c1', JSON.stringify('清空前的回复'), null, 1000, null);
+ insert.run('m2', 'c2', JSON.stringify('真正的上一条回复'), null, 2000, null);
+ insert.run('m3', 'c3', JSON.stringify('已回退的回复'), null, 3000, 3500);
+ insert.run('m4', 'c4', '', JSON.stringify({ goalCompletion: { turnsUsed: 3 } }), 4000, null);
+
+ await expect(latestNonEmptyMessageText('s1', 'assistant')).resolves.toBe('真正的上一条回复');
+ });
+
+ it('returns an empty string when nothing visible has text', async () => {
+ const { sqlite } = createHarness();
+ sqlite.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, NULL)').run('s1');
+ sqlite
+ .prepare(
+ `INSERT INTO messages (id, client_id, session_id, role, content, created_at)
+ VALUES ('m1', 'c1', 's1', 'assistant', '', 1000)`,
+ )
+ .run();
+
+ await expect(latestNonEmptyMessageText('s1', 'assistant')).resolves.toBe('');
+ });
+});
diff --git a/apps/desktop/src/main/localDb/latestMessageText.ts b/apps/desktop/src/main/localDb/latestMessageText.ts
index 264e8037fd..1c22170793 100644
--- a/apps/desktop/src/main/localDb/latestMessageText.ts
+++ b/apps/desktop/src/main/localDb/latestMessageText.ts
@@ -227,6 +227,35 @@ export async function latestMessageText(
return (await latestMessage(sessionId, role)).text;
}
+/** 跳过空正文记录(如只带 agentMeta 的目标达成分隔条)时最多往回看的行数。 */
+const NON_EMPTY_SCAN_LIMIT = 20;
+
+/** 最近一条正文非空的消息文本;窗口内都为空时返回空串。 */
+export async function latestNonEmptyMessageText(
+ sessionId: string,
+ role: 'user' | 'assistant',
+): Promise<string> {
+ const db = getDbClient().drizzle;
+ const clearedAt = await sessionClearedAt(sessionId);
+ const conds = [
+ eq(messages.sessionId, sessionId),
+ eq(messages.role, role),
+ isNull(messages.rewindAt),
+ ];
+ if (clearedAt != null) conds.push(gt(messages.createdAt, clearedAt));
+ const rows = await db
+ .select({ content: messages.content })
+ .from(messages)
+ .where(and(...conds))
+ .orderBy(desc(messages.createdAt), desc(messageRowid))
+ .limit(NON_EMPTY_SCAN_LIMIT);
+ for (const row of rows) {
+ const text = extractText(row.content, role);
+ if (text.trim()) return text;
+ }
+ return '';
+}
+
/**
* 最近 `limit` 条有效的 user / assistant 素材,时间正序。`limit` 现在按真实
* conversation turn 收口后的有效消息计数,不是原始 DB 行数;一个 turn 中的
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
index a4e3e574c2..b48cf07985 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
@@ -2967,6 +2967,74 @@ describe('session-agent-switch handoff injection', () => {
expect(session.send).toHaveBeenCalledWith(withUiLanguageUserMessage('新消息'), expect.anything());
});
+ it('目标状态说明在计划对账外层前置进 wire payload,落库内容保持用户原文', async () => {
+ const { deps, session } = createDeps({
+ peekPlanReconcileNote: vi.fn(async () => ({ note: 'RECONCILE-NOTE' })),
+ peekGoalInactiveNote: vi.fn(async () => 'GOAL-NOTE'),
+ });
+ const transaction = createMakerSendTransaction(deps);
+
+ await transaction.sendToAgentAccepted('session-1', { type: 'user', content: '新消息' }, undefined, {
+ persistUserMessage: { clientId: 'client-1', content: '{"text":"新消息","images":[],"files":[]}' },
+ });
+
+ expect(session.send).toHaveBeenCalledWith(
+ withUiLanguageUserMessage('GOAL-NOTE\n\nRECONCILE-NOTE\n\n新消息'),
+ expect.anything(),
+ );
+ const persisted = vi.mocked(deps.createDbMessage).mock.calls[0]?.[1];
+ expect(persisted?.content).toBe('{"text":"新消息","images":[],"files":[]}');
+ });
+
+ it('目标状态说明覆盖自动任务轮次,不进自动续跑、斜杠指令与 steer', async () => {
+ const peekGoalInactiveNote = vi.fn(async () => 'GOAL-NOTE');
+ const { deps, session } = createDeps({ peekGoalInactiveNote });
+ const transaction = createMakerSendTransaction(deps);
+
+ await transaction.sendToAgentAccepted('session-1', { type: 'user', content: '定时活' }, undefined, {
+ origin: { kind: 'scheduler', scheduleId: 's1', scheduleName: 'n' },
+ });
+ expect(session.send).toHaveBeenLastCalledWith(
+ withUiLanguageUserMessage('GOAL-NOTE\n\n定时活'),
+ expect.anything(),
+ );
+ expect(peekGoalInactiveNote).toHaveBeenCalledTimes(1);
+
+ await transaction.sendToAgentAccepted('session-1', { type: 'user', content: '继续' }, undefined, {
+ persistUserMessage: { clientId: 'c2', content: '继续', autoResume: true },
+ });
+ expect(session.send).toHaveBeenLastCalledWith(withUiLanguageUserMessage('继续'), expect.anything());
+
+ await transaction.sendToAgentAccepted('session-1', { type: 'user', content: '/compact' }, undefined, {
+ persistUserMessage: {
+ clientId: 'c3',
+ content: '{"text":"/compact","images":[],"files":[],"slashCommandRanges":[{"start":0,"end":8}]}',
+ },
+ });
+ expect(session.send).toHaveBeenLastCalledWith(withUiLanguageUserMessage('/compact'), expect.anything());
+
+ await transaction.sendToAgentAccepted('session-1', { type: 'user', content: '顺便看下' }, undefined, {
+ persistUserMessage: { clientId: 'c4', content: '{"text":"顺便看下"}', delivery: 'steer' },
+ });
+ expect(session.send).toHaveBeenLastCalledWith(withUiLanguageUserMessage('顺便看下'), expect.anything());
+
+ expect(peekGoalInactiveNote).toHaveBeenCalledTimes(1);
+ });
+
+ it('目标状态说明读取抛错时静默跳过,不挡发送', async () => {
+ const { deps, session } = createDeps({
+ peekGoalInactiveNote: vi.fn(async () => {
+ throw new Error('db unavailable');
+ }),
+ });
+ const transaction = createMakerSendTransaction(deps);
+
+ await transaction.sendToAgentAccepted('session-1', { type: 'user', content: '新消息' }, undefined, {
+ persistUserMessage: { clientId: 'client-1', content: '{"text":"新消息","images":[],"files":[]}' },
+ });
+ expect(session.send).toHaveBeenCalledWith(withUiLanguageUserMessage('新消息'), expect.anything());
+ });
+
it('仅在 sealed 保护已被 vendor accepted 后消费', async () => {
const consumeSealedPlanReconcileNote = vi.fn(async () => undefined);
const { deps } = createDeps({
diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
index 596742ee1c..41c49382bb 100644
--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
@@ -494,6 +494,11 @@ export interface MakerSendTransactionDeps {
sealedTurnId?: string;
} | null>;
consumeSealedPlanReconcileNote?(sessionId: string, turnId: string): void | Promise<void>;
+ /**
+ * 目标状态说明:会话没有运行中的目标、上一条回复却仍以 goal_status 裁决块收尾时,
+ * 返回一段只进 wire payload 的说明(见 goal-host/inactiveNote.ts);无需注入返回 null。
+ */
+ peekGoalInactiveNote?(sessionId: string): Promise<string | null>;
/**
* 本次调用是否来自手机控制端(缺省 = 否)。**纯体验分流,不是安全判据。**
*
@@ -1242,6 +1247,16 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
const withPlanReconcile = planReconcile
? prependNoteToWireUserMessage(withHandoff as HandoffWireMessage, planReconcile.note)
: withHandoff;
+ // 目标状态说明:用户的普通新轮次与自动任务轮次都要带上,模型才不会照着历史继续
+ // 吐裁决块、承诺自动续跑。原生命令必须留在消息开头,同手机说明的占位规则。
+ const goalInactiveNote =
+ (isOrdinaryUserTurn || soForReconcile.origin?.kind === 'scheduler') &&
+ shouldPrependMobileClientPromptNote(normalized, sess.agentKind)
+ ? ((await deps.peekGoalInactiveNote?.(sessionId).catch(() => null)) ?? null)
+ : null;
+ const withGoalInactiveNote = goalInactiveNote
+ ? prependNoteToWireUserMessage(withPlanReconcile as HandoffWireMessage, goalInactiveNote)
+ : withPlanReconcile;
const so = (outgoingSendOpts ?? {}) as MakerSendOptions;
// 手机客户端说明:同样只进 wire payload,落库/显示内容(persistUserMessage.content)
// 不含它。位置在交接段**之前** —— 交接正文自带「以下是用户的新消息」结束标记,
@@ -1255,8 +1270,8 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
? buildMobileClientPromptNote()
: null;
const withMobileNote = mobileClientNote
- ? prependNoteToWireUserMessage(withPlanReconcile as HandoffWireMessage, mobileClientNote)
- : withPlanReconcile;
+ ? prependNoteToWireUserMessage(withGoalInactiveNote as HandoffWireMessage, mobileClientNote)
+ : withGoalInactiveNote;
// 个人版制作任务说明:与手机说明同层、同占位规则(原生命令必须留在消息开头)。
const cindyMakeNote =
(await deps.isCindyMakeSession?.(sessionId).catch(() => false)) === true &&
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 9086c8c76c..26d736f622 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -893,6 +893,7 @@ import {
} from './sessionLastLiveUsage.js';
import { clearSealedCodexPlanState, readCodexPlanState } from '../localDb/codexPlanState.js';
import { buildCompletedPlanGuardNote, buildPlanReconcileNote } from './planReconcile.js';
+import { peekGoalInactiveNote } from '../goal-host/inactiveNote.js';
import { type MakerSessionCreateOpts, withCreateSessionStderr } from './sessionRequest.js';
import { persistAndHydrateSessionProvider } from './sessionProviderBootstrap.js';
import { registerMakerSessionSendHandler } from './sessionSendHandler.js';
@@ -14253,6 +14254,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
enqueueDurableWrite(`plan-seal-consume:${sessionId}:${turnId}`, () =>
clearSealedCodexPlanState(sessionId, turnId),
),
+ // 读排在持久化 FIFO 之后,与计划对账同口径,避免读到上一条回复尚未落库的旧快照。
+ peekGoalInactiveNote: (sessionId) =>
+ enqueueDurableWrite(`goal-inactive-read:${sessionId}`, () => peekGoalInactiveNote(sessionId)),
// 手机客户端说明的开关:被控端盖章的来源判据(本机 renderer / 桌面控制端 / 平台
// 未知一律 false)。必须在这里现取,不能提前求值缓存——同一个装配好的事务会服务
// 后续所有 send,来源是逐次调用的属性。