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): move plan progress into chat (#3054)

Kafeifei336d2bf9353e
diff --git a/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts b/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts
index 0bc741503d..893a429892 100644
--- a/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts
+++ b/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts
@@ -29,6 +29,8 @@ import {
insertForkOriginItem,
isScrollNavigationKey,
pickDeleteCompensationAnchorKey,
+ isPlanCardVisibleInViewport,
+ planSessionBelongsToLatestUserTurn,
shouldBlockAssistantFork,
type RenderItem,
} from '../components/chat/MessageStream';
@@ -121,6 +123,64 @@ const todoInput = (items: Array<{ content: string; status: 'pending' | 'in_progr
})),
});
+const rect = (top: number, bottom: number, left = 0, right = 100) => ({
+ top,
+ right,
+ bottom,
+ left,
+ width: right - left,
+ height: bottom - top,
+});
+
+describe('isPlanCardVisibleInViewport', () => {
+ const viewport = rect(0, 600, 0, 800);
+
+ it('treats a partially visible card as visible', () => {
+ expect(isPlanCardVisibleInViewport(rect(-20, 40), viewport)).toBe(true);
+ });
+
+ it('treats a card covered by the composer overlay as invisible', () => {
+ expect(isPlanCardVisibleInViewport(rect(520, 580), viewport, 100)).toBe(false);
+ });
+
+ it('keeps the card visible when any pixels remain above the composer overlay', () => {
+ expect(isPlanCardVisibleInViewport(rect(480, 540), viewport, 100)).toBe(true);
+ });
+});
+
+describe('planSessionBelongsToLatestUserTurn', () => {
+ it('does not reactivate an older plan when a later user turn starts', () => {
+ expect(
+ planSessionBelongsToLatestUserTurn(
+ [mkUser('u1'), mkTool('plan1', 'update_plan'), mkUser('u2')],
+ ['plan1'],
+ ),
+ ).toBe(false);
+ });
+
+ it('keeps steer rows inside the current plan turn', () => {
+ expect(
+ planSessionBelongsToLatestUserTurn(
+ [mkUser('u1'), mkTool('plan1', 'update_plan'), { ...mkUser('steer'), delivery: 'steer' }],
+ ['plan1'],
+ ),
+ ).toBe(true);
+ });
+
+ it('keeps synthetic continuation rows inside the current plan turn', () => {
+ expect(
+ planSessionBelongsToLatestUserTurn(
+ [
+ mkUser('u1'),
+ mkTool('plan1', 'update_plan'),
+ { ...mkUser('auto-resume'), isSyntheticTrigger: true },
+ ],
+ ['plan1'],
+ ),
+ ).toBe(true);
+ });
+});
+
describe('assistant fork boundary detection', () => {
it('allows assistant fork only after the turn has a following user boundary', () => {
const messages = [
@@ -531,48 +591,247 @@ describe('buildRenderItems — key stability', () => {
expect(taskItem.update?.summary).toBe('Found the relevant renderer path');
});
- // ── case 3: plan 工具调用被整体吞掉 —— 流内不再渲染计划卡 ────────────────
- // 计划的唯一呈现是 composer 上方的 PinnedPlanPanel(Codex IDE 扩展式钉住面板)。
+ // ── case 3:plan session 在流内只产一张 stable-key 卡 ─────────────────────
// session 分组 / 输入解析语义的覆盖在 @cindy/maker-shared 的 messageRender.test.ts;
- // 这里只锁桌面流内行为:不产 item、不切段、结尾不留无效 tail。
+ // 这里只锁桌面时间线行为:多步骤计划插卡,单步骤计划继续保持紧凑。
- it('plan tool calls are swallowed without splitting the surrounding tool segment', () => {
+ it('inserts a multi-step plan card between surrounding tool segments', () => {
const seq: ChatMessage[] = [
mkUser('u1'),
mkTool('t1', 'Bash'),
- mkTool('tw1', 'TodoWrite', todoInput([{ content: 'a', status: 'pending' }])),
+ mkTool(
+ 'tw1',
+ 'TodoWrite',
+ todoInput([
+ { content: 'Inspect state', status: 'completed' },
+ { content: 'Patch renderer', status: 'in_progress' },
+ ]),
+ ),
mkResult('r-tw1', 'tu-tw1', 'ok'),
mkTool('t2', 'Read'),
mkAssistant('a1', 'done'),
];
const { items } = buildRenderItems(seq);
- // 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']);
+ expect(items.map((it) => it.type)).toEqual([
+ 'message',
+ 'tool_segment',
+ 'agent_plan',
+ 'tool_segment',
+ 'message',
+ ]);
+ const plan = items[2] as Extract<RenderItem, { type: 'agent_plan' }>;
+ expect(plan.key).toBe('todo-tw1');
+ expect(plan.sourceClientIds).toEqual(['tw1']);
+ expect(plan.todos.map((todo) => todo.content)).toEqual(['Inspect state', 'Patch renderer']);
});
- 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' }],
+ it('updates one logical plan card at the latest row while keeping its first key', () => {
+ const first = mkTool('plan1', 'update_plan', {
+ plan: [
+ { step: 'Read code', status: 'in_progress' },
+ { step: 'Patch renderer', status: 'pending' },
+ ],
});
- const taskCreate = mkTool('tc1', 'TaskCreate', { subject: 'Collect logs' });
+ const second = mkTool('plan2', 'update_plan', {
+ plan: [
+ { step: 'Read code', status: 'completed' },
+ { step: 'Patch renderer', status: 'in_progress' },
+ ],
+ });
+
+ const { items } = buildRenderItems([
+ mkUser('u1'),
+ first,
+ mkTool('t1', 'Read'),
+ second,
+ mkAssistant('a1', 'On it'),
+ ]);
+
+ const plans = items.filter(
+ (item): item is Extract<RenderItem, { type: 'agent_plan' }> => item.type === 'agent_plan',
+ );
+ expect(plans).toHaveLength(1);
+ expect(plans[0].key).toBe('todo-plan1');
+ expect(plans[0].sourceClientIds).toEqual(['plan1', 'plan2']);
+ expect(plans[0].todos).toEqual([
+ { content: 'Read code', status: 'completed' },
+ { content: 'Patch renderer', status: 'in_progress' },
+ ]);
+ });
- const { items } = buildRenderItems([mkUser('u1'), plan, taskCreate, mkAssistant('a1', 'On it')]);
+ it('renders a reconstructed multi-step Task plan as one inline card', () => {
+ const first = mkTool('tc1', 'TaskCreate', { subject: 'Collect logs' });
+ const second = mkTool('tc2', 'TaskCreate', { subject: 'Run tests' });
+
+ const { items } = buildRenderItems([
+ mkUser('u1'),
+ first,
+ mkResult('r-tc1', 'tu-tc1', 'Task #1 created successfully: Collect logs'),
+ second,
+ mkResult('r-tc2', 'tu-tc2', 'Task #2 created successfully: Run tests'),
+ mkAssistant('a1', 'On it'),
+ ]);
- expect(items.map((it) => it.type)).toEqual(['message', 'message']);
+ expect(items.map((it) => it.type)).toEqual(['message', 'agent_plan', 'message']);
+ const plan = items[1] as Extract<RenderItem, { type: 'agent_plan' }>;
+ expect(plan.key).toBe('todo-tc1');
+ expect(plan.todos.map((todo) => todo.content)).toEqual(['Collect logs', 'Run tests']);
});
- it('a trailing plan call keeps the tail invariant on the previous valid item', () => {
+ it('keeps a single-step plan suppressed without splitting the surrounding tool segment', () => {
const { items } = buildRenderItems([
mkUser('u1'),
- mkTool('tw1', 'TodoWrite', todoInput([{ content: 'a', status: 'pending' }])),
+ mkTool('t1', 'Bash'),
+ mkTool('tw1', 'TodoWrite', todoInput([{ content: 'Only step', status: 'pending' }])),
mkResult('r-tw1', 'tu-tw1', 'ok'),
+ mkTool('t2', 'Read'),
+ mkAssistant('a1', 'done'),
]);
- expect(items.map((it) => it.type)).toEqual(['message']);
+ expect(items.map((it) => it.type)).toEqual(['message', 'tool_segment', 'message']);
+ const segment = items[1] as Extract<RenderItem, { type: 'tool_segment' }>;
+ expect(segment.toolCalls.map((tool) => tool.clientId)).toEqual(['t1', 't2']);
+ });
+
+ it('waits for older Task history before showing a partial inline plan', () => {
+ const first = mkTool('tc2', 'TaskCreate', { subject: 'Fix renderer' });
+ const second = mkTool('tc3', 'TaskCreate', { subject: 'Run tests' });
+ const messages = [
+ first,
+ mkResult('r-tc2', 'tu-tc2', 'Task #2 created successfully: Fix renderer'),
+ second,
+ mkResult('r-tc3', 'tu-tc3', 'Task #3 created successfully: Run tests'),
+ ];
+
+ expect(
+ buildRenderItems(messages, undefined, undefined, { historyWindowIncomplete: true }).items,
+ ).toEqual([]);
+ expect(
+ buildRenderItems(messages, undefined, undefined, {
+ historyWindowIncomplete: false,
+ }).items.map((item) => item.type),
+ ).toEqual(['agent_plan']);
+ });
+
+ it('filters an earlier partial Task card when a later plan session is resolved', () => {
+ const messages = [
+ mkTool('tc2', 'TaskCreate', { subject: 'Fix renderer' }),
+ mkResult('r-tc2', 'tu-tc2', 'Task #2 created successfully: Fix renderer'),
+ mkTool('tc3', 'TaskCreate', { subject: 'Run tests' }),
+ mkResult('r-tc3', 'tu-tc3', 'Task #3 created successfully: Run tests'),
+ mkUser('u2', 'Start a different plan'),
+ mkTool('plan2', 'update_plan', {
+ plan: [
+ { step: 'Read code', status: 'in_progress' },
+ { step: 'Patch renderer', status: 'pending' },
+ ],
+ }),
+ ];
+
+ const plans = buildRenderItems(messages, undefined, undefined, {
+ historyWindowIncomplete: true,
+ }).items.filter(
+ (item): item is Extract<RenderItem, { type: 'agent_plan' }> => item.type === 'agent_plan',
+ );
+
+ expect(plans).toHaveLength(1);
+ expect(plans[0].key).toBe('todo-plan2');
+ });
+
+ it('keeps an authoritative TaskList card when its result follows the insertion row', () => {
+ const messages = [
+ mkUser('u1', 'Show the current tasks'),
+ mkTool('task-list', 'TaskList'),
+ mkResult(
+ 'r-task-list',
+ 'tu-task-list',
+ JSON.stringify({
+ tasks: [
+ { id: '1', subject: 'Inspect renderer', status: 'in_progress' },
+ { id: '2', subject: 'Run tests', status: 'pending' },
+ ],
+ }),
+ ),
+ ];
+
+ const plans = buildRenderItems(messages, undefined, undefined, {
+ historyWindowIncomplete: true,
+ }).items.filter(
+ (item): item is Extract<RenderItem, { type: 'agent_plan' }> => item.type === 'agent_plan',
+ );
+
+ expect(plans).toHaveLength(1);
+ expect(plans[0]).toMatchObject({
+ key: 'todo-task-list',
+ todos: [
+ { content: 'Inspect renderer', status: 'in_progress' },
+ { content: 'Run tests', status: 'pending' },
+ ],
+ });
+ });
+
+ it('renders a new Task plan after a real user turn despite an older orphan update', () => {
+ const messages = [
+ mkTool('old-update', 'TaskUpdate', { taskId: 'old', status: 'in_progress' }),
+ mkUser('u2', 'Start a new plan'),
+ mkTool('new-task-1', 'TaskCreate', { subject: 'Inspect renderer' }),
+ mkResult(
+ 'r-new-task-1',
+ 'tu-new-task-1',
+ 'Task #new-1 created successfully: Inspect renderer',
+ ),
+ mkTool('new-task-2', 'TaskCreate', { subject: 'Run tests' }),
+ mkResult(
+ 'r-new-task-2',
+ 'tu-new-task-2',
+ 'Task #new-2 created successfully: Run tests',
+ ),
+ ];
+
+ const plans = buildRenderItems(messages, undefined, undefined, {
+ historyWindowIncomplete: true,
+ }).items.filter(
+ (item): item is Extract<RenderItem, { type: 'agent_plan' }> => item.type === 'agent_plan',
+ );
+
+ expect(plans).toHaveLength(1);
+ expect(plans[0]).toMatchObject({
+ key: 'todo-new-task-1',
+ todos: [
+ { content: 'Inspect renderer', status: 'pending' },
+ { content: 'Run tests', status: 'pending' },
+ ],
+ });
+ });
+
+ it('recovers an old plan anchor after prepend changes the session key', () => {
+ const oldWindow = buildRenderItems([
+ mkTool('plan2', 'update_plan', {
+ plan: [
+ { step: 'Read code', status: 'completed' },
+ { step: 'Patch renderer', status: 'in_progress' },
+ ],
+ }),
+ ]).items;
+ const prepended = buildRenderItems([
+ mkTool('plan1', 'update_plan', {
+ plan: [
+ { step: 'Read code', status: 'in_progress' },
+ { step: 'Patch renderer', status: 'pending' },
+ ],
+ }),
+ mkTool('plan2', 'update_plan', {
+ plan: [
+ { step: 'Read code', status: 'completed' },
+ { step: 'Patch renderer', status: 'in_progress' },
+ ],
+ }),
+ ]).items;
+
+ expect(oldWindow[0]?.key).toBe('todo-plan2');
+ expect(prepended[0]?.key).toBe('todo-plan1');
+ expect(findRestorableViewportItemIdx(prepended, 'todo-plan2')).toBe(0);
});
// ── case 4: orphan tool_result 补到末尾不产生新 item / 不重 key ─────────
@@ -1134,13 +1393,20 @@ describe('groupWorkRuns — work-group collapsing', () => {
]);
});
- 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' }]));
- // 正文前后各放一次:两个位置都不应折出 work_group,也不应出现任何计划 item。
+ it('keeps inline plan cards outside work-group folding', () => {
+ const todo = mkTool(
+ 'tw1',
+ 'TodoWrite',
+ todoInput([
+ { content: 'Inspect', status: 'completed' },
+ { content: 'Patch', status: 'in_progress' },
+ ]),
+ );
+ // 正文前后各放一次:两个位置都保留流内计划卡,且不折进 work_group。
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']);
+ expect(before.map((it) => it.type)).toEqual(['message', 'agent_plan', 'message']);
+ expect(after.map((it) => it.type)).toEqual(['message', 'message', 'agent_plan']);
});
it('computes durationMs from the previous boundary (user message) to the terminating text createdAt', () => {
diff --git a/apps/desktop/src/renderer/__tests__/workGroupHistoryGap.test.ts b/apps/desktop/src/renderer/__tests__/workGroupHistoryGap.test.ts
index ce1ac73ddd..75846d83f0 100644
--- a/apps/desktop/src/renderer/__tests__/workGroupHistoryGap.test.ts
+++ b/apps/desktop/src/renderer/__tests__/workGroupHistoryGap.test.ts
@@ -422,8 +422,8 @@ describe('历史窗口空洞 — 正常 turn 不受影响', () => {
//
// ghost_card(意识供卡)是那次调用在流里的**唯一**呈现——工具行被卡片取代、不再
// 单独渲染。它原先在 renderItemStartMs / renderItemEndMs 里没有分支,一律报 null。
-// (agent_plan 卡曾同属此类;计划卡现已整体移出流内,唯一呈现改为 composer 上方的
-// PinnedPlanPanel,不再参与流内时间判定。)
+// agent_plan 也属于同类:计划工具行被流内卡取代,卡片本身必须继续参与时间判定;
+// composer 上方的 PinnedPlanPanel 只在流内卡离开可见区域后接力。
//
// 实测过后果的具体形状(两侧都跑过,只留能真正区分的断言):
// - 工作组切分本身**不受影响**:卡会被 groupAnsweredTurnItems 提到组外,而空洞后
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index ff60a5be23..ff9400f9bf 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -38,8 +38,11 @@ import {
type AgentTaskTerminalStatus,
} from '@cindy/maker-shared/agent-task';
import {
+ findMessageTodoInsertions,
+ getLatestMessageTodoState,
isAgentPlanToolName,
isDeliveryProseText,
+ isPlanUserBoundary,
isSubagentParentToolUseId,
} from '@cindy/maker-shared/message-render';
// 子代理卡判据只能有一份:此前桌面自带一份只认 Agent/Task/collab:* 的副本,新增 harness
@@ -222,6 +225,7 @@ import { ErrorMessageCard } from './ErrorMessageCard';
import { APP_EXIT_INTERRUPTED_REASON } from '../../../shared/interruptedTurn';
import { PlanReviewBubble } from './PlanReviewBubble';
import { ToolCallCard, getToolSummary } from './ToolCallCard';
+import { InlinePlanCard, type TodoItem } from './TodoListCard';
import { SystemCard } from './SystemCard';
import { NewMessageIndicator } from './NewMessageIndicator';
import { ThinkingCard } from './ThinkingCard';
@@ -342,6 +346,8 @@ interface MessageStreamProps {
onLoadMore?: (automatic?: boolean) => Promise<boolean>;
isLoadingMore?: boolean;
hasMoreMessages?: boolean;
+ /** 当前逻辑历史窗口中间仍有缺口;与 hasMoreMessages 一样会让父调用归属不可信。 */
+ historyWindowHasIsland?: boolean;
/** Dynamic bottom padding (px) to reserve space for the input overlay */
bottomPadding?: number;
/** Distance from the chat viewport bottom to the visible composer stack top. */
@@ -376,6 +382,16 @@ interface MessageStreamProps {
* Split panes keep every MessageStream mounted; only the focused owner may act.
*/
ownsHardwareScrollActions?: boolean;
+ /**
+ * 当前计划的流内卡是否仍在用户可见区域。父层据此决定 composer 上方的
+ * 兜底胶囊是否需要接力;key 防止新旧计划切换时沿用上一张卡的可见状态。
+ */
+ onInlinePlanVisibilityChange?: (state: InlinePlanVisibility | null) => void;
+}
+
+export interface InlinePlanVisibility {
+ key: string;
+ visible: boolean;
}
// ---------------------------------------------------------------------------
@@ -392,6 +408,15 @@ interface MessageStreamProps {
// 引用这两个成员(WorkChildItem),让「children 只含这两类」由类型系统保证,
// 渲染处无需 as 强转;其余成员保持内联。
type MessageRenderItem = { type: 'message'; key: string; message: ChatMessage };
+type AgentPlanRenderItem = {
+ type: 'agent_plan';
+ key: string;
+ todos: TodoItem[];
+ /** 同一 session 的计划工具行;历史 prepend 改变首行 key 后仍可恢复旧锚点。 */
+ sourceClientIds: string[];
+ /** 计划调用在流里的位置与时间锚点;原 tool_use 行由本卡取代。 */
+ createdAt?: string;
+};
type ToolSegmentRenderItem = {
/** A run of consecutive tool_use messages between text segments,
* rendered as a single AgentActionsBlock. v2 — no isStreaming
@@ -468,6 +493,7 @@ interface WorkGroupRenderItem {
export type RenderItem =
| MessageRenderItem
+ | AgentPlanRenderItem
| ToolSegmentRenderItem
| AgentTaskRenderItem
| ForkOriginRenderItem
@@ -582,6 +608,47 @@ export function shouldBoostDefaultWindow({
return visibleItemCount < allItemCount;
}
+type VisibilityRect = Pick<DOMRect, 'top' | 'right' | 'bottom' | 'left' | 'width' | 'height'>;
+
+/**
+ * 判定流内计划卡是否至少有一个可见像素。
+ *
+ * scroll 容器底部被 composer overlay 覆盖,单看容器的 DOMRect 会把“实际藏在
+ * 输入框后面”误判为可见,所以把 overlay 高度作为 bottomInset 从可视区扣掉。
+ */
+export function isPlanCardVisibleInViewport(
+ card: VisibilityRect,
+ viewport: VisibilityRect,
+ bottomInset = 0,
+): boolean {
+ if (card.width <= 0 || card.height <= 0 || viewport.width <= 0 || viewport.height <= 0) {
+ return false;
+ }
+ const safeBottomInset = Math.min(Math.max(0, bottomInset), Math.max(0, viewport.height - 1));
+ const visibleBottom = viewport.bottom - safeBottomInset;
+ return (
+ card.bottom > viewport.top &&
+ card.top < visibleBottom &&
+ card.right > viewport.left &&
+ card.left < viewport.right
+ );
+}
+
+export function planSessionBelongsToLatestUserTurn(
+ messages: readonly ChatMessage[],
+ sourceClientIds: readonly string[],
+): boolean {
+ const sourceIds = new Set(sourceClientIds);
+ let latestNormalUserIndex = -1;
+ let latestPlanRowIndex = -1;
+ for (let index = 0; index < messages.length; index += 1) {
+ const message = messages[index];
+ if (isPlanUserBoundary(message)) latestNormalUserIndex = index;
+ if (sourceIds.has(message.clientId)) latestPlanRowIndex = index;
+ }
+ return latestPlanRowIndex >= 0 && latestNormalUserIndex <= latestPlanRowIndex;
+}
+
export function resolveDefaultWindowStartIdx({
allItemCount,
defaultWindowItems,
@@ -899,12 +966,10 @@ export function collectTurnFinalAssistantClientIds(messages: readonly ChatMessag
* collapsed; user click → persisted).
*
* 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 快照,与本函数无关。
+ * Pass 1 groups TodoWrite / update_plan / Task* calls into logical plan
+ * sessions. Pass 2 replaces each session's latest tool row with one
+ * `agent_plan` item in the chat timeline. The composer capsule observes the
+ * latest inline card and only takes over after that card leaves the viewport.
*/
/**
* 锚点丢失恢复:DB 加载更老历史 prepend 时,若新拉回的末尾是 tool_use 且当前
@@ -917,7 +982,8 @@ export function collectTurnFinalAssistantClientIds(messages: readonly ChatMessag
* 扫描 allRenderItems 找哪个 item **现在覆盖**这个 clientId:
* - message: msg.clientId 严格匹配
* - tool_segment: toolCalls.*.clientId 任一匹配(段合并后老 toolCall 仍在新段内)
- * - tool_media / ghost_card: 用 key 后缀匹配(它们的 key 派生自 stable message clientId)
+ * - tool_media / ghost_card:用派生 key 后缀匹配
+ * - agent_plan:除 key 外还保留 session 内全部计划行的 clientId
*
* 找到即返回该 index,visible slice 从这里继续;找不到才退回默认窗口。
*
@@ -941,6 +1007,14 @@ function recoverLostAnchorIdx(items: RenderItem[], lostKey: string): number {
if (it.toolCalls.some((tc) => tc.clientId === lostCid)) return i;
} else if (it.type === 'agent_task') {
if (it.toolCall?.clientId === lostCid) return i;
+ } else if (it.type === 'agent_plan') {
+ if (
+ it.key === lostKey ||
+ it.key.endsWith(`-${lostCid}`) ||
+ it.sourceClientIds.includes(lostCid)
+ ) {
+ return i;
+ }
} else if (it.type === 'work_group') {
// work_group 可能嵌套完成态时间线 — 老锚点(`seg-${cid}` /
// `msg-${cid}` / `work-${cid}`)递归落到任一后代即由外组接住。
@@ -1398,6 +1472,47 @@ export function buildRenderItems(
}
}
+ // ── Pass 1: group plan events into timeline cards ──
+ // 分组与 composer 兜底胶囊共用 maker-shared 的同一口径。历史窗口不完整时
+ // Task* 计划先不画半张卡,等更早页补齐后再由同一 stable key 插入。
+ const planInsertAt = findMessageTodoInsertions(messages, {
+ taskHistoryMayBeIncomplete: opts?.historyWindowIncomplete === true,
+ });
+ // findMessageTodoInsertions 负责完整历史时间线,不会自行裁掉分页窗口里的半截
+ // Task session。不能只检查整窗「最新」计划:后面若已有可解析的新 session,
+ // 较早的半截 Task 卡仍会漏出来。逐个 Task insertion 用其前缀复核,等 prepend
+ // 补齐标题/早期 TaskCreate 后再由同一 stable key 插回。
+ if (opts?.historyWindowIncomplete === true) {
+ for (const [index, insertion] of planInsertAt) {
+ if (insertion.source !== 'task') continue;
+ const prefix = messages.slice(0, index + 1);
+ const prefixPlanToolUseIds = new Set(
+ prefix
+ .filter((message) => isAgentPlanToolName(message.toolName))
+ .map((message) => message.toolUseId)
+ .filter((toolUseId): toolUseId is string => Boolean(toolUseId)),
+ );
+ // TaskList / TaskGet 的权威内容在后续 tool_result 行里。只切到工具行会把
+ // 已完整的 snapshot 重新判成半截;保留当前前缀中计划调用的匹配结果,但
+ // 不把后续计划事件带进来,避免改变「正在复核哪张 insertion」的语义。
+ const validationMessages = [
+ ...prefix,
+ ...messages.slice(index + 1).filter(
+ (message) =>
+ message.role === 'tool_result' &&
+ typeof message.toolUseId === 'string' &&
+ prefixPlanToolUseIds.has(message.toolUseId),
+ ),
+ ];
+ const stateAtInsertion = getLatestMessageTodoState(validationMessages, {
+ taskHistoryMayBeIncomplete: true,
+ });
+ if (!stateAtInsertion.isResolved || stateAtInsertion.latestInsertionIndex !== index) {
+ planInsertAt.delete(index);
+ }
+ }
+ }
+
const isOrcaCommunicationTool = (toolName: string): boolean => {
const normalized = toolName.replace(/^mcp__/, 'mcp:').replace(/__/g, ':');
return (
@@ -1631,10 +1746,22 @@ export function buildRenderItems(
continue;
}
- // Plan tools (TodoWrite / update_plan / Task*) — swallowed like F7:
- // 计划的唯一呈现是 composer 上方的 PinnedPlanPanel(钉住式常驻面板),
- // 流内不再插卡;也不切段,周围工具保持聚组,如同调用不存在。
+ // Plan tools (TodoWrite / update_plan / Task*)由流内计划卡取代。只有
+ // session 的最新快照所在行插卡;中间更新只刷新同一 stable-key 卡片。
if (isAgentPlanToolName(toolName)) {
+ const insertion = planInsertAt.get(i);
+ // 与悬浮胶囊保持一致:单步清单不占计划 UI;没有可画卡片时也不切开
+ // 周围工具段,保留旧的紧凑聚组语义。
+ if (insertion && insertion.todos.length >= 2) {
+ flushSegment();
+ items.push({
+ type: 'agent_plan',
+ key: insertion.key,
+ todos: insertion.todos,
+ sourceClientIds: insertion.sourceClientIds,
+ createdAt: msg.createdAt,
+ });
+ }
let j = i + 1;
while (j < messages.length && messages[j].role === 'tool_result') j++;
i = j;
@@ -2108,6 +2235,7 @@ function renderItemContainsClientId(item: RenderItem, clientId: string): boolean
if (item.type === 'tool_segment')
return item.toolCalls.some((toolCall) => toolCall.clientId === clientId);
if (item.type === 'agent_task') return item.toolCall?.clientId === clientId;
+ if (item.type === 'agent_plan') return item.sourceClientIds.includes(clientId);
if (item.type === 'work_group') {
return item.children.some((child) => renderItemContainsClientId(child, clientId));
}
@@ -2127,6 +2255,10 @@ function renderItemStartMs(item: RenderItem): number | null {
const ms = Date.parse(item.toolCall?.createdAt ?? item.update?.createdAt ?? '');
return Number.isFinite(ms) ? ms : null;
}
+ if (item.type === 'agent_plan') {
+ const ms = Date.parse(item.createdAt ?? '');
+ return Number.isFinite(ms) ? ms : null;
+ }
// ghost_card 是那次调用在流里的**唯一**呈现(工具行被卡片取代),所以它必须
// 报出调用时间。漏掉的后果是间隔判定把它当"无时间戳"跳过:空洞后的第一个
// 动作恰好是卡片时切不开,卡片还会被归到空洞前那一组里(#676 review)。
@@ -2804,6 +2936,7 @@ export function MessageStream({
onLoadMore,
isLoadingMore,
hasMoreMessages,
+ historyWindowHasIsland = false,
bottomPadding,
composerStackTopOffset,
contentWidth,
@@ -2813,6 +2946,7 @@ export function MessageStream({
onOpenForkOrigin,
isLocalUserSend,
ownsHardwareScrollActions = true,
+ onInlinePlanVisibilityChange,
}: MessageStreamProps) {
// 右上角 chip 栈插槽 —— PrevMessageJumpChip 通过 portal 挂到这里,
// 与 DiffPanelToggle 在同一栈中各占一行。Provider 不存在时返回 null,
@@ -3047,11 +3181,21 @@ export function MessageStream({
const { items: ungroupedRenderItems, singleResultMap } = useMemo(
() =>
buildRenderItems(messages, taskUpdates, ghostCardSnapshot, {
- historyWindowIncomplete: Boolean(hasMoreMessages),
+ historyWindowIncomplete:
+ !historyLoaded || Boolean(hasMoreMessages) || historyWindowHasIsland,
turnChangeSets,
workingDir,
}),
- [messages, taskUpdates, ghostCardSnapshot, hasMoreMessages, turnChangeSets, workingDir],
+ [
+ messages,
+ taskUpdates,
+ ghostCardSnapshot,
+ historyLoaded,
+ hasMoreMessages,
+ historyWindowHasIsland,
+ turnChangeSets,
+ workingDir,
+ ],
);
const assistantsWithFollowingUserBoundary = useMemo(
() => collectAssistantsWithFollowingUserBoundary(visibleMessages),
@@ -3073,6 +3217,21 @@ export function MessageStream({
() => insertForkOriginItem(groupWorkRuns(ungroupedRenderItems, isSessionStreaming), forkOrigin),
[ungroupedRenderItems, isSessionStreaming, forkOrigin],
);
+ const latestInlinePlan = useMemo(() => {
+ for (let index = allRenderItems.length - 1; index >= 0; index -= 1) {
+ const item = allRenderItems[index];
+ if (item.type === 'agent_plan') return item;
+ }
+ return null;
+ }, [allRenderItems]);
+ const latestInlinePlanKey = latestInlinePlan?.key ?? null;
+ const latestInlinePlanBelongsToActiveTurn = useMemo(
+ () =>
+ latestInlinePlan
+ ? planSessionBelongsToLatestUserTurn(messages, latestInlinePlan.sourceClientIds)
+ : false,
+ [latestInlinePlan, messages],
+ );
/**
* render-window-bidirectional 已实施:锚定窗口改为双向有界
@@ -5343,6 +5502,79 @@ export function MessageStream({
composerStackTopOffset,
});
+ const latestInlinePlanRendered = Boolean(
+ latestInlinePlanKey && visibleRenderItems.some((item) => item.key === latestInlinePlanKey),
+ );
+ useLayoutEffect(() => {
+ if (!onInlinePlanVisibilityChange) return;
+ if (!latestInlinePlanKey) {
+ onInlinePlanVisibilityChange(null);
+ return;
+ }
+ // shell-first 的首帧故意不挂消息树。此时保持“未知”而不是误报不可见,避免
+ // 品牌 loading 帧里 composer 胶囊抢先闪一下。
+ if (firstMountDeferred) return;
+
+ const root = scrollRef.current;
+ const card = root
+ ? [...root.querySelectorAll<HTMLElement>('[data-inline-plan-key]')].find(
+ (candidate) => candidate.dataset.inlinePlanKey === latestInlinePlanKey,
+ )
+ : undefined;
+ if (!root || !card || !latestInlinePlanRendered) {
+ onInlinePlanVisibilityChange({ key: latestInlinePlanKey, visible: false });
+ return;
+ }
+
+ const bottomInset = Math.min(
+ Math.max(0, resolvedBottomPadding),
+ Math.max(0, root.clientHeight - 1),
+ );
+ const reportMeasuredVisibility = () => {
+ onInlinePlanVisibilityChange({
+ key: latestInlinePlanKey,
+ visible: isPlanCardVisibleInViewport(
+ card.getBoundingClientRect(),
+ root.getBoundingClientRect(),
+ bottomInset,
+ ),
+ });
+ };
+
+ // 首次结果在 paint 前同步给父层,计划刚出现时不会先闪一次悬浮胶囊。
+ reportMeasuredVisibility();
+
+ if (typeof IntersectionObserver !== 'undefined') {
+ const observer = new IntersectionObserver(reportMeasuredVisibility, {
+ root,
+ rootMargin: `0px 0px -${bottomInset}px 0px`,
+ threshold: 0,
+ });
+ observer.observe(card);
+ return () => observer.disconnect();
+ }
+
+ // Electron 正常支持 IntersectionObserver;测试壳或极老 runtime 缺失时用
+ // 轻量 scroll/resize 兜底,不能因为能力缺失让胶囊永久不出现。
+ root.addEventListener('scroll', reportMeasuredVisibility, { passive: true });
+ window.addEventListener('resize', reportMeasuredVisibility);
+ const resizeObserver =
+ typeof ResizeObserver !== 'undefined' ? new ResizeObserver(reportMeasuredVisibility) : null;
+ resizeObserver?.observe(root);
+ resizeObserver?.observe(card);
+ return () => {
+ root.removeEventListener('scroll', reportMeasuredVisibility);
+ window.removeEventListener('resize', reportMeasuredVisibility);
+ resizeObserver?.disconnect();
+ };
+ }, [
+ firstMountDeferred,
+ latestInlinePlanKey,
+ latestInlinePlanRendered,
+ onInlinePlanVisibilityChange,
+ resolvedBottomPadding,
+ ]);
+
// 「提及 → 兑现」关联(方案 2):从会话历史现算,软提示卡据此升级为召唤卡。
// 引用缓存:内容不变时复用上一个 Map 引用——UserMessage 顶层订阅该
// context,流式期间 messages 每批 delta 都换引用,不缓存会让全部历史
@@ -5441,6 +5673,21 @@ export function MessageStream({
return <ForkOriginMarker key={item.key} onClick={onOpenForkOrigin} />;
}
+ if (item.type === 'agent_plan') {
+ return (
+ <div key={item.key} data-inline-plan-key={item.key}>
+ <InlinePlanCard
+ todos={item.todos}
+ animated={
+ isSessionStreaming &&
+ latestInlinePlanBelongsToActiveTurn &&
+ item.key === latestInlinePlanKey
+ }
+ />
+ </div>
+ );
+ }
+
if (item.type === 'turn_changes') {
if (!sessionId) return null;
return (
diff --git a/apps/desktop/src/renderer/components/chat/TodoListCard.tsx b/apps/desktop/src/renderer/components/chat/TodoListCard.tsx
index be4fbbe276..3d1646e93a 100644
--- a/apps/desktop/src/renderer/components/chat/TodoListCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/TodoListCard.tsx
@@ -21,7 +21,15 @@
*/
import { useEffect, useId, useRef, useState } from 'react';
-import { CircleCheck, CircleDot, Circle, X } from 'lucide-react';
+import {
+ ChevronDown,
+ ChevronRight,
+ CircleCheck,
+ CircleDot,
+ Circle,
+ ListTodo,
+ X,
+} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import type { MessageRenderTodoItem } from '@cindy/maker-shared/message-render';
@@ -95,6 +103,133 @@ function ProgressRing({
);
}
+/**
+ * InlinePlanCard —— 计划在聊天时间线里的主呈现。
+ *
+ * 计划默认留在产生它的消息位置,用户滚回任务经过时能直接看到完整清单;
+ * composer 上方的 TodoListCard 只在这张卡离开可见区域后接力。两者消费同一份
+ * todos,但交互职责不同:流内卡负责阅读与历史,胶囊负责滚动后的轻量提醒。
+ */
+export function InlinePlanCard({
+ todos,
+ animated = false,
+}: {
+ todos: TodoItem[];
+ /** 只有会话确实在跑时,进行中行才呼吸;失败/中断后的历史卡保持静止。 */
+ animated?: boolean;
+}) {
+ const [expanded, setExpanded] = useState(true);
+
+ if (!todos || todos.length === 0) return null;
+
+ const completed = todos.filter((todo) => todo.status === 'completed').length;
+ const total = todos.length;
+ const progress = total > 0 ? (completed / total) * 100 : 0;
+ const activeItem = todos.find((todo) => todo.status === 'in_progress');
+ const summary = activeItem?.content ?? todos[todos.length - 1]?.content ?? '';
+
+ return (
+ <div className="flex w-full justify-start" data-inline-plan-card="true">
+ <div
+ className={cn(
+ 'max-w-full overflow-hidden rounded-[12px] border border-[var(--msg-tool-card-border)]',
+ 'bg-[var(--msg-tool-card-bg)]',
+ )}
+ >
+ <button
+ type="button"
+ aria-expanded={expanded}
+ onClick={() => setExpanded((current) => !current)}
+ className={cn(
+ 'flex w-full cursor-pointer select-none items-center gap-2 px-[14px] py-[10px]',
+ 'transition-opacity hover:opacity-80',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset',
+ 'focus-visible:ring-[var(--focus-ring)]',
+ )}
+ >
+ {expanded ? (
+ <ChevronDown size={14} className="shrink-0 text-[var(--msg-tool-card-chevron)]" />
+ ) : (
+ <ChevronRight size={14} className="shrink-0 text-[var(--msg-tool-card-chevron)]" />
+ )}
+ <ListTodo size={16} className="shrink-0 text-[var(--msg-tool-card-text)]" />
+ <span className="shrink-0 font-mono text-13 font-medium leading-none 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)]">
+ {summary}
+ </span>
+ </button>
+
+ {!expanded && (
+ <div className="h-[2px] w-full bg-[var(--todo-bar-track)]">
+ <div
+ className="h-full bg-[var(--msg-tool-card-text)] transition-[width] duration-[var(--motion-base)] ease-[var(--motion-ease-move)] motion-reduce:transition-none"
+ style={{ width: `${progress}%` }}
+ />
+ </div>
+ )}
+
+ {expanded && (
+ <div className="border-t border-[var(--msg-tool-card-border)] px-[14px] pb-[12px] pt-[10px]">
+ <div className="flex flex-col gap-[2px]">
+ {todos.map((todo, index) => (
+ <div
+ key={`${todo.content}:${index}`}
+ className="flex min-h-[30px] items-center gap-[10px]"
+ >
+ {todo.status === 'completed' && (
+ <CircleCheck
+ size={18}
+ strokeWidth={1.5}
+ className="shrink-0 text-[var(--msg-tool-card-chevron)]"
+ />
+ )}
+ {todo.status === 'in_progress' && (
+ <span
+ data-inline-plan-step-active="true"
+ data-inline-plan-step-breathing={animated ? 'true' : 'false'}
+ className={cn('inline-flex shrink-0', animated && 'session-status-breathing')}
+ >
+ <CircleDot
+ size={18}
+ strokeWidth={1.5}
+ className="shrink-0 text-[var(--msg-tool-card-text)]"
+ />
+ </span>
+ )}
+ {todo.status === 'pending' && (
+ <Circle
+ size={18}
+ strokeWidth={1.5}
+ className="shrink-0 text-[var(--msg-tool-card-text)]"
+ />
+ )}
+ <span
+ className={cn(
+ 'min-w-0 break-words text-13 leading-[1.45]',
+ todo.status === 'completed' &&
+ 'font-normal text-[var(--msg-tool-card-chevron)]',
+ todo.status === 'in_progress' &&
+ 'font-medium text-[var(--msg-tool-card-text)]',
+ todo.status === 'pending' && 'font-normal text-[var(--msg-tool-card-text)]',
+ )}
+ >
+ {todo.content}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/TodoListCard.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/TodoListCard.test.tsx
index a65092fac0..701f014e2f 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/TodoListCard.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/TodoListCard.test.tsx
@@ -3,7 +3,7 @@
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { TodoListCard } from '../TodoListCard';
+import { InlinePlanCard, TodoListCard } from '../TodoListCard';
vi.mock('react-i18next', () => ({
useTranslation: () => ({
@@ -229,3 +229,40 @@ describe('TodoListCard flyout interaction', () => {
expect(animatedContent.getAttribute('aria-hidden')).toBe('true');
});
});
+
+describe('InlinePlanCard', () => {
+ it('shows the shared focus ring when the collapse control is keyboard-focused', () => {
+ render(<InlinePlanCard todos={TODOS} animated={false} />);
+
+ const trigger = screen.getByRole('button');
+ expect(trigger.classList.contains('focus-visible:outline-none')).toBe(true);
+ expect(trigger.classList.contains('focus-visible:ring-2')).toBe(true);
+ expect(trigger.classList.contains('focus-visible:ring-[var(--focus-ring)]')).toBe(true);
+ });
+
+ it('starts expanded and can collapse back to a compact summary', () => {
+ const { container } = render(<InlinePlanCard todos={TODOS} animated={false} />);
+
+ const trigger = screen.getByRole('button');
+ expect(trigger.getAttribute('aria-expanded')).toBe('true');
+ expect(container.querySelector('[data-inline-plan-step-active="true"]')).not.toBeNull();
+
+ fireEvent.click(trigger);
+
+ expect(trigger.getAttribute('aria-expanded')).toBe('false');
+ expect(container.querySelector('[data-inline-plan-step-active="true"]')).toBeNull();
+ });
+
+ it('breathes the active inline step only while the session is running', () => {
+ const view = render(<InlinePlanCard todos={TODOS} animated />);
+ const active = view.container.querySelector('[data-inline-plan-step-active="true"]');
+
+ expect(active?.getAttribute('data-inline-plan-step-breathing')).toBe('true');
+ expect(active?.classList.contains('session-status-breathing')).toBe(true);
+
+ view.rerender(<InlinePlanCard todos={TODOS} animated={false} />);
+ const idle = view.container.querySelector('[data-inline-plan-step-active="true"]');
+ expect(idle?.getAttribute('data-inline-plan-step-breathing')).toBe('false');
+ expect(idle?.classList.contains('session-status-breathing')).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx b/apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx
index 9cb0844de1..80ebe5069a 100644
--- a/apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx
@@ -1,9 +1,9 @@
/**
* PinnedPlanPanel —— agent 计划清单的常驻胶囊(composer 上方)。
*
- * 对齐 Codex IDE 扩展的交互模型:计划不进聊天流(MessageStream 已把 plan 工具
- * 调用整体吞掉),唯一呈现就是这里 —— 输入框上方一枚居中小胶囊(Step N / M),
- * 鼠标悬停时完整清单以浮层向上展开,原地实时更新,不会被后续消息冲走。
+ * 计划的主呈现在聊天流内;当最新计划卡滚出可见区域后,这里以输入框上方一枚
+ * 居中小胶囊(Step N / M)接力。鼠标悬停时完整清单以浮层向上展开,原地实时
+ * 更新;滚回流内计划卡后胶囊再次隐藏。
* 数据从会话消息派生(findLatestMessageTodoInsertion):跨 source(TodoWrite /
* update_plan / Task*)取最近更新的 plan session 快照;历史 session 不再逐张
* 展示。无计划时返回 null,不占位。
@@ -11,16 +11,19 @@
* **退场条件是 host 的终态章,不是"步骤全勾完"**(`insertion.sealed`,来源见
* maker-shared 的 `terminalPlanSnapshot`)。agent 收尾时漏勾最后几步是常态,
* 以"全勾完"为退场条件会让干完的活儿永远挂在屏幕上;而中断、失败、断线自动
- * 续跑都不盖章,那种情况计划必须留着——任务还活着,用户正要接着指挥。
+ * 续跑都不盖章,那种情况在用户尚未继续指挥时留着。后续真实 user turn
+ * 是所有权边界:旧计划退场,除非 agent 在新 turn 再次 update_plan 明确认领。
*
- * 盖章后同样保留 2 秒再收起,时刻锚在章上(章落库,所以重载/新窗口看到的是
- * 同一个时刻,不会重新数 2 秒)。旧数据没有章,按"全勾完"兜底,行为不变。
- * 兜底只属于旧数据:turn 还在流式时,未盖章的 codex 计划正在等 host 的终态章,
- * 这时候按"全勾完"抢跑退场,会在章晚到(>2s)时先消失再被章复活闪回 2 秒。
+ * 未接入流内卡的旧调用方仍沿用“盖章后保留 2 秒再收起”。接入
+ * `inlinePlanVisibility` 后,进行中的计划由卡片可见性控制;完成后流内卡片
+ * 继续留在聊天记录里,但胶囊立即永久退场。
*/
import { useEffect, useMemo, useRef, useState } from 'react';
-import { getLatestMessageTodoState } from '@cindy/maker-shared/message-render';
+import {
+ getLatestMessageTodoState,
+ isPlanUserBoundary,
+} from '@cindy/maker-shared/message-render';
import { TodoListCard } from '@/components/chat/TodoListCard';
import type { ChatMessage } from '@/lib/makerChatStore';
@@ -36,6 +39,7 @@ export function PinnedPlanPanel({
taskHistoryMayBeIncomplete = false,
visible = true,
streaming = false,
+ inlinePlanVisibility,
className,
}: {
sessionId: string | null;
@@ -52,6 +56,11 @@ export function PinnedPlanPanel({
visible?: boolean;
/** turn 还在流式:未盖章的 codex 计划正在等终态章,不走"全勾完"兜底退场。 */
streaming?: boolean;
+ /**
+ * 同一计划在消息流中的可见状态。undefined 表示调用方未接入观察器(保持旧行为);
+ * null 表示观察器已接入但消息树尚未就绪;key 匹配且 visible 时由流内卡独家呈现。
+ */
+ inlinePlanVisibility?: { key: string; visible: boolean } | null;
className?: string;
}): React.ReactElement | null {
const todoState = useMemo(
@@ -59,18 +68,19 @@ export function PinnedPlanPanel({
[messages, taskHistoryMayBeIncomplete],
);
const insertion = todoState.insertion;
- // `streaming` is session-wide, but a legacy plan can outlive its turn. Only
- // suppress the legacy all-done fallback while the latest normal user turn
- // still owns this plan; steer rows do not start a new turn.
- const latestNormalUserIndex = useMemo(() => {
+ // `streaming` is session-wide, but a plan belongs to the user turn that last
+ // updated it. A later real user turn supersedes the old snapshot unless the
+ // agent explicitly calls update_plan again. Steer, scheduler/auto-resume, and
+ // subagent user rows are continuations rather than ownership boundaries.
+ const latestPlanUserBoundaryIndex = useMemo(() => {
for (let index = messages.length - 1; index >= 0; index -= 1) {
- const message = messages[index];
- if (message.role === 'user' && message.delivery !== 'steer') return index;
+ if (isPlanUserBoundary(messages[index])) return index;
}
return -1;
}, [messages]);
const planBelongsToLatestTurn =
- todoState.latestInsertionIndex < 0 || latestNormalUserIndex <= todoState.latestInsertionIndex;
+ todoState.latestInsertionIndex < 0 ||
+ latestPlanUserBoundaryIndex <= todoState.latestInsertionIndex;
const allDone = Boolean(
insertion &&
insertion.todos.length > 0 &&
@@ -80,16 +90,22 @@ export function PinnedPlanPanel({
// - turn 流式中且未盖章:正在等 host 的终态章,agent 提前勾完不算数——按
// allDone 抢跑会在章晚到时产生"消失再闪回";
// - host 给该行盖了 turnCompleted:false(中断/失败终态,见 persistCodexPlanOnDone):
- // 按设计不盖章,计划必须留在屏幕上供用户继续指挥,哪怕步骤恰好全勾完。
+ // 在用户尚未继续指挥时留在屏幕上,哪怕步骤恰好全勾完。后续真实
+ // user turn 一旦开始,旧失败印记不能继续冒充"当前计划";若确实继续,
+ // agent 会在新 turn 再次 update_plan 明确认领。
// TodoWrite / Task 永远不会有这两种印记,codex 旧历史数据也不会再有,它们照旧
// 走全勾完兜底——否则旧会话的计划会永远挂着。
const codexPlanAlive =
insertion?.source === 'codex' &&
insertion.sealed !== true &&
- ((streaming && planBelongsToLatestTurn) || insertion.turnFailed === true);
- // 退场 = host 盖了终态章(权威),或计划自己勾完了(没有章的旧数据兜底)。
+ planBelongsToLatestTurn &&
+ (streaming || insertion.turnFailed === true);
+ const supersededPlan = !planBelongsToLatestTurn;
+ // 退场 = host 盖了终态章(权威),或后续 user turn 已取代这份
+ // 计划(所有权边界),或计划自己勾完了(没有章的旧数据兜底)。
const retired =
- Boolean(insertion) && (insertion?.sealed === true || (allDone && !codexPlanAlive));
+ Boolean(insertion) &&
+ (insertion?.sealed === true || supersededPlan || (allDone && !codexPlanAlive));
const completedAtMs =
insertion?.sealedAtMs ?? insertion?.updatedAtMs ?? Date.parse(insertion?.createdAt ?? '');
// 章的时刻来自执行端时钟;device-link 被控场景下本机时钟可能与其偏差任意大。
@@ -144,6 +160,8 @@ export function PinnedPlanPanel({
const completedPlanExpired = Boolean(
completionDeadlineMs !== null && completionDeadlineMs <= Date.now(),
);
+ const completionRetirementEnabled = inlinePlanVisibility === undefined;
+ const completedInlinePlan = !completionRetirementEnabled && retired;
const [hiddenInsertionKey, setHiddenInsertionKey] = useState<string | null>(null);
const [dismissedSnapshotIdentity, setDismissedSnapshotIdentity] = useState<string | null>(null);
@@ -176,12 +194,18 @@ export function PinnedPlanPanel({
return () => window.clearTimeout(timer);
}, [retired, completionDeadlineMs, completionIdentity, insertion?.key]);
+ const hiddenByInlinePlan =
+ inlinePlanVisibility === null ||
+ (inlinePlanVisibility?.key === insertion?.key && inlinePlanVisibility?.visible === true);
+
if (
!visible ||
+ hiddenByInlinePlan ||
!insertion ||
insertion.todos.length < 2 ||
- completedPlanExpired ||
- hiddenInsertionKey === insertion.key ||
+ completedInlinePlan ||
+ (completionRetirementEnabled &&
+ (completedPlanExpired || hiddenInsertionKey === insertion.key)) ||
dismissedSnapshotIdentity === snapshotIdentity
)
return null;
diff --git a/apps/desktop/src/renderer/components/new-chat/__tests__/PinnedPlanPanel.test.tsx b/apps/desktop/src/renderer/components/new-chat/__tests__/PinnedPlanPanel.test.tsx
index 571c2ca7af..fc18f201f7 100644
--- a/apps/desktop/src/renderer/components/new-chat/__tests__/PinnedPlanPanel.test.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/__tests__/PinnedPlanPanel.test.tsx
@@ -51,6 +51,59 @@ function planMessage(
};
}
+function legacyPlanMessages(source: 'todo' | 'task'): ChatMessage[] {
+ if (source === 'todo') {
+ return [
+ {
+ clientId: 'todo-1',
+ role: 'tool_use',
+ content: '',
+ toolName: 'TodoWrite',
+ toolUseId: 'todo:turn-1',
+ toolInput: {
+ todos: [
+ { content: 'Inspect renderer', status: 'in_progress' },
+ { content: 'Run tests', status: 'pending' },
+ ],
+ },
+ createdAt: new Date(T0).toISOString(),
+ },
+ ];
+ }
+ return [
+ {
+ clientId: 'task-1',
+ role: 'tool_use',
+ content: '',
+ toolName: 'TaskCreate',
+ toolUseId: 'create-1',
+ toolInput: { subject: 'Inspect renderer' },
+ createdAt: new Date(T0).toISOString(),
+ },
+ {
+ clientId: 'result-1',
+ role: 'tool_result',
+ content: 'Task #1 created successfully: Inspect renderer',
+ toolUseId: 'create-1',
+ },
+ {
+ clientId: 'task-2',
+ role: 'tool_use',
+ content: '',
+ toolName: 'TaskCreate',
+ toolUseId: 'create-2',
+ toolInput: { subject: 'Run tests' },
+ createdAt: new Date(T0 + 1_000).toISOString(),
+ },
+ {
+ clientId: 'result-2',
+ role: 'tool_result',
+ content: 'Task #2 created successfully: Run tests',
+ toolUseId: 'create-2',
+ },
+ ];
+}
+
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(T0);
@@ -61,6 +114,111 @@ afterEach(() => {
vi.useRealTimers();
});
+describe('PinnedPlanPanel inline handoff', () => {
+ it('waits while the inline observer is not ready, then shows when the card is offscreen', () => {
+ const messages = [planMessage('in_progress')];
+ const view = render(
+ <PinnedPlanPanel
+ sessionId="inline-pending"
+ messages={messages}
+ animated
+ width={400}
+ inlinePlanVisibility={null}
+ />,
+ );
+
+ expect(screen.queryByTestId('plan-pill')).toBeNull();
+
+ view.rerender(
+ <PinnedPlanPanel
+ sessionId="inline-pending"
+ messages={messages}
+ animated
+ width={400}
+ inlinePlanVisibility={{ key: 'todo-plan-1', visible: false }}
+ />,
+ );
+ expect(screen.getByTestId('plan-pill')).not.toBeNull();
+ });
+
+ it('hides only for the matching visible inline plan card', () => {
+ const messages = [planMessage('in_progress')];
+ const view = render(
+ <PinnedPlanPanel
+ sessionId="inline-visible"
+ messages={messages}
+ animated
+ width={400}
+ inlinePlanVisibility={{ key: 'todo-plan-1', visible: true }}
+ />,
+ );
+
+ expect(screen.queryByTestId('plan-pill')).toBeNull();
+
+ view.rerender(
+ <PinnedPlanPanel
+ sessionId="inline-visible"
+ messages={messages}
+ animated
+ width={400}
+ inlinePlanVisibility={{ key: 'todo-older-plan', visible: true }}
+ />,
+ );
+ expect(screen.getByTestId('plan-pill')).not.toBeNull();
+ });
+
+ it('never hands off a completed plan after the inline card scrolls offscreen', () => {
+ const completed = planMessage('completed');
+ const view = render(
+ <PinnedPlanPanel
+ sessionId="inline-completed"
+ messages={[completed]}
+ animated={false}
+ width={400}
+ inlinePlanVisibility={{ key: 'todo-plan-1', visible: true }}
+ />,
+ );
+
+ expect(screen.queryByTestId('plan-pill')).toBeNull();
+ act(() => vi.advanceTimersByTime(2_000));
+
+ view.rerender(
+ <PinnedPlanPanel
+ sessionId="inline-completed"
+ messages={[completed]}
+ animated={false}
+ width={400}
+ inlinePlanVisibility={{ key: 'todo-plan-1', visible: false }}
+ />,
+ );
+ expect(screen.queryByTestId('plan-pill')).toBeNull();
+ });
+
+ it('removes an offscreen pill as soon as its inline plan completes', () => {
+ const view = render(
+ <PinnedPlanPanel
+ sessionId="inline-running-completes"
+ messages={[planMessage('in_progress')]}
+ animated
+ width={400}
+ inlinePlanVisibility={{ key: 'todo-plan-1', visible: false }}
+ />,
+ );
+ expect(screen.getByTestId('plan-pill')).not.toBeNull();
+
+ view.rerender(
+ <PinnedPlanPanel
+ sessionId="inline-running-completes"
+ messages={[planMessage('completed', T0, T0 + 1_000)]}
+ animated={false}
+ width={400}
+ inlinePlanVisibility={{ key: 'todo-plan-1', visible: false }}
+ />,
+ );
+ expect(screen.queryByTestId('plan-pill')).toBeNull();
+ });
+});
+
describe('PinnedPlanPanel completed plan lifetime', () => {
it('does not show a progress pill for a single-step plan', () => {
render(
@@ -529,6 +687,153 @@ describe('PinnedPlanPanel terminal seal', () => {
expect(screen.queryByTestId('plan-pill')).not.toBeNull();
});
+ it('retires an interrupted plan after a later real user turn supersedes it', () => {
+ const interrupted: ChatMessage = {
+ ...planMessage('in_progress'),
+ turnCompleted: false,
+ };
+ vi.setSystemTime(T0 + 60_000);
+
+ render(
+ <PinnedPlanPanel
+ sessionId="interrupted-then-new-turn"
+ messages={[
+ interrupted,
+ {
+ clientId: 'new-turn-user',
+ role: 'user',
+ content: 'Do something else instead',
+ createdAt: new Date(T0 + 30_000).toISOString(),
+ delivery: 'turn',
+ },
+ ]}
+ animated={false}
+ width={400}
+ />,
+ );
+
+ expect(screen.queryByTestId('plan-pill')).toBeNull();
+ });
+
+ it('retires an open legacy codex plan after a later real user turn supersedes it', () => {
+ vi.setSystemTime(T0 + 60_000);
+
+ render(
+ <PinnedPlanPanel
+ sessionId="legacy-open-then-new-turn"
+ messages={[
+ planMessage('in_progress'),
+ {
+ clientId: 'new-turn-user',
+ role: 'user',
+ content: 'Change direction',
+ createdAt: new Date(T0 + 30_000).toISOString(),
+ delivery: 'turn',
+ },
+ ]}
+ animated={false}
+ width={400}
+ />,
+ );
+
+ expect(screen.queryByTestId('plan-pill')).toBeNull();
+ });
+
+ it.each(['todo', 'task'] as const)(
+ 'retires an open legacy %s plan after a later real user turn supersedes it',
+ (source) => {
+ vi.setSystemTime(T0 + 60_000);
+
+ render(
+ <PinnedPlanPanel
+ sessionId={`${source}-open-then-new-turn`}
+ messages={[
+ ...legacyPlanMessages(source),
+ {
+ clientId: 'new-turn-user',
+ role: 'user',
+ content: 'Change direction',
+ createdAt: new Date(T0 + 30_000).toISOString(),
+ delivery: 'turn',
+ },
+ ]}
+ animated={false}
+ width={400}
+ inlinePlanVisibility={{
+ key: source === 'todo' ? 'todo-todo-1' : 'todo-task-1',
+ visible: false,
+ }}
+ />,
+ );
+
+ expect(screen.queryByTestId('plan-pill')).toBeNull();
+ },
+ );
+
+ it('keeps an interrupted plan across synthetic continuation user rows', () => {
+ const interrupted: ChatMessage = {
+ ...planMessage('in_progress'),
+ turnCompleted: false,
+ };
+ vi.setSystemTime(T0 + 60_000);
+
+ render(
+ <PinnedPlanPanel
+ sessionId="interrupted-auto-resume"
+ messages={[
+ interrupted,
+ {
+ clientId: 'auto-resume-user',
+ role: 'user',
+ content: '',
+ createdAt: new Date(T0 + 30_000).toISOString(),
+ delivery: 'turn',
+ isSyntheticTrigger: true,
+ },
+ ]}
+ animated={false}
+ width={400}
+ />,
+ );
+
+ expect(screen.queryByTestId('plan-pill')).not.toBeNull();
+ });
+
+ it('shows a plan again when the later user turn explicitly updates it', () => {
+ const interrupted: ChatMessage = {
+ ...planMessage('in_progress'),
+ turnCompleted: false,
+ };
+ const reclaimed: ChatMessage = {
+ ...planMessage('in_progress', T0 + 30_000),
+ clientId: 'plan-2',
+ toolUseId: 'plan:turn-2',
+ };
+ vi.setSystemTime(T0 + 60_000);
+
+ render(
+ <PinnedPlanPanel
+ sessionId="interrupted-then-reclaimed"
+ messages={[
+ interrupted,
+ {
+ clientId: 'new-turn-user',
+ role: 'user',
+ content: 'Continue this work',
+ createdAt: new Date(T0 + 20_000).toISOString(),
+ delivery: 'turn',
+ },
+ reclaimed,
+ ]}
+ animated
+ streaming
+ width={400}
+ />,
+ );
+
+ expect(screen.queryByTestId('plan-pill')).not.toBeNull();
+ });
+
it('shows the capsule again when a new plan update clears the seal', () => {
const view = render(
<PinnedPlanPanel
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index dbb1ba7bbe..76e07f5542 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -70,7 +70,7 @@ import { PluginSetupPrompt } from '@/components/new-chat/PluginSetupPrompt';
import { PlanViewerCard } from '@/components/new-chat/PlanViewerCard';
import { PlanActionCard } from '@/components/new-chat/PlanActionCard';
import { InteractionPromptHost } from '@/components/interaction-portal';
-import { MessageStream } from '@/components/chat/MessageStream';
+import { MessageStream, type InlinePlanVisibility } from '@/components/chat/MessageStream';
import {
readSendFollowCancelGeneration,
tryRequestFollowLatest,
@@ -1214,6 +1214,30 @@ export function CCAgentSessionView({
const [composerStackTopOffset, setComposerStackTopOffset] = useState<number | undefined>(
undefined,
);
+ const [inlinePlanVisibilityState, setInlinePlanVisibilityState] = useState<{
+ sessionId: string | undefined;
+ value: InlinePlanVisibility | null;
+ }>({ sessionId, value: null });
+ const inlinePlanVisibility =
+ inlinePlanVisibilityState.sessionId === sessionId ? inlinePlanVisibilityState.value : null;
+ const handleInlinePlanVisibilityChange = useCallback(
+ (value: InlinePlanVisibility | null) => {
+ setInlinePlanVisibilityState((current) => {
+ if (
+ current.sessionId === sessionId &&
+ current.value?.key === value?.key &&
+ current.value?.visible === value?.visible
+ ) {
+ return current;
+ }
+ if (current.sessionId === sessionId && current.value === null && value === null) {
+ return current;
+ }
+ return { sessionId, value };
+ });
+ },
+ [sessionId],
+ );
useEffect(() => {
if (!overlayEl) return;
@@ -3953,6 +3977,7 @@ export function CCAgentSessionView({
onLoadMore={loadOlderMessages}
isLoadingMore={isLoadingMore}
hasMoreMessages={hasMoreMessages}
+ historyWindowHasIsland={historyWindowHasIsland}
bottomPadding={overlayHeight}
composerStackTopOffset={composerStackTopOffset}
contentWidth={messageWidth}
@@ -3962,6 +3987,7 @@ export function CCAgentSessionView({
onOpenForkOrigin={handleOpenForkOrigin}
isLocalUserSend={isLocalUserSend}
ownsHardwareScrollActions={ownsHardwareTaskActions}
+ onInlinePlanVisibilityChange={handleInlinePlanVisibilityChange}
/>
);
@@ -4231,6 +4257,7 @@ export function CCAgentSessionView({
animated={isStreaming}
streaming={isStreaming}
width={inputWidth}
+ inlinePlanVisibility={inlinePlanVisibility}
taskHistoryMayBeIncomplete={
!historyLoaded || hasMoreMessages || historyWindowHasIsland
}
diff --git a/packages/maker-shared/src/__tests__/messageRender.test.ts b/packages/maker-shared/src/__tests__/messageRender.test.ts
index e2067ae039..b5a8e2f424 100644
--- a/packages/maker-shared/src/__tests__/messageRender.test.ts
+++ b/packages/maker-shared/src/__tests__/messageRender.test.ts
@@ -1388,6 +1388,87 @@ describe('message render todo grouping', () => {
});
});
+ it('resolves a new Task session after a real user boundary despite an older orphan update', () => {
+ const orphanUpdate = tool(
+ 'old-task-update',
+ 'TaskUpdate',
+ { taskId: 'old', status: 'in_progress' },
+ 'update-old',
+ );
+ const newUserTurn: MessageRenderSourceMessageLike = {
+ role: 'user',
+ clientId: 'user-2',
+ content: 'Start a new plan',
+ };
+ const first = tool('new-task-1', 'TaskCreate', { subject: 'Inspect renderer' }, 'create-new-1');
+ const second = tool('new-task-2', 'TaskCreate', { subject: 'Run tests' }, 'create-new-2');
+
+ expect(getLatestMessageTodoState([
+ orphanUpdate,
+ newUserTurn,
+ first,
+ result('create-new-1', 'Task #new-1 created successfully: Inspect renderer'),
+ second,
+ result('create-new-2', 'Task #new-2 created successfully: Run tests'),
+ ], { taskHistoryMayBeIncomplete: true })).toMatchObject({
+ isResolved: true,
+ insertion: {
+ key: 'todo-new-task-1',
+ todos: [
+ { content: 'Inspect renderer', status: 'pending' },
+ { content: 'Run tests', status: 'pending' },
+ ],
+ },
+ });
+ });
+
+ it('treats a visible real user row as the boundary of the first Task session in a paged window', () => {
+ const newUserTurn: MessageRenderSourceMessageLike = {
+ role: 'user',
+ clientId: 'user-1',
+ content: 'Start a plan',
+ };
+ const first = tool('task-1', 'TaskCreate', { subject: 'Inspect renderer' }, 'create-1');
+ const second = tool('task-2', 'TaskCreate', { subject: 'Run tests' }, 'create-2');
+
+ expect(getLatestMessageTodoState([
+ newUserTurn,
+ first,
+ result('create-1', 'Task #1 created successfully: Inspect renderer'),
+ second,
+ result('create-2', 'Task #2 created successfully: Run tests'),
+ ], { taskHistoryMayBeIncomplete: true })).toMatchObject({
+ isResolved: true,
+ insertion: {
+ key: 'todo-task-1',
+ todos: [
+ { content: 'Inspect renderer', status: 'pending' },
+ { content: 'Run tests', status: 'pending' },
+ ],
+ },
+ });
+ });
+
+ it('keeps a first TaskGet unresolved when a visible user row does not prove the old plan is complete', () => {
+ const newUserTurn: MessageRenderSourceMessageLike = {
+ role: 'user',
+ clientId: 'user-1',
+ content: 'Continue the existing task',
+ };
+ const getExisting = tool('task-get', 'TaskGet', { taskId: 'old' }, 'get-old');
+
+ expect(getLatestMessageTodoState([
+ newUserTurn,
+ getExisting,
+ result('get-old', JSON.stringify({
+ task: { id: 'old', subject: 'Inspect renderer', status: 'in_progress' },
+ })),
+ ], { taskHistoryMayBeIncomplete: true })).toMatchObject({
+ insertion: null,
+ isResolved: false,
+ });
+ });
+
it('keeps a titleless TaskList unresolved until the missing task title is reconstructed', () => {
const list = tool('task-list', 'TaskList', {}, 'list-1');
const listResult = result('list-1', JSON.stringify({
diff --git a/packages/maker-shared/src/messageRender.ts b/packages/maker-shared/src/messageRender.ts
index 977251a39b..683b99eba2 100644
--- a/packages/maker-shared/src/messageRender.ts
+++ b/packages/maker-shared/src/messageRender.ts
@@ -230,6 +230,8 @@ export type MessageRenderTodoSource = 'todo' | 'codex' | 'task';
export interface MessageRenderTodoInsertion {
key: string;
todos: MessageRenderTodoItem[];
+ /** 组成同一计划 session 的全部工具行,用于历史 prepend 后恢复旧滚动锚点。 */
+ sourceClientIds: string[];
createdAt?: string;
updatedAtMs?: number;
source: MessageRenderTodoSource;
@@ -243,7 +245,8 @@ export interface MessageRenderTodoInsertion {
sealedAtMs?: number;
/**
* host 在中断/失败 turn 给该计划行盖的 `turnCompleted: false`(见
- * `persistCodexPlanOnDone`):任务还活着,常驻面板不得按"全勾完"兜底退场。
+ * `persistCodexPlanOnDone`):在下一个真实 user turn 取代它前,常驻面板不得按
+ * "全勾完"兜底退场。
*/
turnFailed?: boolean;
}
@@ -500,6 +503,16 @@ function isSyntheticUserRow(message: MessageRenderSourceMessageLike): boolean {
);
}
+/**
+ * 会为计划开启新所有权 turn 的真实 user 行。
+ *
+ * 计划分组、失败回扫与置顶计划退场必须共用同一判据,避免一个界面已经把
+ * 输入视为新 turn,另一个界面却继续展示上一轮计划。
+ */
+export function isPlanUserBoundary(message: MessageRenderSourceMessageLike): boolean {
+ return message.role === 'user' && !isSyntheticUserRow(message);
+}
+
function isHookUserRow(message: MessageRenderSourceMessageLike): boolean {
const hookSource =
(message as Record<string, unknown>).hookSource ??
@@ -580,6 +593,7 @@ export function findMessageTodoInsertions<TMessage extends MessageRenderSourceMe
const resultByToolUseId = buildToolResultLookup(messages);
const sessions: Array<{
todos: MessageRenderTodoItem[];
+ sourceClientIds: string[];
firstIndex: number;
lastIndex: number;
source: MessageRenderTodoSource;
@@ -593,7 +607,7 @@ export function findMessageTodoInsertions<TMessage extends MessageRenderSourceMe
for (let index = 0; index < messages.length; index++) {
const message = messages[index];
if (message.role === 'user') {
- if (!isSyntheticUserRow(message)) lastUserIndex = index;
+ if (isPlanUserBoundary(message)) lastUserIndex = index;
continue;
}
const source = agentPlanSource(toolNameOf(message));
@@ -648,10 +662,12 @@ export function findMessageTodoInsertions<TMessage extends MessageRenderSourceMe
if (!startsNewSession && previous) {
previous.todos = parsed;
+ previous.sourceClientIds.push(sourceClientId(message));
previous.lastIndex = index;
} else {
const session = {
todos: parsed,
+ sourceClientIds: [sourceClientId(message)],
firstIndex: index,
lastIndex: index,
source,
@@ -670,6 +686,7 @@ export function findMessageTodoInsertions<TMessage extends MessageRenderSourceMe
out.set(session.lastIndex, {
key: `${keyPrefix}-${sourceClientId(first)}`,
todos: session.todos,
+ sourceClientIds: session.sourceClientIds,
createdAt: lastRow?.createdAt,
updatedAtMs: lastRow?.planUpdatedAtMs,
source: session.source,
@@ -908,7 +925,7 @@ export function markCodexPlanTurnFailed<TMessage extends MessageRenderSourceMess
): { messages: readonly TMessage[]; changed: boolean; toolUseId: string | null } {
for (let index = messages.length - 1; index >= 0; index -= 1) {
const message = messages[index];
- if (message.role === 'user' && !isSyntheticUserRow(message)) break;
+ if (isPlanUserBoundary(message)) break;
if (message.role !== 'tool_use' || toolNameOf(message) !== 'update_plan') continue;
if (planRowSealOf(message).sealed || planRowTurnFailed(message)) {
return { messages, changed: false, toolUseId: null };
@@ -1062,11 +1079,18 @@ function isTaskPlanWindowResolved<TMessage extends MessageRenderSourceMessageLik
let previousTaskTodos: MessageRenderTodoItem[] | null = null;
let sawTaskEvent = false;
let currentSessionBoundaryKnown = !hasEarlierMessages;
+ let lastUserBoundaryIndex = -1;
+ let currentSessionUserBoundaryIndex = -1;
for (let index = 0; index <= latestPlanIndex; index += 1) {
const message = messages[index];
+ if (isPlanUserBoundary(message)) {
+ lastUserBoundaryIndex = index;
+ continue;
+ }
if (agentPlanSource(toolNameOf(message)) !== 'task') continue;
+ const toolName = toolNameOf(message);
const resultText = resultByToolUseId.get(toolUseIdOf(message) ?? '');
const resultTasks = taskRecordsFromResult(resultText);
const input = readRecord(toolInputOf(message)) ?? {};
@@ -1079,22 +1103,40 @@ function isTaskPlanWindowResolved<TMessage extends MessageRenderSourceMessageLik
[...unresolvedTaskStatuses.values()].every(
(status) => status === 'completed' || status === 'deleted',
);
+ const targetsExistingTask = taskToolTargetsExistingTask(message, resultText, taskState);
const continuesCompletedTaskSession =
previousAllDone &&
- (taskToolTargetsExistingTask(message, resultText, taskState) ||
+ (targetsExistingTask ||
Boolean(targetTaskId && unresolvedTaskStatuses.has(targetTaskId)));
+ // 与 findMessageTodoInsertions 保持同一条所有权边界:真实 user turn 后的
+ // 新 TaskCreate / 新清单不能继承前一轮的孤儿状态;显式更新当前已知 Task
+ // 仍允许跨 turn 续写,且不移动 session 的原始所有权锚点。
+ const crossesUserBoundary =
+ sawTaskEvent &&
+ lastUserBoundaryIndex > currentSessionUserBoundaryIndex &&
+ !targetsExistingTask;
const startsNewSession =
!sawTaskEvent ||
+ crossesUserBoundary ||
(previousAllDone && !continuesCompletedTaskSession);
if (startsNewSession) {
+ const startsAfterCompletedSession =
+ sawTaskEvent && previousAllDone && !continuesCompletedTaskSession;
+ const startsWithTaskCreateAfterVisibleUser =
+ toolName === 'TaskCreate' &&
+ lastUserBoundaryIndex >= 0 &&
+ (!sawTaskEvent || crossesUserBoundary);
taskState.clear();
unresolvedTaskStatuses.clear();
previousTaskTodos = null;
- if (sawTaskEvent) currentSessionBoundaryKnown = true;
+ currentSessionBoundaryKnown =
+ !hasEarlierMessages ||
+ startsAfterCompletedSession ||
+ startsWithTaskCreateAfterVisibleUser;
+ currentSessionUserBoundaryIndex = lastUserBoundaryIndex;
}
sawTaskEvent = true;
- const toolName = toolNameOf(message);
if (toolName === 'TaskList') {
if (taskListResultIsAuthoritative(resultText)) {
currentSessionBoundaryKnown = true;