Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(chat): 修复步骤计划回填与浮层交互 (#1517)

Lizi831e43cd9df1
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.ts
index f4215df230..350aa322b9 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.ts
@@ -418,6 +418,163 @@ describe('makerChatStore active view tracking', () => {
expect(makerChatStore.getSnapshot(sessionId).oldestMessageId).toBe('task-create');
});
+ it('continues plan backfill when the visible TaskCreate may be a later step in the same plan', async () => {
+ const sessionId = sid('initial-plan-missing-earlier-create');
+ vi.mocked(messageService.list).mockClear();
+ const filler = Array.from({ length: 47 }, (_, i) =>
+ dbMessage(
+ sessionId,
+ `latest-${String(i).padStart(2, '0')}`,
+ `latest message ${i}`,
+ new Date(BASE_TIME.getTime() + (100 + i) * 1000).toISOString(),
+ ),
+ );
+ const laterCreate = dbToolUseMessage(
+ sessionId,
+ 'later-task-create',
+ 'TaskCreate',
+ { subject: 'Fix renderer' },
+ new Date(BASE_TIME.getTime() + 200_000).toISOString(),
+ );
+ const laterResult = dbToolResultMessage(
+ sessionId,
+ 'later-task-result',
+ 'tool-later-task-create',
+ 'Task #2 created successfully: Fix renderer',
+ new Date(BASE_TIME.getTime() + 201_000).toISOString(),
+ );
+ const laterUpdate = dbToolUseMessage(
+ sessionId,
+ 'later-task-update',
+ 'TaskUpdate',
+ { taskId: '2', status: 'in_progress' },
+ new Date(BASE_TIME.getTime() + 202_000).toISOString(),
+ );
+ const earlierCreate = dbToolUseMessage(
+ sessionId,
+ 'earlier-task-create',
+ 'TaskCreate',
+ { subject: 'Inspect logs' },
+ new Date(BASE_TIME.getTime() - 2_000).toISOString(),
+ );
+ const earlierResult = dbToolResultMessage(
+ sessionId,
+ 'earlier-task-result',
+ 'tool-earlier-task-create',
+ 'Task #1 created successfully: Inspect logs',
+ new Date(BASE_TIME.getTime() - 1_000).toISOString(),
+ );
+
+ vi.mocked(messageService.list)
+ .mockResolvedValueOnce([...filler, laterCreate, laterResult, laterUpdate])
+ .mockResolvedValueOnce([earlierCreate, earlierResult]);
+
+ makerChatStore.ensureInitialMessages(sessionId);
+ await flushPromises(10);
+
+ expect(messageService.list).toHaveBeenCalledTimes(2);
+ expect(messageService.list).toHaveBeenNthCalledWith(2, sessionId, {
+ limit: 50,
+ before: 'latest-00',
+ });
+ expect(makerChatStore.getSnapshot(sessionId).oldestMessageId).toBe('earlier-task-create');
+ });
+
+ it('continues plan backfill past an unrelated visible task until the updated task is found', async () => {
+ const sessionId = sid('initial-plan-unrelated-task');
+ vi.mocked(messageService.list).mockClear();
+ const fillerPage = (prefix: string, startOffsetSeconds: number, count = 49) =>
+ Array.from({ length: count }, (_, 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 unrelatedCreate = dbToolUseMessage(
+ sessionId,
+ 'unrelated-task-create',
+ 'TaskCreate',
+ { subject: 'Fix existing tests' },
+ new Date(BASE_TIME.getTime() + 1_100_000).toISOString(),
+ );
+ const unrelatedResult = dbToolResultMessage(
+ sessionId,
+ 'unrelated-task-result',
+ 'tool-unrelated-task-create',
+ 'Task #def created successfully: Fix existing tests',
+ new Date(BASE_TIME.getTime() + 1_100_001).toISOString(),
+ );
+ const targetCreate = dbToolUseMessage(
+ sessionId,
+ 'target-task-create',
+ 'TaskCreate',
+ { subject: 'Run stress tests' },
+ new Date(BASE_TIME.getTime() - 4_000).toISOString(),
+ );
+ const targetResult = dbToolResultMessage(
+ sessionId,
+ 'target-task-result',
+ 'tool-target-task-create',
+ 'Task #abc created successfully: Run stress tests',
+ new Date(BASE_TIME.getTime() - 3_000).toISOString(),
+ );
+ const missingOlderUpdate = dbToolUseMessage(
+ sessionId,
+ 'missing-task-update',
+ 'TaskUpdate',
+ { taskId: 'legacy', status: 'completed' },
+ new Date(BASE_TIME.getTime() - 2_000).toISOString(),
+ );
+ const missingOlderCreate = dbToolUseMessage(
+ sessionId,
+ 'missing-task-create',
+ 'TaskCreate',
+ { subject: 'Inspect collision failures' },
+ new Date(BASE_TIME.getTime() - 6_000).toISOString(),
+ );
+ const missingOlderResult = dbToolResultMessage(
+ sessionId,
+ 'missing-task-result',
+ 'tool-missing-task-create',
+ 'Task #legacy created successfully: Inspect collision failures',
+ new Date(BASE_TIME.getTime() - 5_000).toISOString(),
+ );
+
+ vi.mocked(messageService.list)
+ .mockResolvedValueOnce([...fillerPage('latest', 2000), latestTaskUpdate])
+ .mockResolvedValueOnce([
+ ...fillerPage('middle', 1000, 48),
+ unrelatedCreate,
+ unrelatedResult,
+ ])
+ .mockResolvedValueOnce([
+ ...fillerPage('older-target', 100, 47),
+ targetCreate,
+ targetResult,
+ missingOlderUpdate,
+ ])
+ .mockResolvedValueOnce([missingOlderCreate, missingOlderResult]);
+
+ makerChatStore.ensureInitialMessages(sessionId);
+ await flushPromises(10);
+
+ expect(messageService.list).toHaveBeenCalledTimes(4);
+ expect(messageService.list).toHaveBeenNthCalledWith(4, sessionId, {
+ limit: 50,
+ before: 'target-task-create',
+ });
+ expect(makerChatStore.getSnapshot(sessionId).oldestMessageId).toBe('missing-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();
@@ -595,6 +752,7 @@ describe('makerChatStore active view tracking', () => {
// 阶段一:窗口里只有孤岛 → 必须播种,游标为 null 会让下一次翻页从最新重开、把跳转位置顶掉。
expect(makerChatStore.getSnapshot(sessionId).oldestMessageId).toBe('older-hit-context');
expect(makerChatStore.getSnapshot(sessionId).historyWindowHasIsland).toBe(true);
+ expect(makerChatStore.getLightSnapshot(sessionId).historyWindowHasIsland).toBe(true);
resolveInitialList([
dbMessage(sessionId, 'latest-page-oldest', 'latest page oldest', '2026-05-19T00:10:00.000Z'),
diff --git a/apps/desktop/src/renderer/components/chat/TodoListCard.tsx b/apps/desktop/src/renderer/components/chat/TodoListCard.tsx
index 678b335d14..ff3952a35d 100644
--- a/apps/desktop/src/renderer/components/chat/TodoListCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/TodoListCard.tsx
@@ -16,7 +16,7 @@
* --msg-tool-card-chevron: secondary(completed 置灰)
*/
-import { useEffect, useId, useState } from 'react';
+import { useEffect, useId, useRef, useState } from 'react';
import { CircleCheck, CircleDashed, Circle } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import type { MessageRenderTodoItem } from '@cindy/maker-shared/message-render';
@@ -50,10 +50,31 @@ export function TodoListCard({
}) {
const { t } = useTranslation();
const flyoutId = useId();
+ const cardRef = useRef<HTMLDivElement>(null);
const [openMode, setOpenMode] = useState<FlyoutOpenMode>('closed');
const [renderFlyout, setRenderFlyout] = useState(false);
const revealed = openMode !== 'closed';
+ useEffect(() => {
+ if (openMode !== 'pinned') return;
+
+ const handlePointerDownOutside = (event: PointerEvent) => {
+ const target = event.target;
+ if (target instanceof Node && cardRef.current?.contains(target)) return;
+ setOpenMode('closed');
+ };
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (event.key === 'Escape') setOpenMode('closed');
+ };
+
+ document.addEventListener('pointerdown', handlePointerDownOutside, true);
+ document.addEventListener('keydown', handleKeyDown);
+ return () => {
+ document.removeEventListener('pointerdown', handlePointerDownOutside, true);
+ document.removeEventListener('keydown', handleKeyDown);
+ };
+ }, [openMode]);
+
useEffect(() => {
if (revealed) setRenderFlyout(true);
}, [revealed]);
@@ -81,6 +102,7 @@ export function TodoListCard({
return (
<div className="flex w-full justify-center">
<div
+ ref={cardRef}
className="relative inline-flex items-center justify-center"
onMouseEnter={() => {
setOpenMode((current) => (current === 'closed' ? 'hover' : current));
@@ -112,12 +134,18 @@ export function TodoListCard({
strokeWidth={2}
className="shrink-0 text-[var(--msg-tool-card-text)]"
/>
- ) : (
+ ) : hasActive ? (
<Spinner
icon={CircleDashed}
size={14}
strokeWidth={2}
- spinning={animated && hasActive}
+ spinning={animated}
+ className="shrink-0 text-[var(--msg-tool-card-text)]"
+ />
+ ) : (
+ <Circle
+ size={14}
+ strokeWidth={2}
className="shrink-0 text-[var(--msg-tool-card-text)]"
/>
)}
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 bc91a04733..ea20ca186d 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/TodoListCard.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/TodoListCard.test.tsx
@@ -20,6 +20,18 @@ const TODOS = [
afterEach(cleanup);
describe('TodoListCard flyout interaction', () => {
+ it('uses the pending icon when no step is currently in progress', () => {
+ const { container } = render(
+ <TodoListCard todos={[{ content: 'Queued step', status: 'pending' }]} animated />,
+ );
+
+ const trigger = screen.getByRole('button', { name: 'Step 1 / 1' });
+
+ expect(trigger.querySelector('svg.lucide-circle')).not.toBeNull();
+ expect(trigger.querySelector('svg.lucide-circle-dashed')).toBeNull();
+ expect(container.querySelector('svg.lucide-circle-dashed')).toBeNull();
+ });
+
it('opens transiently on hover and closes when the pointer leaves', () => {
render(<TodoListCard todos={TODOS} animated={false} />);
@@ -55,6 +67,30 @@ describe('TodoListCard flyout interaction', () => {
expect(trigger.getAttribute('aria-expanded')).toBe('true');
});
+ it('closes a pinned flyout when the pointer goes outside the card', () => {
+ render(<TodoListCard todos={TODOS} animated={false} />);
+
+ const trigger = screen.getByRole('button', { name: 'Step 1 / 2' });
+ fireEvent.click(trigger);
+ expect(trigger.getAttribute('aria-expanded')).toBe('true');
+
+ fireEvent.pointerDown(document.body);
+
+ expect(trigger.getAttribute('aria-expanded')).toBe('false');
+ });
+
+ it('closes a pinned flyout with Escape', () => {
+ render(<TodoListCard todos={TODOS} animated={false} />);
+
+ const trigger = screen.getByRole('button', { name: 'Step 1 / 2' });
+ fireEvent.click(trigger);
+ expect(trigger.getAttribute('aria-expanded')).toBe('true');
+
+ fireEvent.keyDown(document, { key: 'Escape' });
+
+ expect(trigger.getAttribute('aria-expanded')).toBe('false');
+ });
+
it('toggles the pinned flyout for keyboard-generated clicks', () => {
render(<TodoListCard todos={TODOS} animated={false} />);
diff --git a/apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx b/apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx
index 0c42977356..42ba4d0781 100644
--- a/apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx
@@ -22,6 +22,7 @@ export function PinnedPlanPanel({
messages,
animated,
width,
+ taskHistoryMayBeIncomplete = false,
visible = true,
}: {
sessionId: string | null;
@@ -30,10 +31,14 @@ export function PinnedPlanPanel({
animated: boolean;
/** 与 composer 同宽(inputWidth),胶囊在该宽度内居中,浮层不超出。 */
width: number;
+ taskHistoryMayBeIncomplete?: boolean;
/** 交互卡接管底部区域时只隐藏视图,保留完成后的计时与已收起状态。 */
visible?: boolean;
}): React.ReactElement | null {
- const insertion = useMemo(() => findLatestMessageTodoInsertion(messages), [messages]);
+ const insertion = useMemo(
+ () => findLatestMessageTodoInsertion(messages, { taskHistoryMayBeIncomplete }),
+ [messages, taskHistoryMayBeIncomplete],
+ );
const allDone = Boolean(
insertion &&
insertion.todos.length > 0 &&
@@ -91,7 +96,7 @@ export function PinnedPlanPanel({
if (
!visible ||
!insertion ||
- insertion.todos.length === 0 ||
+ insertion.todos.length < 2 ||
completedPlanExpired ||
hiddenInsertionKey === insertion.key
)
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 d1d347908b..593adde031 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
@@ -18,14 +18,21 @@ function planMessage(
status: 'pending' | 'in_progress' | 'completed',
createdAtMs: number | null = T0,
planUpdatedAtMs?: number,
+ stepCount = 2,
): ChatMessage {
+ const plan = Array.from({ length: stepCount }, (_, index) => ({
+ step: index === 0 ? 'Finish work' : `Follow-up ${index}`,
+ status:
+ status === 'completed' ? ('completed' as const) : index === 0 ? status : ('pending' as const),
+ }));
+
return {
clientId: 'plan-1',
role: 'tool_use',
content: '',
toolName: 'update_plan',
toolUseId: 'plan:turn-1',
- toolInput: { plan: [{ step: 'Finish work', status }] },
+ toolInput: { plan },
...(createdAtMs === null ? {} : { createdAt: new Date(createdAtMs).toISOString() }),
...(planUpdatedAtMs === undefined ? {} : { planUpdatedAtMs }),
};
@@ -42,6 +49,74 @@ afterEach(() => {
});
describe('PinnedPlanPanel completed plan lifetime', () => {
+ it('does not show a progress pill for a single-step plan', () => {
+ render(
+ <PinnedPlanPanel
+ sessionId="single-step"
+ messages={[planMessage('in_progress', T0, undefined, 1)]}
+ animated
+ width={400}
+ />,
+ );
+
+ expect(screen.queryByTestId('plan-pill')).toBeNull();
+ });
+
+ it('does not show a Task plan while older messages may contain earlier steps', () => {
+ const messages: ChatMessage[] = [
+ {
+ clientId: 'task-2',
+ role: 'tool_use',
+ content: '',
+ toolName: 'TaskCreate',
+ toolUseId: 'create-2',
+ toolInput: { subject: 'Fix renderer' },
+ },
+ {
+ clientId: 'result-2',
+ role: 'tool_result',
+ content: 'Task #2 created successfully: Fix renderer',
+ toolUseId: 'create-2',
+ },
+ {
+ clientId: 'task-3',
+ role: 'tool_use',
+ content: '',
+ toolName: 'TaskCreate',
+ toolUseId: 'create-3',
+ toolInput: { subject: 'Run tests' },
+ },
+ {
+ clientId: 'result-3',
+ role: 'tool_result',
+ content: 'Task #3 created successfully: Run tests',
+ toolUseId: 'create-3',
+ },
+ ];
+
+ const view = render(
+ <PinnedPlanPanel
+ sessionId="partial-task-plan"
+ messages={messages}
+ animated
+ width={400}
+ taskHistoryMayBeIncomplete
+ />,
+ );
+ expect(screen.queryByTestId('plan-pill')).toBeNull();
+
+ view.rerender(
+ <PinnedPlanPanel
+ sessionId="partial-task-plan"
+ messages={messages}
+ animated
+ width={400}
+ taskHistoryMayBeIncomplete={false}
+ />,
+ );
+ expect(screen.getByTestId('plan-pill').textContent).toBe('Fix renderer,Run tests');
+ });
+
it('keeps a completed plan visible for 2 seconds, then hides it', () => {
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 2450255ae4..eb908b6ddb 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -1204,6 +1204,7 @@ export function CCAgentSessionView({
loadOlderMessages,
isLoadingMore,
hasMoreMessages,
+ historyWindowHasIsland,
pendingPermission,
respondToPermission,
pendingAskUser,
@@ -3562,6 +3563,9 @@ export function CCAgentSessionView({
messages={messages}
animated={isStreaming}
width={inputWidth}
+ taskHistoryMayBeIncomplete={
+ !historyLoaded || hasMoreMessages || historyWindowHasIsland
+ }
visible={!(
pendingPlanReview ||
pendingPermission ||
diff --git a/apps/desktop/src/renderer/hooks/useCCAgentChat.ts b/apps/desktop/src/renderer/hooks/useCCAgentChat.ts
index 03ee5b57a4..4ba977dc01 100644
--- a/apps/desktop/src/renderer/hooks/useCCAgentChat.ts
+++ b/apps/desktop/src/renderer/hooks/useCCAgentChat.ts
@@ -194,6 +194,7 @@ interface UseCCAgentChatReturn {
loadOlderMessages: () => void;
isLoadingMore: boolean;
hasMoreMessages: boolean;
+ historyWindowHasIsland: boolean;
/** F-PERM-2: Currently pending permission request */
pendingPermission: PendingPermission | null;
/** F-PERM-2: Respond to a pending permission request */
@@ -845,6 +846,7 @@ export function useCCAgentChat(
loadOlderMessages,
isLoadingMore: lightState.isLoadingMore,
hasMoreMessages: lightState.hasMoreMessages,
+ historyWindowHasIsland: lightState.historyWindowHasIsland === true,
pendingPermission: lightState.pendingPermission,
respondToPermission,
pendingAskUser: lightState.pendingAskUser,
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index d2311052bd..33ba8b03ee 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -1057,6 +1057,7 @@ export type SessionChatLightState = Pick<
| 'continuationInFlightProjectionCapability'
| 'isLoadingMore'
| 'hasMoreMessages'
+ | 'historyWindowHasIsland'
| 'isFirstMessage'
| 'historyLoaded'
| 'pendingPermission'
@@ -5014,6 +5015,7 @@ function selectLightState(state: SessionChatState): SessionChatLightState {
continuationInFlightProjectionCapability: state.continuationInFlightProjectionCapability,
isLoadingMore: state.isLoadingMore,
hasMoreMessages: state.hasMoreMessages,
+ historyWindowHasIsland: state.historyWindowHasIsland,
isFirstMessage: state.isFirstMessage,
historyLoaded: state.historyLoaded,
pendingPermission: state.pendingPermission,
@@ -5056,6 +5058,7 @@ function lightStateEquals(a: SessionChatLightState, b: SessionChatLightState): b
a.isLoadingMore === b.isLoadingMore &&
a.hasMoreMessages === b.hasMoreMessages &&
+ a.historyWindowHasIsland === b.historyWindowHasIsland &&
a.isFirstMessage === b.isFirstMessage &&
a.historyLoaded === b.historyLoaded &&
a.pendingPermission === b.pendingPermission &&
@@ -5965,7 +5968,7 @@ function ensureInitialMessages(sessionId: string): void {
while (hasMore) {
const needsAnchorBackfill =
merged.every(isNonAnchorHistoryRow) && pagesFetched < MAX_NO_ANCHOR_BACKFILL_PAGES;
- const planState = historyRowsPlanBackfillState(merged);
+ const planState = historyRowsPlanBackfillState(merged, hasMore);
const needsPlanResolution =
planState.hasPlanEvent &&
!planState.isResolved &&
@@ -10210,11 +10213,13 @@ function serverMessagePageHasMore(rows: Message[], pageSize = 50): boolean {
return rows.length >= pageSize || rows.some((row) => row.agentMeta?.remoteRowsTrimmed === true);
}
-function historyRowsPlanBackfillState(rows: Message[]): {
+function historyRowsPlanBackfillState(rows: Message[], taskHistoryMayBeIncomplete: boolean): {
hasPlanEvent: boolean;
isResolved: boolean;
} {
- const state = getLatestMessageTodoState(mapServerMessages(rows));
+ const state = getLatestMessageTodoState(mapServerMessages(rows), {
+ taskHistoryMayBeIncomplete,
+ });
return {
hasPlanEvent: state.hasPlanEvent,
isResolved: state.isResolved,
diff --git a/packages/maker-shared/src/__tests__/messageRender.test.ts b/packages/maker-shared/src/__tests__/messageRender.test.ts
index 8fc69d070a..4f32f64657 100644
--- a/packages/maker-shared/src/__tests__/messageRender.test.ts
+++ b/packages/maker-shared/src/__tests__/messageRender.test.ts
@@ -7,6 +7,7 @@ import {
findLatestMessageTodoInsertion,
findMessageTodoInsertions,
formatDuration,
+ getLatestMessageTodoState,
type MessageRenderItem,
type MessageRenderNormalizedMessage,
type MessageRenderSourceMessageLike,
@@ -896,6 +897,166 @@ describe('message render todo grouping', () => {
expect(findLatestMessageTodoInsertion([todo, update])).toBeNull();
});
+ it('keeps a Task update unresolved when the loaded window only contains a different task', () => {
+ const visibleCreate = tool(
+ 'task4',
+ 'TaskCreate',
+ { subject: 'Fix existing tests' },
+ 'create-4',
+ );
+ const olderTaskUpdate = tool(
+ 'task3-update',
+ 'TaskUpdate',
+ { taskId: '3', status: 'completed' },
+ 'update-3',
+ );
+
+ expect(findLatestMessageTodoInsertion([
+ visibleCreate,
+ result('create-4', 'Task #4 created successfully: Fix existing tests'),
+ olderTaskUpdate,
+ ])).toBeNull();
+ });
+
+ it('keeps the Task window unresolved until every earlier updated task is reconstructed', () => {
+ const missingOlderUpdate = tool(
+ 'task1-update',
+ 'TaskUpdate',
+ { taskId: '1', status: 'completed' },
+ 'update-1',
+ );
+ const visibleTarget = tool(
+ 'task3',
+ 'TaskCreate',
+ { subject: 'Run stress tests' },
+ 'create-3',
+ );
+ const visiblePending = tool(
+ 'task4',
+ 'TaskCreate',
+ { subject: 'Fix existing tests' },
+ 'create-4',
+ );
+ const latestUpdate = tool(
+ 'task3-update',
+ 'TaskUpdate',
+ { taskId: '3', status: 'completed' },
+ 'update-3',
+ );
+
+ expect(findLatestMessageTodoInsertion([
+ visibleTarget,
+ result('create-3', 'Task #3 created successfully: Run stress tests'),
+ missingOlderUpdate,
+ visiblePending,
+ result('create-4', 'Task #4 created successfully: Fix existing tests'),
+ latestUpdate,
+ ])).toBeNull();
+ });
+
+ it('keeps a partial Task session unresolved while older messages may contain earlier creates', () => {
+ const create = tool('task2', 'TaskCreate', { subject: 'Fix renderer' }, 'create-2');
+ const update = tool(
+ 'task2-update',
+ 'TaskUpdate',
+ { taskId: '2', status: 'in_progress' },
+ 'update-2',
+ );
+ const messages = [
+ create,
+ result('create-2', 'Task #2 created successfully: Fix renderer'),
+ update,
+ ];
+
+ expect(getLatestMessageTodoState(messages, { taskHistoryMayBeIncomplete: true })).toMatchObject({
+ insertion: null,
+ isResolved: false,
+ });
+ expect(getLatestMessageTodoState(messages, { taskHistoryMayBeIncomplete: false })).toMatchObject({
+ isResolved: true,
+ insertion: {
+ todos: [{ content: 'Fix renderer', status: 'in_progress' }],
+ },
+ });
+ });
+
+ 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({
+ tasks: [
+ { id: 'abc', status: 'completed' },
+ { id: 'def', subject: 'Write summary', status: 'pending' },
+ ],
+ }));
+
+ expect(getLatestMessageTodoState([list, listResult])).toMatchObject({
+ insertion: null,
+ isResolved: false,
+ });
+
+ const create = tool('task-create', 'TaskCreate', { subject: 'Collect logs' }, 'create-1');
+ expect(getLatestMessageTodoState([
+ create,
+ result('create-1', 'Task #abc created successfully: Collect logs'),
+ list,
+ listResult,
+ ])).toMatchObject({
+ isResolved: true,
+ insertion: {
+ todos: [
+ { content: 'Collect logs', status: 'completed' },
+ { content: 'Write summary', status: 'pending' },
+ ],
+ },
+ });
+ });
+
+ it('preserves a completed task title when a later TaskList repeats the same id', () => {
+ const create = tool('task-create', 'TaskCreate', { subject: 'Collect logs' }, 'create-1');
+ const complete = tool(
+ 'task-complete',
+ 'TaskUpdate',
+ { taskId: 'abc', status: 'completed' },
+ 'update-1',
+ );
+ const list = tool('task-list', 'TaskList', {}, 'list-1');
+
+ expect(findLatestMessageTodoInsertion([
+ create,
+ result('create-1', 'Task #abc created successfully: Collect logs'),
+ complete,
+ list,
+ result('list-1', JSON.stringify({ tasks: [{ id: 'abc', status: 'completed' }] })),
+ ])).toMatchObject({
+ todos: [{ content: 'Collect logs', status: 'completed' }],
+ });
+ });
+
+ it('does not let an orphan completed update block a later complete task session', () => {
+ const orphanUpdate = tool(
+ 'old-task-update',
+ 'TaskUpdate',
+ { taskId: 'old', status: 'completed' },
+ 'update-old',
+ );
+ const first = tool('new-task-1', 'TaskCreate', { subject: 'Inspect logs' }, 'create-new-1');
+ const second = tool('new-task-2', 'TaskCreate', { subject: 'Fix renderer' }, 'create-new-2');
+
+ expect(findLatestMessageTodoInsertion([
+ orphanUpdate,
+ first,
+ result('create-new-1', 'Task #new-1 created successfully: Inspect logs'),
+ second,
+ result('create-new-2', 'Task #new-2 created successfully: Fix renderer'),
+ ])).toMatchObject({
+ key: 'todo-new-task-1',
+ todos: [
+ { content: 'Inspect logs', status: 'pending' },
+ { content: 'Fix renderer', status: 'pending' },
+ ],
+ });
+ });
+
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');
@@ -973,6 +1134,20 @@ describe('message render todo grouping', () => {
])).toBeNull();
});
+ it('treats deleted-only TaskList snapshots as clearing the latest task plan', () => {
+ const create = tool('task1', 'TaskCreate', { subject: 'Collect logs' }, 'create-1');
+ const listDeleted = tool('task2', 'TaskList', {}, 'list-1');
+
+ expect(findLatestMessageTodoInsertion([
+ create,
+ result('create-1', 'Task #abc created successfully: Collect logs'),
+ listDeleted,
+ result('list-1', JSON.stringify({
+ tasks: [{ id: 'abc', status: 'deleted' }],
+ })),
+ ])).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 c21fdff712..215dd9869a 100644
--- a/packages/maker-shared/src/messageRender.ts
+++ b/packages/maker-shared/src/messageRender.ts
@@ -203,6 +203,8 @@ export interface MessageRenderLatestTodoState {
export interface MessageRenderTodoGroupingOptions {
keyPrefix?: string;
+ /** True when the loaded window may omit TaskCreate events or contain history gaps. */
+ taskHistoryMayBeIncomplete?: boolean;
}
const TASK_PLAN_TOOL_NAMES = new Set(['TaskCreate', 'TaskUpdate', 'TaskList', 'TaskGet']);
@@ -512,7 +514,16 @@ export function getLatestMessageTodoState<TMessage extends MessageRenderSourceMe
}
}
const hasPlanEvent = latestPlanIndex >= 0;
- const insertionBelongsToLatestEvent = latestIndex === latestPlanIndex;
+ const latestTaskWindowResolved =
+ latestPlanMessage === null ||
+ agentPlanSource(toolNameOf(latestPlanMessage)) !== 'task' ||
+ isTaskPlanWindowResolved(
+ messages,
+ latestPlanIndex,
+ options.taskHistoryMayBeIncomplete === true,
+ );
+ const insertionBelongsToLatestEvent =
+ latestIndex === latestPlanIndex && latestTaskWindowResolved;
const latestEventClearsPlan =
latestPlanMessage !== null &&
(isExplicitPlanClearEvent(latestPlanMessage) ||
@@ -520,7 +531,10 @@ export function getLatestMessageTodoState<TMessage extends MessageRenderSourceMe
return {
insertion: insertionBelongsToLatestEvent ? latest : null,
hasPlanEvent,
- isResolved: !hasPlanEvent || insertionBelongsToLatestEvent || latestEventClearsPlan,
+ isResolved:
+ !hasPlanEvent ||
+ insertionBelongsToLatestEvent ||
+ (latestTaskWindowResolved && latestEventClearsPlan),
latestPlanIndex,
latestInsertionIndex: latestIndex,
};
@@ -716,6 +730,104 @@ function latestTaskEventClearsPlan<TMessage extends MessageRenderSourceMessageLi
return false;
}
+/**
+ * A paged history window is only a complete Task-plan snapshot when every
+ * status/read event in the current task session can be tied back to a visible
+ * TaskCreate or an authoritative TaskList snapshot. Otherwise an unrelated
+ * visible task can make the latest update look resolved and stop history
+ * backfill before the rest of the plan has been reconstructed.
+ */
+function isTaskPlanWindowResolved<TMessage extends MessageRenderSourceMessageLike>(
+ messages: readonly TMessage[],
+ latestPlanIndex: number,
+ hasEarlierMessages: boolean,
+): boolean {
+ const resultByToolUseId = buildToolResultLookup(messages);
+ const taskState = new Map<string, MessageRenderTodoItem>();
+ const unresolvedTaskStatuses = new Map<
+ string,
+ MessageRenderTodoItem['status'] | 'deleted'
+ >();
+ let previousTaskTodos: MessageRenderTodoItem[] | null = null;
+ let sawTaskEvent = false;
+ let currentSessionBoundaryKnown = !hasEarlierMessages;
+
+ 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 resultTasks = taskRecordsFromResult(resultText);
+ const input = readRecord(toolInputOf(message)) ?? {};
+ const targetTaskId = taskId(input) ?? taskId(resultTasks[0]);
+ const hasPreviousTaskContext =
+ previousTaskTodos !== null || unresolvedTaskStatuses.size > 0;
+ const previousAllDone =
+ hasPreviousTaskContext &&
+ (previousTaskTodos?.every((todo) => todo.status === 'completed') ?? true) &&
+ [...unresolvedTaskStatuses.values()].every(
+ (status) => status === 'completed' || status === 'deleted',
+ );
+ const continuesCompletedTaskSession =
+ previousAllDone &&
+ (taskToolTargetsExistingTask(message, resultText, taskState) ||
+ Boolean(targetTaskId && unresolvedTaskStatuses.has(targetTaskId)));
+ const startsNewSession =
+ !sawTaskEvent ||
+ (previousAllDone && !continuesCompletedTaskSession);
+ if (startsNewSession) {
+ taskState.clear();
+ unresolvedTaskStatuses.clear();
+ previousTaskTodos = null;
+ if (sawTaskEvent) currentSessionBoundaryKnown = true;
+ }
+ sawTaskEvent = true;
+
+ const toolName = toolNameOf(message);
+ if (toolName === 'TaskList') {
+ if (taskListResultIsAuthoritative(resultText)) {
+ currentSessionBoundaryKnown = true;
+ }
+ if (resultTasks.length > 0) {
+ const previousTaskState = new Map(taskState);
+ unresolvedTaskStatuses.clear();
+ for (const task of resultTasks) {
+ const id = taskId(task);
+ const status = normalizeTaskStatus(task.status) ?? 'pending';
+ if (!id || status === 'deleted') continue;
+ if (!taskContent(task) && !previousTaskState.has(id)) {
+ unresolvedTaskStatuses.set(id, status);
+ }
+ }
+ } else if (taskListResultClearsPlan(resultText)) {
+ unresolvedTaskStatuses.clear();
+ }
+ } else if (toolName !== 'TaskCreate') {
+ const resultTask = resultTasks[0];
+ const id = taskId(input) ?? taskId(resultTask);
+ if (id && !taskState.has(id)) {
+ unresolvedTaskStatuses.set(
+ id,
+ taskToolStatus(message, resultText) ?? 'pending',
+ );
+ }
+ }
+
+ const parsed = applyTaskPlanTool(taskState, message, resultText);
+ for (const id of taskState.keys()) unresolvedTaskStatuses.delete(id);
+ previousTaskTodos = parsed ?? currentTaskTodos(taskState);
+ if (
+ previousTaskTodos === null &&
+ unresolvedTaskStatuses.size === 0 &&
+ taskState.size === 0
+ ) {
+ previousTaskTodos = [];
+ }
+ }
+
+ return currentSessionBoundaryKnown && unresolvedTaskStatuses.size === 0;
+}
+
function buildToolResultLookup<TMessage extends MessageRenderSourceMessageLike>(
messages: readonly TMessage[],
): Map<string, string> {
@@ -787,6 +899,12 @@ function taskToolTargetsExistingTask(
taskState: ReadonlyMap<string, MessageRenderTodoItem>,
): boolean {
const toolName = toolNameOf(message);
+ if (toolName === 'TaskList') {
+ return taskRecordsFromResult(resultText).some((task) => {
+ const id = taskId(task);
+ return Boolean(id && taskState.has(id));
+ });
+ }
if (toolName !== 'TaskUpdate' && toolName !== 'TaskGet') return false;
const input = readRecord(toolInputOf(message));
const resultTask = taskRecordsFromResult(resultText)[0];
@@ -870,8 +988,16 @@ function applyTaskPlanTool(
const id = taskId(input) ?? taskId(resultTask);
if (!id) return currentTaskTodos(taskState);
+ // A status-only TaskUpdate / TaskGet can only be applied after the target task
+ // has been reconstructed from an earlier TaskCreate or TaskList snapshot. In a
+ // paged history window, returning some other tasks here would make the latest
+ // event look resolved and stop backfill early, producing a partial plan such
+ // as "Step 1 / 1" for what was actually the fourth task.
+ const existing = taskState.get(id);
+ const suppliedContent = taskContent(input) ?? taskContent(resultTask);
+ if (!existing && !suppliedContent) return null;
+
if (toolName === 'TaskGet' && resultTask) {
- const existing = taskState.get(id);
const status = normalizeTaskStatus(resultTask.status) ?? taskState.get(id)?.status ?? 'pending';
if (status === 'deleted') {
taskState.delete(id);
@@ -886,13 +1012,12 @@ function applyTaskPlanTool(
return currentTaskTodos(taskState);
}
- const existing = taskState.get(id);
const status = normalizeTaskStatus(input.status ?? resultTask?.status) ?? existing?.status ?? 'pending';
if (status === 'deleted') {
taskState.delete(id);
return currentTaskTodos(taskState);
}
- const content = taskContent(input) ?? taskContent(resultTask) ?? existing?.content;
+ const content = suppliedContent ?? existing?.content;
if (!content) return currentTaskTodos(taskState);
taskState.set(id, {
content,
@@ -903,7 +1028,16 @@ function applyTaskPlanTool(
function taskListResultClearsPlan(resultText: string | undefined): boolean {
const parsed = tryParseJsonRecord(resultText);
- return Boolean(parsed && Array.isArray(parsed.tasks) && parsed.tasks.length === 0);
+ if (!parsed || !Array.isArray(parsed.tasks)) return false;
+ return parsed.tasks.every((task) => {
+ const record = readRecord(task);
+ return Boolean(record && normalizeTaskStatus(record.status) === 'deleted');
+ });
+}
+
+function taskListResultIsAuthoritative(resultText: string | undefined): boolean {
+ const parsed = tryParseJsonRecord(resultText);
+ return Boolean(parsed && Array.isArray(parsed.tasks));
}
function currentTaskTodos(taskState: Map<string, MessageRenderTodoItem>): MessageRenderTodoItem[] | null {