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): fold earlier background-wake seals into the work group

Dashd89df127edc3
diff --git a/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts b/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts
index cf56345841..beb1d6bff8 100644
--- a/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts
+++ b/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts
@@ -459,7 +459,7 @@ describe('collectTurnFinalAssistantClientIds', () => {
expect(finals.has('a2-draft')).toBe(false);
});
- it('marks every sealed SDK turn when background work auto-continues without a user boundary', () => {
+ it('marks only the last sealed SDK turn when background work auto-continues without a user boundary', () => {
const messages = [
mkUser('u1'),
{ ...mkAssistant('main-summary'), turnCompleted: true },
@@ -467,9 +467,21 @@ describe('collectTurnFinalAssistantClientIds', () => {
{ ...mkAssistant('gate-followup'), turnCompleted: true },
];
- const finals = collectTurnFinalAssistantClientIds(messages);
- expect([...finals]).toEqual(expect.arrayContaining(['main-summary', 'gate-followup']));
- expect(finals.size).toBe(2);
+ expect(collectTurnFinalAssistantClientIds(messages)).toEqual(new Set(['gate-followup']));
+ });
+
+ it('keeps an earlier sealed delivery-prose summary as a turn final', () => {
+ const report = '## 结论\n\n- 第一条\n- 第二条\n- 第三条';
+ const messages = [
+ mkUser('u1'),
+ { ...mkAssistant('main-summary', report), turnCompleted: true },
+ mkTool('gate', 'Bash'),
+ { ...mkAssistant('gate-followup'), turnCompleted: true },
+ ];
+
+ expect(collectTurnFinalAssistantClientIds(messages)).toEqual(
+ new Set(['main-summary', 'gate-followup']),
+ );
});
it('does not add an unsealed progress message once the user turn contains sealed answers', () => {
@@ -480,9 +492,7 @@ describe('collectTurnFinalAssistantClientIds', () => {
{ ...mkAssistant('gate-followup'), turnCompleted: true },
];
- const finals = collectTurnFinalAssistantClientIds(messages);
- expect([...finals]).toEqual(expect.arrayContaining(['main-summary', 'gate-followup']));
- expect(finals.has('unsealed-progress')).toBe(false);
+ expect(collectTurnFinalAssistantClientIds(messages)).toEqual(new Set(['gate-followup']));
});
it('does not treat steer messages as turn boundaries', () => {
diff --git a/apps/desktop/src/renderer/__tests__/workGroupProjectionParity.test.ts b/apps/desktop/src/renderer/__tests__/workGroupProjectionParity.test.ts
index 715673120c..7e24b9fee7 100644
--- a/apps/desktop/src/renderer/__tests__/workGroupProjectionParity.test.ts
+++ b/apps/desktop/src/renderer/__tests__/workGroupProjectionParity.test.ts
@@ -204,7 +204,7 @@ const cases: Array<{ name: string; events: Event[]; streaming?: boolean; expecte
expected: [['u'], ['work-read', [['read']]], ['compact'], ['work-think', [['think']]]],
},
{
- name: 'each seal retains its contiguous final prose through continuation',
+ name: 'only the last seal stays final; earlier short seals fold through continuation',
events: [
user(),
tool('read', 1, 2),
@@ -215,13 +215,24 @@ const cases: Array<{ name: string; events: Event[]; streaming?: boolean; expecte
],
expected: [
['u'],
- ['work-read', [['read']]],
- ['part1'],
- ['part2'],
- ['work-next', [['next']]],
+ [
+ 'work-summary-read',
+ [['work-read', [['read']]], ['part1'], ['part2'], ['work-next', [['next']]]],
+ ],
['final'],
],
},
+ {
+ name: 'an earlier delivery-prose seal stays visible through continuation',
+ events: [
+ user(),
+ tool('read', 1, 2),
+ answer('report', 3, true, '# Report\nThe result'),
+ thinking('next', 4),
+ answer('final', 5, true),
+ ],
+ expected: [['u'], ['work-read', [['read']]], ['report'], ['work-next', [['next']]], ['final']],
+ },
{
name: 'legacy text followed by more work remains a visible boundary',
events: [user(), tool('read', 1, 2), answer('progress', 3), thinking('next', 4)],
diff --git a/apps/desktop/src/renderer/__tests__/workGroupRunningSubagent.test.ts b/apps/desktop/src/renderer/__tests__/workGroupRunningSubagent.test.ts
index f0dcfb9117..64cf79cdd5 100644
--- a/apps/desktop/src/renderer/__tests__/workGroupRunningSubagent.test.ts
+++ b/apps/desktop/src/renderer/__tests__/workGroupRunningSubagent.test.ts
@@ -20,7 +20,11 @@
*/
import { describe, it, expect } from 'vitest';
-import { buildRenderItems, groupWorkRuns } from '../components/chat/MessageStream';
+import {
+ buildRenderItems,
+ collectTurnFinalAssistantClientIds,
+ groupWorkRuns,
+} from '../components/chat/MessageStream';
import type { AgentTaskUpdate, ChatMessage } from '@/lib/makerChatStore';
// ── 工厂 ───────────────────────────────────────────────────────────────────
@@ -164,14 +168,22 @@ describe('运行中子 Agent — 已回答 turn(groupAnsweredTurnItems)', () =>
// ── Scenario C:流式尾 turn 的 legacy 折叠路径 ───────────────────────────────
-describe('后台任务自动续跑 — 每个 SDK turn 的正式总结都保留', () => {
- it('主任务总结不会被后台门禁完成后的补充回复顶进「已工作」', () => {
+describe('后台任务自动续跑 — 只有最后一次 seal 是收尾正文', () => {
+ const formalSummary = [
+ '## 改动总结',
+ '',
+ '- 实现了功能主体',
+ '- 补了回归测试',
+ '- 本地门禁通过',
+ ].join('\n');
+
+ it('交付正文形态的主任务总结不会被后台门禁完成后的补充回复顶进「已工作」', () => {
const messages: ChatMessage[] = [
mkUser('u1', '实现功能并跑完整门禁'),
mkThinking('main-thinking'),
mkTool('main-edit', 'Edit'),
mkResult('main-edit-result', 'tu-main-edit'),
- mkAssistant('main-summary', '功能已实现并通过验证。正式总结如下。', true),
+ mkAssistant('main-summary', formalSummary, true),
mkTool('gate-check', 'Bash'),
mkResult('gate-result', 'tu-gate-check', 'exit 0'),
mkAssistant('gate-followup', '后台预跑的仓库级门禁已通过。', true),
@@ -191,6 +203,56 @@ describe('后台任务自动续跑 — 每个 SDK turn 的正式总结都保留'
)).toBe(false);
});
+ // 原始形状(2026-09-27):主对话开 4 个后台子 Agent,每回来一个就被唤醒核对一次、
+ // 各盖一次 seal。中间几句「还在等 / 核实了」曾各自当成最终答复留在外面,把工作过程
+ // 切成 5 段「已工作」。
+ it('后台唤醒产生的中间短句 seal 折进同一个「已工作」,只留最后的总结', () => {
+ const messages: ChatMessage[] = [
+ mkUser('u1', '对比安卓和 iOS 的交互差异'),
+ mkTool('survey', 'Bash'),
+ mkResult('survey-result', 'tu-survey'),
+ mkAssistant('wait', 'Four agents are still running. I\'ll hold here until they report back.', true),
+ mkAssistant('wake-1', '伙伴部分先回来了。我先抽查它报的两条行为差异。'),
+ mkTool('check-1', 'Bash'),
+ mkResult('check-1-result', 'tu-check-1'),
+ mkAssistant('verified-1', 'The host rejects it rather than truncating, so that finding holds.', true),
+ mkAssistant('wake-2', '最后一部分也回来了。我再核对两条。'),
+ mkTool('check-2', 'Bash'),
+ mkResult('check-2-result', 'tu-check-2'),
+ mkAssistant('final', formalSummary, true),
+ ];
+
+ const items = groupWorkRuns(buildRenderItems(messages).items, false);
+ const topLevelMessages = items
+ .filter((item) => item.type === 'message')
+ .map((item) => item.message.clientId);
+
+ expect(topLevelMessages).toEqual(['u1', 'final']);
+ expect(workGroups(items)).toHaveLength(1);
+ expect(collectTurnFinalAssistantClientIds(messages)).toEqual(new Set(['final']));
+ });
+
+ it('更早的交付正文 seal 仍留在组外并保留操作行', () => {
+ const messages: ChatMessage[] = [
+ mkUser('u1'),
+ mkTool('work', 'Bash'),
+ mkResult('work-result', 'tu-work'),
+ mkAssistant('early-report', formalSummary, true),
+ mkAssistant('short-wait', '还有一个子任务在跑。', true),
+ mkTool('check', 'Bash'),
+ mkResult('check-result', 'tu-check'),
+ mkAssistant('final', '全部核对完毕。', true),
+ ];
+
+ const items = groupWorkRuns(buildRenderItems(messages).items, false);
+ const topLevelMessages = items
+ .filter((item) => item.type === 'message')
+ .map((item) => item.message.clientId);
+
+ expect(topLevelMessages).toEqual(['u1', 'early-report', 'final']);
+ expect(collectTurnFinalAssistantClientIds(messages)).toEqual(new Set(['early-report', 'final']));
+ });
+
it('同一 sealed SDK turn 的连续多段正式正文都留在组外', () => {
const messages: ChatMessage[] = [
mkUser('u1'),
@@ -207,20 +269,23 @@ describe('后台任务自动续跑 — 每个 SDK turn 的正式总结都保留'
expect(topLevelMessages).toEqual(['u1', 'summary-part-1', 'summary-part-2']);
});
- it('现有 turnCostUsd 也能让已落库历史恢复每个 SDK turn 的 seal', () => {
+ it('现有 turnCostUsd 也能让已落库历史恢复 SDK turn 的 seal', () => {
const messages: ChatMessage[] = [
mkUser('u1'),
+ mkTool('cost-work', 'Bash'),
+ mkResult('cost-work-result', 'tu-cost-work'),
{ ...mkAssistant('cost-summary', '历史正式总结'), turnCostUsd: 1 },
mkTool('cost-tool', 'Bash'),
mkResult('cost-result', 'tu-cost-tool'),
- { ...mkAssistant('cost-followup', '历史后台补充'), turnCostUsd: 0.1 },
+ mkAssistant('trailing-progress', '未封口的尾部进度'),
];
const items = groupWorkRuns(buildRenderItems(messages).items, false);
const topLevelMessages = items
.filter((item) => item.type === 'message')
.map((item) => item.message.clientId);
- expect(topLevelMessages).toEqual(['u1', 'cost-summary', 'cost-followup']);
+ // 没有 seal 时会回退成保留最后一条正文(trailing-progress)。
+ expect(topLevelMessages).toEqual(['u1', 'cost-summary']);
});
it('无 turn seal 的旧历史继续只保留最后一条 assistant 回退', () => {
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index b06a8d7ad3..123430296a 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -68,6 +68,7 @@ import {
findMessageTodoInsertions,
getLatestMessageTodoState,
isAgentPlanToolName,
+ isDeliveryProseText,
isPlanUserBoundary,
isSubagentParentToolUseId,
} from '@cindy/maker-shared/message-render';
@@ -909,7 +910,9 @@ export function collectTurnFinalAssistantClientIds(messages: readonly ChatMessag
continue;
}
if (isCompletedAssistantMessage(message)) {
- out.add(message.clientId);
+ // 后台唤醒会让同一 user turn 盖多次 seal:只有最后一次是收尾正文,更早的
+ // 只在作为交付正文留在折叠组外时保留操作行(与 groupWorkRuns 同口径)。
+ if (!sealedAnswerFound || isDeliveryProseText(message.content)) out.add(message.clientId);
sealedAnswerFound = true;
pendingLegacyFallback = null;
continue;
diff --git a/apps/desktop/src/renderer/features/bots/botConversationPresentation.ts b/apps/desktop/src/renderer/features/bots/botConversationPresentation.ts
index 8b3303c92e..31334dcb84 100644
--- a/apps/desktop/src/renderer/features/bots/botConversationPresentation.ts
+++ b/apps/desktop/src/renderer/features/bots/botConversationPresentation.ts
@@ -29,6 +29,11 @@ function publicItems(items: readonly RenderItem[]): RenderItem[] {
});
}
+function expandWorkGroups(items: readonly RenderItem[]): RenderItem[] {
+ return items.flatMap((item): RenderItem[] =>
+ item.type === 'work_group' ? expandWorkGroups(item.children) : [item]);
+}
+
/** A presentation-only projection. Never mutate messages or infer intent from prose.
* isFinal from the adapters closes a text block, not a turn (Pi/Claude can call
* another tool afterwards). Reuse the normal work-group turn seal, omitting
@@ -69,13 +74,14 @@ function projectWindow(
isStreaming: boolean,
visibleGeneratedFileKeys?: ReadonlySet<string>,
): RenderItem[] {
- // groupWorkRuns leaves every contiguous block of a sealed answer outside its
- // work group. Only the last block carries the seal. Capture that run before
- // unwrapping groups/removing thinking, which must remain answer boundaries.
+ // A sealed answer may span several contiguous prose blocks; only the last carries
+ // the seal. groupWorkRuns folds earlier background-wake seals into work groups, so
+ // scan the expanded sequence while tools and thinking still act as boundaries.
+ const expanded = expandWorkGroups(items);
const sealedAnswers = new Set<ChatMessage>();
let sealedRun = false;
- for (let index = items.length - 1; index >= 0; index -= 1) {
- const item = items[index];
+ for (let index = expanded.length - 1; index >= 0; index -= 1) {
+ const item = expanded[index];
if (!isProse(item) || !item.message.content.trim()) {
sealedRun = false;
continue;
diff --git a/apps/mobile/src/__tests__/companionConversationPresentation.test.ts b/apps/mobile/src/__tests__/companionConversationPresentation.test.ts
index d04688c8a7..6fb2b19031 100644
--- a/apps/mobile/src/__tests__/companionConversationPresentation.test.ts
+++ b/apps/mobile/src/__tests__/companionConversationPresentation.test.ts
@@ -29,6 +29,16 @@ it('keeps all contiguous blocks of a sealed final answer', () => {
const text = items.filter(item => item.type === 'message').map(item => item.message.body);
expect(text).toEqual(['Help', 'Part one', 'Part two']);
});
+it('keeps every sealed reply block after a continuation even when the main timeline folds earlier seals', () => {
+ const items = bodies([...base,
+ row('a4', 'assistant', 'First block'), row('a5', 'assistant', 'First reply', { turnCompleted: true }),
+ row('t6', 'tool_use', { toolName: 'Read', toolUseId: 't6', input: { path: 'private' } }),
+ row('r7', 'tool_result', { toolUseId: 't6', result: 'more technical details' }),
+ row('a8', 'assistant', 'Second reply', { turnCompleted: true }),
+ ], false);
+ const text = items.filter(item => item.type === 'message').map(item => item.message.body);
+ expect(text).toEqual(['Help', 'First block', 'First reply', 'Second reply']);
+});
it('keeps delivered attachments without their preamble', () => {
const items = bodies([...base, row('a4', 'assistant', '![Picture](https://example.com/picture.png)')], false);
expect(JSON.stringify(items)).toContain('picture.png');
diff --git a/apps/mobile/src/__tests__/messageRenderModel.test.ts b/apps/mobile/src/__tests__/messageRenderModel.test.ts
index 57654a25c6..d7c89040c5 100644
--- a/apps/mobile/src/__tests__/messageRenderModel.test.ts
+++ b/apps/mobile/src/__tests__/messageRenderModel.test.ts
@@ -534,14 +534,14 @@ describe('messageRenderModel', () => {
expect(turnFinalKeys(items)).toEqual(['a1-final', 'a2-final']);
});
- it('marks every sealed SDK turn when a background task auto-continues the user request', () => {
- const items = buildMobileMessageRenderItems([
+ function backgroundContinuation(mainSummary: string) {
+ return buildMobileMessageRenderItems([
message({ id: 'u1', role: 'user', content: { text: 'q' }, createdAt: at(1) }),
toolUse('main-work', 'Read', { file_path: '/repo/a.ts' }, 2),
message({
id: 'main-summary',
role: 'assistant',
- content: '正式总结',
+ content: mainSummary,
agentMeta: { turnCompleted: true },
createdAt: at(3),
}),
@@ -554,6 +554,17 @@ describe('messageRenderModel', () => {
createdAt: at(5),
}),
]);
+ }
+
+ it('folds an earlier short sealed reply when a background task auto-continues the user request', () => {
+ const items = backgroundContinuation('还有一个后台任务在跑。');
+
+ expect(turnFinalKeys(items)).toEqual(['gate-followup']);
+ expect(items.map((item) => item.type)).toEqual(['message', 'work_group', 'message']);
+ });
+
+ it('keeps an earlier sealed delivery-prose summary visible across a background auto-continuation', () => {
+ const items = backgroundContinuation('## 正式总结\n\n- 第一条\n- 第二条\n- 第三条');
expect(turnFinalKeys(items)).toEqual(['main-summary', 'gate-followup']);
expect(items.map((item) => item.type)).toEqual([
diff --git a/apps/mobile/src/session/companionConversationPresentation.ts b/apps/mobile/src/session/companionConversationPresentation.ts
index acf51a555e..be96b9c1cb 100644
--- a/apps/mobile/src/session/companionConversationPresentation.ts
+++ b/apps/mobile/src/session/companionConversationPresentation.ts
@@ -7,12 +7,17 @@ const isDelivery = (item: MobileMessageRenderItem) => item.type === 'tool_media'
|| !!item.message.attachments?.length || !!item.message.media?.length
|| !!item.message.files?.length || collectMobileMarkdownImages(item.message.body).length > 0);
+const expandWorkGroups = (items: readonly MobileMessageRenderItem[]): MobileMessageRenderItem[] =>
+ items.flatMap(item => item.type === 'work_group' ? expandWorkGroups(item.children) : [item]);
+
/** Presentation only. The host's persisted messages and lazy history remain intact. */
export function companionConversationItems(items: readonly MobileMessageRenderItem[]): MobileMessageRenderItem[] {
+ // The main timeline folds earlier background-wake seals into work groups; teammate chats
+ // still show every sealed reply, so find sealed runs with tools/thinking as boundaries.
const sealed = new Set<string>();
let sealedRun = false;
let nextAssistantAt: number | null = null;
- for (const item of [...items].reverse()) {
+ for (const item of expandWorkGroups(items).reverse()) {
if (item.type !== 'message' || item.message.kind !== 'assistant' || !item.message.body.trim() || item.message.systemCardType) {
sealedRun = false;
nextAssistantAt = null;
diff --git a/apps/mobile/src/session/messageRenderModel.ts b/apps/mobile/src/session/messageRenderModel.ts
index 88ef759f7d..dc2829e91f 100644
--- a/apps/mobile/src/session/messageRenderModel.ts
+++ b/apps/mobile/src/session/messageRenderModel.ts
@@ -3,6 +3,7 @@ import {
buildMessageRenderItems,
extractTodosFromSourceMessage,
formatDuration,
+ isDeliveryProseText,
type MessageRenderAgentTaskItem,
type MessageRenderItem,
type MessageRenderOptions,
@@ -165,12 +166,12 @@ export function markTurnFinalAssistants(
): void {
const suppressTailFinalAssistant = isSessionStreaming && hasActiveLoadedTail(normalized);
let lastCandidate: NormalizedRemoteMessage | null = null;
- let sealedAnswerFound = false;
+ let lastSealed: NormalizedRemoteMessage | null = null;
for (const message of normalized) {
if (message.kind === 'user' && message.label === 'user' && !isSubagentChildMessage(message)) {
- if (!sealedAnswerFound && lastCandidate) lastCandidate.isTurnFinalAssistant = true;
+ if (!lastSealed && lastCandidate) lastCandidate.isTurnFinalAssistant = true;
lastCandidate = null;
- sealedAnswerFound = false;
+ lastSealed = null;
continue;
}
if (
@@ -180,12 +181,17 @@ export function markTurnFinalAssistants(
) {
lastCandidate = message;
if (message.turnCompleted === true) {
+ // 后台唤醒会让同一 turn 盖多次 seal:只有最后一次是收尾正文,更早的只在
+ // 作为交付正文留在折叠组外时保留操作行(与 groupWorkRuns 同口径)。
+ if (lastSealed && !isDeliveryProseText(lastSealed.body)) {
+ delete lastSealed.isTurnFinalAssistant;
+ }
message.isTurnFinalAssistant = true;
- sealedAnswerFound = true;
+ lastSealed = message;
}
}
}
- if (!sealedAnswerFound && lastCandidate && !suppressTailFinalAssistant) {
+ if (!lastSealed && lastCandidate && !suppressTailFinalAssistant) {
lastCandidate.isTurnFinalAssistant = true;
}
}
diff --git a/packages/maker-shared/src/__tests__/messageRender.test.ts b/packages/maker-shared/src/__tests__/messageRender.test.ts
index 26429da6fa..56d2f4b028 100644
--- a/packages/maker-shared/src/__tests__/messageRender.test.ts
+++ b/packages/maker-shared/src/__tests__/messageRender.test.ts
@@ -204,8 +204,8 @@ describe('message render shared model', () => {
expect(todo.todos).toEqual([{ content: 'Implement', status: 'completed', activeForm: undefined }]);
});
- it('keeps every sealed SDK-turn summary visible across a background auto-continuation', () => {
- const items = buildMessageRenderItems([
+ function backgroundContinuation(mainSummary: string): MessageRenderItem<FixtureSource>[] {
+ return buildMessageRenderItems([
message({ kind: 'user', source: source('user', 'start', 1), body: 'start', label: 'user' }),
message({
kind: 'thinking',
@@ -215,8 +215,8 @@ describe('message render shared model', () => {
}),
message({
kind: 'assistant',
- source: source('main-summary', 'formal summary', 4),
- body: 'formal summary',
+ source: source('main-summary', mainSummary, 4),
+ body: mainSummary,
label: 'assistant',
turnCompleted: true,
}),
@@ -234,6 +234,19 @@ describe('message render shared model', () => {
turnCompleted: true,
}),
]);
+ }
+
+ // 后台唤醒(异步子 Agent、后台 shell)会在同一个 user turn 里盖多次 seal;
+ // 只有最后一次是收尾正文,更早的短句按过程文字折叠。
+ it('folds earlier short sealed replies when background work auto-continues the turn', () => {
+ const items = backgroundContinuation('Agents are still running; waiting for them.');
+
+ expect(items.map((item) => item.type)).toEqual(['message', 'work_group', 'message']);
+ expect(expectType(items[2], 'message').message.key).toBe('gate-followup');
+ });
+
+ it('keeps an earlier sealed delivery-prose summary visible across a background auto-continuation', () => {
+ const items = backgroundContinuation('## Summary\n\n- implemented\n- tested\n- verified');
expect(items.map((item) => item.type)).toEqual([
'message',
diff --git a/packages/maker-shared/src/workRunGrouping.ts b/packages/maker-shared/src/workRunGrouping.ts
index a89a95fbe7..86e0ad950a 100644
--- a/packages/maker-shared/src/workRunGrouping.ts
+++ b/packages/maker-shared/src/workRunGrouping.ts
@@ -167,35 +167,35 @@ function groupAnsweredTurn<TItem, TChild extends TItem>(
): TItem[] | null {
const answers = new Set<number>();
let lastAnswer = -1;
+ let lastSealed = -1;
for (let index = 0; index < items.length; index++) {
if (!adapter.isAnswer(items[index])) continue;
lastAnswer = index;
- if (adapter.isSealedAnswer(items[index])) answers.add(index);
+ if (adapter.isSealedAnswer(items[index])) lastSealed = index;
}
if (lastAnswer < 0) return null;
- if (answers.size > 0) {
- let segmentStart = 0;
- for (const sealedIndex of [...answers]) {
- let lastActivity = -1;
- for (let index = sealedIndex - 1; index >= segmentStart; index--) {
- if (adapter.isActivity(items[index])) {
- lastActivity = index;
- break;
- }
- }
- let answerStart = sealedIndex;
- while (
- answerStart > lastActivity + 1 &&
- answerStart > segmentStart &&
- adapter.isAnswer(items[answerStart - 1])
- ) {
- answerStart--;
- }
- for (let index = answerStart; index <= sealedIndex; index++) {
- if (adapter.isAnswer(items[index])) answers.add(index);
+ if (lastSealed >= 0) {
+ // Background wake-ups (async agents, background shells) seal several SDK turns under
+ // one user row; only the last seal is the turn's answer. Earlier seals fold like any
+ // progress text unless isArchivable keeps them visible as delivery prose.
+ const sealedIndex = lastSealed;
+ let lastActivity = -1;
+ for (let index = sealedIndex - 1; index >= 0; index--) {
+ if (adapter.isActivity(items[index])) {
+ lastActivity = index;
+ break;
}
- segmentStart = sealedIndex + 1;
+ }
+ let answerStart = sealedIndex;
+ while (
+ answerStart > lastActivity + 1 &&
+ adapter.isAnswer(items[answerStart - 1])
+ ) {
+ answerStart--;
+ }
+ for (let index = answerStart; index <= sealedIndex; index++) {
+ if (adapter.isAnswer(items[index])) answers.add(index);
}
} else {
if (