Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 107 additions & 16 deletions apps/web/src/components/chat/MessagesTimeline.logic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -546,7 +546,7 @@ describe("deriveMessagesTimelineRows", () => {
expect(foldRow?.label).toBe("Worked for 22s");
expect(collapsedRows.map((row) => row.id)).toEqual([
"user-entry",
"turn-fold:turn-1",
"turn-fold:assistant-first-entry",
"assistant-final-entry",
]);

Expand All @@ -561,7 +561,7 @@ describe("deriveMessagesTimelineRows", () => {

expect(expandedRows.map((row) => row.id)).toEqual([
"user-entry",
"turn-fold:turn-1",
"turn-fold:assistant-first-entry",
"assistant-first-entry",
"work-toggle:work-entry-1",
"assistant-final-entry",
Expand Down Expand Up @@ -625,7 +625,10 @@ describe("deriveMessagesTimelineRows", () => {
revertTurnCountByUserMessageId: new Map(),
});

expect(rows.map((row) => row.id)).toEqual(["turn-fold:turn-1", "assistant-final-entry"]);
expect(rows.map((row) => row.id)).toEqual([
"turn-fold:assistant-first-entry",
"assistant-final-entry",
]);
});

it("derives a sane duration for a steer-superseded turn with one instant commentary message", () => {
Expand Down Expand Up @@ -822,7 +825,7 @@ describe("deriveMessagesTimelineRows", () => {
});

expect(rows.map((row) => row.id)).toEqual([
"turn-fold:turn-1",
"turn-fold:work-entry-1",
"assistant-final-entry",
"user-followup-entry",
"working-indicator-row",
Expand Down Expand Up @@ -1379,7 +1382,7 @@ describe("deriveMessagesTimelineRows", () => {
// turn id that opened the response.
expect(rows.map((row) => row.id)).toEqual([
"user-1-entry",
"turn-fold:turn-1",
"turn-fold:work-1-entry",
"assistant-final-entry",
]);
const foldRow = rows.find(
Expand Down Expand Up @@ -1411,7 +1414,7 @@ describe("deriveMessagesTimelineRows", () => {
expect(rows.some((row) => row.kind === "turn-fold")).toBe(false);
});

it("keeps one fold across a same-turn steer and keeps both user messages visible", () => {
it("folds a same-turn steer as one segment per side of the steer", () => {
const timelineEntries = [
userEntry("user-1", "2026-01-01T00:00:00Z"),
workEntry("work-1", "2026-01-01T00:00:05Z", "turn-1"),
Expand All @@ -1425,30 +1428,43 @@ describe("deriveMessagesTimelineRows", () => {
latestTurn: {
turnId: "turn-1" as never,
state: "running",
startedAt: "2026-01-01T00:00:00Z",
// The turn started after its user message waited in the queue.
startedAt: "2026-01-01T00:00:02Z",
completedAt: null,
},
isWorking: true,
activeTurnStartedAt: "2026-01-01T00:00:00Z",
activeTurnStartedAt: "2026-01-01T00:00:02Z",
});
expect(runningRows.some((row) => row.kind === "turn-fold")).toBe(false);
// Work the steer already interrupted is finished, so it folds even though
// the turn is still running; the live segment stays open.
expect(runningRows.filter((row) => row.kind === "turn-fold")).toEqual([
expect.objectContaining({ id: "turn-fold:work-1-entry", label: "Worked for 3.0s" }),
]);
expect(runningRows.map((row) => row.id)).toContain("work-toggle:work-2-entry");

const settledRows = deriveMessagesTimelineRows({
...baseFoldInput,
timelineEntries,
latestTurn: {
turnId: "turn-1" as never,
state: "completed",
startedAt: "2026-01-01T00:00:00Z",
startedAt: "2026-01-01T00:00:02Z",
completedAt: "2026-01-01T00:00:30Z",
},
});
expect(settledRows.map((row) => row.id)).toEqual([
"user-1-entry",
"turn-fold:turn-1",
"turn-fold:work-1-entry",
"user-steer-entry",
"turn-fold:work-2-entry",
"assistant-final-entry",
]);
// Pre-steer segment runs from the turn's own start to the steer; the
// post-steer segment runs from the steer to the turn's completion.
expect(settledRows.filter((row) => row.kind === "turn-fold").map((row) => row.label)).toEqual([
"Worked for 3.0s",
"Worked for 20s",
]);
});

it("keeps fold row ids unique when an old-turn row straddles the next user message", () => {
Expand Down Expand Up @@ -1478,12 +1494,48 @@ describe("deriveMessagesTimelineRows", () => {

expect(rows.map((row) => row.id)).toEqual([
"user-1-entry",
"turn-fold:turn-1",
"turn-fold:work-1-entry",
"assistant-one-entry",
"user-2-entry",
"turn-fold:work-2-entry",
"assistant-two-entry",
]);
});

it("keeps a straggling old-turn row from stealing the next response's start", () => {
const rows = deriveMessagesTimelineRows({
...baseFoldInput,
timelineEntries: [
userEntry("user-1", "2026-01-01T00:00:00Z"),
workEntry("work-1", "2026-01-01T00:00:05Z", "turn-1"),
assistantEntry("assistant-one", "2026-01-01T00:00:10Z", "turn-1"),
userEntry("user-2", "2026-01-01T00:00:20Z"),
// The straggler lands before turn-2 opens: turn-1 already answered, so
// the row is residue and the second response still starts at user-2.
workEntry("work-late", "2026-01-01T00:00:21Z", "turn-1"),
workEntry("work-2", "2026-01-01T00:00:22Z", "turn-2"),
assistantEntry("assistant-two", "2026-01-01T00:00:40Z", "turn-2"),
],
latestTurn: {
turnId: "turn-2" as never,
state: "completed",
startedAt: "2026-01-01T00:00:21Z",
completedAt: "2026-01-01T00:00:40Z",
},
});

expect(rows.map((row) => row.id)).toEqual([
"user-1-entry",
"turn-fold:work-1-entry",
"assistant-one-entry",
"user-2-entry",
"turn-fold:turn-2",
"turn-fold:work-2-entry",
"assistant-two-entry",
]);
expect(rows.filter((row) => row.kind === "turn-fold").map((row) => row.turnId)).toEqual([
"turn-1",
"turn-2",
]);
});

it("folds turn-less background rows into the latest response segment", () => {
Expand Down Expand Up @@ -1518,10 +1570,10 @@ describe("deriveMessagesTimelineRows", () => {

expect(rows.map((row) => row.id)).toEqual([
"user-1-entry",
"turn-fold:turn-1",
"turn-fold:work-1-entry",
"assistant-one-entry",
"user-2-entry",
"turn-fold:turn-2",
"turn-fold:work-2-entry",
"assistant-two-entry",
]);
});
Expand Down Expand Up @@ -1558,7 +1610,7 @@ describe("deriveMessagesTimelineRows", () => {
const rows = deriveMessagesTimelineRows({ ...baseFoldInput, timelineEntries, latestTurn });
expect(rows.map((row) => row.id)).toEqual([
"user-1-entry",
"turn-fold:turn-1",
"turn-fold:work-1-entry",
"spawn-1-entry",
"spawn-wf-entry",
"assistant-final-entry",
Expand All @@ -1584,6 +1636,45 @@ describe("deriveMessagesTimelineRows", () => {
});
});

it("keeps the response and its spawn row in the post-steer segment only", () => {
const rows = deriveMessagesTimelineRows({
...baseFoldInput,
timelineEntries: [
userEntry("user-1", "2026-01-01T00:00:00Z"),
assistantEntry("assistant-plan", "2026-01-01T00:00:04Z", "turn-1"),
workEntry("work-1", "2026-01-01T00:00:06Z", "turn-1"),
userEntry("user-steer", "2026-01-01T00:00:12Z"),
workEntry("work-2", "2026-01-01T00:00:18Z", "turn-1"),
spawnEntry("spawn-1", "2026-01-01T00:00:20Z", "turn-1", ["agent-a"]),
assistantEntry("assistant-final", "2026-01-01T00:00:40Z", "turn-1"),
],
latestTurn: {
turnId: "turn-1" as never,
state: "completed",
startedAt: "2026-01-01T00:00:00Z",
completedAt: "2026-01-01T00:00:45Z",
},
});

// The pre-steer segment hides its commentary too; only the segment that
// ends the turn keeps the response, its spawn row and the separator.
expect(rows.map((row) => row.id)).toEqual([
"user-1-entry",
"turn-fold:assistant-plan-entry",
"user-steer-entry",
"turn-fold:work-2-entry",
"spawn-1-entry",
"assistant-final-entry",
]);
expect(rows.filter((row) => row.kind === "turn-fold").map((row) => row.label)).toEqual([
"Worked for 6.0s",
"Worked for 33s",
]);
expect(
rows.flatMap((row) => (row.kind === "message" && row.showsTurnFoldSeparator ? [row.id] : [])),
).toEqual(["assistant-final-entry"]);
});

it("uses the stopped label when the interrupted turn is a grouped synthetic continuation", () => {
const rows = deriveMessagesTimelineRows({
...baseFoldInput,
Expand Down
60 changes: 46 additions & 14 deletions apps/web/src/components/chat/MessagesTimeline.logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,8 @@ export type MessagesTimelineRow =
message: ChatMessage;
durationStart: string;
showAssistantMeta: boolean;
/** Draws the fold's separator above this message when a fold leads into it. */
showsTurnFoldSeparator: boolean;

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

【给审查者的说明】消息行多一个布尔字段:这条最终回复上面要不要画分隔线。原来分隔线画在折叠行底部,会落在"Ran N subagents"行的上面;你要求的顺序是 折叠行、subagents 行、分隔线、最终回复,所以分隔线要挪到最终回复的顶部。渲染层一次只看一行,不知道上面有没有折叠,必须由这里算好告诉它。

showAssistantCopyButton: boolean;
assistantCopyStreaming: boolean;
assistantTurnDiffSummary?: TurnDiffSummary | undefined;
Expand Down Expand Up @@ -341,6 +343,8 @@ interface TurnFold {
createdAt: string;
hiddenEntryIds: ReadonlySet<string>;
label: string;
/** The terminal assistant message this fold leads into, when it has one. */
terminalEntryId: string | null;

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

【说明】折叠记录里记下它通向哪条最终回复。上面那个布尔字段就是靠这个算出来的。没有最终回复的折叠(steer 之前的那一段)这里是 null,于是不画分隔线,符合"上方折叠只显示 Worked for X"。

/** The group's direct-spawn CTA, carrying every direct spawn the fold absorbed. */
spawnRow: { entryId: string; entry: WorkLogEntry } | null;
}
Expand Down Expand Up @@ -395,6 +399,8 @@ function workEntryIsActiveTurnActivity(entry: WorkLogEntry): boolean {
* Settled turns keep only their terminal assistant message visible.
* Everything before it folds behind a "Worked for ..." row anchored at the
* first hidden entry, so the duration leads directly into the final response.
* A user message that lands mid-turn (a steer) splits the turn into segments
* that fold separately, so each fold stays above the work it covers.
Comment on lines +402 to +403

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

【说明】只是把函数说明补一句:一个回合里出现 steer 时,会按 steer 前后分成几段,各自折叠。

*/
function deriveTurnFolds(input: {
timelineEntries: ReadonlyArray<TimelineEntry>;
Expand All @@ -405,6 +411,8 @@ function deriveTurnFolds(input: {
interface TurnGroup {
/** The turn id that opened the group; keeps the fold's identity stable. */
turnId: TurnId;
/** Opened by a steer, so it cannot read the turn's own start time. */
steered: boolean;
Comment on lines +414 to +415

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

【说明】分组多一个布尔:这一段是不是由 steer 开出来的。它只在算时长时用:由 steer 开出来的段,起点是 steer 那条消息,不能再用回合本身的开始时间。

entries: Array<TimelineEntry>;
terminalEntry: Extract<TimelineEntry, { kind: "message" }> | null;
hasStreamingMessage: boolean;
Expand All @@ -416,6 +424,8 @@ function deriveTurnFolds(input: {
*/
startBoundary: string | null;
}
// Every segment in timeline order, plus the one each turn id writes into now.
const groups: Array<TurnGroup> = [];
Comment on lines +427 to +428

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

【说明】新增一个按时间线顺序排的分组列表。原来只有一张"回合 id → 分组"的表,一个回合拆成两段之后,后一段会把前一段从表里顶掉,前一段就再也折叠不到了。这个列表保证每一段都会被折叠。表本身保留,用来找"这个回合当前正在写入哪一段"。

const groupsByTurnId = new Map<TurnId, TurnGroup>();

let pendingUserBoundary: string | null = null;
Expand All @@ -435,20 +445,32 @@ function deriveTurnFolds(input: {
// group, even past the next user message, since no new response has
// started until a turn id shows up.
let group: TurnGroup | null = turnId ? (groupsByTurnId.get(turnId) ?? null) : lastGroup;
// The turn read a steer and kept working: close the segment it interrupted
// so that fold stays above the work it covers, and open a new one below the
// steer. Trade-off: a group that already holds its response is done talking,
// so a late row is residue and rides it instead of splitting.
const steeredGroup: TurnGroup | null =
group?.terminalEntry === null && turnId && pendingUserBoundary !== null ? group : null;
if (steeredGroup) group = null;
Comment on lines +448 to +454

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

【说明】这就是拆分本身,整个 PR 的核心判断。条件:这一行属于某个回合、它当前的段还没有出现最终回复、而且中间来过一条用户消息(steer)。满足就把当前段关掉,后面的行落到新段里。

取舍写在注释里:如果当前段已经有了最终回复,说明回合已经说完话,之后再来的行是后台残留(比如迟到的工具完成记录),不拆,跟着原来的段走。Codex 机器人提的第三条(被中断、从没回复过的旧回合的残留行会被当成 steer)就是这个取舍的另一面:不往前看时间线没法区分,作为已知限制写在 PR 正文里。

if (!group) {
if (!turnId) {
continue;
}
// A fresh turn id with no user message since the last group opened is a
// synthetic mid-response continuation (subagent wake-up, stop-hook
// retry): it joins that group instead of starting a fold of its own.
group = (pendingUserBoundary === null ? lastGroup : null) ?? {
turnId,
const joinedGroup: TurnGroup | null = pendingUserBoundary === null ? lastGroup : null;
group = joinedGroup ?? {
// A split segment keeps the interrupted group's turn id, so both of
// the turn's folds still expand together.
turnId: steeredGroup?.turnId ?? turnId,
steered: steeredGroup !== null,
entries: [],
terminalEntry: null,
hasStreamingMessage: false,
startBoundary: pendingUserBoundary,
};
if (!joinedGroup) groups.push(group);
Comment on lines +462 to +473

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

【说明】新开一段时的三处改动:(1) turnId 用被打断那段的回合 id,而不是这一行自己的 id。两者通常相同;只有在"合成续接"(子代理唤醒等,带一个新 id 但归入原回合)时不同,用原 id 才能让两段折叠一起展开,这是 Codex 机器人第二条的修法。(2) steered 标记这一段是 steer 开出来的。(3) 新段推进上面的列表;沿用已有分组(joinedGroup)时不推,否则会重复折叠。

pendingUserBoundary = null;
groupsByTurnId.set(turnId, group);
lastGroup = group;
Expand All @@ -465,7 +487,7 @@ function deriveTurnFolds(input: {
}

const foldsByAnchorEntryId = new Map<string, TurnFold>();
for (const group of new Set(groupsByTurnId.values())) {
for (const group of groups) {

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

【说明】折叠时改成遍历有序列表,而不是表里的值。原因同上:表里每个回合只剩最后一段。

const { turnId } = group;
if (input.unsettledTurnId !== null && groupsByTurnId.get(input.unsettledTurnId) === group) {
continue;
Expand Down Expand Up @@ -517,20 +539,20 @@ function deriveTurnFolds(input: {
const isLatestInterruptedTurn =
input.latestTurn?.state === "interrupted" &&
groupsByTurnId.get(input.latestTurn.turnId) === group;
// The turn's own clock, when this group opened under the latest turn.
const ownTurn = input.latestTurn?.turnId === turnId ? input.latestTurn : null;
Comment on lines +542 to +543

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

【说明】把"这个分组属于最新那个回合"的判断提出来,下面两处都用;提出来之后下面的表达式就短了。

// A turn cut short by a steer leaves trailing work entries behind its
// terminal message — take whichever ended last.
const lastEntryEnd =
lastEntry.kind === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt;
const elapsedMs =
input.latestTurn?.turnId === turnId &&
input.latestTurn.startedAt &&
input.latestTurn.completedAt
? computeElapsedMs(input.latestTurn.startedAt, input.latestTurn.completedAt)
: computeElapsedMs(
group.startBoundary ?? firstEntry.createdAt,
maxIsoTimestamp(group.terminalEntry?.message.updatedAt ?? null, lastEntryEnd) ??
lastEntryEnd,
);
// Only the segment that opened the turn may read its start, and only the
// one that closed it may read its completion; a steer bounds the rest.
const elapsedMs = computeElapsedMs(
(group.steered ? null : ownTurn?.startedAt) ?? group.startBoundary ?? firstEntry.createdAt,
(groupsByTurnId.get(turnId) === group ? ownTurn?.completedAt : null) ??
maxIsoTimestamp(group.terminalEntry?.message.updatedAt ?? null, lastEntryEnd) ??
lastEntryEnd,
);
Comment on lines +548 to +555

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

【说明】时长计算改写。原来:如果是最新回合,就直接用回合的开始和结束时间;否则用条目时间。拆成几段之后不能整段照搬:只有开回合的那段(steered 为 false)能用回合的开始时间,只有收尾的那段(表里当前指向的那段)能用回合的完成时间,中间被 steer 截断的那头用条目时间。顺带修了 Codex 机器人第一条:被 steer 的回合,第一段也应从回合真正开始算,而不是从消息排队的时间算。

const duration = elapsedMs !== null ? formatDuration(elapsedMs) : null;
const label = isLatestInterruptedTurn
? duration
Expand All @@ -546,6 +568,7 @@ function deriveTurnFolds(input: {
createdAt: firstHiddenEntry.createdAt,
hiddenEntryIds,
label,
terminalEntryId: group.terminalEntry?.id ?? null,

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

【说明】把最终回复的 id 写进折叠记录,见上面 terminalEntryId 的说明。

spawnRow,
});
}
Expand Down Expand Up @@ -580,7 +603,13 @@ export function deriveMessagesTimelineRows(input: {
});
const collapsedEntryIds = new Set<string>();
const mergedSpawnEntries = new Map<string, WorkLogEntry>();
// A fold's separator rides the response it leads into, so it lands below any
// spawn row the fold kept visible.
const foldTerminalEntryIds = new Set<string>();
for (const fold of foldsByAnchorEntryId.values()) {
if (fold.terminalEntryId !== null) {
foldTerminalEntryIds.add(fold.terminalEntryId);
}
Comment on lines +606 to +612

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

【说明】收集所有"有折叠通向它"的最终回复 id,下面给消息行打分隔线标记时查一下。放在这个已有的循环里,不另起循环。

if (!input.expandedTurnIds?.has(fold.turnId)) {
for (const entryId of fold.hiddenEntryIds) {
collapsedEntryIds.add(entryId);
Expand Down Expand Up @@ -704,7 +733,8 @@ export function deriveMessagesTimelineRows(input: {
if (anchoredTurnFold) {
nextRows.push({
kind: "turn-fold",
id: `turn-fold:${anchoredTurnFold.turnId}`,
// Keyed by anchor, not by turn: a steered turn folds once per segment.
id: `turn-fold:${anchoredTurnFold.anchorEntryId}`,
Comment on lines +736 to +737

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

【说明】折叠行的 id 原来是 turn-fold:<回合 id>,一个回合两段就重了。改用锚点条目(折叠隐藏的第一条)的 id,天然唯一,不需要段号计数。这替代了旧版本的 segmentIndex 和计数表。

createdAt: anchoredTurnFold.createdAt,
turnId: anchoredTurnFold.turnId,
label: anchoredTurnFold.label,
Expand Down Expand Up @@ -858,6 +888,7 @@ export function deriveMessagesTimelineRows(input: {
message: timelineEntry.message,
durationStart,
showAssistantMeta,
showsTurnFoldSeparator: foldTerminalEntryIds.has(timelineEntry.id),

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

【说明】给消息行填上分隔线标记。

showAssistantCopyButton: showAssistantMeta,
assistantCopyStreaming: timelineEntry.message.streaming || assistantTurnStillInProgress,
assistantTurnDiffSummary:
Expand Down Expand Up @@ -962,6 +993,7 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
a.message === bm.message &&
a.durationStart === bm.durationStart &&
a.showAssistantMeta === bm.showAssistantMeta &&
a.showsTurnFoldSeparator === bm.showsTurnFoldSeparator &&

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

【说明】行复用比较里加上新字段,否则标记变了行也不会重画。

a.showAssistantCopyButton === bm.showAssistantCopyButton &&
a.assistantCopyStreaming === bm.assistantCopyStreaming &&
a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
Expand Down
Loading
Loading