Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): preserve objectives across task follow-ups (#5175)
Chris Zhange0b3f71bf16a
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex 3b9e469392..242c1e0e46 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -5175,6 +5175,164 @@ describe('Bot Session task end-to-end runtime', () => {} finally { runtime.dispose(); }});+ it('keeps the full original objective and each ordered follow-up once across 70 executions', async () => {+ await seedPair();+ const runtime = createDelegationRuntime();+ const objective = 'Original objective\n' + 'O'.repeat(11_981);+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective });+ if (!task.ok) throw new Error('missing task');+ for (let index = 1; index <= 70; index += 1) {+ await runtime.settleChild(task.childSessionId, 'R'.repeat(8_000));+ const text = `Follow-up ${index}: ` + 'F'.repeat(3_960) + '\nKEEP THIS END';+ const result = await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text });+ expect(result).toMatchObject({ ok: true, childSessionId: task.childSessionId });+ const sent = runtime.dispatch.mock.calls.filter(([input]) => input.targetSessionId === task.childSessionId).at(-1)![0];+ expect(sent.persistedContent).toBe(text);+ expect(sent.message.split(objective)).toHaveLength(2);+ expect(sent.message.split(text)).toHaveLength(2);+ expect(sent.message).not.toContain('Previous objective:');+ expect(sent.message).not.toContain('R'.repeat(100));+ if (index > 1) expect(sent.message).not.toContain(`Follow-up ${index - 1}: `);+ expect(h.sqlite!.prepare('SELECT objective FROM bot_delegations WHERE id = ?').pluck().get(task.delegationId)).toBe(objective);+ }+ const inputs = h.sqlite!.prepare("SELECT content FROM messages WHERE session_id = ? AND role = 'user' ORDER BY rowid").all(task.childSessionId) as Array<{ content: string }>;+ expect(inputs).toHaveLength(71);+ expect(inputs[0].content).toBe(objective);+ for (let index = 1; index <= 70; index += 1) expect(inputs[index].content.startsWith(`Follow-up ${index}: `)).toBe(true);+ } finally { runtime.dispose(); }+ });++ it('keeps active queued supplements ordered and deduplicated without changing the objective', async () => {+ await seedPair();+ const runtime = createDelegationRuntime({ readSessionExecution: () => ({ instanceId: 'fixture-runtime', generation: 1 }) });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Stable objective.' });+ if (!task.ok) throw new Error('missing task');+ for (const index of [1, 1, 2, 2]) {+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId,+ { kind: 'message', text: `Queued requirement ${index}.`, idempotencyKey: `input-${index}` })).toMatchObject({ ok: true });+ }+ const inputs = h.sqlite!.prepare("SELECT content FROM messages WHERE session_id = ? AND role = 'user' ORDER BY rowid").all(task.childSessionId);+ expect(inputs).toEqual([{ content: 'Stable objective.' }, { content: 'Queued requirement 1.' }, { content: 'Queued requirement 2.' }]);+ expect(h.sqlite!.prepare('SELECT objective FROM bot_delegations WHERE id = ?').pluck().get(task.delegationId)).toBe('Stable objective.');+ expect(runtime.started.filter(turn => turn.sessionId === task.childSessionId)).toHaveLength(3);+ } finally { runtime.dispose(); }+ });++ it.each(['pause', 'cancel'] as const)('blocks old dispatch timers and late completion after a follow-up is %s before acceptance', async mode => {+ vi.useFakeTimers();+ await seedPair();+ let unavailable = false;+ const runtime = createDelegationRuntime({ taskControl: true, transientUnavailable: () => unavailable });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Stable objective.' });+ if (!task.ok) throw new Error('missing task');+ await runtime.settleChild(task.childSessionId, 'Initial work done.');+ unavailable = true;+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId,+ { kind: 'message', text: 'Deferred follow-up.' })).toMatchObject({ ok: true, queued: true });+ expect(await runtime.delegation.stopSessionTask('session-1', task.delegationId, mode)).toMatchObject({ ok: true });+ const started = runtime.started.filter(turn => turn.sessionId === task.childSessionId).length;+ unavailable = false;+ runtime.advance(60_000);+ await vi.advanceTimersByTimeAsync(60_000);+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done',+ expectedRunSequence: 1, resultText: 'Old duplicate result.' });+ await runtime.delegation.restore();+ expect(runtime.started.filter(turn => turn.sessionId === task.childSessionId)).toHaveLength(started);+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId)).toMatchObject({+ task: { status: mode === 'pause' ? 'queued' : 'cancelled' },+ });+ if (mode === 'pause') {+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId,+ { kind: 'message', text: 'Must not release pause.' })).toMatchObject({ ok: false, errorCode: 'TASK_PAUSED' });+ }+ } finally { runtime.dispose(); vi.useRealTimers(); }+ });++ it.each(['available', 'missing', 'rewound', 'cleared'] as const)('continues legacy nested objectives safely with %s initial input', async history => {+ await seedPair();+ const runtime = createDelegationRuntime();+ const objective = 'Keep the original\n formatting and Requester follow-up: literal text.';+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective });+ if (!task.ok) throw new Error('missing task');+ await runtime.settleChild(task.childSessionId, 'Old work done.');+ const legacy = ('Continue the same Session task with the requester’s follow-up.\n\nPrevious objective:\n').repeat(60) + 'truncated legacy text';+ h.sqlite!.prepare("UPDATE bot_delegations SET objective = ?, run_sequence = 5, permission_snapshot_json = json_remove(permission_snapshot_json, '$.taskInput') WHERE id = ?").run(legacy, task.delegationId);+ const firstId = `bot-delegation-start:${task.delegationId}`;+ if (history === 'missing') h.sqlite!.prepare('DELETE FROM messages WHERE session_id = ? AND client_id = ?').run(task.childSessionId, firstId);+ if (history === 'rewound') h.sqlite!.prepare('UPDATE messages SET rewind_at = 20000 WHERE session_id = ? AND client_id = ?').run(task.childSessionId, firstId);+ if (history === 'cleared') h.sqlite!.prepare('UPDATE sessions SET cleared_at = 20000 WHERE id = ?').run(task.childSessionId);+ const oldRows = h.sqlite!.prepare('SELECT id, content FROM messages WHERE session_id = ? ORDER BY rowid').all(task.childSessionId);+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'Only this new request.' })).toMatchObject({ ok: true });+ const sent = runtime.dispatch.mock.calls.filter(([input]) => input.targetSessionId === task.childSessionId).at(-1)![0];+ expect(sent.persistedContent).toBe('Only this new request.');+ expect(sent.message).not.toContain(legacy);+ if (history === 'available') expect(sent.message).toContain(objective);+ else {+ expect(sent.message).toContain('could not be recovered');+ expect(sent.message).not.toContain(objective);+ }+ expect(h.sqlite!.prepare('SELECT objective FROM bot_delegations WHERE id = ?').pluck().get(task.delegationId)).toBe(history === 'available' ? objective : legacy);+ expect(h.sqlite!.prepare('SELECT id, content FROM messages WHERE session_id = ? ORDER BY rowid').all(task.childSessionId).slice(0, oldRows.length)).toEqual(oldRows);+ } finally { runtime.dispose(); }+ });++ it.each(['queued', 'accepted'] as const)('restores the correct follow-up after restart at the %s boundary without replaying completed actions', async boundary => {+ await seedPair();+ let unavailable = false;+ const before = createDelegationRuntime({ transientUnavailable: () => unavailable });+ const objective = 'Stable original objective.';+ const text = 'Now verify the existing change; do not apply it again.';+ const task = await before.delegation.startSessionTask({ callerSessionId: 'session-1', objective });+ if (!task.ok) throw new Error('missing task');+ await before.settleChild(task.childSessionId, 'The tool already applied the change.');+ before.advance(1_000);+ unavailable = boundary === 'queued';+ expect(await before.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text })).toMatchObject({ ok: true });+ before.dispose();+ const after = createDelegationRuntime({ startTime: 20_000, taskControl: true,+ readSessionExecution: () => ({ instanceId: 'restored-runtime', generation: 1 }) });+ try {+ await after.delegation.restore();+ const sent = after.dispatch.mock.calls.filter(([input]) => input.targetSessionId === task.childSessionId);+ expect(sent).toHaveLength(1);+ expect(sent[0][0].message).toContain(objective);+ expect(sent[0][0].message).toContain(text);+ if (boundary === 'queued') expect(sent[0][0].persistedContent).toBe(text);+ else {+ expect(sent[0][0].message).toContain('Do not repeat completed tool actions');+ expect(sent[0][0].persistedContent).not.toBe(text);+ expect(sent[0][0].persistedContent).not.toBe(objective);+ }+ await after.delegation.restore();+ expect(after.started.filter(turn => turn.sessionId === task.childSessionId)).toHaveLength(1);+ expect(h.sqlite!.prepare("SELECT COUNT(*) FROM messages WHERE session_id = ? AND role = 'user' AND content = ?").pluck().get(task.childSessionId, text)).toBe(1);+ } finally { after.dispose(); }+ });++ it.each([false, true])('starts only an explicit new follow-up after confirmed cancellation (previously paused: %s)', async paused => {+ await seedPair();+ const runtime = createDelegationRuntime({ taskControl: true });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Original task.' });+ if (!task.ok) throw new Error('missing task');+ if (paused) await runtime.delegation.stopSessionTask('session-1', task.delegationId, 'pause');+ expect(await runtime.delegation.stopSessionTask('session-1', task.delegationId, 'cancel')).toMatchObject({ ok: true, control: { state: 'cancelling' } });+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'Too early.' })).toMatchObject({ ok: false, errorCode: 'STOP_UNCONFIRMED' });+ await runtime.settleChild(task.childSessionId, 'Cancelled.');+ const count = runtime.started.filter(turn => turn.sessionId === task.childSessionId).length;+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', resultText: 'Late callback.' });+ expect(runtime.started.filter(turn => turn.sessionId === task.childSessionId)).toHaveLength(count);+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'New explicitly requested work.' })).toMatchObject({ ok: true });+ expect(runtime.started.filter(turn => turn.sessionId === task.childSessionId)).toHaveLength(count + 1);+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId)).toMatchObject({ task: { status: 'running', control: { state: 'active' } } });+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'resume' })).toMatchObject({ ok: false, errorCode: 'NOT_PAUSED' });+ } finally { runtime.dispose(); }+ });+it('rechecks explicit archive inside the continuation transaction', async () => {await seedPair();let childId = '';diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.tsindex 3c3a8903e3..4919396d2e 100644--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts@@ -342,6 +342,33 @@ function parsePendingInteraction(}}+/** Per-run input is separate from the immutable objective; never store a rendered prompt here. */+interface SessionTaskInputSnapshot {+ runSequence: number;+ originalObjective: string | null;+ followUp: string | null;+}++function readSessionTaskInput(row: Pick<DelegationRow, 'permissionSnapshotJson' | 'runSequence'>): SessionTaskInputSnapshot | null {+ const input = parseRecord(row.permissionSnapshotJson).taskInput as Partial<SessionTaskInputSnapshot> | undefined;+ if (!input || input.runSequence !== row.runSequence+ || (input.originalObjective !== null && (typeof input.originalObjective !== 'string'+ || input.originalObjective.length > MAX_OBJECTIVE_CHARS))+ || (input.followUp !== null && (typeof input.followUp !== 'string'+ || input.followUp.length > MAX_INTERJECTION_CHARS))) return null;+ return input as SessionTaskInputSnapshot;+}++function taskObjectiveContext(row: Pick<DelegationRow, 'objective' | 'permissionSnapshotJson' | 'runSequence'>): string {+ const input = readSessionTaskInput(row);+ const objective = input ? input.originalObjective : row.objective;+ return [+ objective !== null ? `Objective:\n${objective}`+ : 'The original objective could not be recovered from the stored initial input. Consult the existing task history; do not infer it from legacy continuation wrappers.',+ input?.followUp ? `Requester follow-up:\n${input.followUp}` : '',+ ].filter(Boolean).join('\n\n');+}+/*** 上下文引用是纯文本指针(文件名、链接、一句背景),随目标事项进入子任务提示词。* 项目绑定退出 v1 后它不再承载路径授权语义:子任务的实际可读写面由它自己的@@ -1531,13 +1558,16 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {id: string;objective: string;contextRefsJson: string;+ permissionSnapshotJson: string;+ runSequence: number;}): string => ['You are running an independent Cindy Session task started from the user\'s Bot task.',`Task ID: ${row.id}`,- `Objective:\n${row.objective}`,+ taskObjectiveContext(row),parseStringArray(row.contextRefsJson).length? `Context references:\n${parseStringArray(row.contextRefsJson).join('\n')}`: '',+ readSessionTaskInput(row)?.followUp ? 'Continue from the existing task history. Apply the new follow-up without repeating completed actions.' : '','Work independently in this task\'s own workspace.','The parent Bot is acting for the user: permission prompts, questions and plan reviews you raise are answered there (or by the user directly). Ask through the normal tools when you genuinely need a decision; otherwise keep going.','Use descriptive filenames instead of generic names such as index, final, or output. If HTML is only a preview or SVG is only a source file, also export a directly viewable PNG or PDF. In the final response, list only user-ready files under a Deliverables heading; list source, preview, and intermediate files separately, and say how the result was verified.',@@ -1672,7 +1702,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {const dispatched = await deps.dispatch({targetSessionId: row.childSessionId,message: buildDelegationPrompt(row),- persistedContent: row.objective,+ persistedContent: readSessionTaskInput(row)?.followUp ?? row.objective,clientId,// 子任务首条消息标出发起委派的父任务,接收方据此渲染可跳转的来源标签。...(row.parentSessionId ? { dispatcherSessionId: row.parentSessionId } : {}),@@ -1919,13 +1949,13 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {const clientId = `bot-delegation-resume:${row.id}:${resumeEpoch}`;const message = ['The previous Session task turn was interrupted by a Cindy host restart.',- 'Inspect the existing task history, continue the original objective, and return the final result.',+ 'Inspect the existing task history and accepted follow-ups, continue the unfinished work, and return the final result. Do not repeat completed tool actions; verify their recorded outcomes before continuing.',`Task ID: ${row.id}`,- `Objective:\n${row.objective}`,+ taskObjectiveContext(row),].join('\n\n');const recovered = await dispatchTrackedInput(row, {message,- persistedContent: row.objective,+ persistedContent: 'Continue the interrupted Session task from its saved history without repeating completed actions.',clientId,});const dispatched = recovered.result;@@ -2124,7 +2154,9 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {},};const createdAt = plan.createdAt;- const permissionSnapshotJson = JSON.stringify(plan);+ const permissionSnapshotJson = JSON.stringify({ ...plan,+ taskInput: { runSequence: 1, originalObjective: input.objective, followUp: null } satisfies SessionTaskInputSnapshot,+ });const childRow = {...sessionCreateToRow(childSessionId,@@ -2803,12 +2835,31 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {completionTarget: { parentSessionId: callerSessionId },limits: { ...oldPlan.limits, deadlineAt },};- const continuationObjective = [- 'Continue the same Session task with the requester’s follow-up.',- `Previous objective:\n${row.objective.slice(0, 5_000)}`,- row.resultSummary ? `Previous result:\n${row.resultSummary.slice(0, 4_000)}` : '',- `Requester follow-up:\n${trimmed}`,- ].filter(Boolean).join('\n\n').slice(0, MAX_OBJECTIVE_CHARS);+ const previousInput = readSessionTaskInput(row);+ let originalObjective = previousInput ? previousInput.originalObjective : row.objective;+ if (!previousInput && row.runSequence > 1+ && row.objective.startsWith('Continue the same Session task with the requester’s follow-up.\n\nPrevious objective:\n')) {+ // Do not parse user text delimiters or rewrite old messages. Only an exact+ // initial input in this same Session can recover a legacy wrapped goal.+ const [initial] = await db.select({ content: messages.content }).from(messages)+ .innerJoin(sessions, eq(sessions.id, messages.sessionId))+ .where(and(eq(messages.sessionId, row.childSessionId),+ eq(messages.clientId, `bot-delegation-start:${row.id}`), eq(messages.role, 'user'),+ isNull(messages.rewindAt),+ sql`(${sessions.clearedAt} IS NULL OR ${messages.createdAt} > ${sessions.clearedAt})`))+ .limit(1);+ originalObjective = initial?.content && initial.content.length <= MAX_OBJECTIVE_CHARS ? initial.content : null;+ }+ const taskInput: SessionTaskInputSnapshot = { runSequence: row.runSequence + 1, originalObjective, followUp: trimmed };+ // Preserve unrecoverable legacy data, but never send its wrappers as a new goal.+ const continuationObjective = originalObjective ?? row.objective;+ const nextState: Record<string, unknown> = { ...nextPlan, taskInput, taskAcceptedInputIds: [] };+ // Explicit new work may reopen a confirmed terminal run. Its old pause and+ // cancel intents must not hold the new input; run-scoped receipts stay intact.+ delete nextState.taskCancelRequested;+ delete nextState.taskPause;+ delete nextState.taskResume;+ const nextSnapshot = JSON.stringify(nextState);const childSessionId = row.childSessionId;try {clearCompletionRetryTimer(row.id);@@ -2821,7 +2872,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {parentSessionId: callerSessionId,childSessionId,objective: continuationObjective,- permissionSnapshotJson: JSON.stringify({ ...nextPlan, taskAcceptedInputIds: [] }),+ permissionSnapshotJson: nextSnapshot,targetBotId: null,targetProfileVersion: null,session: {@@ -2874,7 +2925,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {parentSessionId: callerSessionId,childSessionId,objective: continuationObjective,- permissionSnapshotJson: JSON.stringify({ ...nextPlan, taskAcceptedInputIds: [] }),+ permissionSnapshotJson: nextSnapshot,createdAt: reopenedAt,};if (reopened.previousParentSessionId !== callerSessionId) {diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex a95d357a46..01313d2715 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -229,6 +229,11 @@ harness + provider + model + effort + fastMode排到下一轮,`mode=steer` 只使用运行中引擎的 same-turn 插话,不支持或旧轮已结束时明确失败,不偷偷降级排队。`mode=resume` 解除可恢复暂停,可附新指令;不重放原请求或已完成操作。它也负责回答等待的权限、提问或计划确认;暂停时先恢复再回答,不为补充一句话重复建任务。+ 已结束任务的续接保留稳定的原始目标,本轮补充独立持久化并按原队列顺序投递;不得把旧完整+ objective、历史结果和旧补充递归拼成新目标。上下文保留完整原目标与本轮补充,不用整体尾部截断+ 裁掉最新要求;旧补充和执行结果读取原任务历史。重启恢复沿用本轮输入与执行回执,只续做未完成部分。+ 旧版嵌套记录仅在下一次明确续接时,从同一任务未清除、未回退的初始输入恢复原目标;缺失时保留+ 旧数据并明确让执行者核对历史,不解析用户正文分隔符猜目标,不批量重写消息或数据库。- `stop_session_task`:`mode=cancel`(默认)终止任务;`mode=request-stop` 只请求当前轮优雅停止,不承诺冻结下一轮;`mode=pause` 持久暂停同一执行任务,保留未消费输入与剩余执行期限。`control.state=pausing` 或 `stop_status=requested/unconfirmed` 不表示引擎已停;活跃执行仍在