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。

feat(desktop): 计划清单改为钉在输入框上方的 Codex 式常驻胶囊 (#1217)

Kafeifei2afd88529b4c
diff --git a/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts b/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts
index 51a76fd693..06adabb426 100644
--- a/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts
+++ b/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts
@@ -371,202 +371,48 @@ describe('buildRenderItems — key stability', () => {
expect(taskItem.update?.summary).toBe('Found the relevant renderer path');
});
- // ── case 3: TodoWrite session 多次 update 后 key 仍指向首条 ─────────────
+ // ── case 3: plan 工具调用被整体吞掉 —— 流内不再渲染计划卡 ────────────────
+ // 计划的唯一呈现是 composer 上方的 PinnedPlanPanel(Codex IDE 扩展式钉住面板)。
+ // session 分组 / 输入解析语义的覆盖在 @cindy/maker-shared 的 messageRender.test.ts;
+ // 这里只锁桌面流内行为:不产 item、不切段、结尾不留无效 tail。
- it('TodoWrite session merging multiple updates keeps todo key pointing at the FIRST update', () => {
- const t1 = mkTool('tw1', 'TodoWrite', todoInput([{ content: 'a', status: 'pending' }]));
- const t2 = mkTool('tw2', 'TodoWrite', todoInput([{ content: 'a', status: 'in_progress' }]));
- const t3 = mkTool('tw3', 'TodoWrite', todoInput([{ content: 'a', status: 'in_progress' }]));
-
- const oneUpdate = buildRenderItems([t1]);
- const threeUpdates = buildRenderItems([t1, t2, t3]);
-
- const oneTodo = oneUpdate.items.find((it): it is Extract<RenderItem, { type: 'agent_plan' }> => it.type === 'agent_plan');
- const threeTodo = threeUpdates.items.find((it): it is Extract<RenderItem, { type: 'agent_plan' }> => it.type === 'agent_plan');
-
- expect(oneTodo?.key).toBe('plan-tw1');
- expect(threeTodo?.key).toBe('plan-tw1'); // 即便 update 加到 tw3, key 仍锚在 tw1
- });
-
- it('Codex update_plan renders as the same visible agent plan card', () => {
- const plan = mkTool('plan1', 'update_plan', { text: '1. Read code\n2. Patch renderer\n3. Run tests' });
- const { items } = buildRenderItems([mkUser('u1'), plan, mkAssistant('a1', 'On it')]);
- expect(items.map((it) => it.type)).toEqual(['message', 'agent_plan', 'message']);
- const planItem = items[1] as Extract<RenderItem, { type: 'agent_plan' }>;
- expect(planItem.key).toBe('plan-plan1');
- expect(planItem.todos.map((todo) => todo.content)).toEqual(['Read code', 'Patch renderer', 'Run tests']);
- expect(planItem.todos.map((todo) => todo.status)).toEqual(['in_progress', 'pending', 'pending']);
- });
-
- it('Codex structured update_plan preserves explicit step statuses', () => {
- const plan = mkTool('plan1', 'update_plan', {
- plan: [
- { step: 'Read code', status: 'completed' },
- { step: 'Patch renderer', status: 'in_progress' },
- { step: 'Run tests', status: 'pending' },
- ],
- });
- const { items } = buildRenderItems([plan]);
- const planItem = items[0] as Extract<RenderItem, { type: 'agent_plan' }>;
- expect(planItem.todos).toEqual([
- { content: 'Read code', status: 'completed' },
- { content: 'Patch renderer', status: 'in_progress' },
- { content: 'Run tests', status: 'pending' },
- ]);
- });
-
- it('Codex structured update_plan accepts app-server camelCase inProgress status', () => {
- const plan = mkTool('plan1', 'update_plan', {
- plan: [
- { step: 'Read code', status: 'completed' },
- { step: 'Patch renderer', status: 'inProgress' },
- ],
- });
- const { items } = buildRenderItems([plan]);
- const planItem = items[0] as Extract<RenderItem, { type: 'agent_plan' }>;
- expect(planItem.todos).toEqual([
- { content: 'Read code', status: 'completed' },
- { content: 'Patch renderer', status: 'in_progress' },
- ]);
- });
-
- it('Claude TaskCreate/TaskUpdate renders through the same visible agent plan card', () => {
- const taskCreate = mkTool('tc1', 'TaskCreate', {
- subject: 'Read code',
- description: 'Read relevant files',
- });
- const taskUpdate = mkTool('tu1', 'TaskUpdate', {
- task_id: 'task-1',
- status: 'in_progress',
- });
- const result = mkResult('tr1', 'tu-tc1', JSON.stringify({
- task: { task_id: 'task-1', status: 'pending', subject: 'Read code' },
- }));
-
- const { items } = buildRenderItems([mkUser('u1'), taskCreate, result, taskUpdate, mkAssistant('a1', 'Working')]);
- expect(items.map((it) => it.type)).toEqual(['message', 'agent_plan', 'message']);
- const planItem = items[1] as Extract<RenderItem, { type: 'agent_plan' }>;
- expect(planItem.key).toBe('plan-tc1');
- expect(planItem.todos).toEqual([{ content: 'Read code', status: 'in_progress' }]);
- });
-
- it('does not render id-only Claude TaskUpdate plan cards from partial history', () => {
- const taskUpdate = mkTool('tu15', 'TaskUpdate', {
- taskId: '15',
- status: 'completed',
- });
- const result = mkResult('tr15', 'tu-tu15', 'Updated task #15 status');
-
- const { items } = buildRenderItems([mkUser('u1'), taskUpdate, result, mkAssistant('a1', 'Done')]);
+ it('plan tool calls are swallowed without splitting the surrounding tool segment', () => {
+ const seq: ChatMessage[] = [
+ mkUser('u1'),
+ mkTool('t1', 'Bash'),
+ mkTool('tw1', 'TodoWrite', todoInput([{ content: 'a', status: 'pending' }])),
+ mkResult('r-tw1', 'tu-tw1', 'ok'),
+ mkTool('t2', 'Read'),
+ mkAssistant('a1', 'done'),
+ ];
+ const { items } = buildRenderItems(seq);
- expect(items.map((it) => it.type)).toEqual(['message', 'message']);
+ // TodoWrite 及其 tool_result 如同不存在:t1 / t2 仍聚在同一段里。
+ expect(items.map((it) => it.type)).toEqual(['message', 'tool_segment', 'message']);
+ const seg = items[1] as Extract<RenderItem, { type: 'tool_segment' }>;
+ expect(seg.key).toBe('seg-t1');
+ expect(seg.toolCalls.map((tc) => tc.clientId)).toEqual(['t1', 't2']);
});
- it('keeps Codex update_plan and Claude TaskCreate in separate plan cards', () => {
+ it('update_plan and Task* plan calls likewise produce no render items', () => {
const plan = mkTool('plan1', 'update_plan', {
- plan: [
- { step: 'Read code', status: 'in_progress' },
- ],
+ plan: [{ step: 'Read code', status: 'in_progress' }],
});
const taskCreate = mkTool('tc1', 'TaskCreate', { subject: 'Collect logs' });
- const { items } = buildRenderItems([plan, taskCreate]);
- const plans = items.filter((it): it is Extract<RenderItem, { type: 'agent_plan' }> => it.type === 'agent_plan');
+ const { items } = buildRenderItems([mkUser('u1'), plan, taskCreate, mkAssistant('a1', 'On it')]);
- expect(plans.length).toBe(2);
- expect(plans[0].key).toBe('plan-plan1');
- expect(plans[0].todos).toEqual([{ content: 'Read code', status: 'in_progress' }]);
- expect(plans[1].key).toBe('plan-tc1');
- expect(plans[1].todos).toEqual([{ content: 'Collect logs', status: 'pending' }]);
+ expect(items.map((it) => it.type)).toEqual(['message', 'message']);
});
- it('Claude text TaskCreate ids line up with later TaskUpdate and TaskList snapshots', () => {
- const create1 = mkTool('tc1', 'TaskCreate', { subject: '收集环境信息' });
- const create1Result = mkResult('tr1', 'tu-tc1', 'Task #1 created successfully: 收集环境信息');
- const create2 = mkTool('tc2', 'TaskCreate', { subject: '演示任务状态流转' });
- const create2Result = mkResult('tr2', 'tu-tc2', 'Task #2 created successfully: 演示任务状态流转');
- const done1 = mkTool('tu1', 'TaskUpdate', { taskId: '1', status: 'completed' });
- const done2 = mkTool('tu2', 'TaskUpdate', { taskId: '2', status: 'completed' });
- const list = mkTool('tl1', 'TaskList', {});
- const listResult = mkResult(
- 'tr-list',
- 'tu-tl1',
- '#1 [completed] 收集环境信息\n#2 [completed] 演示任务状态流转',
- );
-
+ it('a trailing plan call keeps the tail invariant on the previous valid item', () => {
const { items } = buildRenderItems([
- create1,
- create1Result,
- create2,
- create2Result,
- done1,
- done2,
- list,
- listResult,
- ]);
- const planItem = items[0] as Extract<RenderItem, { type: 'agent_plan' }>;
- expect(planItem.todos).toEqual([
- { content: '收集环境信息', status: 'completed' },
- { content: '演示任务状态流转', status: 'completed' },
- ]);
- });
-
- it('Claude TaskList snapshots replace the current task plan state', () => {
- const taskCreate = mkTool('tc1', 'TaskCreate', { subject: 'Old task' });
- const createResult = mkResult('tr1', 'tu-tc1', JSON.stringify({
- task: { task_id: 'old', status: 'pending', subject: 'Old task' },
- }));
- const taskList = mkTool('tl1', 'TaskList', {});
- const listResult = mkResult('tr2', 'tu-tl1', JSON.stringify({
- tasks: [
- { task_id: 'a', status: 'completed', subject: 'Inspect code' },
- { task_id: 'b', status: 'running', subject: 'Patch UI' },
- ],
- }));
-
- const { items } = buildRenderItems([taskCreate, createResult, taskList, listResult]);
- const plans = items.filter((it): it is Extract<RenderItem, { type: 'agent_plan' }> => it.type === 'agent_plan');
- expect(plans.length).toBe(1);
- expect(plans[0].key).toBe('plan-tc1');
- expect(plans[0].todos).toEqual([
- { content: 'Inspect code', status: 'completed' },
- { content: 'Patch UI', status: 'in_progress' },
- ]);
- });
-
- it('Claude TaskList status-only snapshots keep existing task titles', () => {
- const taskCreate = mkTool('tc1', 'TaskCreate', { subject: 'Inspect code' });
- const createResult = mkResult('tr1', 'tu-tc1', 'Task #a created successfully: Inspect code');
- const taskList = mkTool('tl1', 'TaskList', {});
- const listResult = mkResult('tr2', 'tu-tl1', JSON.stringify({
- tasks: [
- { id: 'a', status: 'completed' },
- ],
- }));
-
- const { items } = buildRenderItems([taskCreate, createResult, taskList, listResult]);
- const planItem = items[0] as Extract<RenderItem, { type: 'agent_plan' }>;
- expect(planItem.todos).toEqual([
- { content: 'Inspect code', status: 'completed' },
+ mkUser('u1'),
+ mkTool('tw1', 'TodoWrite', todoInput([{ content: 'a', status: 'pending' }])),
+ mkResult('r-tw1', 'tu-tw1', 'ok'),
]);
- });
-
- it('Claude TaskCreate starts a fresh task plan after the previous batch is completed without TaskList', () => {
- const oldCreate = mkTool('tc1', 'TaskCreate', { subject: 'Old task' });
- const oldDone = mkTool('tu1', 'TaskUpdate', {
- taskId: 'task-create:tu-tc1',
- status: 'completed',
- });
- const newCreate = mkTool('tc2', 'TaskCreate', { subject: 'New task' });
-
- const { items } = buildRenderItems([oldCreate, oldDone, newCreate]);
- const plans = items.filter((it): it is Extract<RenderItem, { type: 'agent_plan' }> => it.type === 'agent_plan');
- expect(plans.length).toBe(2);
- expect(plans[0].key).toBe('plan-tc1');
- expect(plans[0].todos).toEqual([{ content: 'Old task', status: 'completed' }]);
- expect(plans[1].key).toBe('plan-tc2');
- expect(plans[1].todos).toEqual([{ content: 'New task', status: 'pending' }]);
+ expect(items.map((it) => it.type)).toEqual(['message']);
});
// ── case 4: orphan tool_result 补到末尾不产生新 item / 不重 key ─────────
@@ -602,26 +448,6 @@ describe('buildRenderItems — key stability', () => {
expect(segs[0].key).not.toBe(segs[1].key);
});
- // ── case 5b: TodoWrite session 在 prev allDone 翻转后开新 session,key 取新首条 ──
- // 锁住 Pass 1 的 `prev && !prevAllDone` 判定 — 如果未来重构把这条改错(例如
- // 漏判 prevAllDone),所有 TodoWrite 会合并到第一个 session 一直更新下去,新
- // 任务的卡片永远不会出现。这条用例保证 allDone 翻转处新 session 必然开启,
- // 且新 key 来自新 session 首条而不是旧 session 首条。
-
- it('TodoWrite session opens fresh after prev allDone — new todo key points at NEW session first call', () => {
- const old1 = mkTool('tw1', 'TodoWrite', todoInput([{ content: 'a', status: 'pending' }]));
- const oldDone = mkTool('tw2', 'TodoWrite', todoInput([{ content: 'a', status: 'completed' }]));
- // prev 全 done → 下一条必开新 session
- const new1 = mkTool('tw3', 'TodoWrite', todoInput([{ content: 'b', status: 'pending' }]));
- const new2 = mkTool('tw4', 'TodoWrite', todoInput([{ content: 'b', status: 'in_progress' }]));
-
- const { items } = buildRenderItems([old1, oldDone, new1, new2]);
- const todos = items.filter((it): it is Extract<RenderItem, { type: 'agent_plan' }> => it.type === 'agent_plan');
- expect(todos.length).toBe(2);
- expect(todos[0].key).toBe('plan-tw1'); // 旧 session 首条
- expect(todos[1].key).toBe('plan-tw3'); // 新 session 首条 — 不是 tw4 也不是 tw1
- });
-
// ── case 6: tool_media key 显式锁规则 (`media-${segment 首 toolCall id}`) ────
// 防御:tool_media 跟其派生来源 segment 共享首 toolCall id,只是 prefix 不同 —
// 任何 key 派生规则的退化(例如改成 `media-${url}`)都会让 result 流式后到时
@@ -1148,18 +974,13 @@ describe('groupWorkRuns — work-group collapsing', () => {
]);
});
- it('keeps TodoWrite plan cards visible before the final answer', () => {
- const todo = mkTool('tw1', 'TodoWrite', todoInput([{ content: 'inspect', status: 'completed' }]));
- const items = build([mkUser('u1'), todo, mkAssistant('a-final', 'Done.')], false);
- expect(items.map((it) => it.type)).toEqual(['message', 'agent_plan', 'message']);
- expect(items[1].key).toBe('plan-tw1');
- });
-
- it('keeps TodoWrite plan cards visible after the final answer', () => {
+ it('plan calls stay absent through work-group folding (sole presentation is the pinned panel)', () => {
const todo = mkTool('tw1', 'TodoWrite', todoInput([{ content: 'inspect', status: 'completed' }]));
- const items = build([mkUser('u1'), mkAssistant('a-final', 'Done.'), todo], false);
- expect(items.map((it) => it.type)).toEqual(['message', 'message', 'agent_plan']);
- expect(items[2].key).toBe('plan-tw1');
+ // 正文前后各放一次:两个位置都不应折出 work_group,也不应出现任何计划 item。
+ const before = build([mkUser('u1'), todo, mkAssistant('a-final', 'Done.')], false);
+ const after = build([mkUser('u1'), mkAssistant('a-final', 'Done.'), todo], false);
+ expect(before.map((it) => it.type)).toEqual(['message', 'message']);
+ expect(after.map((it) => it.type)).toEqual(['message', 'message']);
});
it('computes durationMs from the previous boundary (user message) to the terminating text createdAt', () => {
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.ts
index 885db3d646..f4215df230 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.ts
@@ -68,6 +68,10 @@ function addMessage(sessionId: string): void {
makerChatStore.insertSystemCard(sessionId, 'status', { label: sessionId });
}
+async function flushPromises(rounds = 6): Promise<void> {
+ for (let i = 0; i < rounds; i += 1) await Promise.resolve();
+}
+
function dbMessage(
sessionId: string,
id: string,
@@ -87,6 +91,45 @@ function dbMessage(
};
}
+function dbToolUseMessage(
+ sessionId: string,
+ id: string,
+ toolName: string,
+ input: unknown,
+ createdAt: string,
+): Message {
+ const toolUseId = `tool-${id}`;
+ return {
+ id,
+ clientId: `client-${id}`,
+ sessionId,
+ role: 'tool_use',
+ content: { toolName, input, toolUseId },
+ toolUseId,
+ agentMeta: null,
+ createdAt,
+ } as unknown as Message;
+}
+
+function dbToolResultMessage(
+ sessionId: string,
+ id: string,
+ toolUseId: string,
+ content: string,
+ createdAt: string,
+): Message {
+ return {
+ id,
+ clientId: `client-${id}`,
+ sessionId,
+ role: 'tool_result',
+ content,
+ toolUseId,
+ agentMeta: null,
+ createdAt,
+ } as unknown as Message;
+}
+
function thinkingDbMessage(
sessionId: string,
id: string,
@@ -111,6 +154,10 @@ describe('makerChatStore active view tracking', () => {
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(BASE_TIME);
+ vi.mocked(messageService.list).mockReset();
+ vi.mocked(messageService.list).mockResolvedValue([]);
+ vi.mocked(messageService.around).mockReset();
+ vi.mocked(messageService.around).mockResolvedValue([]);
disposers = [];
sessionIds = [];
});
@@ -188,6 +235,221 @@ describe('makerChatStore active view tracking', () => {
expect(makerChatStore.getSnapshot(otherIds[0]).messages).toHaveLength(0);
});
+ it('initial history load backfills to the latest plan boundary', async () => {
+ const sessionId = sid('initial-plan-backfill');
+ const latestPage = Array.from({ length: 50 }, (_, i) =>
+ dbMessage(
+ sessionId,
+ `latest-${String(i).padStart(2, '0')}`,
+ `latest message ${i}`,
+ new Date(BASE_TIME.getTime() + (60 + i) * 1000).toISOString(),
+ ),
+ );
+ const planRow = dbToolUseMessage(
+ sessionId,
+ 'older-plan',
+ 'update_plan',
+ { plan: [{ step: 'Restore pinned plan', status: 'in_progress' }] },
+ new Date(BASE_TIME.getTime() + 30_000).toISOString(),
+ );
+ vi.mocked(messageService.list)
+ .mockResolvedValueOnce(latestPage)
+ .mockResolvedValueOnce([planRow]);
+
+ makerChatStore.ensureInitialMessages(sessionId);
+ await flushPromises();
+
+ const snapshot = makerChatStore.getSnapshot(sessionId);
+ expect(messageService.list).toHaveBeenNthCalledWith(1, sessionId, undefined);
+ expect(messageService.list).toHaveBeenNthCalledWith(2, sessionId, {
+ limit: 50,
+ before: 'latest-00',
+ });
+ expect(snapshot.messages.some((message) => message.toolName === 'update_plan')).toBe(true);
+ expect(snapshot.oldestMessageId).toBe('older-plan');
+ });
+
+ it('initial history load treats swallowed plan tool rows as non-anchor rows', async () => {
+ const sessionId = sid('initial-plan-non-anchor');
+ vi.mocked(messageService.list).mockClear();
+ const latestPage = Array.from({ length: 50 }, (_, i) =>
+ dbToolUseMessage(
+ sessionId,
+ `plan-${String(i).padStart(2, '0')}`,
+ 'update_plan',
+ { plan: [{ step: `Plan row ${i}`, status: 'completed' }] },
+ new Date(BASE_TIME.getTime() + (60 + i) * 1000).toISOString(),
+ ),
+ );
+ vi.mocked(messageService.list)
+ .mockResolvedValueOnce(latestPage)
+ .mockResolvedValueOnce([
+ dbMessage(sessionId, 'older-visible', 'older visible message', BASE_TIME.toISOString()),
+ ]);
+
+ makerChatStore.ensureInitialMessages(sessionId);
+ await flushPromises();
+
+ expect(messageService.list).toHaveBeenCalledTimes(2);
+ expect(messageService.list).toHaveBeenNthCalledWith(2, sessionId, {
+ limit: 50,
+ before: 'plan-00',
+ });
+ expect(makerChatStore.getSnapshot(sessionId).oldestMessageId).toBe('older-visible');
+ });
+
+ it('continues initial history backfill until the latest plan boundary is found', async () => {
+ const sessionId = sid('initial-plan-backfill-deep');
+ vi.mocked(messageService.list).mockClear();
+ const page = (prefix: string, startOffsetSeconds: number) =>
+ Array.from({ length: 50 }, (_, i) =>
+ dbMessage(
+ sessionId,
+ `${prefix}-${String(i).padStart(2, '0')}`,
+ `${prefix} message ${i}`,
+ new Date(BASE_TIME.getTime() + (startOffsetSeconds + i) * 1000).toISOString(),
+ ),
+ );
+ vi.mocked(messageService.list)
+ .mockResolvedValueOnce(page('latest', 300))
+ .mockResolvedValueOnce(page('older-1', 200))
+ .mockResolvedValueOnce(page('older-2', 100))
+ .mockResolvedValueOnce(page('older-3', 0))
+ .mockResolvedValueOnce([
+ dbToolUseMessage(
+ sessionId,
+ 'older-plan',
+ 'update_plan',
+ { plan: [{ step: 'Deep plan boundary', status: 'in_progress' }] },
+ new Date(BASE_TIME.getTime() - 100_000).toISOString(),
+ ),
+ ]);
+
+ makerChatStore.ensureInitialMessages(sessionId);
+ await flushPromises();
+
+ expect(messageService.list).toHaveBeenCalledTimes(5);
+ expect(messageService.list).toHaveBeenNthCalledWith(5, sessionId, {
+ limit: 50,
+ before: 'older-3-00',
+ });
+ expect(makerChatStore.getSnapshot(sessionId).oldestMessageId).toBe('older-plan');
+ });
+
+ it('caps initial plan discovery backfill for sessions that never used plans', async () => {
+ const sessionId = sid('initial-plan-backfill-no-plan');
+ vi.mocked(messageService.list).mockClear();
+ const page = (prefix: string, startOffsetSeconds: number) =>
+ Array.from({ length: 50 }, (_, i) =>
+ dbMessage(
+ sessionId,
+ `${prefix}-${String(i).padStart(2, '0')}`,
+ `${prefix} message ${i}`,
+ new Date(BASE_TIME.getTime() + (startOffsetSeconds + i) * 1000).toISOString(),
+ ),
+ );
+ vi.mocked(messageService.list)
+ .mockResolvedValueOnce(page('latest', 1000));
+ for (let i = 0; i < 12; i += 1) {
+ vi.mocked(messageService.list).mockResolvedValueOnce(page(`older-${i}`, 900 - i * 100));
+ }
+
+ makerChatStore.ensureInitialMessages(sessionId);
+ await flushPromises(20);
+
+ expect(messageService.list).toHaveBeenCalledTimes(11);
+ expect(makerChatStore.getSnapshot(sessionId).oldestMessageId).toBe('older-9-00');
+ });
+
+ it('continues initial plan backfill past older sources until a latest TaskUpdate can be resolved', async () => {
+ const sessionId = sid('initial-plan-task-boundary');
+ vi.mocked(messageService.list).mockClear();
+ const fillerPage = (prefix: string, startOffsetSeconds: number) =>
+ Array.from({ length: 49 }, (_, i) =>
+ dbMessage(
+ sessionId,
+ `${prefix}-${String(i).padStart(2, '0')}`,
+ `${prefix} message ${i}`,
+ new Date(BASE_TIME.getTime() + (startOffsetSeconds + i) * 1000).toISOString(),
+ ),
+ );
+ const latestTaskUpdate = dbToolUseMessage(
+ sessionId,
+ 'latest-task-update',
+ 'TaskUpdate',
+ { taskId: 'abc', status: 'completed' },
+ new Date(BASE_TIME.getTime() + 3_000_000).toISOString(),
+ );
+ const olderTodo = dbToolUseMessage(
+ sessionId,
+ 'older-todo',
+ 'TodoWrite',
+ { todos: [{ content: 'Older source should not stop backfill', status: 'in_progress' }] },
+ new Date(BASE_TIME.getTime() + 1_100_000).toISOString(),
+ );
+ const taskCreate = dbToolUseMessage(
+ sessionId,
+ 'task-create',
+ 'TaskCreate',
+ { subject: 'Collect logs' },
+ new Date(BASE_TIME.getTime() - 2_000).toISOString(),
+ );
+ const taskCreateResult = dbToolResultMessage(
+ sessionId,
+ 'task-create-result',
+ 'tool-task-create',
+ 'Task #abc created successfully: Collect logs',
+ new Date(BASE_TIME.getTime() - 1_000).toISOString(),
+ );
+
+ vi.mocked(messageService.list)
+ .mockResolvedValueOnce([...fillerPage('latest', 2000), latestTaskUpdate])
+ .mockResolvedValueOnce([...fillerPage('older-1', 1000), olderTodo])
+ .mockResolvedValueOnce([taskCreate, taskCreateResult]);
+
+ makerChatStore.ensureInitialMessages(sessionId);
+ await flushPromises(10);
+
+ expect(messageService.list).toHaveBeenCalledTimes(3);
+ expect(messageService.list).toHaveBeenNthCalledWith(3, sessionId, {
+ limit: 50,
+ before: 'older-1-00',
+ });
+ expect(makerChatStore.getSnapshot(sessionId).oldestMessageId).toBe('task-create');
+ });
+
+ it('caps initial plan resolution backfill when a latest TaskUpdate cannot be resolved', async () => {
+ const sessionId = sid('initial-plan-task-boundary-missing');
+ vi.mocked(messageService.list).mockClear();
+ const page = (prefix: string, startOffsetSeconds: number) =>
+ Array.from({ length: 50 }, (_, i) =>
+ dbMessage(
+ sessionId,
+ `${prefix}-${String(i).padStart(2, '0')}`,
+ `${prefix} message ${i}`,
+ new Date(BASE_TIME.getTime() + (startOffsetSeconds + i) * 1000).toISOString(),
+ ),
+ );
+ const latestPage = page('latest', 1000);
+ latestPage[49] = dbToolUseMessage(
+ sessionId,
+ 'latest-task-update',
+ 'TaskUpdate',
+ { taskId: 'missing', status: 'completed' },
+ new Date(BASE_TIME.getTime() + 2_000_000).toISOString(),
+ );
+ vi.mocked(messageService.list).mockResolvedValueOnce(latestPage);
+ for (let i = 0; i < 12; i += 1) {
+ vi.mocked(messageService.list).mockResolvedValueOnce(page(`older-${i}`, 900 - i * 100));
+ }
+
+ makerChatStore.ensureInitialMessages(sessionId);
+ await flushPromises(20);
+
+ expect(messageService.list).toHaveBeenCalledTimes(11);
+ expect(makerChatStore.getSnapshot(sessionId).oldestMessageId).toBe('older-9-00');
+ });
+
it('enterView disposer leaves the session', () => {
const sessionId = sid('disposer');
const dispose = enter(sessionId);
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreJumpBackfill.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreJumpBackfill.test.ts
index e44e3b54a1..cbdac01fb6 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreJumpBackfill.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreJumpBackfill.test.ts
@@ -119,6 +119,22 @@ function serverMessage(over: Partial<Message>): Message {
} as Message;
}
+function planToolMessage(over: Partial<Message>): Message {
+ const toolUseId = over.toolUseId ?? over.id ?? over.clientId ?? 'plan-tool';
+ return serverMessage({
+ role: 'tool_use',
+ content: {
+ toolName: 'update_plan',
+ toolUseId,
+ input: {
+ plan: [{ content: 'Preserve current plan after trim', status: 'in_progress' }],
+ },
+ },
+ toolUseId,
+ ...over,
+ } as Partial<Message>);
+}
+
/** 让挂起的 store 异步链推进若干轮微任务(store 内部多层 await)。 */
async function flushMicrotasks(rounds = 8): Promise<void> {
for (let i = 0; i < rounds; i++) await Promise.resolve();
@@ -138,6 +154,10 @@ function fullPageNewestFirst(): Message[] {
describe('跳转补齐 — 窗口连续,不留历史空洞', () => {
beforeEach(() => {
+ vi.mocked(listMessagesFor).mockReset();
+ vi.mocked(listMessagesFor).mockResolvedValue([]);
+ vi.mocked(aroundMessagesByClientIdFor).mockReset();
+ vi.mocked(aroundMessagesByClientIdFor).mockResolvedValue([]);
(globalThis as { window?: unknown }).window = { electronAPI: makeElectronApiStub() };
makerChatStore.initGlobalListeners();
});
@@ -1320,6 +1340,39 @@ describe('跳转补齐 — 窗口连续,不留历史空洞', () => {
expect(makerChatStore.getSnapshot(SID).historyWindowHasIsland).toBe(true);
});
+ it('Y2. 超长裁剪丢掉当前计划边界时,允许重入重新首拉补回计划', async () => {
+ const oldPlan = planToolMessage({
+ id: 'trimmed-plan',
+ clientId: 'trimmed-plan',
+ createdAt: '2026-07-24T00:00:00.000Z',
+ });
+ vi.mocked(aroundMessagesByClientIdFor).mockResolvedValueOnce([oldPlan]);
+ let page = 0;
+ vi.mocked(listMessagesFor).mockImplementation(async () => {
+ const base = page++;
+ return Array.from({ length: 100 }, (_, i) =>
+ serverMessage({
+ id: `post-plan-${base}-${i}`,
+ clientId: `post-plan-${base}-${i}`,
+ createdAt: new Date(
+ Date.UTC(2026, 6, 25, 12, 0, 0) - (base * 100 + i) * 60_000,
+ ).toISOString(),
+ }),
+ );
+ });
+ await makerChatStore.loadAroundMessageClientId(SID, 'trimmed-plan', { radius: 60 });
+ expect(makerChatStore.getSnapshot(SID).messages.length).toBeGreaterThan(300);
+ expect(makerChatStore.getSnapshot(SID).historyLoaded).toBe(true);
+
+ const leave = makerChatStore.enterView(SID);
+ leave();
+
+ const snapshot = makerChatStore.getSnapshot(SID);
+ expect(snapshot.messages).toHaveLength(200);
+ expect(snapshot.messages.some((message) => message.clientId === 'trimmed-plan')).toBe(false);
+ expect(snapshot.historyLoaded).toBe(false);
+ });
+
it('X. /clear 清空窗口时一并清掉孤岛标记,不把会话永久钉在"不连续"', async () => {
// review #676(codex P1):covered 刻意保留孤岛标记(到达本次目标不证明更早的洞都补
// 上了),所以标记只能由「窗口整体重建」清零。/clear 清了 messages / 游标 / 锁却漏了
diff --git a/apps/desktop/src/renderer/__tests__/messageStreamRenderWindowIntegration.test.ts b/apps/desktop/src/renderer/__tests__/messageStreamRenderWindowIntegration.test.ts
index 82ecc1e2f1..74bc82a9c9 100644
--- a/apps/desktop/src/renderer/__tests__/messageStreamRenderWindowIntegration.test.ts
+++ b/apps/desktop/src/renderer/__tests__/messageStreamRenderWindowIntegration.test.ts
@@ -96,14 +96,6 @@ const mkAskUser = (id: string): ChatMessage => ({
content: '',
});
-const todoInput = (items: Array<{ content: string; status: 'pending' | 'in_progress' | 'completed' }>) => ({
- todos: items.map((t, idx) => ({
- id: `todo-${idx}`,
- content: t.content,
- status: t.status,
- })),
-});
-
/**
* 构造一个"现实风格"的消息序列:user → (thinking → assistant text → tool_use × k → tool_result × k) × turn
* 用于 perf 微基准,模拟真实 session 形态。
@@ -281,12 +273,13 @@ describe('Scenario 2 — U1 short session full two-stage trace (build → decide
// ── Scenario 2b: render-window 不从 Task/Todo 卡中间开窗 ───────────────────
describe('Scenario 2b — render-window start snaps to user turn boundary', () => {
- it('includes the preceding user message when the default 80-item window would start at a plan card', () => {
+ it('includes the preceding user message when the default 80-item window would start at a task card', () => {
const messages: ChatMessage[] = [
mkUser('u-before', 'before'),
mkAssistant('a-before', 'before answer'),
mkUser('u-task', 'fix the task card'),
- mkTool('tw-task', 'TodoWrite', todoInput([{ content: 'fix the task card', status: 'completed' }])),
+ // 运行中的子 Agent 卡(无 result)—— 非 boundary item,窗口不该从它开窗。
+ mkTool('task-1', 'Task', { description: 'fix the task card' }),
mkAssistant('a-task', 'done'),
];
for (let i = 0; i < 39; i++) {
@@ -297,7 +290,7 @@ describe('Scenario 2b — render-window start snaps to user turn boundary', () =
const allRenderItems = groupWorkRuns(buildRenderItems(messages).items, false);
const rawStartIdx = Math.max(0, allRenderItems.length - RENDER_WINDOW_INITIAL_ITEMS);
- expect(allRenderItems[rawStartIdx]?.type).toBe('agent_plan');
+ expect(allRenderItems[rawStartIdx]?.type).toBe('agent_task');
const snappedStartIdx = snapRenderWindowStartIdx(allRenderItems, rawStartIdx);
const firstVisible = allRenderItems[snappedStartIdx];
@@ -307,7 +300,7 @@ describe('Scenario 2b — render-window start snaps to user turn boundary', () =
expect(firstVisible.message.role).toBe('user');
expect(firstVisible.message.clientId).toBe('u-task');
}
- expect(allRenderItems[snappedStartIdx + 1]?.type).toBe('agent_plan');
+ expect(allRenderItems[snappedStartIdx + 1]?.type).toBe('agent_task');
});
});
diff --git a/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts b/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts
index 497f6bec01..5bfdc51b6c 100644
--- a/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts
@@ -61,6 +61,26 @@ function dbMessage(sessionId: string, id: string, content: string, ts: string):
};
}
+function dbPlanToolMessage(sessionId: string, id: string, ts: string): Message {
+ const toolUseId = `tool-${id}`;
+ return {
+ id,
+ clientId: `client-${id}`,
+ sessionId,
+ role: 'tool_use',
+ content: {
+ toolName: 'update_plan',
+ toolUseId,
+ input: {
+ plan: [{ content: 'Cached remote plan', status: 'in_progress' }],
+ },
+ },
+ toolUseId,
+ agentMeta: null,
+ createdAt: ts,
+ } as unknown as Message;
+}
+
/** 被控端经隧道返回的权威列表;可换成挂起的 promise 模拟慢隧道 / 离线。 */
let remoteList: Message[] = [];
let remoteListPromise: Promise<Message[]> | null = null;
@@ -221,6 +241,26 @@ describe('冷缓存 hydrate', () => {
expect(snapshot.hasMoreMessages).toBe(false);
});
+ it('缓存页只有计划工具行时仍种入,供 PinnedPlanPanel 派生计划', async () => {
+ const s = sid();
+ cachedMessages.set(`${DEVICE_ID}::${s}`, [
+ dbPlanToolMessage(s, 'plan', '2026-01-01T00:00:00.000Z') as unknown as Record<
+ string,
+ unknown
+ >,
+ ]);
+ registerRemote(s);
+ remoteListPromise = new Promise<Message[]>(() => {});
+
+ makerChatStore.ensureInitialMessages(s);
+ await flush();
+
+ const snapshot = makerChatStore.getSnapshot(s);
+ expect(snapshot.messages.map((m) => m.clientId)).toEqual(['client-plan']);
+ expect(snapshot.messages[0].cacheHydrated).toBe(true);
+ expect(snapshot.historyLoaded).toBe(false);
+ });
+
it('fresh 落地后整批剔除缓存行:权威页里没有的缓存消息不残留', async () => {
const s = sid();
cachedMessages.set(`${DEVICE_ID}::${s}`, [
diff --git a/apps/desktop/src/renderer/__tests__/workGroupHistoryGap.test.ts b/apps/desktop/src/renderer/__tests__/workGroupHistoryGap.test.ts
index 3b6695d0f6..ce1ac73ddd 100644
--- a/apps/desktop/src/renderer/__tests__/workGroupHistoryGap.test.ts
+++ b/apps/desktop/src/renderer/__tests__/workGroupHistoryGap.test.ts
@@ -420,17 +420,18 @@ describe('历史窗口空洞 — 正常 turn 不受影响', () => {
// ── Scenario C:被卡片取代的调用也必须报出时间(review #676 copilot) ──────────
//
-// ghost_card(意识供卡)与 agent_plan(TodoWrite / update_plan)是各自那次调用在流里的
-// **唯一**呈现——工具行被卡片取代、不再单独渲染。它们原先在 renderItemStartMs /
-// renderItemEndMs 里没有分支,一律报 null。
+// ghost_card(意识供卡)是那次调用在流里的**唯一**呈现——工具行被卡片取代、不再
+// 单独渲染。它原先在 renderItemStartMs / renderItemEndMs 里没有分支,一律报 null。
+// (agent_plan 卡曾同属此类;计划卡现已整体移出流内,唯一呈现改为 composer 上方的
+// PinnedPlanPanel,不再参与流内时间判定。)
//
// 实测过后果的具体形状(两侧都跑过,只留能真正区分的断言):
-// - 工作组切分本身**不受影响**:两类卡都会被 groupAnsweredTurnItems 提到组外,而空洞后
+// - 工作组切分本身**不受影响**:卡会被 groupAnsweredTurnItems 提到组外,而空洞后
// 只要还有任何带时间戳的 item,切分照旧发生 —— 分组结果与时长两侧完全一致。
// - 真正会错的是另外两处:
// C1 长供卡调用(出图 / 出视频跑很久)的结束时间没算进 tool_result → 紧随其后的正文被
// 误判成空洞,进度文字被当成最终答复留在工作组外(与 A4 同一退化)。
-// C2 / C3 insertForkOriginItem 按"第一个时间 >= 分叉时刻的 item"插标记 → 报 null 的卡
+// C2 insertForkOriginItem 按"第一个时间 >= 分叉时刻的 item"插标记 → 报 null 的卡
// 被跳过,于是**分叉之后**生成的卡片渲染在「从这里分叉」标记之上,视觉上被算进父会话。
const GHOST_TOOL = 'mcp__cindy__ghost_call';
@@ -469,16 +470,6 @@ const ghostSnapshot = (cardIds: string[]): GhostCardSnapshot => ({
liveCards: [],
});
-const mkTodoWrite = (id: string, createdAt: string, content: string): ChatMessage => ({
- clientId: id,
- role: 'tool_use',
- content: '',
- toolUseId: `tu-${id}`,
- toolName: 'TodoWrite',
- toolInput: { todos: [{ content, status: 'pending', activeForm: content }] },
- createdAt,
-});
-
const forkOrigin = {
parentSessionId: 'parent-sess',
forkedAtMessageId: 'msg-fork',
@@ -532,24 +523,6 @@ describe('历史窗口空洞 — 被卡片取代的调用', () => {
// 卡片报不出时间时会被 findIndex 跳过,标记插到它**后面** → 卡片被算进父会话。
expect(markerIdx).toBeLessThan(cardIdx);
});
-
- it('C3. 分叉之后的 agent_plan 渲染在分叉标记之下', () => {
- const messages: ChatMessage[] = [
- mkUser('u1', '2026-07-25T10:00:00.000Z', '继续'),
- mkTodoWrite('p1', '2026-07-25T10:06:00.000Z', '先跑门禁'),
- mkResult('pr1', 'tu-p1', '2026-07-25T10:06:01.000Z'),
- mkAssistant('a1', '2026-07-25T10:07:00.000Z', '计划已更新。'),
- ];
-
- const { items } = buildRenderItems(messages);
- const withMarker = insertForkOriginItem(items, forkOrigin);
-
- const markerIdx = withMarker.findIndex((it) => it.type === 'fork_origin');
- const planIdx = withMarker.findIndex((it) => it.type === 'agent_plan');
- expect(markerIdx).toBeGreaterThanOrEqual(0);
- expect(planIdx).toBeGreaterThanOrEqual(0);
- expect(markerIdx).toBeLessThan(planIdx);
- });
});
// ── Scenario D:被空洞收尾的工作组时长(review #676 codex P1) ─────────────────
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index 0842d921c9..e8644db823 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -32,7 +32,6 @@ import { GitFork } from 'lucide-react';
import { SelectionQuoteButton } from './SelectionQuoteButton';
import { useTranslation } from 'react-i18next';
import {
- findMessageTodoInsertions,
isAgentPlanToolName,
isDeliveryProseText,
} from '@cindy/maker-shared/message-render';
@@ -143,7 +142,6 @@ import { ErrorMessageCard } from './ErrorMessageCard';
import { APP_EXIT_INTERRUPTED_REASON } from '../../../shared/interruptedTurn';
import { PlanReviewBubble } from './PlanReviewBubble';
import { ToolCallCard, getToolSummary } from './ToolCallCard';
-import { TodoListCard, type TodoItem } from './TodoListCard';
import { SystemCard } from './SystemCard';
import { NewMessageIndicator } from './NewMessageIndicator';
import { ThinkingCard } from './ThinkingCard';
@@ -260,15 +258,6 @@ interface MessageStreamProps {
// 引用这两个成员(WorkChildItem),让「children 只含这两类」由类型系统保证,
// 渲染处无需 as 强转;其余成员保持内联。
type MessageRenderItem = { type: 'message'; key: string; message: ChatMessage };
-type AgentPlanRenderItem = {
- type: 'agent_plan';
- key: string;
- todos: TodoItem[];
- /** 派生自哪条 TodoWrite / update_plan 调用(该调用的行被卡片取代,不再单独渲染)。
- * 空洞判定与工作组锚定需要它:卡片是这次调用在流里的**唯一**呈现,没有时间戳的
- * item 会被间隔判定跳过,于是"空洞后的第一个动作恰好是计划卡"时切不开(#676 review)。 */
- createdAt?: string;
-};
type ToolSegmentRenderItem = {
/** A run of consecutive tool_use messages between text segments,
* rendered as a single AgentActionsBlock. v2 — no isStreaming
@@ -331,7 +320,6 @@ interface WorkGroupRenderItem {
export type RenderItem =
| MessageRenderItem
- | AgentPlanRenderItem
| ToolSegmentRenderItem
| AgentTaskRenderItem
| ForkOriginRenderItem
@@ -383,7 +371,7 @@ function isRenderWindowBoundaryItem(item: RenderItem | undefined): boolean {
}
// export 仅供 render-window 集成单测使用。窗口默认/扩窗时如果刚好切在
-// agent_plan / work_group / assistant 中间,顶部会出现无上下文的 Task/Todo 卡。
+// agent_task / work_group / assistant 中间,顶部会出现无上下文的卡片。
// 向前吸收同一 user turn 的开头,但限制 lookback 防止单个超长 turn 破坏首屏预算。
export function snapRenderWindowStartIdx(
items: readonly RenderItem[],
@@ -634,17 +622,13 @@ export function collectTurnFinalAssistantClientIds(messages: readonly ChatMessag
* their own per-block expand state via useExpandedBlockMemory (default
* collapsed; user click → persisted).
*
- * Agent plan handling (two-pass):
- * Pass 1 — Pre-scan all messages to group TodoWrite / update_plan /
- * TaskCreate/TaskUpdate/TaskList calls into logical "sessions".
- * A session is one logical task list. A new session starts after the
- * previous one's items are all completed. Within a session every
- * plan update refreshes the same card; only the LAST update's position
- * and state are kept (the card "moves down" as updates arrive).
- * Pass 2 — Linear build. Plan tool_use messages are skipped, but at the
- * position of each session's last update an `agent_plan` RenderItem is injected.
- * Pending tool_segment is flushed before the plan card so order is
- * preserved.
+ * Agent plan handling:
+ * Plan tool calls (TodoWrite / update_plan / TaskCreate…) are swallowed
+ * entirely — same treatment as F7's AskUserQuestion / ExitPlanMode: the
+ * call and its tool_results produce no render item and do NOT cut the
+ * surrounding tool_segment. 计划的唯一呈现是 composer 上方的常驻面板
+ * (PinnedPlanPanel,Codex IDE 扩展式钉住交互),它直接从 messages 派生
+ * 最新 plan session 快照,与本函数无关。
*/
/**
* 锚点丢失恢复:DB 加载更老历史 prepend 时,若新拉回的末尾是 tool_use 且当前
@@ -657,7 +641,7 @@ export function collectTurnFinalAssistantClientIds(messages: readonly ChatMessag
* 扫描 allRenderItems 找哪个 item **现在覆盖**这个 clientId:
* - message: msg.clientId 严格匹配
* - tool_segment: toolCalls.*.clientId 任一匹配(段合并后老 toolCall 仍在新段内)
- * - tool_media / agent_plan: 用 key 后缀匹配(它们的 key 派生自 stable message clientId)
+ * - tool_media / ghost_card: 用 key 后缀匹配(它们的 key 派生自 stable message clientId)
*
* 找到即返回该 index,visible slice 从这里继续;找不到才退回默认窗口。
*
@@ -687,7 +671,7 @@ function recoverLostAnchorIdx(items: RenderItem[], lostKey: string): number {
if (it.key === lostKey || it.key.endsWith(`-${lostCid}`)) return i;
if (renderItemContainsClientId(it, lostCid)) return i;
} else if (it.type !== 'fork_origin') {
- // tool_media / agent_plan:其 key 派生自 stable message clientId,精确后缀匹配
+ // tool_media / ghost_card:其 key 派生自 stable message clientId,精确后缀匹配
if (it.key === lostKey || it.key.endsWith(`-${lostCid}`)) return i;
}
}
@@ -868,12 +852,6 @@ export function buildRenderItems(
}
}
- // ── Pass 1: pre-scan agent plan sessions ──
- // Shared groups TodoWrite / update_plan / Task* into logical sessions.
- // Desktop keeps the existing `agent_plan` render item and `plan-*` keys,
- // while mobile can consume the same shared logic through buildMessageRenderItems.
- const planInsertAt = findMessageTodoInsertions(messages, { keyPrefix: 'plan' });
-
const isOrcaCommunicationTool = (toolName: string): boolean => {
const normalized = toolName.replace(/^mcp__/, 'mcp:').replace(/__/g, ':');
return (
@@ -1019,19 +997,10 @@ export function buildRenderItems(
continue;
}
- // Todo/plan updates — break the segment so the plan card doesn't get buried
- // inside the tool block.
+ // Plan tools (TodoWrite / update_plan / Task*) — swallowed like F7:
+ // 计划的唯一呈现是 composer 上方的 PinnedPlanPanel(钉住式常驻面板),
+ // 流内不再插卡;也不切段,周围工具保持聚组,如同调用不存在。
if (isAgentPlanToolName(toolName)) {
- const sessionTodos = planInsertAt.get(i);
- if (sessionTodos) {
- flushSegment();
- items.push({
- type: 'agent_plan',
- key: sessionTodos.key,
- todos: sessionTodos.todos,
- createdAt: msg.createdAt,
- });
- }
let j = i + 1;
while (j < messages.length && messages[j].role === 'tool_result') j++;
i = j;
@@ -1515,17 +1484,13 @@ function renderItemStartMs(item: RenderItem): number | null {
const ms = Date.parse(item.toolCall?.createdAt ?? item.update?.createdAt ?? '');
return Number.isFinite(ms) ? ms : null;
}
- // ghost_card / agent_plan 是各自那次调用在流里的**唯一**呈现(工具行被卡片取代),
- // 所以它们必须报出调用时间。漏掉的后果是间隔判定把它们当"无时间戳"跳过:空洞后的
- // 第一个动作恰好是卡片时切不开,卡片还会被归到空洞前那一组里(#676 review)。
+ // ghost_card 是那次调用在流里的**唯一**呈现(工具行被卡片取代),所以它必须
+ // 报出调用时间。漏掉的后果是间隔判定把它当"无时间戳"跳过:空洞后的第一个
+ // 动作恰好是卡片时切不开,卡片还会被归到空洞前那一组里(#676 review)。
if (item.type === 'ghost_card') {
const ms = Date.parse(item.toolCall.createdAt ?? '');
return Number.isFinite(ms) ? ms : null;
}
- if (item.type === 'agent_plan') {
- const ms = Date.parse(item.createdAt ?? '');
- return Number.isFinite(ms) ? ms : null;
- }
if (item.type === 'work_group') {
for (const child of item.children) {
const childMs = renderItemStartMs(child);
@@ -1850,7 +1815,7 @@ function groupActiveWorkRuns(items: RenderItem[], turnStartTs: number | null = n
*
* 没有最终正文(被中断 / 停在工具)或最终正文后仍有已完成动作时返回
* handled:false,交回 groupLegacyWorkRuns 按连续动作折叠。tool_media /
- * agent_plan /运行中子 Agent 等非可归档项保持可见,并作为顺序锚点切开工作组。
+ * 运行中子 Agent 等非可归档项保持可见,并作为顺序锚点切开工作组。
*/
function groupAnsweredTurnItems(
turnItems: RenderItem[],
@@ -2332,7 +2297,7 @@ export function MessageStream({
* 末尾、**没有上界**。这是 #676 review 反复指向的根因:补齐 / 跳转让 messages 变长后,
* 深跳会一次挂载"锚点 → 末尾"的全部 item。因为它无界,store 侧只能靠"跳转补齐预算"
* 间接限制挂载量,而那个预算必须逐一追平 buildRenderItems 的每种 item 展开规则
- * (agent_task 卡、空洞切段、ghost_card、agent_plan、tool_media…),review 中已发现 5 种
+ * (agent_task 卡、空洞切段、ghost_card、tool_media…),review 中已发现 5 种
* 被低估的路径 —— 是一条追不完的线。
*
* 决定:把锚定窗口做成双向有界 + 配套向下扩窗,作为紧随其后的独立改动(不塞进本 PR ——
@@ -3479,16 +3444,6 @@ export function MessageStream({
return <ForkOriginMarker key={item.key} onClick={onOpenForkOrigin} />;
}
- if (item.type === 'agent_plan') {
- return (
- <TodoListCard
- key={item.key}
- todos={item.todos}
- animated={isSessionStreaming}
- />
- );
- }
-
if (item.type === 'tool_segment') {
return (
<AgentActionsBlock
diff --git a/apps/desktop/src/renderer/components/chat/TodoListCard.tsx b/apps/desktop/src/renderer/components/chat/TodoListCard.tsx
index d374642355..90810cc57f 100644
--- a/apps/desktop/src/renderer/components/chat/TodoListCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/TodoListCard.tsx
@@ -1,33 +1,24 @@
/**
* TodoListCard
* ---------------------------------------------------------------------------
- * TodoChecklistCard · Showcase visual contract
+ * 计划清单常驻胶囊(composer 上方,PinnedPlanPanel 专用)。
*
- * Card with border, collapsible (default expanded).
- * Uses the same color tokens as ToolCallCard for consistency:
- * --msg-tool-card-text: primary (icons, completed/in_progress text)
- * --msg-tool-card-chevron: secondary (chevron, pending icon/text, separator)
+ * 交互与形态 1:1 对齐 Codex IDE 扩展:
+ * - 收起态:居中小胶囊 `[进度 icon] Step N / M`,不占整行宽度;
+ * - 鼠标悬停(或点击/Enter)时,完整清单以浮层形式向上展开;移开即收起。
+ * 浮层绝对定位(bottom-full),不改变 composer overlay 的实测高度,
+ * 消息流不会因 hover 抖动。
+ * - 浮层行:completed 灰(check 圆圈),in_progress 高亮(虚线圆圈 + 旋转),
+ * pending 正常前景色(空心圆圈)。
*
- * Collapsed: top rounded-12 / bottom square
- * chevron + list-todo 16px + "X/Y" (mono bold) + "·" + msg + bar 2px
- * Expanded: all corners rounded-12
- * chevron + same header + divider + todo list
- *
- * Item states:
- * completed: circle-check + font-semibold (--msg-tool-card-text)
- * in_progress: circle-dashed + font-semibold (--msg-tool-card-text) + pulse
- * pending: circle + font-normal (--msg-tool-card-chevron) opacity-60
+ * 颜色沿用 ToolCallCard 同套 token(设计系统零阴影,浮层用 1px 边框):
+ * --msg-tool-card-text: primary(icon、in_progress/pending 文本)
+ * --msg-tool-card-chevron: secondary(completed 置灰)
*/
-import { useState } from 'react';
-import {
- ChevronRight,
- ChevronDown,
- ListTodo,
- CircleCheck,
- CircleDashed,
- Circle,
-} from 'lucide-react';
+import { useEffect, useId, useState } from 'react';
+import { CircleCheck, CircleDashed, Circle } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
import type { MessageRenderTodoItem } from '@cindy/maker-shared/message-render';
import { cn } from '@/lib/utils';
@@ -46,116 +37,153 @@ export type TodoItem = MessageRenderTodoItem;
export function TodoListCard({
todos,
animated = true,
+ maxWidth,
}: {
todos: TodoItem[];
/** When false, in_progress items render the dashed circle but no pulse / spin —
* used after the session stops so frozen todos don't keep "spinning". */
animated?: boolean;
+ /** Composer/chat column width. Keeps the flyout inside clipped compact panes. */
+ maxWidth?: number;
}) {
- const [expanded, setExpanded] = useState(true);
+ const { t } = useTranslation();
+ const flyoutId = useId();
+ const [hovered, setHovered] = useState(false);
+ const [pinnedOpen, setPinnedOpen] = useState(false);
+ const [renderFlyout, setRenderFlyout] = useState(false);
+ const revealed = hovered || pinnedOpen;
+
+ useEffect(() => {
+ if (revealed) setRenderFlyout(true);
+ }, [revealed]);
if (!todos || todos.length === 0) return null;
- const completed = todos.filter((t) => t.status === 'completed').length;
+ const completed = todos.filter((todo) => todo.status === 'completed').length;
const total = todos.length;
- const pct = total > 0 ? (completed / total) * 100 : 0;
-
- // Header message: content of current in_progress item, or last item
- const activeItem = todos.find((t) => t.status === 'in_progress');
- const headerMsg = activeItem
- ? activeItem.content + (expanded ? '' : '…')
- : todos[todos.length - 1]?.content ?? '';
+ const allDone = completed >= total;
+ const activeIndex = todos.findIndex((todo) => todo.status === 'in_progress');
+ const pendingIndex = todos.findIndex((todo) => todo.status === 'pending');
+ const currentIndex =
+ activeIndex >= 0 ? activeIndex : pendingIndex >= 0 ? pendingIndex : Math.min(completed, total - 1);
+ const currentStep = allDone ? total : currentIndex + 1;
+ const hasActive = todos.some((todo) => todo.status === 'in_progress');
+ const flyoutMaxWidth =
+ typeof maxWidth === 'number' && Number.isFinite(maxWidth) && maxWidth > 0
+ ? `${Math.floor(maxWidth)}px`
+ : null;
return (
- <div className="flex w-full justify-start">
+ <div className="flex w-full justify-center">
<div
- className={cn(
- 'border border-[var(--msg-tool-card-border)]',
- 'bg-[var(--msg-tool-card-bg)]',
- 'overflow-hidden max-w-full',
- expanded ? 'rounded-[12px]' : 'rounded-t-[12px] rounded-b-none',
- )}
+ className="relative inline-flex items-center justify-center"
+ onMouseEnter={() => setHovered(true)}
+ onMouseLeave={() => setHovered(false)}
>
- {/* Header row */}
+ {/* Collapsed pill — `[icon] Step N / M`,点击/Enter 也可切换浮层(键盘可达)。 */}
<button
type="button"
- onClick={() => setExpanded((prev) => !prev)}
+ onClick={(event) => {
+ if (event.detail === 0) {
+ setPinnedOpen((prev) => !prev);
+ return;
+ }
+ setPinnedOpen((prev) => !prev);
+ }}
+ aria-controls={flyoutId}
+ aria-expanded={revealed}
className={cn(
- 'flex w-full items-center gap-2',
- 'px-[14px] py-[10px]',
+ 'flex items-center gap-2 rounded-full',
+ 'border border-[var(--msg-tool-card-border)]',
+ 'bg-[var(--msg-tool-card-bg)]',
+ 'px-[14px] py-[8px]',
'cursor-pointer select-none',
'hover:opacity-80 transition-opacity',
)}
>
- {expanded ? (
- <ChevronDown size={14} className="shrink-0 text-[var(--msg-tool-card-chevron)]" />
+ {allDone ? (
+ <CircleCheck size={14} strokeWidth={2} className="shrink-0 text-[var(--msg-tool-card-text)]" />
) : (
- <ChevronRight size={14} className="shrink-0 text-[var(--msg-tool-card-chevron)]" />
+ <Spinner
+ icon={CircleDashed}
+ size={14}
+ strokeWidth={2}
+ spinning={animated && hasActive}
+ className="shrink-0 text-[var(--msg-tool-card-text)]"
+ />
)}
- <ListTodo size={16} className="shrink-0 text-[var(--msg-tool-card-text)]" />
- <span className="shrink-0 font-mono text-[13px] leading-none font-semibold text-[var(--msg-tool-card-text)]">
- {completed}/{total}
- </span>
- <span className="shrink-0 text-13 leading-none text-[var(--msg-tool-card-chevron)]">·</span>
- <span className="mt-px truncate text-13 leading-none text-[var(--msg-tool-card-text)]">
- {headerMsg}
+ <span className="text-13 leading-none tabular-nums text-[var(--msg-tool-card-text)]">
+ {t('chat.planPill.step', { current: currentStep, total })}
</span>
</button>
- {/* Progress bar — collapsed only */}
- {!expanded && (
- <div className="h-[2px] w-full bg-[var(--todo-bar-track)]">
- <div
- className="h-full bg-[var(--msg-tool-card-text)] transition-all duration-300"
- style={{ width: `${pct}%` }}
- />
- </div>
- )}
-
- {/* Expanded: divider + todo list */}
- {expanded && (
+ {/* Hover flyout — 完整清单向上浮出;绝对定位不占布局高度,消息流不抖动。 */}
+ {renderFlyout && (
<>
- <div className="h-px w-full bg-[var(--msg-tool-card-border)]" />
- <div className="flex flex-col gap-[2px] px-[14px] pb-[12px] pt-[10px]">
- {todos.map((todo, i) => (
- <div
- key={i}
- className={cn(
- 'flex h-[30px] items-center gap-[10px]',
- todo.status === 'in_progress' && animated && 'animate-pulse',
- )}
- >
- {/* Icon */}
- {todo.status === 'completed' && (
- <CircleCheck size={18} strokeWidth={1.5} className="shrink-0 text-[var(--msg-tool-card-text)]" />
- )}
- {todo.status === 'in_progress' && (
- <Spinner
- icon={CircleDashed}
- size={18}
- strokeWidth={1.5}
- spinning={animated}
- className="text-[var(--msg-tool-card-text)]"
- style={{ animationDuration: '3s' }}
- />
- )}
- {todo.status === 'pending' && (
- <Circle size={18} strokeWidth={1.5} className="shrink-0 text-[var(--msg-tool-card-chevron)]" />
- )}
-
- {/* Text */}
- <span
+ <div className="absolute bottom-full left-1/2 h-2 min-w-full -translate-x-1/2" aria-hidden="true" />
+ <div
+ id={flyoutId}
+ className={cn(
+ 'absolute bottom-full left-1/2 z-10 mb-2 -translate-x-1/2',
+ 'w-max',
+ flyoutMaxWidth === null && 'min-w-[220px] max-w-[min(420px,calc(100vw-32px))]',
+ 'origin-bottom overflow-hidden rounded-[12px]',
+ 'border border-[var(--msg-tool-card-border)]',
+ 'bg-[var(--msg-tool-card-bg)]',
+ revealed ? 'animate-float-in' : 'animate-float-out',
+ )}
+ style={
+ flyoutMaxWidth === null
+ ? undefined
+ : {
+ minWidth: `min(220px, ${flyoutMaxWidth})`,
+ maxWidth: `min(420px, ${flyoutMaxWidth}, calc(100vw - 32px))`,
+ }
+ }
+ onAnimationEnd={() => {
+ if (!revealed) setRenderFlyout(false);
+ }}
+ >
+ <div className="flex max-h-[280px] flex-col gap-[2px] overflow-y-auto px-[14px] py-[10px]">
+ {todos.map((todo, i) => (
+ <div
+ key={i}
className={cn(
- 'mt-px truncate text-13',
- todo.status === 'completed' && 'font-semibold text-[var(--msg-tool-card-text)]',
- todo.status === 'in_progress' && 'font-semibold text-[var(--msg-tool-card-text)]',
- todo.status === 'pending' && 'font-normal text-[var(--msg-tool-card-chevron)] opacity-60',
+ 'flex h-[30px] items-center gap-[10px]',
+ todo.status === 'in_progress' && animated && 'animate-pulse',
)}
>
- {todo.content}
- </span>
- </div>
- ))}
+ {/* Icon */}
+ {todo.status === 'completed' && (
+ <CircleCheck size={18} strokeWidth={1.5} className="shrink-0 text-[var(--msg-tool-card-chevron)]" />
+ )}
+ {todo.status === 'in_progress' && (
+ <Spinner
+ icon={CircleDashed}
+ size={18}
+ strokeWidth={1.5}
+ spinning={animated}
+ className="text-[var(--msg-tool-card-text)]"
+ />
+ )}
+ {todo.status === 'pending' && (
+ <Circle size={18} strokeWidth={1.5} className="shrink-0 text-[var(--msg-tool-card-text)]" />
+ )}
+
+ {/* Text — 对齐 Codex:completed 置灰,in_progress 高亮,pending 正常。 */}
+ <span
+ className={cn(
+ 'mt-px truncate text-13',
+ todo.status === 'completed' && 'font-normal text-[var(--msg-tool-card-chevron)]',
+ todo.status === 'in_progress' && 'font-semibold text-[var(--msg-tool-card-text)]',
+ todo.status === 'pending' && 'font-normal text-[var(--msg-tool-card-text)]',
+ )}
+ >
+ {todo.content}
+ </span>
+ </div>
+ ))}
+ </div>
</div>
</>
)}
diff --git a/apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx b/apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx
new file mode 100644
index 0000000000..01848b81e5
--- /dev/null
+++ b/apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx
@@ -0,0 +1,39 @@
+/**
+ * PinnedPlanPanel —— agent 计划清单的常驻胶囊(composer 上方)。
+ *
+ * 对齐 Codex IDE 扩展的交互模型:计划不进聊天流(MessageStream 已把 plan 工具
+ * 调用整体吞掉),唯一呈现就是这里 —— 输入框上方一枚居中小胶囊(Step N / M),
+ * 鼠标悬停时完整清单以浮层向上展开,原地实时更新,不会被后续消息冲走。
+ * 数据从会话消息派生(findLatestMessageTodoInsertion):跨 source(TodoWrite /
+ * update_plan / Task*)取最近更新的 plan session 快照;历史 session 不再逐张
+ * 展示。无计划时返回 null,不占位。
+ */
+
+import { useMemo } from 'react';
+import { findLatestMessageTodoInsertion } from '@cindy/maker-shared/message-render';
+
+import { TodoListCard } from '@/components/chat/TodoListCard';
+import type { ChatMessage } from '@/lib/makerChatStore';
+
+export function PinnedPlanPanel({
+ messages,
+ animated,
+ width,
+}: {
+ messages: readonly ChatMessage[];
+ /** 会话仍在流式时进行中项呼吸/旋转;停止后冻结。 */
+ animated: boolean;
+ /** 与 composer 同宽(inputWidth),胶囊在该宽度内居中,浮层不超出。 */
+ width: number;
+}): React.ReactElement | null {
+ const insertion = useMemo(() => findLatestMessageTodoInsertion(messages), [messages]);
+
+ if (!insertion || insertion.todos.length === 0) return null;
+
+ return (
+ <div className="mb-1.5 max-w-full" style={{ width }}>
+ {/* key 按 plan session 锚定:新计划重挂载,浮层/进度从头开始。 */}
+ <TodoListCard key={insertion.key} todos={insertion.todos} animated={animated} maxWidth={width} />
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 4a753e9ccc..d9377d3734 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -52,6 +52,7 @@ import { setRemoteReceiptDisplayReady } from '@/lib/sessionAttentionStore';
import { shortSessionId } from '@/lib/sessionId';
import { ChatInput } from '@/components/new-chat/ChatInput';
import { GoalIndicator } from '@/components/new-chat/GoalIndicator';
+import { PinnedPlanPanel } from '@/components/new-chat/PinnedPlanPanel';
import { sessionsStore } from '@/lib/sessionsStore';
import { useStopOrcaCollab } from './hooks/useStopOrcaCollab';
import { CreateWorkerPopover, type CreateWorkerForm } from './CreateWorkerPopover';
@@ -3507,6 +3508,22 @@ export function CCAgentSessionView({
</InteractionPromptHost>
{/* 会话内 /goal 进行中状态条(composer 上方);无 goal 时返回 null 不占位。 */}
<GoalIndicator sessionId={sessionId} />
+ {/* Codex IDE 扩展式常驻计划面板 —— 计划在流内不再渲染,这里是唯一
+ 呈现处:钉在输入框上方原地更新。任意 pending interaction(计划
+ 审核 / 权限 / 提问 / 插件配置 / 各类确认卡)接管底部区时隐藏:
+ 胶囊的悬停浮层向上展开,会盖住交互卡内容(条件集与下方 ternary
+ 的静默判定保持一致)。 */}
+ {!(
+ pendingPlanReview ||
+ pendingPermission ||
+ pendingAskUser ||
+ pendingPluginSetup ||
+ pendingIssueConfirm ||
+ pendingRenameSessionsConfirm ||
+ pendingGhostGrantConfirm
+ ) && (
+ <PinnedPlanPanel messages={messages} animated={isStreaming} width={inputWidth} />
+ )}
{/* 互斥:有任意 pending interaction 时,下方 takeover/overlay/ChatInput
全部静默 — 跟改造前 ternary 链 (Plan ? : Perm ? : Ask ? :
Takeover ? : ChatInput) 的语义一致。
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index c4bb425469..79edd01e8b 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -5141,6 +5141,9 @@
"lastTool": "Last tool: {{tool}}",
"outputFile": "Output: {{path}}"
},
+ "planPill": {
+ "step": "Step {{current}} / {{total}}"
+ },
"forkOrigin": {
"label": "Created from another session"
},
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 3a2cfa8441..44a158475b 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -5139,6 +5139,9 @@
"lastTool": "直近のツール: {{tool}}",
"outputFile": "出力: {{path}}"
},
+ "planPill": {
+ "step": "ステップ {{current}} / {{total}}"
+ },
"forkOrigin": {
"label": "元のセッションから作成"
},
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index db25759845..985ad1be6a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -5139,6 +5139,9 @@
"lastTool": "최근 도구: {{tool}}",
"outputFile": "출력: {{path}}"
},
+ "planPill": {
+ "step": "단계 {{current}} / {{total}}"
+ },
"forkOrigin": {
"label": "원래 세션에서 생성됨"
},
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 9759c8fe2f..26063f4217 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -5139,6 +5139,9 @@
"lastTool": "最近工具:{{tool}}",
"outputFile": "输出:{{path}}"
},
+ "planPill": {
+ "step": "步骤 {{current}} / {{total}}"
+ },
"forkOrigin": {
"label": "基于原任务创建"
},
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index c699dd8cf8..945e38380a 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -23,7 +23,11 @@
import type { CindyRegion } from '@cindy/maker-shared/brand-identity';
import { redactSensitiveText } from '@cindy/maker-shared/error-redaction';
-import { applyCodexPlanSnapshotOnDone } from '@cindy/maker-shared/message-render';
+import {
+ applyCodexPlanSnapshotOnDone,
+ getLatestMessageTodoState,
+ isAgentPlanToolName,
+} from '@cindy/maker-shared/message-render';
import {
normalizeWorkflowProgressEntries,
type WorkflowProgressEntry,
@@ -1359,12 +1363,21 @@ function _trimMessagesIfNeeded(sessionId: string): void {
if (s.messages.length <= TRIM_THRESHOLD) {
return s.isLoadingMore ? { ...s, isLoadingMore: false } : s;
}
+ const preTrimPlanState = getLatestMessageTodoState(s.messages);
+ const trimmedMessages = s.messages.slice(-TRIM_TARGET);
+ const trimmedPlanState = getLatestMessageTodoState(trimmedMessages);
+ const needsPlanReloadAfterTrim =
+ s.historyLoaded &&
+ preTrimPlanState.insertion !== null &&
+ (!trimmedPlanState.hasPlanEvent || !trimmedPlanState.isResolved);
+
return {
...s,
- messages: s.messages.slice(-TRIM_TARGET),
+ messages: trimmedMessages,
hasMoreMessages: true,
oldestMessageId: null,
isLoadingMore: false,
+ ...(needsPlanReloadAfterTrim ? { historyLoaded: false } : {}),
// 孤岛标记**保持原值**:`slice(-TRIM_TARGET)` 只保证"取最新的 200 行",不保证这 200 行
// 连续 —— 若先前几次深跳留下多个孤岛、而真正连续的尾段不足 200 行,裁剪结果里就还夹着
// 孤岛。清掉标记会让 canFocusWithoutJumpLoad 把命中孤岛当成已覆盖直接 focus,而从孤岛
@@ -1655,6 +1668,7 @@ function markSessionHasUserMessage(sessionId: string): void {
function requestInputProjection(sessionId: string): void {
if (!sessionId) return;
+ if (typeof window === 'undefined' || !window.electronAPI?.maker?.input?.getProjection) return;
makerApiFor(sessionId)
.input.getProjection(sessionId)
.then(applyInputProjection)
@@ -5325,11 +5339,16 @@ function hydrateRemoteMessagesFromCache(sessionId: string): void {
// 而 CCAgentSessionView 又会因 messages 非空而收起 loading 覆盖层 —— 被控端离线时
// 就是一片永久空白(review: codex P1)。这种页对首屏没有价值,让 loading 照常显示、
// 交给 fresh 首拉的 no-anchor-backfill 往前翻页处理。
- if (rows.every(isNonAnchorHistoryRow)) return;
const mapped = mapServerMessages(rows).map((message) => ({
...message,
cacheHydrated: true as const,
}));
+ if (
+ rows.every(isNonAnchorHistoryRow) &&
+ getLatestMessageTodoState(mapped).insertion === null
+ ) {
+ return;
+ }
if (mapped.length === 0) return;
// 读缓存这一跳期间归属可能已经变了:设备被移除(mapping 消失)或会话换到了另一台设备。
// 只看 chat state 挡不住这种情况 —— 于是 A 设备的历史会被种进一个已经不属于 A 的会话,
@@ -5480,16 +5499,23 @@ function ensureInitialMessages(sessionId: string): void {
return;
}
- // no-anchor-backfill: 初始页若全是"渲染后不留可见锚点"的行,映射结果就是空列表,
+ // no-anchor / plan-boundary backfill: 初始页若全是"渲染后不留可见锚点"的行,映射结果就是空列表,
// 而 MessageStream 在 visibleRenderItems.length === 0 时不触发自动翻页 —— 结果是
// DB 里有 2000+ 条消息,重启后 ChatView 渲染 0 项,看起来"内容消失了"。
- // 两类命中(见 isNonAnchorHistoryRow):
+ // 四类命中(见 isNonAnchorHistoryRow):
// - 全是 tool_result:配对的 tool_use 父消息在更老的页里,orphan 会被丢弃;
// - 全是被隐藏的 thinking 行:如一轮搜索密集、在产出可见正文前就失败的会话,
// 最新 50 行可能全是加密推理;
- // - 合成指令行:渲染 null,混在上面两类里同样撑不出可见锚点。
- // 这里继续往前翻页,直到出现可渲染锚点或翻完。
- // 上限 10 页(500 行)防御异常长的连续无锚点队列。
+ // - 计划工具行:计划只在输入框上方的胶囊呈现,不在消息流中留锚点;
+ // - 合成指令行:渲染 null,混在这些行里同样撑不出可见锚点。
+ //
+ // PinnedPlanPanel 的唯一数据源同样是当前消息窗口。计划工具行不再在消息流中渲染,
+ // 所以冷开超过一页的会话时,如果最近一次 plan 在更早页,胶囊会直接消失。这里也继续
+ // 往前翻到最近 plan 边界,保证初始窗口能派生当前计划快照。
+ //
+ // 无锚点按 10 页(500 行)兜底。计划胶囊分两段:
+ // - 当前窗口没有任何计划事件时,最多探测 10 页,避免从未使用计划的长会话全量拉历史;
+ // - 已看到计划事件但最新 TaskUpdate 还缺创建/列表边界时,最多再补 10 页。
let merged: Message[] = existing;
let oldestRow = oldestMessageRow(merged, 'newest-first');
if (!oldestRow) {
@@ -5503,14 +5529,26 @@ function ensureInitialMessages(sessionId: string): void {
return;
}
let hasMore = serverMessagePageHasMore(existing);
- const MAX_BACKFILL_PAGES = 10;
+ const MAX_NO_ANCHOR_BACKFILL_PAGES = 10;
+ const MAX_PLAN_DISCOVERY_BACKFILL_PAGES = 10;
+ const MAX_PLAN_RESOLUTION_BACKFILL_PAGES = 10;
let pagesFetched = 0;
- while (
- hasMore &&
- pagesFetched < MAX_BACKFILL_PAGES &&
- merged.every(isNonAnchorHistoryRow)
- ) {
+ let planResolutionPagesFetched = 0;
+ while (hasMore) {
+ const needsAnchorBackfill =
+ merged.every(isNonAnchorHistoryRow) && pagesFetched < MAX_NO_ANCHOR_BACKFILL_PAGES;
+ const planState = historyRowsPlanBackfillState(merged);
+ const needsPlanResolution =
+ planState.hasPlanEvent &&
+ !planState.isResolved &&
+ planResolutionPagesFetched < MAX_PLAN_RESOLUTION_BACKFILL_PAGES;
+ const needsPlanBackfill = planState.hasPlanEvent
+ ? needsPlanResolution
+ : pagesFetched < MAX_PLAN_DISCOVERY_BACKFILL_PAGES;
+ if (!needsAnchorBackfill && !needsPlanBackfill) break;
+
pagesFetched += 1;
+ if (needsPlanResolution) planResolutionPagesFetched += 1;
try {
const older = await listMessagesFor(sessionId, {
limit: 50,
@@ -6239,7 +6277,8 @@ function loadOlderMessages(sessionId: string): void {
* 为什么不再按 role / 工具名折算:折算模型必须逐一追平 buildRenderItems 的每种 item
* 展开规则,而那套规则会持续演化。#676 的 review 连着四轮各挖出一种被低估的展开路径:
* agent_task 卡(每个 Agent/Task/Workflow 调用 1:1)、按空洞切段后的孤立单行调用、
- * ghost_call 配卡后的独立 ghost_card、TodoWrite / update_plan 的 agent_plan 卡、
+ * ghost_call 配卡后的独立 ghost_card、TodoWrite / update_plan 的 agent_plan 卡
+ * (该卡现已移出流内,计划改钉在 composer 上方的 PinnedPlanPanel;历史结论不变)、
* 以及结果含媒体时额外产出的 tool_media —— 每次都是"某行额外产生 item",而折算恰恰
* 假设"多行合成一个 item"。低估预算的方向是危险的那一侧(放进更多实际渲染量),所以
* 不再猜比例:一行最多产出一个可见 item 的量级,直接按行数当上界。
@@ -9566,6 +9605,17 @@ function serverMessagePageHasMore(rows: Message[], pageSize = 50): boolean {
return rows.length >= pageSize || rows.some((row) => row.agentMeta?.remoteRowsTrimmed === true);
}
+function historyRowsPlanBackfillState(rows: Message[]): {
+ hasPlanEvent: boolean;
+ isResolved: boolean;
+} {
+ const state = getLatestMessageTodoState(mapServerMessages(rows));
+ return {
+ hasPlanEvent: state.hasPlanEvent,
+ isResolved: state.isResolved,
+ };
+}
+
function shouldStopRemoteReconciliationAtOverlap(
rows: Message[],
hasKnownOverlap: boolean,
@@ -9681,9 +9731,10 @@ function isHiddenThinkingRow(m: Message): boolean {
/**
* 该服务端行**渲染后不会留下可见锚点**(初始页全是这类行时必须继续往前翻页)。
*
- * 三类:
+ * 四类:
* - `tool_result`:配对的 tool_use 父消息可能在更老的页里,MessageStream 会丢弃 orphan;
* - 被 `isHiddenThinkingRow` 过滤掉的行:直接不进渲染列表;
+ * - 计划工具调用:MessageStream 会吞掉,只更新 composer 上方的计划胶囊;
* - 合成指令行(`isSyntheticTriggerRow`):MessageStream 渲染 null、content 置空,
* 与 `loadOlderMessages` 的可见锚点判定同口径(见该处「合成指令行渲染 null,不算可见
* 锚点」)。少了这一类,一页里只要混进一条合成 user 行就会被当成锚点提前停止回填,
@@ -9694,7 +9745,23 @@ function isHiddenThinkingRow(m: Message): boolean {
* 再也拉不回来。
*/
function isNonAnchorHistoryRow(m: Message): boolean {
- return m.role === 'tool_result' || isHiddenThinkingRow(m) || isSyntheticTriggerRow(m);
+ return (
+ m.role === 'tool_result' ||
+ isHiddenThinkingRow(m) ||
+ isAgentPlanHistoryToolUseRow(m) ||
+ isSyntheticTriggerRow(m)
+ );
+}
+
+function isAgentPlanHistoryToolUseRow(m: Message): boolean {
+ if (m.role !== 'tool_use') return false;
+ return isAgentPlanToolName(historyToolName(m));
+}
+
+function historyToolName(m: Message): string | undefined {
+ if (!m.content || typeof m.content !== 'object') return undefined;
+ const toolName = (m.content as Record<string, unknown>).toolName;
+ return typeof toolName === 'string' ? toolName : undefined;
}
function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {
diff --git a/packages/maker-shared/src/__tests__/messageRender.test.ts b/packages/maker-shared/src/__tests__/messageRender.test.ts
index dc1c34804f..8fc69d070a 100644
--- a/packages/maker-shared/src/__tests__/messageRender.test.ts
+++ b/packages/maker-shared/src/__tests__/messageRender.test.ts
@@ -4,6 +4,7 @@ import {
dedupeToolMediaByUrl,
extractPlanTodos,
extractTodosFromSourceMessage,
+ findLatestMessageTodoInsertion,
findMessageTodoInsertions,
formatDuration,
type MessageRenderItem,
@@ -832,6 +833,146 @@ describe('message render todo grouping', () => {
expect([...insertions.values()].map((item) => item.key)).toEqual(['todo-todo1', 'todo-todo2']);
});
+ // findLatestMessageTodoInsertion:桌面钉住式计划面板(PinnedPlanPanel)的数据源 ——
+ // 面板只展示"当前计划"一份,跨 source 取最近一次更新的 session 快照。
+
+ it('findLatestMessageTodoInsertion picks the most recently updated plan session across sources', () => {
+ const codex = tool('plan1', 'update_plan', {
+ plan: [{ step: 'Check desktop', status: 'in_progress' }],
+ });
+ const create = tool('task1', 'TaskCreate', { subject: 'Collect logs' }, 'create-1');
+
+ const latest = findLatestMessageTodoInsertion([
+ codex,
+ create,
+ result('create-1', 'Task #abc created successfully: Collect logs'),
+ ]);
+
+ expect(latest).toMatchObject({ key: 'todo-task1', source: 'task' });
+ });
+
+ it('findLatestMessageTodoInsertion returns the merged session snapshot with the FIRST call key', () => {
+ const first = tool('todo1', 'TodoWrite', {
+ todos: [{ content: 'Read code', status: 'in_progress' }],
+ });
+ const second = tool('todo2', 'TodoWrite', {
+ todos: [{ content: 'Read code', status: 'completed' }],
+ });
+
+ expect(findLatestMessageTodoInsertion([first, second])).toMatchObject({
+ key: 'todo-todo1',
+ todos: [{ content: 'Read code', status: 'completed' }],
+ });
+ });
+
+ it('findLatestMessageTodoInsertion returns null when the conversation has no plan calls', () => {
+ expect(findLatestMessageTodoInsertion([tool('t1', 'Bash', {})])).toBeNull();
+ });
+
+ it('findLatestMessageTodoInsertion treats empty plan updates as clearing the pinned plan', () => {
+ const first = tool('todo1', 'TodoWrite', {
+ todos: [{ content: 'Read code', status: 'in_progress' }],
+ });
+ const clearTodo = tool('todo2', 'TodoWrite', { todos: [] });
+ const codex = tool('plan1', 'update_plan', {
+ plan: [{ step: 'Run tests', status: 'in_progress' }],
+ });
+ const clearCodex = tool('plan2', 'update_plan', { plan: [] });
+ const clearCodexObject = tool('plan3', 'update_plan', {});
+ const clearCodexText = tool('plan4', 'update_plan', { text: ' \n ' });
+
+ expect(findLatestMessageTodoInsertion([first, clearTodo])).toBeNull();
+ expect(findLatestMessageTodoInsertion([codex, clearCodex])).toBeNull();
+ expect(findLatestMessageTodoInsertion([codex, clearCodexObject])).toBeNull();
+ expect(findLatestMessageTodoInsertion([codex, clearCodexText])).toBeNull();
+ });
+
+ it('findLatestMessageTodoInsertion does not fall back to an older source when the latest Task update is unresolved', () => {
+ const todo = tool('todo1', 'TodoWrite', {
+ todos: [{ content: 'Old todo source', status: 'in_progress' }],
+ });
+ const update = tool('task2', 'TaskUpdate', { taskId: 'abc', status: 'completed' }, 'update-1');
+
+ expect(findLatestMessageTodoInsertion([todo, update])).toBeNull();
+ });
+
+ it('findLatestMessageTodoInsertion clears the pinned plan when the latest Task update deletes the last task', () => {
+ const create = tool('task1', 'TaskCreate', { subject: 'Collect logs' }, 'create-1');
+ const remove = tool('task2', 'TaskUpdate', { taskId: 'abc', status: 'deleted' }, 'update-1');
+
+ expect(findLatestMessageTodoInsertion([
+ create,
+ result('create-1', 'Task #abc created successfully: Collect logs'),
+ remove,
+ ])).toBeNull();
+ });
+
+ it('findLatestMessageTodoInsertion keeps remaining tasks when the latest Task update deletes one task', () => {
+ const first = tool('task1', 'TaskCreate', { subject: 'Collect logs' }, 'create-1');
+ const second = tool('task2', 'TaskCreate', { subject: 'Write summary' }, 'create-2');
+ const remove = tool('task3', 'TaskUpdate', { taskId: 'abc', status: 'deleted' }, 'update-1');
+
+ expect(findLatestMessageTodoInsertion([
+ first,
+ result('create-1', 'Task #abc created successfully: Collect logs'),
+ second,
+ result('create-2', 'Task #def created successfully: Write summary'),
+ remove,
+ ])).toMatchObject({
+ key: 'todo-task1',
+ source: 'task',
+ todos: [{ content: 'Write summary', status: 'pending' }],
+ });
+ });
+
+ it('keeps other completed tasks when the latest Task update deletes one completed task', () => {
+ const first = tool('task1', 'TaskCreate', { subject: 'Collect logs' }, 'create-1');
+ const second = tool('task2', 'TaskCreate', { subject: 'Write summary' }, 'create-2');
+ const completeFirst = tool('task3', 'TaskUpdate', { taskId: 'abc', status: 'completed' }, 'update-1');
+ const completeSecond = tool('task4', 'TaskUpdate', { taskId: 'def', status: 'completed' }, 'update-2');
+ const removeFirst = tool('task5', 'TaskUpdate', { taskId: 'abc', status: 'deleted' }, 'update-3');
+
+ expect(findLatestMessageTodoInsertion([
+ first,
+ result('create-1', 'Task #abc created successfully: Collect logs'),
+ second,
+ result('create-2', 'Task #def created successfully: Write summary'),
+ completeFirst,
+ completeSecond,
+ removeFirst,
+ ])).toMatchObject({
+ key: 'todo-task1',
+ source: 'task',
+ todos: [{ content: 'Write summary', status: 'completed' }],
+ });
+ });
+
+ it('treats TaskGet deleted results as clearing the latest task plan', () => {
+ const create = tool('task1', 'TaskCreate', { subject: 'Collect logs' }, 'create-1');
+ const getDeleted = tool('task2', 'TaskGet', { taskId: 'abc' }, 'get-1');
+
+ expect(findLatestMessageTodoInsertion([
+ create,
+ result('create-1', 'Task #abc created successfully: Collect logs'),
+ getDeleted,
+ result('get-1', JSON.stringify({
+ task: { id: 'abc', subject: 'Collect logs', status: 'deleted' },
+ })),
+ ])).toBeNull();
+ });
+
+ it('treats explicit empty TaskList snapshots as clearing the latest task plan', () => {
+ const create = tool('task1', 'TaskCreate', { subject: 'Collect logs' }, 'create-1');
+ const listEmpty = tool('task2', 'TaskList', {}, 'list-1');
+
+ expect(findLatestMessageTodoInsertion([
+ create,
+ result('create-1', 'Task #abc created successfully: Collect logs'),
+ listEmpty,
+ result('list-1', JSON.stringify({ tasks: [] })),
+ ])).toBeNull();
+ });
+
it('parses Codex update_plan text and structured plan statuses', () => {
expect(extractPlanTodos('update_plan', { text: '1. Read code\n2. Run tests' })).toEqual([
{ content: 'Read code', status: 'in_progress' },
diff --git a/packages/maker-shared/src/messageRender.ts b/packages/maker-shared/src/messageRender.ts
index da57fe81c0..89c0d8314f 100644
--- a/packages/maker-shared/src/messageRender.ts
+++ b/packages/maker-shared/src/messageRender.ts
@@ -190,6 +190,14 @@ export interface MessageRenderTodoInsertion {
source: MessageRenderTodoSource;
}
+export interface MessageRenderLatestTodoState {
+ insertion: MessageRenderTodoInsertion | null;
+ hasPlanEvent: boolean;
+ isResolved: boolean;
+ latestPlanIndex: number;
+ latestInsertionIndex: number;
+}
+
export interface MessageRenderTodoGroupingOptions {
keyPrefix?: string;
}
@@ -421,9 +429,14 @@ export function findMessageTodoInsertions<TMessage extends MessageRenderSourceMe
const source = agentPlanSource(toolNameOf(message));
if (!source) continue;
+ const resultText = resultByToolUseId.get(toolUseIdOf(message) ?? '');
const previous = lastSessionBySource.get(source);
const previousAllDone = previous?.todos.every((todo) => todo.status === 'completed');
- const startsNewSession = !previous || Boolean(previousAllDone);
+ const continuesCompletedTaskSession =
+ source === 'task'
+ && Boolean(previousAllDone)
+ && taskToolTargetsExistingTask(message, resultText, taskState);
+ const startsNewSession = !previous || (Boolean(previousAllDone) && !continuesCompletedTaskSession);
if (source === 'task' && startsNewSession) {
taskState.clear();
}
@@ -433,7 +446,7 @@ export function findMessageTodoInsertions<TMessage extends MessageRenderSourceMe
?? applyTaskPlanTool(
taskState,
message,
- resultByToolUseId.get(toolUseIdOf(message) ?? ''),
+ resultText,
);
if (!parsed) continue;
@@ -460,6 +473,55 @@ export function findMessageTodoInsertions<TMessage extends MessageRenderSourceMe
return out;
}
+/**
+ * 常驻计划面板(composer 上方钉住式)用:取整段会话里**最近一次更新**的 plan
+ * session 快照 —— 跨 source(TodoWrite / update_plan / Task*)按 lastIndex 取
+ * 最大者。面板只展示"当前计划"一份,历史 session 不再逐张呈现。
+ * 没有任何 plan 调用时返回 null(面板不渲染、不占位)。
+ */
+export function findLatestMessageTodoInsertion<TMessage extends MessageRenderSourceMessageLike>(
+ messages: readonly TMessage[],
+ options: MessageRenderTodoGroupingOptions = {},
+): MessageRenderTodoInsertion | null {
+ return getLatestMessageTodoState(messages, options).insertion;
+}
+
+export function getLatestMessageTodoState<TMessage extends MessageRenderSourceMessageLike>(
+ messages: readonly TMessage[],
+ options: MessageRenderTodoGroupingOptions = {},
+): MessageRenderLatestTodoState {
+ let latestPlanIndex = -1;
+ let latestPlanMessage: TMessage | null = null;
+ for (let index = 0; index < messages.length; index++) {
+ const message = messages[index];
+ if (!isAgentPlanToolName(toolNameOf(message))) continue;
+ latestPlanIndex = index;
+ latestPlanMessage = message;
+ }
+
+ let latest: MessageRenderTodoInsertion | null = null;
+ let latestIndex = -1;
+ for (const [index, insertion] of findMessageTodoInsertions(messages, options)) {
+ if (index > latestIndex) {
+ latestIndex = index;
+ latest = insertion;
+ }
+ }
+ const hasPlanEvent = latestPlanIndex >= 0;
+ const insertionBelongsToLatestEvent = latestIndex === latestPlanIndex;
+ const latestEventClearsPlan =
+ latestPlanMessage !== null &&
+ (isExplicitPlanClearEvent(latestPlanMessage) ||
+ latestTaskEventClearsPlan(messages, latestPlanIndex));
+ return {
+ insertion: insertionBelongsToLatestEvent ? latest : null,
+ hasPlanEvent,
+ isResolved: !hasPlanEvent || insertionBelongsToLatestEvent || latestEventClearsPlan,
+ latestPlanIndex,
+ latestInsertionIndex: latestIndex,
+ };
+}
+
export interface CodexPlanSnapshotApplyResult<
TMessage extends MessageRenderSourceMessageLike,
> {
@@ -584,6 +646,68 @@ export function extractTodos(toolInput: unknown): MessageRenderTodoItem[] | null
return out.length > 0 ? out : null;
}
+function isExplicitPlanClearEvent(message: MessageRenderSourceMessageLike): boolean {
+ const toolName = toolNameOf(message);
+ const input = readRecord(toolInputOf(message));
+ if (toolName === 'TodoWrite') return Array.isArray(input?.todos) && input.todos.length === 0;
+ if (toolName === 'update_plan') {
+ return (
+ (Array.isArray(input?.items) && input.items.length === 0) ||
+ (Array.isArray(input?.plan) && input.plan.length === 0) ||
+ (typeof input?.text === 'string' && input.text.trim().length === 0) ||
+ (input !== null && Object.keys(input).length === 0)
+ );
+ }
+ return false;
+}
+
+function latestTaskEventClearsPlan<TMessage extends MessageRenderSourceMessageLike>(
+ messages: readonly TMessage[],
+ latestPlanIndex: number,
+): boolean {
+ const latest = messages[latestPlanIndex];
+ const latestToolName = toolNameOf(latest);
+ const resultByToolUseId = buildToolResultLookup(messages);
+ const latestResultText = resultByToolUseId.get(toolUseIdOf(latest) ?? '');
+ if (latestToolName === 'TaskList') return taskListResultClearsPlan(latestResultText);
+ if (latestToolName !== 'TaskUpdate' && latestToolName !== 'TaskGet') return false;
+ if (taskToolStatus(latest, latestResultText) !== 'deleted') return false;
+
+ const taskState = new Map<string, MessageRenderTodoItem>();
+ let previousTaskTodos: MessageRenderTodoItem[] | null = null;
+ let resolvedTaskContext = false;
+
+ for (let index = 0; index <= latestPlanIndex; index += 1) {
+ const message = messages[index];
+ if (agentPlanSource(toolNameOf(message)) !== 'task') continue;
+
+ const resultText = resultByToolUseId.get(toolUseIdOf(message) ?? '');
+ const startsNewSession =
+ previousTaskTodos === null ||
+ (
+ previousTaskTodos.every((todo) => todo.status === 'completed') &&
+ !taskToolTargetsExistingTask(message, resultText, taskState)
+ );
+ if (startsNewSession) taskState.clear();
+
+ const hadTaskContext = taskState.size > 0;
+ const parsed = applyTaskPlanTool(
+ taskState,
+ message,
+ resultText,
+ );
+ if (parsed) {
+ resolvedTaskContext = true;
+ previousTaskTodos = parsed;
+ continue;
+ }
+ if (index === latestPlanIndex) {
+ return resolvedTaskContext && hadTaskContext && taskState.size === 0;
+ }
+ }
+ return false;
+}
+
function buildToolResultLookup<TMessage extends MessageRenderSourceMessageLike>(
messages: readonly TMessage[],
): Map<string, string> {
@@ -638,6 +762,30 @@ function normalizeTaskStatus(status: unknown): MessageRenderTodoItem['status'] |
return null;
}
+function taskToolStatus(
+ message: MessageRenderSourceMessageLike,
+ resultText: string | undefined,
+): MessageRenderTodoItem['status'] | 'deleted' | null {
+ const toolName = toolNameOf(message);
+ const input = readRecord(toolInputOf(message));
+ const resultTask = taskRecordsFromResult(resultText)[0];
+ if (toolName === 'TaskGet' && resultTask) return normalizeTaskStatus(resultTask.status);
+ return normalizeTaskStatus(input?.status ?? resultTask?.status);
+}
+
+function taskToolTargetsExistingTask(
+ message: MessageRenderSourceMessageLike,
+ resultText: string | undefined,
+ taskState: ReadonlyMap<string, MessageRenderTodoItem>,
+): boolean {
+ const toolName = toolNameOf(message);
+ if (toolName !== 'TaskUpdate' && toolName !== 'TaskGet') return false;
+ const input = readRecord(toolInputOf(message));
+ const resultTask = taskRecordsFromResult(resultText)[0];
+ const id = taskId(input ?? undefined) ?? taskId(resultTask);
+ return Boolean(id && taskState.has(id));
+}
+
function extractStructuredPlanItems(items: unknown): MessageRenderTodoItem[] | null {
if (!Array.isArray(items) || items.length === 0) return null;
const todos = items
@@ -674,7 +822,13 @@ function applyTaskPlanTool(
const resultTasks = taskRecordsFromResult(resultText);
if (toolName === 'TaskList') {
- if (resultTasks.length === 0) return currentTaskTodos(taskState);
+ if (resultTasks.length === 0) {
+ if (taskListResultClearsPlan(resultText)) {
+ taskState.clear();
+ return null;
+ }
+ return currentTaskTodos(taskState);
+ }
const previousTaskState = new Map(taskState);
taskState.clear();
for (const task of resultTasks) {
@@ -739,6 +893,11 @@ function applyTaskPlanTool(
return currentTaskTodos(taskState);
}
+function taskListResultClearsPlan(resultText: string | undefined): boolean {
+ const parsed = tryParseJsonRecord(resultText);
+ return Boolean(parsed && Array.isArray(parsed.tasks) && parsed.tasks.length === 0);
+}
+
function currentTaskTodos(taskState: Map<string, MessageRenderTodoItem>): MessageRenderTodoItem[] | null {
const todos = [...taskState.values()].filter((todo) => todo.content.trim().length > 0);
return todos.length > 0 ? todos : null;