diff --git a/docs/architecture/session-projection.md b/docs/architecture/session-projection.md
index 5fdcdd723b..e04b01edc0 100644
--- a/docs/architecture/session-projection.md
+++ b/docs/architecture/session-projection.md
@@ -113,6 +113,15 @@ canonical text or thinking, remove a round or tool result, or turn a settled
record back into an executing one. Externally projected sessions such as ACP
remain owned by their external projection.
+The generation journal also owns the relative order of its model rounds.
+Checkpoints may contain only a suffix or scattered rounds; filling gaps by tail
+append would place earlier tool calls after the final response. Merge metadata
+by stable round ID, then restore journal order and chronological round indexes.
+Keep prior generations ahead of the current generation and retain other rounds
+absent from the journal beside their preceding shared round. Repeating the merge
+must preserve order and all retained records. Completion timestamps and the
+checkpoint's partial indexes are not evidence of execution order.
+
Native Turn completion also reconciles cumulative token usage from the executing
host's durable request ledger before publishing the settled record. The query
uses native request-attempt identities scoped to the Session and Turn, including
diff --git a/src/apps/mobile/AGENTS.md b/src/apps/mobile/AGENTS.md
index 686ac4c127..d3bdf6d6e5 100644
--- a/src/apps/mobile/AGENTS.md
+++ b/src/apps/mobile/AGENTS.md
@@ -105,6 +105,13 @@ UiState or an Intent declared there, and no module above it is visible to them.
same `commonTest` sources onto ART; they are not in CI, so run them by hand
when touching either module.
+## Chat Markdown verification
+
+For chat Markdown ranges, double-tilde strikethrough, escapes and streaming
+prefixes, run from `shared/` with the Android guide's Java runtime:
+`./gradlew :core-feature:jvmTest --tests '*MarkdownParserTest*'`.
+Android and iOS share this parser; their native inline renderers own styles.
+
## Remote capability ownership
For next-input suggestion replay, stale-turn retirement, host restart and session
diff --git a/src/apps/mobile/README.md b/src/apps/mobile/README.md
index 3c0859aaa0..e35d9373c7 100644
--- a/src/apps/mobile/README.md
+++ b/src/apps/mobile/README.md
@@ -20,6 +20,15 @@ and platform adapters. Product logic and stable contracts should remain in the
platform-agnostic Rust layers and be exposed to these apps through explicit
interfaces.
+## Chat Markdown
+
+Android, iOS and HarmonyOS keep single tildes literal in chat, matching the
+desktop and mobile-web renderers: `24~30°C`, `1~2mm` and `~5 min` remain plain
+text. Use `~~removed~~` for strikethrough. Escaped tildes (`\~`) and inline code
+keep their literal text; unfinished double pairs remain literal while streaming.
+This rendering policy applies to existing transcripts without changing the
+host's saved Markdown or requiring a protocol upgrade.
+
## Image messages
All three apps can send images with or without text. Camera photos are decoded
diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/MarkdownContent.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/MarkdownContent.kt
index ab5ee71f2c..b2a198140c 100644
--- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/MarkdownContent.kt
+++ b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/MarkdownContent.kt
@@ -190,6 +190,8 @@ private fun annotatedInlines(
"emphasis" -> withStyle(SpanStyle(fontStyle = FontStyle.Italic)) { append(inline.text) }
+ "delete" -> withStyle(SpanStyle(textDecoration = TextDecoration.LineThrough)) { append(inline.text) }
+
"code" -> withStyle(SpanStyle(fontFamily = FontFamily.Monospace)) { append(inline.text) }
// A link in an agent turn is nearly always a file it just touched,
diff --git a/src/apps/mobile/harmonyos/AGENTS.md b/src/apps/mobile/harmonyos/AGENTS.md
index 8d750879ef..8200064950 100644
--- a/src/apps/mobile/harmonyos/AGENTS.md
+++ b/src/apps/mobile/harmonyos/AGENTS.md
@@ -135,6 +135,14 @@ insertion, 30 identical publications, text correction, deletion and completion;
block counts must be 2, 3, 3, 3, 2, 2, with one visible answer. Verify compact,
wide and live fold transitions, then return to normal `EntryAbility`.
+For chat Markdown tildes, escapes, streaming prefixes and plain/rich copy, run
+`node --test tools/tests/markdown-html-serializer.test.cjs tools/tests/streaming-markdown.test.cjs`.
+These host tests execute the production parser and serializer; they do not
+replace native rendering checks.
+For a parser-only ArkTS compile without packaging/signing, source
+`scripts/ohos-env.sh`, then run
+`"$HVIGORW" --mode module -p product=default -p module=entry@default 'default@CompileArkTS' --no-daemon`.
+
For host shutdown/restart handling, run
`node --test tools/tests/connection-health.test.cjs tools/tests/session-record.test.cjs tools/tests/host-stream.test.cjs`.
In `durable-timeline`, **Host offline** must retain content and disable Stop;
diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/MarkdownParser.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/MarkdownParser.ets
index 37825986a8..52a39ad200 100644
--- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/MarkdownParser.ets
+++ b/src/apps/mobile/harmonyos/entry/src/main/ets/services/MarkdownParser.ets
@@ -114,16 +114,13 @@ export class MarkdownParser {
}
static formatInlineText(value: string): string {
- let text = value;
- text = text.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1 ($2)');
- text = text.replace(/<(https?:\/\/|computer:\/\/|file:\/\/)([^\s<>]+)>/g, '$1$2');
- text = text.replace(/`([^`]+)`/g, '$1');
- text = text.replace(/\*\*([^*]+)\*\*/g, '$1');
- text = text.replace(/__([^_]+)__/g, '$1');
- text = text.replace(/~~([^~]+)~~/g, '$1');
- text = text.replace(/\*([^*]+)\*/g, '$1');
- text = text.replace(/_([^_]+)_/g, '$1');
- return text;
+ return MarkdownParser.plainInlineText(MarkdownParser.parseInlineText(value));
+ }
+
+ private static plainInlineText(inlines: ParsedMarkdownInline[]): string {
+ return inlines.map((inline: ParsedMarkdownInline) => {
+ return inline.type === 'link' && inline.text !== inline.url ? `${inline.text} (${inline.url})` : inline.text;
+ }).join('');
}
private static readCodeBlock(lines: string[], start: number, blocks: ParsedMarkdownBlock[]): number {
@@ -198,11 +195,12 @@ export class MarkdownParser {
text += ' ' + continuationTrimmed;
nextIndex += 1;
}
+ const inlines = MarkdownParser.parseInlineText(text, `li-${start}-${items.length}`);
const item: ParsedMarkdownListItem = {
id: `li-${start}-${items.length}`,
marker,
- text: MarkdownParser.formatInlineText(text),
- inlines: MarkdownParser.parseInlineText(text, `li-${start}-${items.length}`),
+ text: MarkdownParser.plainInlineText(inlines),
+ inlines,
depth: MarkdownParser.listDepth(raw),
checked: taskMatch ? (taskMatch[1].toLowerCase() === 'x' ? 1 : 0) : -1
};
@@ -268,8 +266,8 @@ export class MarkdownParser {
tableRows: ParsedMarkdownTableRow[] = []
): void {
const id = `md-${blocks.length}-${type}`;
- const normalizedText = MarkdownParser.shouldParseInline(type) ? MarkdownParser.formatInlineText(text) : text;
const inlines = MarkdownParser.shouldParseInline(type) ? MarkdownParser.parseInlineText(text, id) : [];
+ const normalizedText = MarkdownParser.shouldParseInline(type) ? MarkdownParser.plainInlineText(inlines) : text;
const block: ParsedMarkdownBlock = {
id,
renderKey: '',
@@ -389,10 +387,13 @@ export class MarkdownParser {
return end + 2;
}
}
- if (value.slice(start, start + 2) === '~~') {
- const end = value.indexOf('~~', start + 2);
+ if (MarkdownParser.isStrikeDelimiter(value, start, false)) {
+ let end = value.indexOf('~~', start + 2);
+ while (end >= 0 && !MarkdownParser.isStrikeDelimiter(value, end, true)) {
+ end = value.indexOf('~~', end + 2);
+ }
if (end > start + 2) {
- MarkdownParser.pushInline(inlines, prefix, 'delete', value.slice(start + 2, end), '');
+ MarkdownParser.pushInline(inlines, prefix, 'delete', MarkdownParser.unescapeText(value.slice(start + 2, end)), '');
return end + 2;
}
}
@@ -448,6 +449,22 @@ export class MarkdownParser {
return next;
}
+ private static isStrikeDelimiter(value: string, index: number, closing: boolean): boolean {
+ // Single tildes are chat ranges; runs longer than two are literal inlines.
+ if (value.slice(index, index + 2) !== '~~' || value.charAt(index - 1) === '~' ||
+ value.charAt(index + 2) === '~' || MarkdownParser.isEscaped(value, index)) {
+ return false;
+ }
+ const before = value.charAt(index - 1);
+ const after = value.charAt(index + 2);
+ const beforeSpace = before.length === 0 || /\s/.test(before);
+ const afterSpace = after.length === 0 || /\s/.test(after);
+ const beforePunctuation = /[\p{P}\p{S}]/u.test(before);
+ const afterPunctuation = /[\p{P}\p{S}]/u.test(after);
+ return closing ? !beforeSpace && (!beforePunctuation || afterSpace || afterPunctuation) :
+ !afterSpace && (!afterPunctuation || beforeSpace || beforePunctuation);
+ }
+
private static pushInline(
inlines: ParsedMarkdownInline[],
prefix: string,
@@ -755,10 +772,11 @@ export class MarkdownParser {
for (let column = 0; column < columnCount; column += 1) {
const text = column < values.length ? values[column] : '';
const id = `table-${start}-${rowIndex}-${column}`;
+ const inlines = MarkdownParser.parseInlineText(text, id);
cells.push({
id,
- text: MarkdownParser.formatInlineText(text),
- inlines: MarkdownParser.parseInlineText(text, id),
+ text: MarkdownParser.plainInlineText(inlines),
+ inlines,
alignment: column < alignments.length ? alignments[column] : 'left'
});
}
diff --git a/src/apps/mobile/harmonyos/tools/tests/markdown-html-serializer.test.cjs b/src/apps/mobile/harmonyos/tools/tests/markdown-html-serializer.test.cjs
index ef3c337b1b..74d527272e 100644
--- a/src/apps/mobile/harmonyos/tools/tests/markdown-html-serializer.test.cjs
+++ b/src/apps/mobile/harmonyos/tools/tests/markdown-html-serializer.test.cjs
@@ -35,6 +35,37 @@ const { MarkdownParser } = parserModule;
const { MarkdownHtmlSerializer } = serializerModule;
const html = (text) => MarkdownHtmlSerializer.toHtml(text);
+test('chat tildes preserve ranges, escapes and code while only double pairs strike', () => {
+ const cases = [
+ ['24~30°C, rain 1~2mm; ~5 min; ~plain~', '24~30°C, rain 1~2mm; ~5 min; ~plain~', []],
+ ['~~removed~~', 'removed', ['removed']],
+ [String.raw`\~escaped\~; \~~literal\~~`, '~escaped~; ~~literal~~', []],
+ ['`~~code~~`', '~~code~~', []],
+ ['before ~~~literal~~~ after', 'before ~~~literal~~~ after', []],
+ ['~~ a~~; ~~b ~~; ~~unfinished', '~~ a~~; ~~b ~~; ~~unfinished', []],
+ [String.raw`~~a\~~b~~`, 'a~~b', ['a~~b']],
+ ];
+ for (const [source, text, deleted] of cases) {
+ const inlines = MarkdownParser.parseInlineText(source);
+ assert.equal(inlines.map(inline => inline.text).join(''), text, source);
+ assert.deepEqual(inlines.filter(inline => inline.type === 'delete').map(inline => inline.text), deleted, source);
+ assert.equal(MarkdownParser.formatInlineText(source), text, source);
+ }
+ assert.equal(html('24~30°C, rain 1~2mm; ~~removed~~'), '
24~30°C, rain 1~2mm; removed
');
+});
+
+test('streaming tildes stay literal until the double pair closes', () => {
+ const cache = new parserModule.MarkdownParseCache();
+ const prefix = '24~30°C, rain 1~2mm; ';
+ for (const suffix of ['~', '~~', '~~removed', '~~removed~']) {
+ const block = cache.blocksFor(prefix + suffix)[0];
+ assert.equal(block.inlines.map(inline => inline.text).join(''), prefix + suffix);
+ assert.deepEqual(block.inlines.filter(inline => inline.type === 'delete'), []);
+ }
+ assert.equal(MarkdownHtmlSerializer.blocksToHtml(cache.blocksFor(prefix + '~~removed~~')),
+ `${prefix}removed
`);
+});
+
test('empty and whitespace-only input produce no payload', () => {
assert.equal(html(''), '');
assert.equal(html(' '), '');
diff --git a/src/apps/mobile/ios/OpenBitFun/Features/Chat/ChatTimelineView.swift b/src/apps/mobile/ios/OpenBitFun/Features/Chat/ChatTimelineView.swift
index cfc1aa57ec..4ec91807fc 100644
--- a/src/apps/mobile/ios/OpenBitFun/Features/Chat/ChatTimelineView.swift
+++ b/src/apps/mobile/ios/OpenBitFun/Features/Chat/ChatTimelineView.swift
@@ -1008,6 +1008,7 @@ private func markdownInlineString(
switch inline.type {
case "strong": part.inlinePresentationIntent = .stronglyEmphasized
case "emphasis": part.inlinePresentationIntent = .emphasized
+ case "delete": part.inlinePresentationIntent = .strikethrough
case "code":
part.inlinePresentationIntent = .code
part.backgroundColor = OpenBitFunTheme.soft
diff --git a/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/markdown/MarkdownParser.kt b/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/markdown/MarkdownParser.kt
index 21b944e597..094fcddd56 100644
--- a/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/markdown/MarkdownParser.kt
+++ b/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/markdown/MarkdownParser.kt
@@ -67,13 +67,11 @@ public object MarkdownParser {
return blocks
}
- public fun formatInlineText(value: String): String = value
- .replace(Regex("\\[([^]]+)]\\(([^)]+)\\)"), "$1 ($2)")
- .replace(Regex("`([^`]+)`"), "$1")
- .replace(Regex("\\*\\*([^*]+)\\*\\*"), "$1")
- .replace(Regex("__([^_]+)__"), "$1")
- .replace(Regex("\\*([^*]+)\\*"), "$1")
- .replace(Regex("_([^_]+)_"), "$1")
+ public fun formatInlineText(value: String): String = plainInlineText(parseInlineText(value))
+
+ private fun plainInlineText(inlines: List): String = inlines.joinToString("") {
+ if (it.type == "link" && it.text != it.url) "${it.text} (${it.url})" else it.text
+ }
public fun parseInlineText(value: String): List = parseInlineText(value, "inline")
@@ -83,10 +81,10 @@ public object MarkdownParser {
while (index < value.length) {
val next = nextInlineMarker(value, index)
if (next < 0) {
- pushInline(inlines, prefix, "text", value.substring(index), "")
+ pushInline(inlines, prefix, "text", unescapeText(value.substring(index)), "")
break
}
- if (next > index) pushInline(inlines, prefix, "text", value.substring(index, next), "")
+ if (next > index) pushInline(inlines, prefix, "text", unescapeText(value.substring(index, next)), "")
val consumed = readInlineAt(value, next, prefix, inlines)
if (consumed <= next) {
pushInline(inlines, prefix, "text", value[next].toString(), "")
@@ -144,7 +142,8 @@ public object MarkdownParser {
val raw = lines[index].trim()
val text = listText(raw)
val id = "li-" + start + "-" + items.size
- items += MarkdownListItem(id, listMarker(raw), formatInlineText(text), parseInlineText(text, id))
+ val inlines = parseInlineText(text, id)
+ items += MarkdownListItem(id, listMarker(raw), plainInlineText(inlines), inlines)
index += 1
}
pushBlock(blocks, "list", 0, "", "", items)
@@ -197,14 +196,15 @@ public object MarkdownParser {
) {
val id = "md-" + blocks.size + "-" + type
val parseInline = shouldParseInline(type)
+ val inlines = if (parseInline) parseInlineText(text, id) else emptyList()
blocks += MarkdownBlock(
id = id,
type = type,
level = level,
language = language,
- text = if (parseInline) formatInlineText(text) else text,
+ text = if (parseInline) plainInlineText(inlines) else text,
items = items,
- inlines = if (parseInline) parseInlineText(text, id) else emptyList(),
+ inlines = inlines,
)
}
@@ -224,6 +224,17 @@ public object MarkdownParser {
if (end > start + 2) return pushAndReturn(inlines, prefix, "strong", value.substring(start + 2, end), "", end + 2)
}
}
+ // Chat ranges use a single tilde. Only an unescaped double pair may
+ // strike text; longer runs and unfinished streaming markers stay literal.
+ if (isStrikeDelimiter(value, start, closing = false)) {
+ var end = value.indexOf("~~", start + 2)
+ while (end >= 0 && !isStrikeDelimiter(value, end, closing = true)) {
+ end = value.indexOf("~~", end + 2)
+ }
+ if (end > start + 2) {
+ return pushAndReturn(inlines, prefix, "delete", unescapeText(value.substring(start + 2, end)), "", end + 2)
+ }
+ }
if (value[start] == '[') {
val labelEnd = value.indexOf(']', start + 1)
if (labelEnd > start + 1 && labelEnd + 1 < value.length && value[labelEnd + 1] == '(') {
@@ -262,11 +273,47 @@ public object MarkdownParser {
}
private fun nextInlineMarker(value: String, start: Int): Int =
- listOf("`", "**", "__", "[", "*", "_")
- .map { value.indexOf(it, start) }
+ listOf("`", "**", "__", "~~", "[", "*", "_")
+ .map { marker ->
+ var index = value.indexOf(marker, start)
+ while (index >= 0 && isEscaped(value, index)) index = value.indexOf(marker, index + marker.length)
+ index
+ }
.filter { it >= 0 }
.minOrNull() ?: -1
+ private fun isStrikeDelimiter(value: String, index: Int, closing: Boolean): Boolean {
+ if (!value.startsWith("~~", index) || value.getOrNull(index - 1) == '~' ||
+ value.getOrNull(index + 2) == '~' || isEscaped(value, index)
+ ) return false
+ val before = value.getOrNull(index - 1)
+ val after = value.getOrNull(index + 2)
+ val beforeSpace = before == null || before.isWhitespace()
+ val afterSpace = after == null || after.isWhitespace()
+ val beforePunctuation = before != null && PUNCTUATION.matches(before.toString())
+ val afterPunctuation = after != null && PUNCTUATION.matches(after.toString())
+ return if (closing) !beforeSpace && (!beforePunctuation || afterSpace || afterPunctuation)
+ else !afterSpace && (!afterPunctuation || beforeSpace || beforePunctuation)
+ }
+
+ private fun isEscaped(value: String, index: Int): Boolean {
+ var cursor = index - 1
+ while (cursor >= 0 && value[cursor] == '\\') cursor -= 1
+ return (index - cursor - 1) % 2 == 1
+ }
+
+ private fun unescapeText(value: String): String = buildString {
+ var index = 0
+ while (index < value.length) {
+ if (value[index] == '\\' && index + 1 < value.length && value[index + 1] in ESCAPABLE) index += 1
+ append(value[index])
+ index += 1
+ }
+ }
+
+ private const val ESCAPABLE = "\\`*{}[]()#+-.!_>~|"
+ private val PUNCTUATION = Regex("[\\p{P}\\p{S}]")
+
private fun pushInline(
inlines: MutableList,
prefix: String,
diff --git a/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/markdown/MarkdownParserTest.kt b/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/markdown/MarkdownParserTest.kt
index 40c92c9153..6913cf0795 100644
--- a/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/markdown/MarkdownParserTest.kt
+++ b/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/markdown/MarkdownParserTest.kt
@@ -4,6 +4,39 @@ import kotlin.test.Test
import kotlin.test.assertEquals
class MarkdownParserTest {
+ @Test
+ fun chatTildesPreserveRangesEscapesAndCode() {
+ val cases = listOf(
+ Triple("24~30°C, rain 1~2mm; ~5 min; ~plain~", "24~30°C, rain 1~2mm; ~5 min; ~plain~", emptyList()),
+ Triple("~~removed~~", "removed", listOf("removed")),
+ Triple("\\~escaped\\~; \\~~literal\\~~", "~escaped~; ~~literal~~", emptyList()),
+ Triple("`~~code~~`", "~~code~~", emptyList()),
+ Triple("before ~~~literal~~~ after", "before ~~~literal~~~ after", emptyList()),
+ Triple("~~ a~~; ~~b ~~; ~~unfinished", "~~ a~~; ~~b ~~; ~~unfinished", emptyList()),
+ Triple("~~a\\~~b~~", "a~~b", listOf("a~~b")),
+ )
+ cases.forEach { (source, text, deleted) ->
+ val inlines = MarkdownParser.parseInlineText(source)
+ assertEquals(text, inlines.joinToString("") { it.text }, source)
+ assertEquals(deleted, inlines.filter { it.type == "delete" }.map { it.text }, source)
+ assertEquals(text, MarkdownParser.formatInlineText(source), source)
+ }
+ }
+
+ @Test
+ fun streamingTildesRemainLiteralUntilTheDoublePairCloses() {
+ val cache = MarkdownParseCache()
+ val prefix = "24~30°C, rain 1~2mm; "
+ listOf("~", "~~", "~~removed", "~~removed~").forEach { suffix ->
+ val block = cache.blocksFor(prefix + suffix).single()
+ assertEquals(prefix + suffix, block.inlines.joinToString("") { it.text })
+ assertEquals(emptyList(), block.inlines.filter { it.type == "delete" })
+ }
+ val complete = cache.blocksFor(prefix + "~~removed~~").single()
+ assertEquals(prefix + "removed", complete.inlines.joinToString("") { it.text })
+ assertEquals(listOf("removed"), complete.inlines.filter { it.type == "delete" }.map { it.text })
+ }
+
@Test
fun parsesCommonMarkdownBlocksIntoStableBlockTypes() {
val blocks = MarkdownParser.parse(
diff --git a/src/crates/assembly/core/AGENTS.md b/src/crates/assembly/core/AGENTS.md
index 08c0c067c4..5b9172c1a7 100644
--- a/src/crates/assembly/core/AGENTS.md
+++ b/src/crates/assembly/core/AGENTS.md
@@ -334,6 +334,17 @@ For durable per-turn token usage, client checkpoint reconciliation, and recovery
The fixtures cover host-ledger isolation and client-free completion, not live SSH,
Relay, Peer Device, or Detached Dispatch connections.
+For model-round order when completion fills sparse client checkpoints:
+
+```bash
+cargo test --locked -p openbitfun-core --no-default-features --features agent-runtime,git --lib generation_round_order
+```
+
+These fixtures cover suffix/scattered checkpoints, legacy record round trips,
+idempotent merge, prior interrupted generations, additive metadata, and headless
+completion/reload. They do not establish live SSH, Relay, Peer Device, or
+Detached Dispatch behavior.
+
For cold dialog startup and the production-feature scheduler stack regression:
```bash
diff --git a/src/crates/assembly/core/src/agentic/session/session_manager.rs b/src/crates/assembly/core/src/agentic/session/session_manager.rs
index 9a3ee5b1b8..f8a30f59ba 100644
--- a/src/crates/assembly/core/src/agentic/session/session_manager.rs
+++ b/src/crates/assembly/core/src/agentic/session/session_manager.rs
@@ -8816,15 +8816,16 @@ impl SessionManager {
new_messages: &[Message],
timestamp: u64,
) -> usize {
- let mut next_round_index = turn
- .model_rounds
- .iter()
- .map(|round| round.round_index)
- .max()
- .map_or(0, |index| index.saturating_add(1));
let generated_rounds =
Self::build_model_rounds_from_messages(new_messages, turn_id, timestamp);
let generated_count = generated_rounds.len();
+ if generated_count == 0 {
+ return 0;
+ }
+ let mut generation_order = BTreeMap::new();
+ for (index, round) in generated_rounds.iter().enumerate() {
+ generation_order.entry(round.id.clone()).or_insert(index);
+ }
for mut round in generated_rounds {
if let Some(existing_index) = turn
.model_rounds
@@ -8917,7 +8918,6 @@ impl SessionManager {
.cloned()
.collect::>();
round.tool_items.extend(derived_tool_items);
- round.round_index = existing.round_index;
round.round_group_id = existing.round_group_id.clone();
round.timestamp = existing.timestamp;
round.start_time = existing.start_time;
@@ -8954,11 +8954,39 @@ impl SessionManager {
}
turn.model_rounds[existing_index] = round;
} else {
- round.round_index = next_round_index;
- next_round_index = next_round_index.saturating_add(1);
turn.model_rounds.push(round);
}
}
+
+ // A client can checkpoint only a suffix or scattered rounds. Appending
+ // missing earlier rounds behind that checkpoint puts the final answer
+ // in the middle. The generation journal owns their relative order.
+ // Keep older generations before the first shared round; other rounds
+ // absent from this journal stay beside their preceding shared round.
+ // Nothing is discarded, including interrupted or client-only records.
+ let mut preceding_generation_index = None;
+ let mut ordered = std::mem::take(&mut turn.model_rounds)
+ .into_iter()
+ .map(|round| {
+ let generation_index = generation_order.get(&round.id).copied();
+ if generation_index.is_some() {
+ preceding_generation_index = generation_index;
+ }
+ (
+ (preceding_generation_index, generation_index.is_none()),
+ round,
+ )
+ })
+ .collect::>();
+ ordered.sort_by_key(|(order, _)| *order);
+ turn.model_rounds = ordered
+ .into_iter()
+ .enumerate()
+ .map(|(index, (_, mut round))| {
+ round.round_index = index;
+ round
+ })
+ .collect();
generated_count
}
@@ -10993,6 +11021,133 @@ mod tests {
assert_eq!(last.attempt_count, Some(1));
}
+ #[test]
+ fn generation_round_order_follows_journal_for_sparse_checkpoints() {
+ let ids = ["z-opening", "b-tool", "y-analysis", "a-tool", "m-final"];
+ let messages = ids
+ .iter()
+ .map(|id| Message::assistant((*id).into()).with_round_id((*id).into()))
+ .collect::>();
+ // Runtime-rebuilt rounds can all have the completion timestamp. Neither
+ // timestamps, lexical IDs nor a partial checkpoint's indexes own order.
+ let rounds = SessionManager::build_model_rounds_from_messages(&messages, "turn", 10);
+ for mask in 0..(1 << ids.len()) {
+ for reverse in [false, true] {
+ let mut turn = DialogTurnData::new(
+ "turn".into(),
+ 0,
+ "session".into(),
+ UserMessageData {
+ id: "input".into(),
+ content: "request".into(),
+ timestamp: 1,
+ metadata: None,
+ },
+ );
+ turn.model_rounds = rounds
+ .iter()
+ .enumerate()
+ .filter(|(index, _)| mask & (1 << index) != 0)
+ .map(|(_, round)| round.clone())
+ .collect();
+ if reverse {
+ turn.model_rounds.reverse();
+ }
+ for (index, round) in turn.model_rounds.iter_mut().enumerate() {
+ round.round_index = index;
+ round.provider_id = Some("checkpoint-provider".into());
+ }
+ // The saved legacy shape needs no new fields to recover order.
+ let mut turn: DialogTurnData =
+ serde_json::from_value(serde_json::to_value(turn).unwrap()).unwrap();
+ for _ in 0..2 {
+ assert_eq!(
+ SessionManager::append_generation_rounds(&mut turn, "turn", &messages, 10),
+ ids.len()
+ );
+ assert_eq!(
+ turn.model_rounds
+ .iter()
+ .map(|round| round.id.as_str())
+ .collect::>(),
+ ids,
+ "mask={mask}, reverse={reverse}"
+ );
+ for (index, round) in turn.model_rounds.iter().enumerate() {
+ assert_eq!(round.round_index, index);
+ assert_eq!(round.text_items[0].content, ids[index]);
+ if mask & (1 << index) != 0 {
+ assert_eq!(round.provider_id.as_deref(), Some("checkpoint-provider"));
+ }
+ }
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn generation_round_order_preserves_prior_generations_and_unjournaled_rounds() {
+ let message = |id: &str| Message::assistant(id.into()).with_round_id(id.into());
+ let mut turn = DialogTurnData::new(
+ "turn".into(),
+ 0,
+ "session".into(),
+ UserMessageData {
+ id: "input".into(),
+ content: "request".into(),
+ timestamp: 1,
+ metadata: None,
+ },
+ );
+ turn.model_rounds = SessionManager::build_model_rounds_from_messages(
+ &[
+ message("interrupted"),
+ message("second"),
+ message("retry"),
+ message("final"),
+ message("pending"),
+ ],
+ "turn",
+ 10,
+ );
+ turn.model_rounds[0].status = "cancelled".into();
+ turn.model_rounds[2].status = "error".into();
+ turn.model_rounds[4].status = "streaming".into();
+ let preserved = [0, 2, 4].map(|index| turn.model_rounds[index].clone());
+ let messages = [message("first"), message("second"), message("final")];
+ for _ in 0..2 {
+ SessionManager::append_generation_rounds(&mut turn, "turn", &messages, 20);
+ assert_eq!(
+ turn.model_rounds
+ .iter()
+ .map(|round| round.id.as_str())
+ .collect::>(),
+ [
+ "interrupted",
+ "first",
+ "second",
+ "retry",
+ "final",
+ "pending"
+ ]
+ );
+ for (old, index) in preserved.iter().zip([0, 3, 5]) {
+ let mut expected = old.clone();
+ expected.round_index = index;
+ assert_eq!(
+ serde_json::to_value(&turn.model_rounds[index]).unwrap(),
+ serde_json::to_value(expected).unwrap()
+ );
+ }
+ }
+ let before = serde_json::to_value(&turn).unwrap();
+ assert_eq!(
+ SessionManager::append_generation_rounds(&mut turn, "turn", &[], 30),
+ 0
+ );
+ assert_eq!(serde_json::to_value(&turn).unwrap(), before);
+ }
+
#[test]
fn classified_edit_history_preserves_detail_and_readable_error() {
let assistant = Message::assistant_with_tools(
@@ -11755,7 +11910,7 @@ mod tests {
}
#[tokio::test]
- async fn completion_replaces_a_projected_text_prefix_with_runtime_generation_content() {
+ async fn generation_round_order_survives_completion_with_a_projected_final_prefix() {
let workspace = TestWorkspace::new();
let persistence_manager = Arc::new(
PersistenceManager::new(workspace.path_manager()).expect("persistence manager"),
@@ -11815,17 +11970,48 @@ mod tests {
.expect("projected prefix should persist");
let complete_response = "Saved prefix: 1. first item\n2. second item";
+ let earlier = Message::assistant_with_tools(
+ "Checking the source".into(),
+ vec![ToolCall {
+ tool_id: "read-source".into(),
+ tool_name: "Read".into(),
+ arguments: json!({"path": "README.md"}),
+ raw_arguments: None,
+ is_error: false,
+ parse_error: None,
+ recovered_from_truncation: false,
+ repair_kind: Default::default(),
+ }],
+ )
+ .with_turn_id(turn_id.clone())
+ .with_round_id("round-first".into());
+ let result = Message::tool_result(ToolResult {
+ tool_id: "read-source".into(),
+ tool_name: "Read".into(),
+ effective_tool_name: None,
+ result: json!({"content": "source"}),
+ result_for_assistant: None,
+ is_error: false,
+ duration_ms: Some(1),
+ image_attachments: None,
+ })
+ .with_turn_id(turn_id.clone())
+ .with_round_id("round-first".into());
manager
.complete_dialog_turn(
&session.session_id,
&turn_id,
complete_response.to_string(),
- &[Message::assistant(complete_response.to_string())
- .with_turn_id(turn_id.clone())
- .with_round_id("round-final".to_string())],
+ &[
+ earlier,
+ result,
+ Message::assistant(complete_response.to_string())
+ .with_turn_id(turn_id.clone())
+ .with_round_id("round-final".to_string()),
+ ],
TurnStats {
- total_rounds: 1,
- total_tools: 0,
+ total_rounds: 2,
+ total_tools: 1,
total_tokens: 0,
duration_ms: 1,
},
@@ -11843,15 +12029,25 @@ mod tests {
assert_eq!(completed.status, TurnStatus::Completed);
assert_eq!(completed.finish_reason.as_deref(), Some("complete"));
assert_eq!(completed.has_final_response, Some(true));
- assert_eq!(completed.model_rounds.len(), 1);
- assert_eq!(completed.model_rounds[0].id, "round-final");
+ assert_eq!(completed.model_rounds.len(), 2);
+ assert_eq!(completed.model_rounds[0].id, "round-first");
+ assert_eq!(completed.model_rounds[0].round_index, 0);
+ assert!(
+ completed.model_rounds[0].tool_items[0]
+ .tool_result
+ .as_ref()
+ .unwrap()
+ .success
+ );
+ assert_eq!(completed.model_rounds[1].id, "round-final");
+ assert_eq!(completed.model_rounds[1].round_index, 1);
assert_eq!(
- completed.model_rounds[0].text_items[0].content,
+ completed.model_rounds[1].text_items[0].content,
complete_response,
);
- assert_eq!(completed.model_rounds[0].tool_items.len(), 1);
+ assert_eq!(completed.model_rounds[1].tool_items.len(), 1);
assert_eq!(
- completed.model_rounds[0].tool_items[0].id,
+ completed.model_rounds[1].tool_items[0].id,
"plan-display-test",
);
}
diff --git a/src/mobile-web/src/components/ChatMarkdown.tsx b/src/mobile-web/src/components/ChatMarkdown.tsx
index 8bb9c4b430..df2540f689 100644
--- a/src/mobile-web/src/components/ChatMarkdown.tsx
+++ b/src/mobile-web/src/components/ChatMarkdown.tsx
@@ -31,6 +31,7 @@ import yaml from 'react-syntax-highlighter/dist/esm/languages/prism/yaml';
import { MobileButton, MobileIconButton, MobileLink } from '@openbitfun/ui/mobile';
import { useI18n } from '../i18n';
import { useTheme } from '../theme';
+import { chatMarkdownGfmOptions } from './chatMarkdownGfm';
import { mayContainMarkdownMath, normalizeMathDelimiters } from './chatMarkdownMath';
import type { MarkdownMathContentProps } from './MarkdownMathContent';
import { RemoteArtifactImage } from './RemoteArtifactImage';
@@ -530,7 +531,7 @@ export const MarkdownContent: React.FC = ({ content, onFil
) : (
{content}
diff --git a/src/mobile-web/src/components/MarkdownMathContent.tsx b/src/mobile-web/src/components/MarkdownMathContent.tsx
index 1b5555e4fb..1c63188409 100644
--- a/src/mobile-web/src/components/MarkdownMathContent.tsx
+++ b/src/mobile-web/src/components/MarkdownMathContent.tsx
@@ -5,6 +5,7 @@ import rehypeKatex from 'rehype-katex';
import remarkGfm from 'remark-gfm';
import remarkMath from 'remark-math';
import 'katex/dist/katex.min.css';
+import { chatMarkdownGfmOptions } from './chatMarkdownGfm';
export interface MarkdownMathContentProps {
content: string;
@@ -24,7 +25,7 @@ export const MarkdownMathContent: React.FC = ({
{content}
diff --git a/src/mobile-web/src/components/chatMarkdownGfm.ts b/src/mobile-web/src/components/chatMarkdownGfm.ts
new file mode 100644
index 0000000000..37875be3a1
--- /dev/null
+++ b/src/mobile-web/src/components/chatMarkdownGfm.ts
@@ -0,0 +1,8 @@
+import type { Options } from 'remark-gfm';
+
+/**
+ * Chat prose uses single tildes for ranges (`~5 min`, `1~3`); only paired
+ * double tildes strike text. Keep aligned with the desktop chat renderer so a
+ * remote-controlled transcript reads the same on both surfaces.
+ */
+export const chatMarkdownGfmOptions: Options = { singleTilde: false };
diff --git a/src/mobile-web/tests/mobile-ui-components.test.mjs b/src/mobile-web/tests/mobile-ui-components.test.mjs
index 56bd5a222b..0903098a3e 100644
--- a/src/mobile-web/tests/mobile-ui-components.test.mjs
+++ b/src/mobile-web/tests/mobile-ui-components.test.mjs
@@ -4,6 +4,11 @@ import path from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import ts from 'typescript';
+import React from 'react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import ReactMarkdown from 'react-markdown';
+import remarkGfm from 'remark-gfm';
+import remarkMath from 'remark-math';
const testDirectory = path.dirname(fileURLToPath(import.meta.url));
const sourceDirectory = path.resolve(testDirectory, '../src');
@@ -333,7 +338,7 @@ test('mobile chat markdown lazily loads katex plugins and keeps mobile display s
assert.match(math, /import rehypeKatex from 'rehype-katex';/);
assert.match(math, /import remarkMath from 'remark-math';/);
assert.match(math, /import 'katex\/dist\/katex\.min\.css';/);
- assert.match(math, /remarkPlugins=\{\[remarkGfm,\s*\[remarkMath,\s*\{\s*singleDollarTextMath:\s*false\s*\}\]\]\}/);
+ assert.match(math, /remarkPlugins=\{\[\[remarkGfm,\s*chatMarkdownGfmOptions\],\s*\[remarkMath,\s*\{\s*singleDollarTextMath:\s*false\s*\}\]\]\}/);
assert.match(math, /rehypePlugins=\{\[\[rehypeKatex,\s*\{\s*strict:\s*false,\s*throwOnError:\s*false\s*\}\]\]\}/);
assert.match(markdown, /import\('\.\/MarkdownMathContent'\)/);
assert.match(markdown, /mayContainMarkdownMath\(content\)/);
@@ -349,6 +354,37 @@ test('mobile chat markdown lazily loads katex plugins and keeps mobile display s
assert.match(markdownStyles, /\.katex-error\s*\{[\s\S]*?color:\s*var\(--openbitfun-color-status-danger-content\);/);
});
+test('mobile chat markdown keeps single tildes literal in both renderers, like desktop chat', async () => {
+ const markdown = await readFile(path.join(sourceDirectory, 'components/ChatMarkdown.tsx'), 'utf8');
+ const math = await readFile(path.join(sourceDirectory, 'components/MarkdownMathContent.tsx'), 'utf8');
+ const options = await readFile(path.join(sourceDirectory, 'components/chatMarkdownGfm.ts'), 'utf8');
+ const code = ts.transpileModule(options, { compilerOptions: { module: ts.ModuleKind.ESNext } }).outputText;
+ const { chatMarkdownGfmOptions } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
+ for (const renderer of [markdown, math]) {
+ assert.match(renderer, /import \{ chatMarkdownGfmOptions \} from '\.\/chatMarkdownGfm';/);
+ assert.match(renderer, /\[remarkGfm,\s*chatMarkdownGfmOptions\]/);
+ assert.doesNotMatch(renderer, /remarkPlugins=\{\[remarkGfm[,\]]/);
+ }
+ const cases = [
+ ['24~30°C, rain 1~2mm; ~5 min; ~plain~', '24~30°C, rain 1~2mm; ~5 min; ~plain~'],
+ ['~~removed~~', 'removed'],
+ [String.raw`\~escaped\~; \~~literal\~~`, '~escaped~; ~~literal~~'],
+ ['`~~code~~`', '~~code~~'],
+ ['before ~~~literal~~~ after', 'before ~~~literal~~~ after'],
+ ['~~ a~~; ~~b ~~; ~~unfinished', '~~ a~~; ~~b ~~; ~~unfinished'],
+ [String.raw`~~a\~~b~~`, 'a~~b'],
+ ['24~30°C; ~~removed~', '24~30°C; ~~removed~'],
+ ];
+ for (const extraPlugins of [[], [[remarkMath, { singleDollarTextMath: false }]]]) {
+ for (const [source, expected] of cases) {
+ const html = renderToStaticMarkup(React.createElement(ReactMarkdown, {
+ remarkPlugins: [[remarkGfm, chatMarkdownGfmOptions], ...extraPlugins],
+ }, source));
+ assert.equal(html, `${expected}
`, source);
+ }
+ }
+});
+
test('math activation ignores currency-only dollar pairs', async () => {
const mathDelimiters = await readFile(path.join(sourceDirectory, 'components/chatMarkdownMath.ts'), 'utf8');
const code = ts.transpileModule(mathDelimiters, { compilerOptions: { module: ts.ModuleKind.ESNext } }).outputText;
diff --git a/src/web-ui/README.md b/src/web-ui/README.md
index e7add3f996..149e8538bc 100644
--- a/src/web-ui/README.md
+++ b/src/web-ui/README.md
@@ -9,6 +9,13 @@ This directory contains OpenBitFun’s **Web UI** (React + TypeScript). The same
- **Desktop**: loaded via **Tauri**
- **Server/Web**: built into static assets and served by the backend
+## Markdown in conversations
+
+Use `~~text~~` for strikethrough. Single tildes stay literal, so ranges such as
+`24~30°C` and `1~2mm` can appear in the same paragraph. Escaped tildes (`\~`)
+and tildes inside code stay literal too. This applies to streamed and completed
+replies, including replies containing math; saved message text is unchanged.
+
## Closing tabs with the keyboard
In Desktop, **Ctrl+W** on Windows/Linux or **Cmd+W** on macOS closes the current
diff --git a/src/web-ui/README.zh-CN.md b/src/web-ui/README.zh-CN.md
index 34b4f558e0..e53164469d 100644
--- a/src/web-ui/README.zh-CN.md
+++ b/src/web-ui/README.zh-CN.md
@@ -9,6 +9,12 @@
- **Desktop**:通过 **Tauri** 加载运行
- **Server/Web**:构建为静态资源,由后端提供访问
+## 会话中的 Markdown
+
+删除线使用 `~~文字~~`。单个波浪号按原样显示,因此 `24~30°C` 和 `1~2mm`
+可以出现在同一段中。转义后的波浪号(`\~`)和代码中的波浪号也按原样显示。
+流式输出、已完成的回复和含数学公式的回复采用相同规则,保存的消息原文不变。
+
## 使用快捷键关闭标签
桌面端使用 **Ctrl+W**(Windows/Linux)或 **Cmd+W**(macOS)关闭当前操作区域的标签。
diff --git a/src/web-ui/src/app/hooks/useSessionTabLabels.ts b/src/web-ui/src/app/hooks/useSessionTabLabels.ts
index 1c8a197046..2aca119a24 100644
--- a/src/web-ui/src/app/hooks/useSessionTabLabels.ts
+++ b/src/web-ui/src/app/hooks/useSessionTabLabels.ts
@@ -15,24 +15,30 @@ function readSessionTabLabels(
tabs: readonly SceneTab[],
translate: (key: string, options?: Record) => string,
formatNumber: (number: number, options?: Intl.NumberFormatOptions) => string,
+ previous?: Record,
): Record {
const labels: Record = {};
const numbersBySurface = new Map>();
+ const activeSurfaceId = getActiveSurfaceId();
+ const activeSessions = flowChatStore.getState().sessions;
for (const tab of tabs) {
if (!tab.session) continue;
// A tab held for a cross-device open names its device's session.
- const sessions = tab.session.surfaceId === getActiveSurfaceId()
- ? flowChatStore.getState().sessions
+ const sessions = tab.session.surfaceId === activeSurfaceId
+ ? activeSessions
: flowChatStore.getSurfaceSessions(tab.session.surfaceId);
let numbers = numbersBySurface.get(tab.session.surfaceId);
if (!numbers) numbersBySurface.set(tab.session.surfaceId, numbers = sessionTitleNumbers(sessions.values()));
const session = sessions.get(tab.session.sessionId);
if (!session) continue;
const number = numbers.get(session.sessionId);
- labels[tab.id] = {
- title: resolveSessionTitle(session, translate),
- number: number === undefined ? undefined : formatNumber(number, { minimumIntegerDigits: 2, useGrouping: false }),
- };
+ const title = resolveSessionTitle(session, translate);
+ const formattedNumber = number === undefined ? undefined : formatNumber(number, { minimumIntegerDigits: 2, useGrouping: false });
+ // Reuse the previous label object when nothing changed so tab rows keep identity.
+ const cached = previous?.[tab.id];
+ labels[tab.id] = cached && cached.title === title && cached.number === formattedNumber
+ ? cached
+ : { title, number: formattedNumber };
}
return labels;
}
@@ -49,7 +55,7 @@ export function useSessionTabLabels(tabs: readonly SceneTab[]): Record {
let snapshot: Record = {};
return () => {
- const next = readSessionTabLabels(tabs, t, formatNumber);
+ const next = readSessionTabLabels(tabs, t, formatNumber, snapshot);
if (Object.keys(snapshot).length !== Object.keys(next).length
|| Object.entries(next).some(([id, label]) => snapshot[id]?.title !== label.title || snapshot[id]?.number !== label.number)) {
snapshot = next;
diff --git a/src/web-ui/src/flow_chat/components/btw/BtwSessionPanel.review-action.test.tsx b/src/web-ui/src/flow_chat/components/btw/BtwSessionPanel.review-action.test.tsx
index e8e4de0903..08f9a49cf3 100644
--- a/src/web-ui/src/flow_chat/components/btw/BtwSessionPanel.review-action.test.tsx
+++ b/src/web-ui/src/flow_chat/components/btw/BtwSessionPanel.review-action.test.tsx
@@ -218,7 +218,7 @@ vi.mock('../../services/FlowChatManager', () => ({
}));
vi.mock('../../store/modernFlowChatStore', () => ({
- sessionToVirtualItems: () => panelMocks.virtualItems,
+ createSessionVirtualItemProjector: () => () => panelMocks.virtualItems,
}));
vi.mock('../../services/ReviewActionBarPersistenceService', () => ({
diff --git a/src/web-ui/src/flow_chat/components/btw/BtwSessionPanel.tsx b/src/web-ui/src/flow_chat/components/btw/BtwSessionPanel.tsx
index 98a1e5119e..0e630a6cf2 100644
--- a/src/web-ui/src/flow_chat/components/btw/BtwSessionPanel.tsx
+++ b/src/web-ui/src/flow_chat/components/btw/BtwSessionPanel.tsx
@@ -19,7 +19,7 @@ import {ChatInputApprovalBand} from '../ChatInputApprovalBand';
import {ScrollToBottomButton} from '@/flow_chat';
import {flowChatStore} from '../../store/FlowChatStore';
import type {DialogTurn, Session} from '../../types/flow-chat';
-import {sessionToVirtualItems} from '../../store/modernFlowChatStore';
+import {createSessionVirtualItemProjector} from '../../store/modernFlowChatStore';
import {FLOWCHAT_FOCUS_ITEM_EVENT, type FlowChatFocusItemRequest} from '../../events/flowchatNavigation';
import {fileTabManager} from '@/shared/services/FileTabManager';
import {createTab} from '@/shared/utils/tabUtils';
@@ -229,9 +229,10 @@ const BtwSessionPanelContent: React.FC sessionToVirtualItems(childSession ?? null),
- [childSession],
+ () => projectSession(childSession ?? null),
+ [childSession, projectSession],
);
const virtualItems = useMemo(
() => viewKind === 'review-check'
diff --git a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md
index e75c6fb4b6..57c4cea6c3 100644
--- a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md
+++ b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md
@@ -16,7 +16,10 @@ each missing what the other had.
| Test | Contract it holds |
|---|---|
-| `../../../infrastructure/markdown/markdownSections.test.ts`, `../../timeline/document.test.ts` | exact source reconstruction and equivalent Markdown ASTs across LF/CRLF/CR, lists/fences/tables/quotes/math, conservative reference/HTML fallback, canonical identities, Unicode search counts, bounded section estimates and no live completion repartition |
+| `../../store/modernFlowChatStore.test.ts`, `../../grouping/selectors.test.ts`, `../../grouping/activityGrouping.test.ts`, `../../../shared/utils/resourceBudget.test.ts` | cached/full projection equivalence across repeated thinking/tool-parameter streams, interior updates, rollback, completion and legacy retry/recovery; alternating live/history/side projections, completed-row reuse on append, same-store clear/reopen invalidation, warm equal-ID source isolation, group alias restoration and group-position independence; interrupted-prefix and shared-reference byte accounting |
+| `useFlowChatVirtualizer.initial-window.test.tsx`, `useFlowChatSearch.test.ts` | delayed observer delivery after live prepend / history tail insertion resizes the surviving key; suspended mounts are observed on resume with or without origin handoff; closing one search releases its match cache without affecting another view |
+| `../../perf/longRoundPerfHarness.test.tsx` | deterministic settled-row/block identity reuse, including interleaved history and side projections, plus diagnostic stage timings; supplied DOM fixtures, not native frame-rate or live remote evidence |
+| `../../../infrastructure/markdown/markdownSections.test.ts`, `../../timeline/document.test.ts` | exact source reconstruction and equivalent Markdown ASTs across LF/CRLF/CR, lists/fences/tables/quotes/math, conservative reference/HTML fallback, canonical identities, Unicode search counts, bounded section estimates, no live completion repartition, and display-only narrative ID handoff with canonical bookmark/navigation IDs, retry/source isolation and alias-collision recovery |
| `../FlowTextBlock.test.tsx`, `../../../infrastructure/markdown/MarkdownCodeBody.test.tsx` | sealed live-prefix DOM/parser reuse, one shared decoration observer, selected-node retention, source-only oversized fences and cleanup; DOM fixtures, not native paint evidence |
| `../../trajectory` | bounded long-session rail, stable range identities, keyboard preview vs selection, searchable summary pagination, legacy-peer gating, stale device/query rejection, canonical peer body navigation, shared detail components and bounded output; local DOM/transport fixtures, not native rendering or live remote evidence |
| `../FlowChatWidthBoundary.test.tsx`, `../../../infrastructure/appearance/preferences/flowChatWidthStore.test.ts`, `../../../app/scenes/settings/pages/application/FlowChatWidthSettingsSection.test.tsx` | symmetric pointer/keyboard column resizing, token-derived bounds, cancellation/cleanup, narrow-pane restoration, persisted preference compatibility and settings/reset synchronization; supplied DOM geometry, not visual or live remote evidence |
@@ -55,9 +58,9 @@ each missing what the other had.
| `useFlowChatViewportAnchor.test.tsx` | capture, restore, carry, the settle window |
| `useFlowChatLeadingExtent.test.tsx` | shared event geometry without repeated rectangle reads; fresh layout reads after resize and collection |
| `VirtualMessageList.session-boundary.test.tsx` | prepend compensation, consecutive paging with/without queued input, passive scroll suppression, navigation-target current Turn with gesture/follow/session handoff, search placement only outside the readable viewport, and real viewport-register acknowledgement before trajectory details/highlights commit for user/search/model/folded-tool/history targets |
-| `VirtualMessageList.resize.test.tsx` | first-frame node and screen-position retention during repeated CSS-only width previews, release, fractional row geometry, native clamping, both row/container observer orders and delayed scroll delivery; completed follow and reader-owned positions on local/simulated peer surfaces, not native or live-transport evidence |
+| `VirtualMessageList.resize.test.tsx` | first-frame node and screen-position retention during repeated CSS-only width previews, release, fractional row geometry, native clamping, both row/container observer orders and delayed scroll delivery; same-size viewport recovery observes suspended mounts without further output, manual re-render or scrolling in live/history layouts; completed follow and reader-owned positions on local/simulated peer surfaces, not native or live-transport evidence |
| `VirtualMessageList.history-prepend.test.tsx` | full list with real virtualization/follow/ownership: stable row identity and screen offset through short/long completed answers, consecutive/dense prepends, delayed measurement/native scroll and reader-chosen positions on local/simulated peer surfaces; supplied row/DOM geometry, not native or live-transport evidence |
-| `VirtualMessageList.timeline-prepend.test.tsx`, `FlowChatPrependSnapshot.test.tsx` | production timeline whole/compound/single-Turn pages; native bottom-origin continuity before observer delivery and zero passive scroll writes, stable hydration lifetime, fractional measurements, bounded long histories, empty-projection navigation, chronological navigation, legacy whole-text and section bookmark coordinates, live handoff and reader-selected block retention; supplied DOM geometry on local/simulated Peer, not native paint or live transport evidence |
+| `VirtualMessageList.timeline-prepend.test.tsx`, `FlowChatPrependSnapshot.test.tsx` | production timeline whole/compound/single-Turn pages; native bottom-origin continuity before observer delivery and zero passive scroll writes, stable hydration lifetime, fractional measurements, bounded long histories, empty-projection navigation, chronological navigation, legacy whole-text and section bookmark coordinates, live handoff and reader-selected block retention; settled host ID replacement retains measured row nodes/positions on every frame and uses canonical bookmarks across reopen; supplied DOM geometry on local/simulated Peer, not native paint or live transport evidence |
| `flowChatScrollbarMask.test.ts`, `VirtualMessageList.session-boundary.test.tsx` | idle gutter masking with symmetric, one-sided and overlay scrollbars; overflow restoration and content/viewport resizing without scroll writes; supplied DOM geometry, not native rendering or live remote evidence |
| `VirtualMessageList.edgeFade.test.ts`, `VirtualMessageList.session-boundary.test.tsx` | repeated scroll-away/back restores the opaque top edge even when an earlier native listener synchronously commits a virtual window; fractional/top-overscroll offsets, one follow notification per event, current gesture callbacks and old-session cleanup; DOM/CSS contracts, not native repaint or live remote evidence |
| `FlowChatOpeningBoundary.test.tsx` | opening-only activation/scroll isolation, bidirectional focus skipping, programmatic focus return, and reveal cleanup; DOM contracts only |
@@ -78,7 +81,7 @@ each missing what the other had.
| `../../selection/flowChatHighlights.test.ts` | exact text-parent scoping across Markdown nodes, shared markers, cleanup and document isolation |
| `../../../infrastructure/appearance/adapters/ThemeTokenAppearanceAdapter.test.ts` | legacy accent projection, alpha preservation, theme changes and paint cleanup |
| `../../selection/flowChatSelection.test.ts` | Markdown selection boundaries, source isolation, repeated text anchors, changed sources and legacy table excerpt offsets across cell presentation wrappers |
-| `../../../infrastructure/markdown/MarkdownRenderer.test.tsx`, `../../../infrastructure/markdown/AsyncPrismSyntaxHighlighter.test.tsx` | compiled CSS and product DOM selection boundaries for mixed replies, hidden/runtime bodies, response/thinking tables and fences; table alignment/semantics, unchanged cross-message ranges, real Prism/fallback whitespace; not native selection paint evidence |
+| `../../../infrastructure/markdown/MarkdownRenderer.test.tsx`, `../../../infrastructure/markdown/AsyncPrismSyntaxHighlighter.test.tsx` | compiled CSS and product DOM selection boundaries for mixed replies, hidden/runtime bodies, response/thinking tables and fences; table alignment/semantics, unchanged cross-message ranges, real Prism/fallback whitespace, literal single/escaped tildes and double-tilde strikethrough in live/completed/math/thinking renderers; not native selection paint evidence |
| `../../selection/FlowChatSelectionBar.test.tsx` | annotation Dialog focus containment and return, frozen excerpts during scroll/resize, and comment submission |
| `../../selection/useExcerptComposerActions.test.tsx` | main/side draft routing, focus after activation, ordinary child ownership, and stale surface rejection |
| `../../../shared/utils/conversationExcerpt.test.ts` | quote deduplication, source-data framing, and legacy/additive presentation metadata |
diff --git a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md
index 5405195713..701fd08cb9 100644
--- a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md
+++ b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md
@@ -8,6 +8,16 @@ History uses a bottom-origin scroller and newest-first internal indexes. Public
row indexes, stable keys, DOM order, navigation and viewport snapshots remain
chronological. `data-virtual-index` is public; `data-flowchat-measure-index` is
private to the adapter and is refreshed for surviving rows after each commit.
+This includes live prepends and new tail rows in bottom-origin history, not only
+origin handoffs. Refresh indexes through the adapter's connected row registry;
+an index update requires no geometry read or DOM subtree scan. A later observer
+delivery must still resize the same row key.
+Rows mounted while the viewport is suspended stay in the pending attachment
+registry until a resumed commit registers them with the measurement observer.
+The viewport recovery frame explicitly requests that commit, even when the
+restored dimensions are unchanged and output has stopped. It must not rely on
+the reader's next scroll or a later resize. Prune disconnected pending rows
+even during suspension.
For native history, internal offset is `-scrollTop`, index zero is the newest
row, and the footer is the scroll margin. The internal window's before/after
@@ -53,6 +63,59 @@ assert zero scroll writes as well as node and screen-position continuity.
These supplied-geometry tests do not establish native paint or live remote
behavior.
+## Projection cache lifetime
+
+Warm session projections are keyed weakly by the canonical `dialogTurns` array,
+so a history eviction or replacement can release both the body and its derived
+rows. Equal session IDs on different device sources do not share that key.
+Per-Turn streaming reconciliation drops removed Turn IDs on paging/rollback;
+each store, history projection and side panel owns its own mutable prefix state.
+Alternating views must not invalidate another view's live prefix. Immutable
+completed-Turn projections are shared weakly across views, while clearing a
+presentation store clears that store's warm projections. A completed Turn's
+normal projection does not depend on newer siblings, so appending a new message
+reuses its existing rows. Only the collapsed background presentation needs a
+separate variant. There is no shared mutable standalone projector; each caller,
+including benchmarks, creates its own. User-message reuse
+depends on the message and its presentation fields, not on its first model round.
+Normalized steering,
+retry and recovery rounds use weak source identities, including both source
+rounds for a merged retry. Inline group caches follow group objects rather than
+positions, which change when candidate groups are collected or expanded.
+
+The group index rebuilds from cached row groups when the transcript changes,
+preserving the original last-alias/first-member ownership rules even when a tail
+that shadowed an earlier alias disappears. Identical transcript arrays reuse
+their weakly cached index. The resource estimator remains a shared-reference-aware
+graph walk; the history owner already caches immutable Turn estimates and
+coalesces active-history accounting at 500 ms. A completed round does not prove
+an unchanged prefix or disjoint object graph.
+
+Search caches only match metadata for an active query in its owning view. Clearing
+search drops that cache, and unmounting drops the matcher. Lowercase transcript
+text exists only during a cache miss and is not retained beside the source body.
+
+### Settled record identity
+
+Live text/thinking items can have client-generated IDs, while the host's settled
+record uses journal-derived IDs. Replacing those IDs as React/measurement keys
+remounted unchanged output and discarded its measured height. A supplied-geometry
+regression observed a 92px downward displacement followed by an eased return.
+`TimelineItemIdentity` keeps view-local aliases across a one-to-one ordered
+narrative handoff inside the same Turn and model round. Types, attempts and
+content must agree (allowing coalesced blank lines and a recovered suffix);
+insertions, removals, unrelated prose and replaced tools do not qualify.
+Unchanged source arrays skip item reconciliation, retired sources are released,
+and aliases are weakly keyed by the source item objects.
+
+Only rendered block keys use these aliases. Canonical item IDs, source references,
+search/navigation membership and persisted records remain host-owned. Bookmarks
+use `getVirtualItemBookmarkKey` and the row's canonical bookmark attribute, so a
+fresh projection can restore them after reopening. Restoration still accepts
+legacy row keys. The full-list regression checks every frame, retained DOM nodes,
+canonical bookmarks and reopening on local/simulated Peer surfaces, both while
+following and while reading. It does not establish native paint or live transport.
+
## Large text and decoration residency
`markdownSections` uses the existing streaming parser's block tokenizer to find
diff --git a/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.history-restore.test.tsx b/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.history-restore.test.tsx
index d8ab2a4e35..cb0e1beb28 100644
--- a/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.history-restore.test.tsx
+++ b/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.history-restore.test.tsx
@@ -33,9 +33,10 @@ vi.mock('../../store/FlowChatStore', () => ({ flowChatStore: {
} }));
vi.mock('../../store/modernFlowChatStore', async importOriginal => {
const original = await importOriginal();
+ const projectSession = original.createSessionVirtualItemProjector();
return { ...original,
useActiveSession: () => fixture.session,
- useVirtualItems: () => original.sessionToVirtualItems(fixture.session!),
+ useVirtualItems: () => projectSession(fixture.session!),
useVisibleTurnInfo: () => null,
};
});
diff --git a/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx b/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx
index a28d6aa8fe..90fabf7b29 100644
--- a/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx
+++ b/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx
@@ -46,7 +46,7 @@ import { TRAJECTORY_NAVIGATE_EVENT, type TrajectoryPanelData, showTrajectoryRang
import type { TrajectoryRangeSummary } from '../../trajectory/trajectoryRange';
import { useTrajectoryNavigation } from '../../trajectory/useTrajectoryNavigation';
import {
- sessionToVirtualItems,
+ createSessionVirtualItemProjector,
useVirtualItems,
useActiveSession,
useVisibleTurnInfo,
@@ -321,6 +321,8 @@ export const ModernFlowChatContainer: React.FC = (
const { t } = useTranslation('flow-chat');
const canonicalVirtualItems = useVirtualItems();
const activeSession = useActiveSession();
+ const [projectContinuousHistory] = useState(createSessionVirtualItemProjector);
+ const [projectHistory] = useState(createSessionVirtualItemProjector);
const surfaceScope = getActiveSurfaceScope();
useLayoutEffect(() => activeSession?.sessionId
? flowChatStore.retainSessionHistory(activeSession.sessionId)
@@ -415,13 +417,14 @@ export const ModernFlowChatContainer: React.FC = (
}, [activeSession, canonicalizedHistoryPresentation]);
const continuousHistoryVirtualItems = useMemo(() => {
if (!activeSession || !continuousHistoryPresentation) {
+ projectContinuousHistory(null);
return null;
}
- return sessionToVirtualItems({
+ return projectContinuousHistory({
...activeSession,
dialogTurns: continuousHistoryPresentation.turns,
});
- }, [activeSession, continuousHistoryPresentation]);
+ }, [activeSession, continuousHistoryPresentation, projectContinuousHistory]);
const continuousHistoryProjectionEligible = canRetainContinuousHistoryProjection(
continuousHistoryPresentation,
continuousHistoryVirtualItems?.length ?? Number.POSITIVE_INFINITY,
@@ -482,14 +485,16 @@ export const ModernFlowChatContainer: React.FC = (
const virtualItems = useMemo(() => {
let items: VirtualItem[];
if (!activeSession || !renderedHistoryPresentation) {
+ projectHistory(null);
items = canonicalVirtualItems;
} else if (
isRenderingContinuousHistoryProjection
&& continuousHistoryVirtualItems
) {
+ projectHistory(null);
items = continuousHistoryVirtualItems;
} else {
- items = sessionToVirtualItems({
+ items = projectHistory({
...activeSession,
dialogTurns: renderedHistoryPresentation.turns,
});
@@ -517,6 +522,7 @@ export const ModernFlowChatContainer: React.FC = (
isViewportDetachedFromLiveTail,
renderedHistoryPresentation,
submittedPreviews,
+ projectHistory,
]);
// The transcript reads the pending list to mark the tool cards that are
diff --git a/src/web-ui/src/flow_chat/components/modern/VirtualItemRenderer.tsx b/src/web-ui/src/flow_chat/components/modern/VirtualItemRenderer.tsx
index 9293281429..1080aad64a 100644
--- a/src/web-ui/src/flow_chat/components/modern/VirtualItemRenderer.tsx
+++ b/src/web-ui/src/flow_chat/components/modern/VirtualItemRenderer.tsx
@@ -14,7 +14,7 @@ import { useFlowChatVolatileContext } from './FlowChatContext';
import { TurnCompletionNoticeItem } from './TurnCompletionNoticeItem';
import { TurnFailureNoticeItem } from './TurnFailureNoticeItem';
import './VirtualItemRenderer.scss';
-import { getVirtualItemStableKey } from './virtualItemIdentity';
+import { getVirtualItemBookmarkKey, getVirtualItemStableKey } from './virtualItemIdentity';
import { useFlowChatSearchPresentation } from './useFlowChatSearchPresentation';
import { useConversationExcerptMarkers } from '../../selection/ConversationExcerptMarkers';
import { getKnownVirtualItemHeightPx } from './virtualItemHeightEstimators';
@@ -166,6 +166,7 @@ export const VirtualItemRenderer = React.memo(
data-turn-boundary-after={endsBeforeUserTurn ? 'true' : undefined}
data-ambient-tool-run-continuation-after={continuesAmbientToolRunAfter ? 'true' : undefined}
data-virtual-item-key={getVirtualItemStableKey(item)}
+ data-virtual-bookmark-key={getVirtualItemBookmarkKey(item)}
data-virtual-index={index}
data-markdown-section-start={item.timeline?.markdownSection?.start}
data-item-index={index}
diff --git a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.resize.test.tsx b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.resize.test.tsx
index 85a8c443c8..77ea48827d 100644
--- a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.resize.test.tsx
+++ b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.resize.test.tsx
@@ -9,7 +9,7 @@ import type { VirtualItem } from '../../store/modernFlowChatStore';
import type { Session } from '../../types/flow-chat';
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
-const state = vi.hoisted(() => ({ items: [] as VirtualItem[], session: null as Session | null }));
+const state = vi.hoisted(() => ({ items: [] as VirtualItem[], session: null as Session | null, processing: false }));
vi.mock('../../store/modernFlowChatStore', () => {
const store = Object.assign((select: (state: unknown) => unknown) => select({ visibleTurnInfo: null }),
{ getState: () => ({ setVisibleTurnInfo() {} }) });
@@ -21,7 +21,7 @@ vi.mock('../../timeline/useConversationTimeline', async () => {
const reader = new FlowChatReaderState();
return { useConversationTimeline: (items: VirtualItem[]) => ({ items, reader }) };
});
-vi.mock('../../hooks/useActiveSessionState', () => ({ useActiveSessionState: () => ({ isProcessing: false }) }));
+vi.mock('../../hooks/useActiveSessionState', () => ({ useActiveSessionState: () => ({ isProcessing: state.processing }) }));
vi.mock('../../store/chatInputStateStore', () => ({ useChatInputState: (select: (state: unknown) => unknown) => select({ inputHeight: 100 }) }));
vi.mock('../../hooks/useScrollToTurnHeader', () => ({ useScrollToTurnHeader: () => ({ shouldShowButton: false, handleClick() {} }) }));
vi.mock('./RuntimeStatusSlot', () => ({ RuntimeStatusSlot: () => null }));
@@ -42,6 +42,7 @@ describe('settled transcript resizing (real controllers, supplied DOM geometry)'
let frames: Map, frameId: number, now: number;
let observers: Array<{ callback: ResizeObserverCallback; targets: Set; sizes: WeakMap }>;
let columnWidth = 900;
+ let viewportHeight = 600;
let containerFirst = false;
const heights = new Map();
const offsets = new WeakMap();
@@ -57,7 +58,7 @@ describe('settled transcript resizing (real controllers, supplied DOM geometry)'
return result;
}
function measureHeight(element: HTMLElement, measured: WeakMap): number {
- if (element.hasAttribute('data-flowchat-scroller')) return 600;
+ if (element.hasAttribute('data-flowchat-scroller')) return viewportHeight;
if (element.dataset.virtualItemKey) return heights.get(element.dataset.virtualItemKey) ?? 100;
if (element.style.height) return px(element.style.height);
const scroller = element.closest('[data-flowchat-scroller]');
@@ -123,7 +124,8 @@ describe('settled transcript resizing (real controllers, supplied DOM geometry)'
const latest = () => host.querySelector('[data-virtual-item-key="model-round:latest:answer-latest"]');
beforeEach(() => {
- activateSurface('local'); columnWidth = 900; containerFirst = false;
+ activateSurface('local'); columnWidth = 900; viewportHeight = 600; containerFirst = false;
+ state.processing = false;
frames = new Map(); frameId = 0; now = 0; observers = []; heights.clear();
vi.useFakeTimers();
vi.spyOn(performance, 'now').mockImplementation(() => now);
@@ -168,6 +170,37 @@ describe('settled transcript resizing (real controllers, supplied DOM geometry)'
vi.restoreAllMocks(); vi.unstubAllGlobals(); vi.useRealTimers();
});
+ it.each(['local', 'peer-resume'].flatMap(surface => [false, true].map(live => ({ surface, live }))))(
+ 'observes suspended mounts after same-size resume without output or scroll on $surface (live=$live)', ({ surface, live }) => {
+ activateSurface(surface);
+ state.processing = live;
+ const completedItems = turn('latest', 180);
+ state.items = completedItems.slice(0, 1);
+ render();
+ for (let frame = 0; frame < 60; frame++) { resize(); tick(); }
+ expect(host.querySelector('[data-open-viewport-settled="true"]')).not.toBeNull();
+
+ viewportHeight = 0;
+ resize();
+ // The final answer mounts while minimized. No more output follows it.
+ state.items = completedItems;
+ state.processing = false;
+ render();
+ for (let frame = 0; frame < 4; frame++) tick();
+ const row = latest()!;
+ expect(row).not.toBeNull();
+ expect(observers.some(observer => observer.targets.has(row))).toBe(false);
+
+ viewportHeight = 600;
+ resize();
+ // Positive geometry schedules recovery, but measurements stay suspended
+ // until that frame. Neither the viewport dimensions nor props changed.
+ expect(observers.some(observer => observer.targets.has(row))).toBe(false);
+ tick();
+ expect(latest()).toBe(row);
+ expect(observers.some(observer => observer.targets.has(row))).toBe(true);
+ });
+
it.each(['local', 'peer-resize'].flatMap(surface => [false, true].map(first => ({ surface, first }))))(
'keeps a loaded transcript fixed on $surface, container observer first=$first', ({ surface, first }) => {
containerFirst = first;
diff --git a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.session-boundary.test.tsx b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.session-boundary.test.tsx
index dd028740bb..650ba1ca0d 100644
--- a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.session-boundary.test.tsx
+++ b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.session-boundary.test.tsx
@@ -21,6 +21,7 @@ import type { TrajectorySelection } from '../../trajectory/TrajectoryExplorer';
import type { Session } from '../../types/flow-chat';
import { useFlowChatReaderValue } from '../../timeline/readerState';
import { projectAdjacentFlowGroups } from '../../grouping/groupProjection';
+import * as viewportGeometry from './flowChatViewportGeometry';
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
@@ -429,6 +430,33 @@ describe('VirtualMessageList natural scroll contract', () => {
vi.unstubAllGlobals();
});
+ it('shares a snapshot geometry read with the anchor when a scroll has no travel', async () => {
+ const restoreLayout = fakeLayout({ clientHeight: 600, scrollHeight: 2000, turnTopFromScrollerTop: 120 });
+ const onViewportSnapshot = vi.fn();
+ const readGeometry = vi.spyOn(viewportGeometry, 'readFlowChatViewportGeometry');
+ try {
+ act(() => root.render());
+ await settleOpenReveal();
+ const scroller = container.querySelector('[data-flowchat-scroller]')!;
+ act(() => scroller.dispatchEvent(new WheelEvent('wheel', { deltaY: -100, bubbles: true })));
+ // Prime the reader's scroll register, then deliver an unchanged offset
+ // while the wheel intent still permits anchor capture.
+ act(() => scroller.dispatchEvent(new Event('scroll')));
+ readGeometry.mockClear();
+ onViewportSnapshot.mockClear();
+ const row = container.querySelector('.virtual-item-wrapper')!;
+ const readRow = vi.spyOn(row, 'getBoundingClientRect');
+ act(() => scroller.dispatchEvent(new Event('scroll')));
+ expect(onViewportSnapshot).toHaveBeenCalledTimes(1);
+ expect(readGeometry).toHaveBeenCalledTimes(1);
+ expect(readRow).toHaveBeenCalledTimes(1);
+ readRow.mockRestore();
+ } finally {
+ readGeometry.mockRestore();
+ restoreLayout();
+ }
+ });
+
it.each([
{ name: 'a session without config', config: undefined, canSynchronize: true },
{ name: 'an ordinary session', config: {}, canSynchronize: true },
diff --git a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.timeline-prepend.test.tsx b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.timeline-prepend.test.tsx
index 6897223172..de5c0f2dba 100644
--- a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.timeline-prepend.test.tsx
+++ b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.timeline-prepend.test.tsx
@@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { activateSurface, getActiveSurfaceScope } from '@/infrastructure/peer-device/deviceSurface';
import { isSubmittedMessageScrollIntentPending, registerSubmittedMessageScrollIntent } from '../../services/submittedMessageScrollIntent';
import { VirtualMessageList, type VirtualMessageListRef } from './VirtualMessageList';
-import { getVirtualItemStableKey } from './virtualItemIdentity';
+import { getVirtualItemBookmarkKey, getVirtualItemStableKey } from './virtualItemIdentity';
import type { VirtualItem } from '../../store/modernFlowChatStore';
import type { FlowToolItem, Session } from '../../types/flow-chat';
@@ -28,7 +28,8 @@ vi.mock('./VirtualItemRenderer', () => ({
item: VirtualItem; index: number; measureRef: (element: HTMLElement | null) => void;
}) => ,
+ data-virtual-item-key={getVirtualItemStableKey(item)} data-virtual-bookmark-key={getVirtualItemBookmarkKey(item)}
+ data-markdown-section-start={item.timeline?.markdownSection?.start} data-member-id={item.timeline?.memberIds[0]} />,
}));
// Full list, virtualizer, viewport owners and follow controller. Only row
@@ -148,7 +149,9 @@ describe('completed history with the production timeline projection', () => {
});
vi.spyOn(HTMLElement.prototype, 'scrollTop', 'get').mockImplementation(function () {
const range = Math.max(0, this.scrollHeight - this.clientHeight);
- return reversed(this) ? Math.max(-range, Math.min(0, offsets.get(this) ?? 0)) : Math.min(offsets.get(this) ?? 0, range);
+ const clamped = reversed(this) ? Math.max(-range, Math.min(0, offsets.get(this) ?? 0)) : Math.min(offsets.get(this) ?? 0, range);
+ offsets.set(this, clamped); // Native clamping persists if the range grows again.
+ return clamped;
});
vi.spyOn(HTMLElement.prototype, 'scrollTop', 'set').mockImplementation(function (value) {
if (this.hasAttribute('data-flowchat-scroller')) writes.push(value);
@@ -170,6 +173,56 @@ describe('completed history with the production timeline projection', () => {
vi.restoreAllMocks(); vi.unstubAllGlobals(); vi.useRealTimers();
});
+ it.each(['local', 'peer-settlement'].flatMap(surface => [false, true].map(reading => ({ surface, reading }))))(
+ 'keeps measured output stationary when settled persistence replaces stream item IDs: %j', ({ surface, reading }) => {
+ activateSurface(surface);
+ state.processing = true;
+ const tail = turn('latest', 1400);
+ state.items = tail;
+ render();
+ for (let frame = 0; frame < 80; frame++) { resize(); tick(); }
+ const scroller = host.querySelector('[data-flowchat-scroller]')!;
+ if (reading) act(() => {
+ scroller.dispatchEvent(new WheelEvent('wheel', { deltaY: -250 }));
+ scroller.scrollTop -= 250;
+ scroller.dispatchEvent(new Event('scroll'));
+ });
+ const before = latest()!;
+ const top = before.getBoundingClientRect().top;
+ const source = tail[1] as Extract;
+ const items = source.data.items.map((item, index) => {
+ const id = `round-latest-text-${index}`;
+ heights.set(`block:latest:${id}`, heights.get(`block:latest:${item.id}`)!);
+ return { ...item, id };
+ });
+ state.processing = false;
+ state.items = [tail[0], { ...source, data: { ...source.data, items } }];
+ render();
+ const after = () => host.querySelector('[data-member-id="round-latest-text-9"]');
+ expect(after()).toBe(before);
+ const samples: number[] = [];
+ for (let frame = 0; frame < 60; frame++) {
+ samples.push(after()?.getBoundingClientRect().top ?? NaN);
+ resize(); tick();
+ if (frame === 2) act(() => scroller.dispatchEvent(new Event('scroll')));
+ if (frame === 5) act(() => vi.advanceTimersByTime(200));
+ }
+ expect(samples.every(value => Math.abs(value - top) <= 1), JSON.stringify({ top, samples })).toBe(true);
+ const snapshot = listRef.current!.captureViewportSnapshot()!;
+ expect(snapshot.anchorItemKey).toBe('block:latest:round-latest-text-9');
+ if (reading) {
+ act(() => {
+ scroller.scrollTop -= 80;
+ expect(listRef.current!.restoreViewportSnapshot(snapshot)).toBe(true);
+ });
+ expect(after()!.getBoundingClientRect().top).toBeCloseTo(top, 1);
+ act(() => root.render());
+ for (let frame = 0; frame < 60; frame++) { resize(); tick(); }
+ expect(after()!.dataset.virtualItemKey).toBe(snapshot.anchorItemKey);
+ expect(after()!.getBoundingClientRect().top).toBeCloseTo(top, 1);
+ }
+ });
+
const pages = [
{ page: 'whole older turn', partial: false, addsTurn: true },
{ page: 'older turn plus missing earlier blocks', partial: true, addsTurn: true },
diff --git a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.tsx b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.tsx
index 1db6f52f79..d42eee058d 100644
--- a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.tsx
+++ b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.tsx
@@ -13,6 +13,7 @@ import React, {
useImperativeHandle,
useLayoutEffect,
useMemo,
+ useReducer,
useRef,
useState,
} from 'react';
@@ -95,7 +96,7 @@ import {
import { getKnownVirtualItemHeightPx } from './virtualItemHeightEstimators';
import { resolveVisibleFlowChatTurnIds } from './flowChatVisibleTurns';
import type { FlowChatViewportSnapshot } from './flowChatViewportSnapshot';
-import { getVirtualItemStableKey } from './virtualItemIdentity';
+import { getVirtualItemBookmarkKey, getVirtualItemStableKey } from './virtualItemIdentity';
import { useConversationTimeline } from '../../timeline/useConversationTimeline';
import { FlowChatReaderProvider } from '../../timeline/readerState';
import { findTimelineBlockIndex } from '../../timeline/document';
@@ -475,6 +476,7 @@ const VirtualMessageListSession = forwardRef revision + 1, 0);
const measurementSuspendedRef = useRef(measurementSuspended);
measurementSuspendedRef.current = measurementSuspended;
/** The last width the observer saw while the pane was still moving. */
@@ -1220,7 +1222,7 @@ const VirtualMessageListSession = forwardRef('.virtual-item-wrapper[data-virtual-item-key]'),
- ).find(element => element.dataset.virtualItemKey === snapshot.anchorItemKey) ?? null
+ ).find(element => element.dataset.virtualBookmarkKey === snapshot.anchorItemKey
+ || element.dataset.virtualItemKey === snapshot.anchorItemKey) ?? null
: null;
const exactAnchorIndex = snapshot.anchorItemKey
- ? virtualItems.findIndex(item => getVirtualItemStableKey(item) === snapshot.anchorItemKey)
+ ? virtualItems.findIndex(item => getVirtualItemBookmarkKey(item) === snapshot.anchorItemKey
+ || getVirtualItemStableKey(item) === snapshot.anchorItemKey)
: -1;
const sourceRow = virtualItems[exactAnchorIndex];
if (snapshot.anchorMarkdownStart === undefined && sourceRow?.timeline?.markdownSection?.start === 0
@@ -1303,14 +1307,15 @@ const VirtualMessageListSession = forwardRef {
+ if (!onViewportSnapshotRef.current) return;
const snapshot = captureViewportSnapshot(sample);
- if (snapshot) onViewportSnapshotRef.current?.(snapshot);
+ if (snapshot) onViewportSnapshotRef.current(snapshot);
}, [captureViewportSnapshot]);
const publishViewportSnapshotRef = useRef(publishViewportSnapshot);
publishViewportSnapshotRef.current = publishViewportSnapshot;
const scheduleViewportSnapshot = useCallback(() => {
- if (viewportSnapshotFrameRef.current !== null) return;
+ if (!onViewportSnapshotRef.current || viewportSnapshotFrameRef.current !== null) return;
viewportSnapshotFrameRef.current = requestAnimationFrame(() => {
viewportSnapshotFrameRef.current = null;
publishViewportSnapshotRef.current();
@@ -1520,6 +1525,10 @@ const VirtualMessageListSession = forwardRef 0.5 ? 'after' : undefined;
+ let geometrySample: FlowChatViewportGeometry | undefined;
+ const getGeometry = () => {
+ if (!geometrySample || geometrySample.scrollTop !== readFlowChatScrollTop(scrollerElement)) {
+ geometrySample = readFlowChatViewportGeometry(scrollerElement);
+ }
+ return geometrySample;
+ };
// Synchronous corrections are removed by the register. Smooth owned
// navigation/follow scrolls are excluded here; unowned momentum counts.
if (direction && (owner === null || owner === 'user-gesture')) {
- captureLeadingExtent(readFlowChatScrollTop(scrollerElement), true, geometry);
+ captureLeadingExtent(readFlowChatScrollTop(scrollerElement), true, getGeometry());
historyPager.readerIntent(direction);
}
- if (owner === 'one-shot-navigation') captureLeadingExtent(readFlowChatScrollTop(scrollerElement), true, geometry);
+ if (owner === 'one-shot-navigation') captureLeadingExtent(readFlowChatScrollTop(scrollerElement), true, getGeometry());
/*
* A scroll under a scrollbar press is the one case where a plain scroll
* event does carry intent — the press is what qualifies it. Left
@@ -1638,9 +1653,15 @@ const VirtualMessageListSession = forwardRef {
+ it('reuses settled matches during search and releases them when that view closes search', () => {
+ const first = createFlowChatSearchMatcher();
+ const side = createFlowChatSearchMatcher();
+ const items = searchableItems(2);
+ const before = first(items, 'needle');
+ const sideBefore = side(items, 'needle');
+ expect(first([...items], 'needle')[0]).toBe(before[0]);
+ expect(first(items, '')).toEqual([]);
+ const reopened = first(items, 'needle');
+ expect(reopened).toEqual(before);
+ expect(reopened[0]).not.toBe(before[0]);
+ expect(side(items, 'needle')[0]).toBe(sideBefore[0]);
+ });
+
it('searches retained quiet execution content through its folded receipt', () => {
const items = [{ type: 'background-run', turnId: 'run', turn: { userMessage: { content: 'Generic task needle' }, modelRounds: [{ items: [{ id: 'text', type: 'text', content: 'Original needle output' }, { id: 'thinking', type: 'thinking', content: 'needle reasoning' }] }] } }] as unknown as VirtualItem[];
expect(buildFlowChatSearchMatches(items, 'needle')).toMatchObject([
diff --git a/src/web-ui/src/flow_chat/components/modern/useFlowChatSearch.ts b/src/web-ui/src/flow_chat/components/modern/useFlowChatSearch.ts
index 7f2dcdced9..e22f1045be 100644
--- a/src/web-ui/src/flow_chat/components/modern/useFlowChatSearch.ts
+++ b/src/web-ui/src/flow_chat/components/modern/useFlowChatSearch.ts
@@ -8,7 +8,7 @@
import { useState, useMemo, useCallback } from 'react';
import type { VirtualItem } from '../../store/modernFlowChatStore';
-import { buildInlineFlowGroupData, getProjectedModelRoundGroups } from '../../grouping/roundGroups';
+import { getCachedInlineFlowGroupData, getProjectedModelRoundGroups } from '../../grouping/roundGroups';
interface SearchableFlowItem {
id?: string;
@@ -45,7 +45,7 @@ export interface UseFlowChatSearchReturn {
}
interface SearchableSource {
- content: string;
+ foldedContent: string;
flowItemId?: string;
expandableIds?: readonly string[];
}
@@ -63,9 +63,10 @@ function flowItemSearchSources(
...(outerExpandableId ? [outerExpandableId] : []),
...(item.type === 'thinking' && item.id ? [item.id] : []),
];
+ const content = item.content ?? '';
return [{
- content: item.content ?? '',
+ foldedContent: content.toLowerCase(),
flowItemId: item.id,
expandableIds: expandableIds.length > 0 ? expandableIds : undefined,
}];
@@ -73,43 +74,45 @@ function flowItemSearchSources(
}
function getVirtualItemSearchSources(item: VirtualItem): SearchableSource[] {
+ let sources: SearchableSource[];
if (item.type === 'background-run') {
- return [{ content: item.turn.userMessage.content }, ...flowItemSearchSources(item.turn.modelRounds.flatMap(round => round.items))];
- }
- if (item.type === 'user-message' || item.type === 'user-steering-message') {
- return [{ content: item.data?.content ?? '' }];
- }
- if (item.type === 'model-round') {
- return getProjectedModelRoundGroups(item).flatMap(group => group.type !== 'critical'
- ? flowItemSearchSources(group.items, buildInlineFlowGroupData(item.data.id, group).groupId)
+ const userContent = item.turn.userMessage.content;
+ sources = [
+ { foldedContent: userContent.toLowerCase() },
+ ...flowItemSearchSources(item.turn.modelRounds.flatMap(round => round.items)),
+ ];
+ } else if (item.type === 'user-message' || item.type === 'user-steering-message') {
+ const content = item.data?.content ?? '';
+ sources = [{ foldedContent: content.toLowerCase() }];
+ } else if (item.type === 'model-round') {
+ sources = getProjectedModelRoundGroups(item).flatMap(group => group.type !== 'critical'
+ ? flowItemSearchSources(group.items, getCachedInlineFlowGroupData(item.data, group).groupId)
: flowItemSearchSources([group.item]));
+ } else if (item.type === 'explore-group') {
+ sources = flowItemSearchSources(item.data.allItems, item.data.groupId);
+ } else if (item.type === 'turn-completion-notice') {
+ const content = item.data.reasonCode;
+ sources = [{ foldedContent: content.toLowerCase() }];
+ } else if (item.type === 'turn-failure-notice') {
+ const content = [
+ item.data.error,
+ item.data.errorDetail?.provider,
+ item.data.errorDetail?.providerCode,
+ item.data.errorDetail?.providerMessage,
+ item.data.errorDetail?.requestId,
+ ].filter(Boolean).join(' ');
+ sources = [{ foldedContent: content.toLowerCase() }];
+ } else {
+ sources = [];
}
- if (item.type === 'explore-group') {
- return flowItemSearchSources(item.data.allItems, item.data.groupId);
- }
- if (item.type === 'turn-completion-notice') {
- return [{ content: item.data.reasonCode }];
- }
- if (item.type === 'turn-failure-notice') {
- return [{
- content: [
- item.data.error,
- item.data.errorDetail?.provider,
- item.data.errorDetail?.providerCode,
- item.data.errorDetail?.providerMessage,
- item.data.errorDetail?.requestId,
- ].filter(Boolean).join(' '),
- }];
- }
- return [];
+ return sources;
}
-function countQueryOccurrences(content: string, foldedQuery: string): number {
- const haystack = content.toLowerCase();
+function countFoldedQueryOccurrences(foldedContent: string, foldedQuery: string): number {
let count = 0;
let from = 0;
for (;;) {
- const index = haystack.indexOf(foldedQuery, from);
+ const index = foldedContent.indexOf(foldedQuery, from);
if (index < 0) {
return count;
}
@@ -118,20 +121,37 @@ function countQueryOccurrences(content: string, foldedQuery: string): number {
}
}
+const emptySearchMatches: SearchMatch[] = [];
+type SearchMatchCache = WeakMap;
+
export function buildFlowChatSearchMatches(
virtualItems: readonly VirtualItem[],
searchQuery: string,
+ cache?: SearchMatchCache,
): SearchMatch[] {
const trimmed = searchQuery.trim();
- if (!trimmed) return [];
+ if (!trimmed) return emptySearchMatches;
const query = trimmed.toLowerCase();
const matches: SearchMatch[] = [];
- virtualItems.forEach((item, virtualItemIndex) => {
+ for (let virtualItemIndex = 0; virtualItemIndex < virtualItems.length; virtualItemIndex += 1) {
+ const item = virtualItems[virtualItemIndex];
+ const cached = cache?.get(item);
+ if (cached && cached.query === query && cached.virtualItemIndex === virtualItemIndex) {
+ for (let i = 0; i < cached.matches.length; i += 1) {
+ matches.push(cached.matches[i]);
+ }
+ continue;
+ }
+ const itemMatches: SearchMatch[] = [];
for (const source of getVirtualItemSearchSources(item)) {
- const occurrenceCount = countQueryOccurrences(source.content, query);
+ const occurrenceCount = countFoldedQueryOccurrences(source.foldedContent, query);
for (let occurrenceIndex = 0; occurrenceIndex < occurrenceCount; occurrenceIndex += 1) {
- matches.push({
+ itemMatches.push({
virtualItemIndex,
turnId: item.turnId,
type: item.type,
@@ -141,18 +161,35 @@ export function buildFlowChatSearchMatches(
});
}
}
- });
+ cache?.set(item, { query, virtualItemIndex, matches: itemMatches });
+ for (let i = 0; i < itemMatches.length; i += 1) {
+ matches.push(itemMatches[i]);
+ }
+ }
return matches;
}
+/** Cache only match metadata while this view searches; folded text is temporary. */
+export function createFlowChatSearchMatcher() {
+ let cache: SearchMatchCache = new WeakMap();
+ return (items: readonly VirtualItem[], query: string): SearchMatch[] => {
+ if (!query.trim()) {
+ cache = new WeakMap();
+ return emptySearchMatches;
+ }
+ return buildFlowChatSearchMatches(items, query, cache);
+ };
+}
+
export function useFlowChatSearch(virtualItems: VirtualItem[]): UseFlowChatSearchReturn {
const [searchQuery, setSearchQuery] = useState('');
+ const [findMatches] = useState(createFlowChatSearchMatcher);
const [currentMatchIndex, setCurrentMatchIndex] = useState(0);
const matches = useMemo(() => (
- buildFlowChatSearchMatches(virtualItems, searchQuery)
- ), [virtualItems, searchQuery]);
+ findMatches(virtualItems, searchQuery)
+ ), [virtualItems, searchQuery, findMatches]);
const resolvedCurrentMatchIndex = matches.length > 0
? Math.min(currentMatchIndex, matches.length - 1)
@@ -196,9 +233,10 @@ export function useFlowChatSearch(virtualItems: VirtualItem[]): UseFlowChatSearc
}, [matches.length]);
const clearSearch = useCallback(() => {
+ findMatches([], '');
setSearchQuery('');
setCurrentMatchIndex(0);
- }, []);
+ }, [findMatches]);
return {
searchQuery,
diff --git a/src/web-ui/src/flow_chat/components/modern/useFlowChatVirtualizer.initial-window.test.tsx b/src/web-ui/src/flow_chat/components/modern/useFlowChatVirtualizer.initial-window.test.tsx
index 5a2dd6d61e..d574d932aa 100644
--- a/src/web-ui/src/flow_chat/components/modern/useFlowChatVirtualizer.initial-window.test.tsx
+++ b/src/web-ui/src/flow_chat/components/modern/useFlowChatVirtualizer.initial-window.test.tsx
@@ -13,6 +13,27 @@ let reconcileEnabled = false;
let shortOverscan = false;
let viewportSuspended = false;
let shiftEnabled = false;
+const unobserve = vi.fn();
+const rowObservers: Array<{ callback: ResizeObserverCallback; elements: Set }> = [];
+
+function KeyedHarness({ items, endOrigin }: { items: string[]; endOrigin: boolean }) {
+ const scrollerRef = useRef(null);
+ const headerRef = useRef(null);
+ const api = useFlowChatVirtualizer({
+ items, scrollerRef, headerRef, endOrigin,
+ isViewportSuspended: () => viewportSuspended,
+ getItemKey: item => item,
+ estimateItemHeightPx: () => 80,
+ scrollPaddingStartPx: 0,
+ writeViewport: () => true,
+ });
+ latestApi = api;
+ return
+
+ {api.rows.map(row =>
)}
+
;
+}
function Harness({ count, tail }: { count: number; tail: boolean }) {
const scrollerRef = useRef(null);
const headerRef = useRef(null);
@@ -67,6 +88,8 @@ describe('initial virtual window with the real virtualizer', () => {
shortOverscan = false;
viewportSuspended = false;
shiftEnabled = false;
+ unobserve.mockClear();
+ rowObservers.length = 0;
vi.useFakeTimers();
vi.stubGlobal('requestAnimationFrame', vi.fn().mockReturnValue(1));
vi.stubGlobal('cancelAnimationFrame', vi.fn());
@@ -75,9 +98,14 @@ describe('initial virtual window with the real virtualizer', () => {
return { top: 0, bottom: height, height, width: this.offsetWidth } as DOMRect;
});
vi.stubGlobal('ResizeObserver', class {
- observe() {}
- unobserve() {}
- disconnect() {}
+ entry: (typeof rowObservers)[number];
+ constructor(callback: ResizeObserverCallback) {
+ this.entry = { callback, elements: new Set() };
+ rowObservers.push(this.entry);
+ }
+ observe(element: Element) { this.entry.elements.add(element); }
+ unobserve(element: Element) { unobserve(element); this.entry.elements.delete(element); }
+ disconnect() { this.entry.elements.clear(); }
});
// Explicit geometry supplies jsdom's missing layout, not performance proof.
vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockImplementation(function () {
@@ -106,6 +134,57 @@ describe('initial virtual window with the real virtualizer', () => {
});
const render = (count: number, tail: boolean) => act(() => root.render());
+ it.each([
+ [false, false], [false, true], [true, false],
+ ])('observes rows mounted during suspension after resuming (%s → %s)', (initialOrigin, resumedOrigin) => {
+ viewportSuspended = true;
+ act(() => root.render());
+ const row = host.querySelector('[data-row-key="b"]')!;
+ expect(row).not.toBeNull();
+ expect(rowObservers.some(entry => entry.elements.has(row))).toBe(false);
+ // A still-suspended commit can discard other rows and switch the origin.
+ act(() => root.render());
+ viewportSuspended = false;
+ act(() => root.render());
+ expect(host.querySelector('[data-row-key="b"]')).toBe(row);
+ const observer = rowObservers.find(entry => entry.elements.has(row));
+ expect(observer).toBeDefined();
+ vi.spyOn(row, 'getBoundingClientRect').mockReturnValue({ height: 221.5 } as DOMRect);
+ act(() => observer!.callback([{ target: row } as ResizeObserverEntry], {} as ResizeObserver));
+ const bounds = latestApi.getItemBounds(1)!;
+ expect(bounds.endPx - bounds.startPx).toBe(221.5);
+ });
+
+ it.each([false, true])('keeps observer measurements on surviving keys after insertion (endOrigin=%s)', endOrigin => {
+ const initial = ['a', 'b', 'c'];
+ act(() => root.render());
+ const row = host.querySelector('[data-row-key="b"]')!;
+ const updated = endOrigin ? [...initial, 'new-tail'] : ['older', ...initial];
+ act(() => root.render());
+ expect(host.querySelector('[data-row-key="b"]')).toBe(row);
+ const observer = rowObservers.find(entry => entry.elements.has(row))!;
+ expect(observer).toBeDefined();
+ vi.spyOn(row, 'getBoundingClientRect').mockReturnValue({ height: 221.5 } as DOMRect);
+ act(() => observer.callback([{ target: row } as ResizeObserverEntry], {} as ResizeObserver));
+ const height = (key: string) => {
+ const bounds = latestApi.getItemBounds(updated.indexOf(key))!;
+ return bounds.endPx - bounds.startPx;
+ };
+ expect(height('b')).toBe(221.5);
+ expect(height('a')).toBe(80);
+ expect(height('c')).toBe(80);
+ });
+
+ it('unobserves removed rows when the transcript becomes empty without new attachments', () => {
+ render(8, false);
+ const rows = [...host.querySelectorAll('[data-virtual-index]')];
+ expect(rows.length).toBeGreaterThan(0);
+ unobserve.mockClear();
+ render(0, false);
+ expect(host.querySelectorAll('[data-virtual-index]')).toHaveLength(0);
+ for (const row of rows) expect(unobserve).toHaveBeenCalledWith(row);
+ });
+
it('mounts the tail first without measuring head rows, then accepts user scrolling', () => {
render(34, true);
const populated = windows.filter(window => window.length);
diff --git a/src/web-ui/src/flow_chat/components/modern/useFlowChatVirtualizer.ts b/src/web-ui/src/flow_chat/components/modern/useFlowChatVirtualizer.ts
index 3c352c7922..a2a6e3268b 100644
--- a/src/web-ui/src/flow_chat/components/modern/useFlowChatVirtualizer.ts
+++ b/src/web-ui/src/flow_chat/components/modern/useFlowChatVirtualizer.ts
@@ -756,7 +756,8 @@ export function useFlowChatVirtualizer({
const key = keys[index] ?? getItemKeyRef.current(item);
const knownHeight = getKnownItemHeightPx(item);
if (knownHeight !== undefined) next.set(key, knownHeight);
- if (knownHeight === undefined && !previous.has(key)) continue;
+ const prevHeight = previous.get(key);
+ if (knownHeight === prevHeight) continue;
// A mounted row has real geometry. An unmounted row must have its old
// key-based measurement replaced now; otherwise virtual padding keeps
@@ -809,20 +810,31 @@ export function useFlowChatVirtualizer({
}, [toVirtualIndex]);
const measuredOriginRef = useRef(endOrigin);
useLayoutEffect(() => {
- const scroller = scrollerRef.current;
const originChanged = measuredOriginRef.current !== endOrigin;
measuredOriginRef.current = endOrigin;
- // Stable DOM rows keep their chronological index while an origin handoff
- // changes the library index. ResizeObserver must see the new mapping too.
- const mountedRows = [...(scroller?.querySelectorAll('[data-virtual-index]') ?? [])]
- .filter(element => element.closest('[data-flowchat-virtual-viewport]') === scroller);
- for (const element of mountedRows) {
- element.setAttribute('data-flowchat-measure-index', String(toVirtualIndex(Number(element.getAttribute('data-virtual-index')))));
+ for (const element of attachingRowsRef.current) {
+ if (!element.isConnected) attachingRowsRef.current.delete(element);
}
- const attached = originChanged ? mountedRows : [...attachingRowsRef.current].filter(element => element.isConnected);
- attachingRowsRef.current.clear();
+ const connectedRows = new Set([...virtualizer.elementsCache.values(), ...attachingRowsRef.current]
+ .filter(element => element.isConnected));
+ // A surviving keyed row does not reattach when insertion changes its
+ // index. Refresh observer addresses on every commit, without measuring
+ // existing rows or scanning nested transcript DOM.
+ for (const element of connectedRows) {
+ const index = String(toVirtualIndex(Number(element.getAttribute('data-virtual-index'))));
+ if (element.getAttribute('data-flowchat-measure-index') !== index) {
+ element.setAttribute('data-flowchat-measure-index', index);
+ }
+ }
+ const attached = originChanged ? [...connectedRows]
+ : [...attachingRowsRef.current].filter(element => element.isConnected);
+ // A shrinking window can detach rows without attaching any replacements.
+ // Cleanup must still unobserve and release those DOM nodes.
virtualizer.measureElement(null);
if (!attached.length || isViewportSuspendedRef.current()) return;
+ // Suspended mounts have not entered elementsCache or its observer yet.
+ // Keep their attachment pending until a resumed commit can register them.
+ attachingRowsRef.current.clear();
// Read before any viewport shift or size-cache notification can write.
measurementBatchRef.current = new Map(attached.map(element => [element, measureRowHeight(element)]));
try {
diff --git a/src/web-ui/src/flow_chat/components/modern/virtualItemIdentity.ts b/src/web-ui/src/flow_chat/components/modern/virtualItemIdentity.ts
index bd2e8b178d..256cd1d45b 100644
--- a/src/web-ui/src/flow_chat/components/modern/virtualItemIdentity.ts
+++ b/src/web-ui/src/flow_chat/components/modern/virtualItemIdentity.ts
@@ -21,3 +21,13 @@ export function getVirtualItemStableKey(item: VirtualItem): string {
return `${item.type}:${item.turnId}`;
}
}
+
+/** Bookmarks use host IDs even while a mounted row retains its live stream key. */
+export function getVirtualItemBookmarkKey(item: VirtualItem): string {
+ const block = item.timeline;
+ if (item.type === 'model-round' && block && (block.kind === 'content' || block.kind === 'group-members') && block.memberIds.length) {
+ const start = block.markdownSection?.start ?? 0;
+ return `block:${item.turnId}:${block.memberIds[0]}${start > 0 ? `:markdown:${start}` : ''}`;
+ }
+ return getVirtualItemStableKey(item);
+}
diff --git a/src/web-ui/src/flow_chat/grouping/activityGrouping.test.ts b/src/web-ui/src/flow_chat/grouping/activityGrouping.test.ts
index a98b71d5dd..787a9c1e59 100644
--- a/src/web-ui/src/flow_chat/grouping/activityGrouping.test.ts
+++ b/src/web-ui/src/flow_chat/grouping/activityGrouping.test.ts
@@ -24,6 +24,20 @@ function groups(rows: VirtualItem[]) {
}
describe('execution activity grouping', () => {
+ it('keeps inline group identities independent of their position in a projected list', () => {
+ const first = tool('read', 'Read');
+ const second = tool('run', 'ExecCommand');
+ const row = model('round', [first, tool('boundary', 'AskUserQuestion'), second]);
+ const firstGroup = { type: 'explore' as const, items: [first], isLast: false };
+ const secondGroup = { type: 'explore' as const, items: [second], isLast: false };
+ const before = getModelRoundFlowGroups(row.data, [firstGroup])[0];
+ const after = getModelRoundFlowGroups(row.data, [secondGroup])[0];
+ expect(after.allItems).toEqual([second]);
+ expect(after.groupId).not.toBe(before.groupId);
+ expect(getModelRoundFlowGroups(row.data, [firstGroup])[0]).toBe(before);
+ expect(getModelRoundFlowGroups(row.data, [secondGroup])[0]).toBe(after);
+ });
+
it.each(['ExecCommand', 'WriteStdin', 'ExecControl', 'Bash'])('collects %s with exploration without any mode hints', toolName => {
for (const call of [tool('shell', toolName),
tool('deferred', 'CallDeferredTool', { tool_name: toolName, args: {} })]) {
diff --git a/src/web-ui/src/flow_chat/grouping/groupProjection.ts b/src/web-ui/src/flow_chat/grouping/groupProjection.ts
index 30396a2942..1dc204457b 100644
--- a/src/web-ui/src/flow_chat/grouping/groupProjection.ts
+++ b/src/web-ui/src/flow_chat/grouping/groupProjection.ts
@@ -4,9 +4,59 @@ import type { FlowGroupData, ModelRoundItemGroup } from './types';
import { getFlowGroupCategory, getFlowGroupStateIds } from './types';
import { canContinueFlowGroup, flowGroupPolicies, hasPendingFlowGroupClassification, joinedFlowGroupCategory } from './policies';
import { flowGroupLifecycle } from './lifecycle';
-import { buildInlineFlowGroupData, getModelRoundFlowGroups, getProjectedModelRoundGroups,
+import { getCachedInlineFlowGroupData, getModelRoundFlowGroups, getProjectedModelRoundGroups,
flowGroupCompanionStart, hasModelRoundLeadingControls, isFlowGroupCompanion, isModelRoundGroupingDisabled, projectedFlowGroup } from './roundGroups';
+export function canStartFreshFlowGroupRunAt(
+ prevItem: VirtualItem | undefined,
+ currItem: VirtualItem,
+): boolean {
+ if (currItem.type !== 'model-round') {
+ return currItem.type !== 'explore-group';
+ }
+ const disabled = isModelRoundGroupingDisabled(currItem.data);
+ if (disabled || hasModelRoundLeadingControls(currItem.data)) return true;
+ const currGroups = getProjectedModelRoundGroups(currItem, true);
+ let firstCurrIndex = 0;
+ while (firstCurrIndex < currGroups.length) {
+ const g = currGroups[firstCurrIndex];
+ if (g.type === 'critical' && isFlowGroupCompanion(g.item)) {
+ firstCurrIndex += 1;
+ continue;
+ }
+ break;
+ }
+ if (firstCurrIndex >= currGroups.length) return false;
+ const firstCurr = currGroups[firstCurrIndex];
+ if (firstCurr.type === 'critical') {
+ return !hasPendingFlowGroupClassification(firstCurr.item);
+ }
+
+ // Current round starts with a collectible group (`firstCurr`).
+ // Check if `prevItem` ended with an open group of a DIFFERENT category or a hard boundary.
+ if (!prevItem || prevItem.type !== 'model-round') return false;
+ if (isModelRoundGroupingDisabled(prevItem.data)) return true;
+ const prevGroups = getProjectedModelRoundGroups(prevItem, true);
+ // If prevGroups has any trailing companion items after its last non-companion,
+ // those companions could be absorbed into `currItem` if we don't include `prevItem`.
+ const lastPrev = prevGroups[prevGroups.length - 1];
+ if (!lastPrev) return false;
+ if (lastPrev.type === 'critical') {
+ if (isFlowGroupCompanion(lastPrev.item) || hasPendingFlowGroupClassification(lastPrev.item)) {
+ return false;
+ }
+ return true;
+ }
+ // `lastPrev` is a collectible group at the very end of `prevItem` (no trailing prose/thinking).
+ // If `firstCurr` has any leading companions, `collect` would behave differently if `continuing` were true vs false,
+ // so only cut when `firstCurrIndex === 0` AND the two group categories cannot continue together.
+ if (firstCurrIndex > 0) return false;
+ return (
+ joinedFlowGroupCategory(lastPrev.type, firstCurr.type) === undefined ||
+ !canContinueFlowGroup(firstCurr.type, lastPrev.items, firstCurr.items)
+ );
+}
+
/** Count only until the policy minimum; the shared threshold helper copies the item list. */
function reachesFlowGroupThreshold(category: ReturnType, items: readonly FlowItem[]): boolean {
const minimum = flowGroupPolicies[category].minimumItems;
@@ -34,9 +84,22 @@ function sourceGroupIds(group: FlowGroupData): readonly string[] {
return [...ids];
}
+const mergedFlowGroupRunCache = new WeakMap();
+
/** Finalize once per run instead of repeatedly copying and recounting its growing prefix. */
function mergeFlowGroupRun(parts: readonly FlowGroupData[]): FlowGroupData {
const first = parts[0];
+ const cached = mergedFlowGroupRunCache.get(first);
+ if (
+ cached &&
+ cached.parts.length === parts.length &&
+ cached.parts.every((part, idx) => part === parts[idx])
+ ) {
+ return cached.merged;
+ }
const last = parts[parts.length - 1];
const mergedIds = new Set();
const rounds: ModelRound[] = [];
@@ -57,7 +120,7 @@ function mergeFlowGroupRun(parts: readonly FlowGroupData[]): FlowGroupData {
for (const item of part.allItems) allItems.push(item);
if (part.isGroupStreaming) isGroupStreaming = true;
}
- return flowGroupPolicies[category ?? getFlowGroupCategory(first)].create({
+ const merged = flowGroupPolicies[category ?? getFlowGroupCategory(first)].create({
...first,
sourceGroupIds: [...mergedIds],
rounds,
@@ -66,6 +129,8 @@ function mergeFlowGroupRun(parts: readonly FlowGroupData[]): FlowGroupData {
isLastGroupInTurn: last.isLastGroupInTurn,
wasCutByCritical: last.wasCutByCritical,
});
+ mergedFlowGroupRunCache.set(first, { parts: [...parts], merged });
+ return merged;
}
/**
@@ -180,11 +245,14 @@ export function projectAdjacentFlowGroups(items: readonly VirtualItem[], options
else boundary();
return;
}
- let data = buildInlineFlowGroupData(item.data.id, group, item.isLastRound && groupIndex === groups.length - 1);
// Read saved disclosure choices from the previous whole-round projection.
- if (group.type === 'explore' && firstExploreIndex === groupIndex) {
- data = { ...data, sourceGroupIds: [...new Set([...getFlowGroupStateIds(data), item.data.id])] };
- }
+ const includeRoundIdAlias = group.type === 'explore' && firstExploreIndex === groupIndex;
+ const data = getCachedInlineFlowGroupData(
+ item.data,
+ group,
+ item.isLastRound && groupIndex === groups.length - 1,
+ includeRoundIdAlias,
+ );
collect(data, next => {
renderedGroups[groupIndex] = projectedFlowGroup(getFlowGroupCategory(next), next.allItems, group.isLast, next);
changed = true;
diff --git a/src/web-ui/src/flow_chat/grouping/lifecycle.ts b/src/web-ui/src/flow_chat/grouping/lifecycle.ts
index 34b53e883c..970c1a68f4 100644
--- a/src/web-ui/src/flow_chat/grouping/lifecycle.ts
+++ b/src/web-ui/src/flow_chat/grouping/lifecycle.ts
@@ -10,14 +10,30 @@ export function isFlowGroupMemberActive(item: FlowItem): boolean {
|| ((item.type === 'thinking' || item.type === 'text') && (item as FlowTextItem).isStreaming);
}
+const lifecycleCache = new WeakMap;
+ sealedFalse?: Pick;
+}>();
+
/** Boundary and execution are independent: a sealed run can still be draining. */
export function flowGroupLifecycle(items: readonly FlowItem[], sealed: boolean): Pick {
+ let entry = lifecycleCache.get(items);
+ if (entry) {
+ const cached = sealed ? entry.sealedTrue : entry.sealedFalse;
+ if (cached) return cached;
+ } else {
+ entry = {};
+ lifecycleCache.set(items, entry);
+ }
const active = items.some(isFlowGroupMemberActive);
const shell = shellActivityStats(items.filter((item): item is FlowToolItem => item.type === 'tool' && isShellActivity(item as FlowToolItem)));
- return {
+ const result: Pick = {
phase: !sealed ? 'collecting' : active ? 'settling' : 'settled',
isGroupStreaming: active,
needsAttention: shell.failed > 0 || shell.stopped > 0 || items.some(item => ['error', 'pending_confirmation', 'cancelled', 'rejected'].includes(item.status)
|| (item.type === 'tool' && (item as FlowToolItem).toolResult?.success === false)),
};
+ if (sealed) entry.sealedTrue = result;
+ else entry.sealedFalse = result;
+ return result;
}
diff --git a/src/web-ui/src/flow_chat/grouping/receiveFeedback.ts b/src/web-ui/src/flow_chat/grouping/receiveFeedback.ts
index 204d8662c2..d041a6399d 100644
--- a/src/web-ui/src/flow_chat/grouping/receiveFeedback.ts
+++ b/src/web-ui/src/flow_chat/grouping/receiveFeedback.ts
@@ -10,30 +10,55 @@ interface FeedbackSnapshot {
groupedMembers: ReadonlySet;
}
-const memberKey = (turnId: string, itemId: string) => JSON.stringify([turnId, itemId]);
+const memberKey = (turnId: string, itemId: string) => `${turnId}\u0000${itemId}`;
-export function captureFlowGroupFeedbackSnapshot(items: readonly VirtualItem[], scope: string | undefined): FeedbackSnapshot {
- const activeMembers = new Set();
- const groupedMembers = new Set();
- for (const item of items) {
- for (const group of getVirtualItemFlowGroups(item)) {
- group.allItems.forEach(member => groupedMembers.add(memberKey(item.turnId, member.id)));
+const itemFeedbackKeysCache = new WeakMap();
+
+function getItemFeedbackKeys(item: VirtualItem) {
+ let cached = itemFeedbackKeysCache.get(item);
+ if (cached) return cached;
+ const groupedKeys: string[] = [];
+ for (const group of getVirtualItemFlowGroups(item)) {
+ for (const member of group.allItems) {
+ groupedKeys.push(memberKey(item.turnId, member.id));
}
- if (item.type !== 'model-round' || item.isTurnComplete) continue;
+ }
+ const activeKeys: string[] = [];
+ if (item.type === 'model-round' && !item.isTurnComplete) {
for (const member of getModelRoundActiveItems(item.data)) {
- if (member.type === 'tool' && ((member as FlowToolItem).isParamsStreaming
- || ['pending', 'queued', 'preparing', 'running', 'streaming', 'pending_confirmation'].includes(member.status))) {
- activeMembers.add(memberKey(item.turnId, member.id));
+ if (
+ member.type === 'tool' &&
+ ((member as FlowToolItem).isParamsStreaming ||
+ ['pending', 'queued', 'preparing', 'running', 'streaming', 'pending_confirmation'].includes(member.status))
+ ) {
+ activeKeys.push(memberKey(item.turnId, member.id));
}
}
}
+ cached = { activeKeys, groupedKeys };
+ itemFeedbackKeysCache.set(item, cached);
+ return cached;
+}
+
+export function captureFlowGroupFeedbackSnapshot(items: readonly VirtualItem[], scope: string | undefined): FeedbackSnapshot {
+ const activeMembers = new Set();
+ const groupedMembers = new Set();
+ for (const item of items) {
+ if (item.type === 'model-round' && item.isTurnComplete) continue;
+ const { activeKeys, groupedKeys } = getItemFeedbackKeys(item);
+ for (let i = 0; i < activeKeys.length; i += 1) activeMembers.add(activeKeys[i]);
+ for (let i = 0; i < groupedKeys.length; i += 1) groupedMembers.add(groupedKeys[i]);
+ }
return { scope, activeMembers, groupedMembers };
}
/** Legacy collection feedback; live windows already show arrivals without a pulse. */
export function collectFlowGroupReceiveFeedback(previous: FeedbackSnapshot | undefined, items: readonly VirtualItem[], scope: string | undefined): ReadonlyMap {
const receipts = new Map();
- if (!previous || previous.scope !== scope) return receipts;
+ if (!previous || previous.scope !== scope || previous.activeMembers.size === 0) return receipts;
for (const item of items) {
for (const group of getVirtualItemFlowGroups(item)) {
if (group.phase !== undefined) continue;
diff --git a/src/web-ui/src/flow_chat/grouping/roundGroups.ts b/src/web-ui/src/flow_chat/grouping/roundGroups.ts
index 5ef9b07d5d..3344e9306d 100644
--- a/src/web-ui/src/flow_chat/grouping/roundGroups.ts
+++ b/src/web-ui/src/flow_chat/grouping/roundGroups.ts
@@ -5,11 +5,11 @@ import { canContinueFlowGroup, classifyFlowGroupItem, flowGroupPolicies, joinedF
import { isFlowGroupMemberActive } from './lifecycle';
import { isShellActivity } from './activityClassification';
import { parseDeepResearchContent } from '../deep-research/deepResearchProtocol';
-import type { ExploreGroupData, FlowGroupCategory, FlowGroupData, GroupedFlowItems, ModelRoundItemGroup } from './types';
+import { getFlowGroupStateIds, isFlowGroupExpanded, type ExploreGroupData, type FlowGroupCategory, type FlowGroupData, type GroupedFlowItems, type ModelRoundItemGroup } from './types';
export type { ModelRoundItemGroup } from './types';
-export { getFlowGroupStateIds, isFlowGroupExpanded } from './types';
-export { getFlowGroupStateIds as getExploreGroupStateIds, isFlowGroupExpanded as isExploreGroupExpanded } from './types';
+export { getFlowGroupStateIds, isFlowGroupExpanded };
+export { getFlowGroupStateIds as getExploreGroupStateIds, isFlowGroupExpanded as isExploreGroupExpanded };
/** Match the visible attempt rather than collecting failed retry history. */
export function getModelRoundActiveItems(round: Pick): FlowItem[] {
@@ -92,22 +92,107 @@ export function buildInlineFlowGroupData(roundId: string, group: GroupedFlowItem
});
}
+const roundGroupsCache = new WeakMap>;
+}>();
+
+function getOrCreateRoundGroupsCacheEntry(round: ModelRound, disabled: boolean) {
+ let entry = roundGroupsCache.get(round);
+ if (!entry || entry.itemsRef !== round.items || entry.attemptsRef !== round.attempts || entry.disabled !== disabled) {
+ entry = {
+ itemsRef: round.items,
+ attemptsRef: round.attempts,
+ disabled,
+ };
+ roundGroupsCache.set(round, entry);
+ }
+ return entry;
+}
+
+export function getCachedInlineFlowGroupData(
+ round: ModelRound,
+ group: GroupedFlowItems,
+ isLastGroupInTurn = group.isLast,
+ includeRoundIdAlias = false,
+): FlowGroupData {
+ if (group.projection) return group.projection;
+ const disabled = isModelRoundGroupingDisabled(round);
+ const entry = getOrCreateRoundGroupsCacheEntry(round, disabled);
+ const key = (isLastGroupInTurn ? 2 : 0) + (includeRoundIdAlias ? 1 : 0);
+ // Candidate retention and cross-round collection can change group positions.
+ // Only the actual immutable group proves which members this projection owns.
+ const groups = entry.inlineGroups ??= new WeakMap();
+ let byKey = groups.get(group);
+ if (!byKey) {
+ byKey = new Map();
+ groups.set(group, byKey);
+ }
+ let cached = byKey.get(key);
+ if (!cached) {
+ cached = buildInlineFlowGroupData(round.id, group, isLastGroupInTurn);
+ if (includeRoundIdAlias) {
+ cached = {
+ ...cached,
+ sourceGroupIds: [...new Set([...getFlowGroupStateIds(cached), round.id])],
+ };
+ }
+ byKey.set(key, cached);
+ }
+ return cached;
+}
+
/** The category and projection are constructed together by the selected policy. */
export function projectedFlowGroup(category: FlowGroupCategory, items: FlowItem[], isLast: boolean, projection?: FlowGroupData): GroupedFlowItems {
return { type: category, items, isLast, ...(projection ? { projection } : {}) } as GroupedFlowItems;
}
export function getModelRoundFlowGroups(round: ModelRound, projectedGroups?: ModelRoundItemGroup[]): FlowGroupData[] {
- return (projectedGroups ?? buildFlowItemGroups({
- items: getModelRoundActiveItems(round), disabled: isModelRoundGroupingDisabled(round),
- })).flatMap(group => group.type === 'critical' ? [] : [buildInlineFlowGroupData(round.id, group)]);
+ if (projectedGroups) {
+ return projectedGroups.flatMap(group => group.type === 'critical'
+ ? []
+ : [getCachedInlineFlowGroupData(round, group)]);
+ }
+ const disabled = isModelRoundGroupingDisabled(round);
+ const entry = getOrCreateRoundGroupsCacheEntry(round, disabled);
+ if (!entry.groups) {
+ entry.groups = buildFlowItemGroups({
+ items: getModelRoundActiveItems(round),
+ disabled,
+ });
+ }
+ return entry.groups.flatMap(group => group.type === 'critical'
+ ? []
+ : [getCachedInlineFlowGroupData(round, group)]);
}
export function getProjectedModelRoundGroups(item: Extract, retainCandidates = false): ModelRoundItemGroup[] {
- return item.projectedGroups ?? buildFlowItemGroups({
- items: getModelRoundActiveItems(item.data),
- disabled: isModelRoundGroupingDisabled(item.data), retainCandidates,
- });
+ if (item.projectedGroups) return item.projectedGroups;
+ const round = item.data;
+ const disabled = isModelRoundGroupingDisabled(round);
+ const entry = getOrCreateRoundGroupsCacheEntry(round, disabled);
+ if (retainCandidates) {
+ if (!entry.retainedCandidateGroups) {
+ entry.retainedCandidateGroups = buildFlowItemGroups({
+ items: getModelRoundActiveItems(round),
+ disabled,
+ retainCandidates: true,
+ });
+ }
+ return entry.retainedCandidateGroups;
+ }
+ if (!entry.groups) {
+ entry.groups = buildFlowItemGroups({
+ items: getModelRoundActiveItems(round),
+ disabled,
+ retainCandidates: false,
+ });
+ }
+ return entry.groups;
}
interface BuildFlowItemGroupsInput extends FlowGroupPolicyOptions {
diff --git a/src/web-ui/src/flow_chat/grouping/selectors.test.ts b/src/web-ui/src/flow_chat/grouping/selectors.test.ts
new file mode 100644
index 0000000000..7013f9e2d3
--- /dev/null
+++ b/src/web-ui/src/flow_chat/grouping/selectors.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from 'vitest';
+import type { VirtualItem } from '../types/flow-chat-projection';
+import { indexFlowGroups } from './selectors';
+
+function group(id: string, aliases: string[] = []): VirtualItem {
+ return { type: 'explore-group', turnId: `turn-${id}`, data: {
+ groupId: id, sourceGroupIds: aliases, rounds: [], allItems: [],
+ isGroupStreaming: false, isLastGroupInTurn: false, wasCutByCritical: true,
+ stats: { readCount: 0, searchCount: 0, commandCount: 0 },
+ } };
+}
+
+describe('flow group ownership index', () => {
+ it('restores a prefix alias when a tail that shadowed it is removed or replaced', () => {
+ const first = group('first', ['shared']);
+ const tail = group('tail', ['shared']);
+ const before = indexFlowGroups([first, tail]);
+ expect(before.byId.get('shared')?.virtualIndex).toBe(1);
+ const shortened = indexFlowGroups([first]);
+ expect(shortened.byId.get('shared')?.group.groupId).toBe('first');
+ indexFlowGroups([first, tail]);
+ const replaced = indexFlowGroups([first, group('replacement')]);
+ expect(replaced.byId.get('shared')?.group.groupId).toBe('first');
+ expect(replaced.byTurnId.has('turn-tail')).toBe(false);
+ expect(before.byId.get('shared')?.group.groupId).toBe('tail');
+ });
+
+ it('reuses an unchanged transcript and keeps indexes isolated across equal-id sessions', () => {
+ const first = [group('same', ['alias'])];
+ const other = [group('same')];
+ const before = indexFlowGroups(first);
+ expect(indexFlowGroups(first)).toBe(before);
+ expect(indexFlowGroups(other).byId.has('alias')).toBe(false);
+ expect(indexFlowGroups(first)).toBe(before);
+ });
+});
diff --git a/src/web-ui/src/flow_chat/grouping/selectors.ts b/src/web-ui/src/flow_chat/grouping/selectors.ts
index bd0876e644..bd348fab45 100644
--- a/src/web-ui/src/flow_chat/grouping/selectors.ts
+++ b/src/web-ui/src/flow_chat/grouping/selectors.ts
@@ -2,10 +2,22 @@ import type { VirtualItem } from '../types/flow-chat-projection';
import { getModelRoundFlowGroups } from './roundGroups';
import { getFlowGroupStateIds, type FlowGroupBase, type FlowGroupData } from './types';
+const virtualItemFlowGroupsCache = new WeakMap();
+const emptyFlowGroups: FlowGroupData[] = [];
+
export function getVirtualItemFlowGroups(item: VirtualItem): FlowGroupData[] {
- if (item.type === 'explore-group') return [item.data];
- if (item.type === 'model-round') return getModelRoundFlowGroups(item.data, item.projectedGroups);
- return [];
+ const cached = virtualItemFlowGroupsCache.get(item);
+ if (cached) return cached;
+ let result: FlowGroupData[];
+ if (item.type === 'explore-group') {
+ result = [item.data];
+ } else if (item.type === 'model-round') {
+ result = getModelRoundFlowGroups(item.data, item.projectedGroups);
+ } else {
+ return emptyFlowGroups;
+ }
+ virtualItemFlowGroupsCache.set(item, result);
+ return result;
}
export interface FlowGroupLocation {
@@ -14,8 +26,21 @@ export interface FlowGroupLocation {
virtualIndex: number;
}
+interface FlowGroupIndex {
+ byId: Map;
+ byMemberId: Map;
+ byTurnId: Map;
+}
+
+const flowGroupIndexCache = new WeakMap();
+
/** One ownership index for disclosure and navigation, including merged legacy aliases. */
-export function indexFlowGroups(items: readonly VirtualItem[]) {
+export function indexFlowGroups(items: readonly VirtualItem[]): FlowGroupIndex {
+ const cached = flowGroupIndexCache.get(items);
+ if (cached) return cached;
+
+ // Copying the old maps already costs O(groups). Rebuild from cached per-row
+ // groups so removed tails restore shadowed aliases, with no retained old array.
const byId = new Map();
const byMemberId = new Map();
const byTurnId = new Map();
@@ -30,5 +55,7 @@ export function indexFlowGroups(items: readonly VirtualItem[]) {
byTurnId.set(item.turnId, turnGroups);
}
});
- return { byId, byMemberId, byTurnId };
+ const result = { byId, byMemberId, byTurnId };
+ flowGroupIndexCache.set(items, result);
+ return result;
}
diff --git a/src/web-ui/src/flow_chat/perf/longRoundPerfHarness.test.tsx b/src/web-ui/src/flow_chat/perf/longRoundPerfHarness.test.tsx
new file mode 100644
index 0000000000..fd6acc993f
--- /dev/null
+++ b/src/web-ui/src/flow_chat/perf/longRoundPerfHarness.test.tsx
@@ -0,0 +1,659 @@
+// @vitest-environment jsdom
+import React, { Profiler, act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { activateSurface } from '@/infrastructure/peer-device/deviceSurface';
+import { VirtualMessageList } from '../components/modern/VirtualMessageList';
+import { getVirtualItemStableKey } from '../components/modern/virtualItemIdentity';
+import { createSessionVirtualItemProjector, type VirtualItem } from '../store/modernFlowChatStore';
+import { useFlowGroupState } from '../components/modern/useFlowGroupState';
+import { FlowChatContext, FlowChatVolatileContext } from '../components/modern/FlowChatContext';
+import {
+ benchBackgroundBudgetAndPersistence,
+ benchGroupStateAndSearch,
+ benchStoreProjection,
+ benchTimelineDocument,
+ buildLongRoundSessionFixture,
+ formatBenchmarkReport,
+ runLongRoundPipelineBenchmark,
+} from './longRoundPerfHarness';
+import type { DialogTurn, FlowTextItem, ModelRound, Session } from '../types/flow-chat';
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true;
+
+const harnessStoreState = vi.hoisted(() => ({
+ items: [] as VirtualItem[],
+ session: null as Session | null,
+ isProcessing: true,
+}));
+
+const renderTelemetry = vi.hoisted(() => ({
+ virtualListCommits: 0,
+ virtualListActualDurationMs: 0,
+ rowRendersByKey: new Map(),
+ reset() {
+ this.virtualListCommits = 0;
+ this.virtualListActualDurationMs = 0;
+ this.rowRendersByKey.clear();
+ },
+}));
+
+vi.mock('../store/modernFlowChatStore', async (importOriginal) => {
+ const actual = await importOriginal();
+ const store = Object.assign(
+ (select: (state: unknown) => unknown) =>
+ select({
+ visibleTurnInfo: null,
+ activeSession: harnessStoreState.session,
+ virtualItems: harnessStoreState.items,
+ }),
+ {
+ getState: () => ({
+ setVisibleTurnInfo() {},
+ activeSession: harnessStoreState.session,
+ virtualItems: harnessStoreState.items,
+ }),
+ }
+ );
+ return {
+ ...actual,
+ useVirtualItems: () => harnessStoreState.items,
+ useActiveSession: () => harnessStoreState.session,
+ useModernFlowChatStore: store,
+ useModernFlowChatStoreApi: () => store,
+ };
+});
+
+vi.mock('../hooks/useActiveSessionState', () => ({
+ useActiveSessionState: () => ({
+ sessionId: harnessStoreState.session?.sessionId ?? null,
+ isProcessing: harnessStoreState.isProcessing,
+ processingPhase: null,
+ error: null,
+ status: harnessStoreState.isProcessing ? 'active' : 'idle',
+ }),
+}));
+
+vi.mock('../store/chatInputStateStore', () => ({
+ useChatInputState: (select: (state: unknown) => unknown) => select({ inputHeight: 100 }),
+}));
+
+vi.mock('../hooks/useScrollToTurnHeader', () => ({
+ useScrollToTurnHeader: () => ({ shouldShowButton: false, handleClick() {} }),
+}));
+
+vi.mock('../components/modern/RuntimeStatusSlot', () => ({
+ RuntimeStatusSlot: () => null,
+}));
+
+vi.mock('../components/ScrollToLatestBar', () => ({
+ ScrollToLatestBar: () => null,
+}));
+
+vi.mock('../components/ScrollToTurnHeaderButton', () => ({
+ ScrollToTurnHeaderButton: () => null,
+}));
+
+// Keep React.memo semantics identical to production VirtualItemRenderer while
+// recording per-row render counts and subscribing to FlowChatVolatileContext.
+vi.mock('../components/modern/VirtualItemRenderer', async () => {
+ const ReactModule = await import('react');
+ const { useFlowChatVolatileContext } = await import('../components/modern/FlowChatContext');
+ const { getVirtualItemStableKey: stableKey } = await import('../components/modern/virtualItemIdentity');
+
+ const InstrumentedRow = ReactModule.memo(
+ ({
+ item,
+ index,
+ measureRef,
+ }: {
+ item: VirtualItem;
+ index: number;
+ isLatestTurn?: boolean;
+ endsBeforeUserTurn?: boolean;
+ continuesAmbientToolRunAfter?: boolean;
+ measureRef?: (element: HTMLElement | null) => void;
+ }) => {
+ useFlowChatVolatileContext();
+ const key = stableKey(item);
+ renderTelemetry.rowRendersByKey.set(key, (renderTelemetry.rowRendersByKey.get(key) ?? 0) + 1);
+ return (
+
+ );
+ },
+ (prev, next) =>
+ prev.item === next.item &&
+ prev.index === next.index &&
+ prev.isLatestTurn === next.isLatestTurn &&
+ prev.endsBeforeUserTurn === next.endsBeforeUserTurn &&
+ prev.continuesAmbientToolRunAfter === next.continuesAmbientToolRunAfter &&
+ prev.measureRef === next.measureRef
+ );
+
+ return { VirtualItemRenderer: InstrumentedRow };
+});
+
+function LiveContainerHarness({ latestTurnId }: { latestTurnId: string }) {
+ const session = harnessStoreState.session;
+ const virtualItems = harnessStoreState.items;
+ const {
+ groupStates,
+ groupReceiveFeedback,
+ expandedToolCapsules,
+ onToolCapsuleExpandedChange,
+ onGroupToggle,
+ onExpandGroup,
+ onExpandAllInTurn,
+ onCollapseGroup,
+ } = useFlowGroupState(
+ virtualItems,
+ undefined,
+ session?.sessionId,
+ undefined,
+ `perf:${session?.sessionId ?? ''}`
+ );
+
+ const contextValue = React.useMemo(
+ () => ({
+ sessionId: session?.sessionId,
+ workspaceId: session?.config?.workspaceId,
+ workspacePath: session?.config?.workspacePath,
+ onGroupToggle,
+ onExploreGroupToggle: onGroupToggle,
+ onExpandGroup,
+ onExpandAllInTurn,
+ onCollapseGroup,
+ onToolCapsuleExpandedChange,
+ }),
+ [
+ session?.sessionId,
+ session?.config?.workspaceId,
+ session?.config?.workspacePath,
+ onGroupToggle,
+ onExpandGroup,
+ onExpandAllInTurn,
+ onCollapseGroup,
+ onToolCapsuleExpandedChange,
+ ]
+ );
+
+ const volatileValue = React.useMemo(
+ () => ({
+ pendingPermissionToolCallIds: new Set(),
+ groupStates,
+ groupReceiveFeedback,
+ exploreGroupStates: groupStates,
+ expandedToolCapsules,
+ searchQuery: '',
+ searchMatchesByVirtualIndex: new Map(),
+ searchCurrentMatch: undefined,
+ }),
+ [groupStates, groupReceiveFeedback, expandedToolCapsules]
+ );
+
+ return (
+
+
+ {
+ renderTelemetry.virtualListCommits += 1;
+ renderTelemetry.virtualListActualDurationMs += actualDuration;
+ }}
+ >
+
+
+
+
+ );
+}
+
+describe('FlowChat Long-Round Categorized Benchmark Suites', () => {
+ describe('Category 1: Store & Adjacent Group Projection [bench:store-projection]', () => {
+ it('keeps live reuse while history and a side session project between streaming flushes', () => {
+ const solo = benchStoreProjection();
+ const result = benchStoreProjection({ interleaveViews: true });
+ expect(result.totalFlushes).toBe(20);
+ expect(result.settledVirtualItemReuseRatio).toBe(solo.settledVirtualItemReuseRatio);
+ });
+
+ it('benchmarks scoped session projection & projectAdjacentFlowGroups scaling and reference reuse', () => {
+ const result = benchStoreProjection({
+ checkpoints: [10, 50, 100, 200, 300],
+ chunksPerCheckpoint: 5,
+ });
+
+ console.info(
+ [
+ `=== [Category 1: Store Projection] ===`,
+ `Total Time (20 flushes) : ${result.totalMs.toFixed(2)} ms (avg ${result.avgFlushMs.toFixed(2)} ms/flush)`,
+ `Scaling (10 -> 300 rounds) : ${result.earlyFlushAvgMs.toFixed(2)} ms -> ${result.lateFlushAvgMs.toFixed(2)} ms (${result.scalingRatio.toFixed(2)}x)`,
+ `Settled VirtualItem Ref Reuse : ${(result.settledVirtualItemReuseRatio * 100).toFixed(1)}%`,
+ ].join('\n')
+ );
+
+ expect(result.totalFlushes).toBe(20);
+ // Identity reuse is deterministic for this fixture; wall-clock timings
+ // remain diagnostics, not a portable machine-speed assertion.
+ expect(result.settledVirtualItemReuseRatio).toBeGreaterThan(0.9);
+ });
+ });
+
+ describe('Category 2: Timeline Document & Rhythm Pass [bench:timeline-document]', () => {
+ it('benchmarks ConversationDocumentProjection.project & getNextVisibleVirtualItemIndexes', () => {
+ const result = benchTimelineDocument({
+ checkpoints: [10, 50, 100, 200, 300],
+ chunksPerCheckpoint: 5,
+ });
+
+ console.info(
+ [
+ `=== [Category 2: Timeline Document & Rhythm] ===`,
+ `Document Projection Total : ${result.documentProjectionTotalMs.toFixed(2)} ms`,
+ `Rhythm Visible-Index Total : ${result.rhythmPassTotalMs.toFixed(2)} ms`,
+ `Scaling (10 -> 300 rounds) : ${result.earlyFlushAvgMs.toFixed(2)} ms -> ${result.lateFlushAvgMs.toFixed(2)} ms (${result.scalingRatio.toFixed(2)}x)`,
+ `Current TimelineBlock Ref Reuse : ${(result.settledTimelineBlockReuseRatio * 100).toFixed(1)}%`,
+ `Isolated Reuse (if Store stable) : ${(result.isolatedSettledTimelineBlockReuseRatio * 100).toFixed(1)}% (${result.isolatedAvgFlushMs.toFixed(2)} ms/flush at 300 rounds)`,
+ ].join('\n')
+ );
+
+ expect(result.totalFlushes).toBe(20);
+ expect(result.settledTimelineBlockReuseRatio).toBeGreaterThan(0.9);
+ });
+ });
+
+ describe('Category 3: Container Group State, Feedback & Search [bench:group-state-search]', () => {
+ it('benchmarks indexFlowGroups, receiveFeedback, and buildFlowChatSearchMatches', () => {
+ const result = benchGroupStateAndSearch({
+ checkpoints: [10, 50, 100, 200, 300],
+ chunksPerCheckpoint: 5,
+ });
+
+ console.info(
+ [
+ `=== [Category 3: Container Group Index, Feedback & Search] ===`,
+ `indexFlowGroups Total : ${result.indexFlowGroupsTotalMs.toFixed(2)} ms`,
+ `receiveFeedback Total : ${result.receiveFeedbackTotalMs.toFixed(2)} ms`,
+ `buildFlowChatSearchMatches Total : ${result.searchPassTotalMs.toFixed(2)} ms`,
+ `Scaling (10 -> 300 rounds) : ${result.earlyCombinedAvgMs.toFixed(2)} ms -> ${result.lateCombinedAvgMs.toFixed(2)} ms (${result.scalingRatio.toFixed(2)}x)`,
+ ].join('\n')
+ );
+
+ expect(result.totalFlushes).toBe(20);
+ });
+ });
+
+ describe('Category 4: Background Memory Budget & Persistence Hash [bench:budget-persistence]', () => {
+ it('benchmarks estimateRetainedBytes and calculateTurnHash across growing turns', () => {
+ const result = benchBackgroundBudgetAndPersistence({
+ checkpoints: [10, 50, 100, 200, 300],
+ iterationsPerCheckpoint: 5,
+ });
+
+ console.info(
+ [
+ `=== [Category 4: Background Budget & Persistence] ===`,
+ `estimateRetainedBytes Total : ${result.retainedBytesTotalMs.toFixed(2)} ms (${result.retainedBytesEarlyAvgMs.toFixed(2)} ms -> ${result.retainedBytesLateAvgMs.toFixed(2)} ms, ${result.retainedBytesScalingRatio.toFixed(2)}x)`,
+ `calculateTurnHash Total : ${result.turnHashTotalMs.toFixed(2)} ms (${result.turnHashEarlyAvgMs.toFixed(2)} ms -> ${result.turnHashLateAvgMs.toFixed(2)} ms)`,
+ `Estimated Turn Size @ 300 rounds : ${(result.estimatedActiveTurnBytesAtMaxRound / 1024).toFixed(1)} KB`,
+ ].join('\n')
+ );
+
+ expect(result.estimatedActiveTurnBytesAtMaxRound).toBeGreaterThan(0);
+ });
+ });
+
+ describe('Category 5: React Framework & Virtualizer DOM Interaction [bench:react-virtualizer]', () => {
+ let root: Root;
+ let host: HTMLDivElement;
+ let frames: Map;
+ let frameId: number;
+ let now: number;
+ let observers: Array<{
+ callback: ResizeObserverCallback;
+ targets: Set;
+ sizes: WeakMap;
+ }>;
+ const heights = new Map();
+ const offsets = new WeakMap();
+ const px = (value: string) => Number.parseFloat(value || '0') || 0;
+ const realHrTimeMs = () => Number(process.hrtime.bigint()) / 1_000_000;
+
+ function measureElementHeight(element: HTMLElement, measured = new WeakMap()): number {
+ const cached = measured.get(element);
+ if (cached !== undefined) return cached;
+ let result = 80;
+ if (element.hasAttribute('data-flowchat-scroller')) {
+ result = 720;
+ } else if (element.dataset.virtualItemKey) {
+ result = heights.get(element.dataset.virtualItemKey) ?? 84;
+ } else if (element.style.height) {
+ result = px(element.style.height);
+ } else {
+ result = Math.max(
+ px(element.style.minHeight),
+ px(element.style.paddingTop) +
+ px(element.style.paddingBottom) +
+ [...element.children].reduce(
+ (sum, child) => sum + measureElementHeight(child as HTMLElement, measured),
+ 0
+ )
+ );
+ }
+ measured.set(element, result);
+ return result;
+ }
+
+ function contentTop(element: HTMLElement, measured: WeakMap): number {
+ let top = 0;
+ let current = element;
+ while (current.parentElement && !current.hasAttribute('data-flowchat-scroller')) {
+ let sibling = current.previousElementSibling;
+ while (sibling) {
+ top += measureElementHeight(sibling as HTMLElement, measured);
+ sibling = sibling.previousElementSibling;
+ }
+ current = current.parentElement;
+ top += px(current.style.paddingTop);
+ }
+ return top;
+ }
+
+ const flushAnimationFrames = () => {
+ now += 16;
+ const pending = [...frames.values()];
+ frames.clear();
+ act(() => pending.forEach(cb => cb(now)));
+ };
+
+ const flushResizeObservers = () =>
+ act(() => {
+ for (const observer of observers) {
+ const measured = new WeakMap();
+ const entries = [...observer.targets]
+ .filter(target => target.isConnected)
+ .flatMap(target => {
+ const blockSize = measureElementHeight(target as HTMLElement, measured);
+ const inlineSize = 900;
+ const size = `${inlineSize}:${blockSize}`;
+ if (observer.sizes.get(target) === size) return [];
+ observer.sizes.set(target, size);
+ return [
+ {
+ target,
+ borderBoxSize: [{ inlineSize, blockSize }],
+ contentRect: target.getBoundingClientRect(),
+ } as ResizeObserverEntry,
+ ];
+ });
+ if (entries.length) observer.callback(entries, {} as ResizeObserver);
+ }
+ });
+
+ beforeEach(() => {
+ activateSurface('local');
+ renderTelemetry.reset();
+ frames = new Map();
+ frameId = 0;
+ now = 1_000;
+ observers = [];
+ heights.clear();
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] });
+ vi.spyOn(performance, 'now').mockImplementation(() => now + (realHrTimeMs() % 1));
+ vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => {
+ frames.set(++frameId, cb);
+ return frameId;
+ });
+ vi.stubGlobal('cancelAnimationFrame', (id: number) => frames.delete(id));
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn(() => ({ matches: false, addEventListener() {}, removeEventListener() {} }))
+ );
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ targets = new Set();
+ sizes = new WeakMap();
+ constructor(public callback: ResizeObserverCallback) {
+ observers.push(this);
+ }
+ observe(target: Element) {
+ this.targets.add(target);
+ }
+ unobserve(target: Element) {
+ this.targets.delete(target);
+ this.sizes.delete(target);
+ }
+ disconnect() {
+ this.targets.clear();
+ this.sizes = new WeakMap();
+ }
+ }
+ );
+
+ vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockImplementation(function () {
+ return Math.round(measureElementHeight(this));
+ });
+ vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockImplementation(function () {
+ return Math.round(measureElementHeight(this));
+ });
+ vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockReturnValue(900);
+ vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(900);
+ vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockImplementation(function () {
+ return Math.round(
+ this.hasAttribute('data-flowchat-scroller')
+ ? measureElementHeight(this.firstElementChild as HTMLElement)
+ : measureElementHeight(this)
+ );
+ });
+ vi.spyOn(HTMLElement.prototype, 'scrollTop', 'get').mockImplementation(function () {
+ const range = Math.max(0, this.scrollHeight - this.clientHeight);
+ return Math.min(offsets.get(this) ?? 0, range);
+ });
+ vi.spyOn(HTMLElement.prototype, 'scrollTop', 'set').mockImplementation(function (value: number) {
+ const range = Math.max(0, this.scrollHeight - this.clientHeight);
+ offsets.set(this, Math.max(0, Math.min(value, range)));
+ });
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function () {
+ const measured = new WeakMap();
+ const scroller = this.closest('[data-flowchat-scroller]');
+ const top =
+ !scroller || this === scroller
+ ? 0
+ : contentTop(this, measured) - (offsets.get(scroller) ?? 0);
+ const h = measureElementHeight(this, measured);
+ const w = 900;
+ return {
+ x: 0,
+ y: top,
+ top,
+ left: 0,
+ right: w,
+ bottom: top + h,
+ width: w,
+ height: h,
+ toJSON: () => ({}),
+ } as DOMRect;
+ });
+
+ host = document.createElement('div');
+ document.body.appendChild(host);
+ root = createRoot(host);
+ });
+
+ afterEach(() => {
+ act(() => root.unmount());
+ host.remove();
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+ });
+
+ it('[bench:react-streaming] measures React commits & wasted settled-row renders during 10 tail stream chunks (120 rounds)', () => {
+ const projectSession = createSessionVirtualItemProjector();
+ const roundCount = 120;
+ const baseSession = buildLongRoundSessionFixture({ roundCount });
+ const activeTurnIndex = baseSession.dialogTurns.length - 1;
+ const baseTurn = baseSession.dialogTurns[activeTurnIndex];
+ const settledRounds = baseTurn.modelRounds.slice(0, -1);
+ const tailRoundIndex = roundCount - 1;
+
+ harnessStoreState.session = baseSession;
+ harnessStoreState.items = projectSession(baseSession);
+ harnessStoreState.isProcessing = true;
+
+ act(() => {
+ root.render();
+ });
+ flushResizeObservers();
+ flushAnimationFrames();
+
+ const scroller = host.querySelector('[data-flowchat-scroller]')!;
+ act(() => {
+ scroller.scrollTop = Math.max(0, scroller.scrollHeight - scroller.clientHeight);
+ scroller.dispatchEvent(new Event('scroll'));
+ });
+ flushResizeObservers();
+ flushAnimationFrames();
+
+ renderTelemetry.reset();
+
+ const streamChunks = 10;
+ const tStreamStart = realHrTimeMs();
+ for (let chunk = 1; chunk <= streamChunks; chunk += 1) {
+ now += 32;
+ const streamingText: FlowTextItem = {
+ id: `stream-tail-text-${tailRoundIndex}`,
+ type: 'text',
+ content: `Live streaming output chunk ${chunk}: ` + 'token '.repeat(chunk * 3),
+ isStreaming: chunk < streamChunks,
+ isMarkdown: true,
+ timestamp: now,
+ status: chunk < streamChunks ? 'streaming' : 'completed',
+ };
+ const tailRound: ModelRound = {
+ ...baseTurn.modelRounds[tailRoundIndex],
+ items: [...baseTurn.modelRounds[tailRoundIndex].items, streamingText],
+ isStreaming: chunk < streamChunks,
+ isComplete: chunk === streamChunks,
+ status: chunk < streamChunks ? 'streaming' : 'completed',
+ };
+ const nextTurn: DialogTurn = {
+ ...baseTurn,
+ modelRounds: [...settledRounds, tailRound],
+ };
+ const nextSession: Session = {
+ ...baseSession,
+ dialogTurns: [...baseSession.dialogTurns.slice(0, activeTurnIndex), nextTurn],
+ lastActiveAt: now,
+ };
+
+ harnessStoreState.session = nextSession;
+ harnessStoreState.items = projectSession(nextSession);
+
+ act(() => {
+ root.render();
+ });
+ flushResizeObservers();
+ flushAnimationFrames();
+ }
+ const streamWallMs = realHrTimeMs() - tStreamStart;
+
+ let settledRowRenderSum = 0;
+ let settledRowKeysCount = 0;
+ let activeRowRenderSum = 0;
+ for (const [key, count] of renderTelemetry.rowRendersByKey.entries()) {
+ if (
+ key.includes(`round-${tailRoundIndex}`) ||
+ key.includes(`stream-tail-text-${tailRoundIndex}`) ||
+ key.includes(`tool-${tailRoundIndex}-`) ||
+ key.includes(`thinking-${tailRoundIndex}`) ||
+ key.includes(`text-${tailRoundIndex}`)
+ ) {
+ activeRowRenderSum += count;
+ } else {
+ settledRowKeysCount += 1;
+ settledRowRenderSum += count;
+ }
+ }
+
+ console.info(
+ [
+ `=== [Category 5A: React Streaming Tail Interaction (120 rounds, 10 chunks)] ===`,
+ `Wall time : ${streamWallMs.toFixed(2)} ms (${(streamWallMs / streamChunks).toFixed(2)} ms/chunk)`,
+ `VirtualMessageList commits : ${renderTelemetry.virtualListCommits}`,
+ `Active tail row renders : ${activeRowRenderSum}`,
+ `Settled row keys re-rendered : ${settledRowKeysCount} keys (${settledRowRenderSum} total wasted renders)`,
+ ].join('\n')
+ );
+
+ expect(renderTelemetry.virtualListCommits).toBeGreaterThan(0);
+ });
+
+ it('[bench:react-scroll] measures Virtualizer windowing commits & latency across 9 viewport scroll steps (120 rounds)', () => {
+ const projectSession = createSessionVirtualItemProjector();
+ const roundCount = 120;
+ const baseSession = buildLongRoundSessionFixture({ roundCount });
+ const activeTurnIndex = baseSession.dialogTurns.length - 1;
+ const baseTurn = baseSession.dialogTurns[activeTurnIndex];
+
+ harnessStoreState.session = baseSession;
+ harnessStoreState.items = projectSession(baseSession);
+ harnessStoreState.isProcessing = true;
+
+ act(() => {
+ root.render();
+ });
+ flushResizeObservers();
+ flushAnimationFrames();
+
+ const scroller = host.querySelector('[data-flowchat-scroller]')!;
+ const maxScroll = Math.max(1, scroller.scrollHeight - scroller.clientHeight);
+ renderTelemetry.reset();
+
+ const scrollSteps = 8;
+ const tScrollStart = realHrTimeMs();
+ for (let step = 0; step <= scrollSteps; step += 1) {
+ now += 16;
+ const targetTop = Math.round((maxScroll * (scrollSteps - step)) / scrollSteps);
+ act(() => {
+ scroller.scrollTop = targetTop;
+ scroller.dispatchEvent(new Event('scroll'));
+ });
+ flushResizeObservers();
+ flushAnimationFrames();
+ }
+ const scrollWallMs = realHrTimeMs() - tScrollStart;
+
+ console.info(
+ [
+ `=== [Category 5B: Virtualizer Scroll Windowing (120 rounds, ${scrollSteps + 1} steps)] ===`,
+ `Scroll distance : ${maxScroll} px`,
+ `Wall time : ${scrollWallMs.toFixed(2)} ms (${(scrollWallMs / (scrollSteps + 1)).toFixed(2)} ms/step)`,
+ `VirtualMessageList commits : ${renderTelemetry.virtualListCommits} (${(renderTelemetry.virtualListCommits / (scrollSteps + 1)).toFixed(1)} commits/step)`,
+ `Total row mounts/renders : ${[...renderTelemetry.rowRendersByKey.values()].reduce((a, b) => a + b, 0)}`,
+ ].join('\n')
+ );
+
+ expect(renderTelemetry.virtualListCommits).toBeGreaterThan(0);
+ });
+ });
+
+ describe('Category 6: End-to-End Combined Pipeline Summary [bench:e2e-pipeline]', () => {
+ it('outputs combined 5-stage pipeline report across 10 -> 300 rounds', () => {
+ const summary = runLongRoundPipelineBenchmark({
+ checkpoints: [10, 50, 100, 200, 300],
+ chunksPerCheckpoint: 5,
+ measureRetainedBytesEveryFlush: true,
+ });
+ console.info('\n' + formatBenchmarkReport(summary));
+ expect(summary.totalFlushes).toBe(20);
+ });
+ });
+});
diff --git a/src/web-ui/src/flow_chat/perf/longRoundPerfHarness.ts b/src/web-ui/src/flow_chat/perf/longRoundPerfHarness.ts
new file mode 100644
index 0000000000..cc13c9fd08
--- /dev/null
+++ b/src/web-ui/src/flow_chat/perf/longRoundPerfHarness.ts
@@ -0,0 +1,905 @@
+/**
+ * Long-round FlowChat performance harness.
+ *
+ * Categorized into 5 focused benchmark suites so each optimization area can be
+ * measured, verified, and regressed independently:
+ *
+ * - Category 1 (`benchStoreProjection`): Store & Adjacent Group Projection
+ * (`projectSession` + `projectAdjacentFlowGroups`, reference stability of `VirtualItem`s)
+ * - Category 2 (`benchTimelineDocument`): Timeline Document & Rhythm Pass
+ * (`ConversationDocumentProjection.project` + `getNextVisibleVirtualItemIndexes`, `TimelineBlock` reference stability)
+ * - Category 3 (`benchGroupStateAndSearch`): Container Derived Passes
+ * (`indexFlowGroups`, `captureFlowGroupFeedbackSnapshot`, `collectFlowGroupReceiveFeedback`, `buildFlowChatSearchMatches`)
+ * - Category 4 (`benchBackgroundBudgetAndPersistence`): Background Budget & Persistence Overhead
+ * (`estimateRetainedBytes` full-turn object walk, `calculateTurnHash` JSON serialization)
+ * - Category 5 (in `longRoundPerfHarness.test.tsx`): React Framework & Virtualizer DOM Interaction
+ * (Streaming tail updates vs viewport scroll windowing)
+ */
+
+import { createSessionVirtualItemProjector, type VirtualItem } from '../store/modernFlowChatStore';
+import { indexFlowGroups, getVirtualItemFlowGroups } from '../grouping/selectors';
+import {
+ captureFlowGroupFeedbackSnapshot,
+ collectFlowGroupReceiveFeedback,
+} from '../grouping/receiveFeedback';
+import { ConversationDocumentProjection, type TimelineProjectionOptions } from '../timeline/document';
+import { FlowChatReaderState } from '../timeline/readerState';
+import { getNextVisibleVirtualItemIndexes } from '../components/modern/flowChatRhythm';
+import { createFlowChatSearchMatcher } from '../components/modern/useFlowChatSearch';
+import { calculateTurnHash } from '../services/flow-chat-manager/PersistenceModule';
+import { estimateRetainedBytes } from '@/shared/utils/resourceBudget';
+import { getVirtualItemStableKey } from '../components/modern/virtualItemIdentity';
+import type {
+ AnyFlowItem,
+ DialogTurn,
+ FlowTextItem,
+ FlowThinkingItem,
+ FlowToolItem,
+ ModelRound,
+ Session,
+} from '../types/flow-chat';
+
+export interface LongRoundScenarioOptions {
+ roundCount: number;
+ priorCompletedTurns?: number;
+ sessionId?: string;
+ turnId?: string;
+}
+
+export interface StreamingStepMetrics {
+ roundIndex: number;
+ stepKind: 'round-start' | 'text-chunk' | 'tool-partial' | 'round-complete';
+ totalPipelineMs: number;
+ stageMs: {
+ storeProjectionMs: number;
+ groupIndexAndFeedbackMs: number;
+ documentProjectionMs: number;
+ rhythmPassMs: number;
+ retainedBytesEstimateMs: number;
+ };
+ counts: {
+ rounds: number;
+ virtualItems: number;
+ timelineBlocks: number;
+ indexedGroups: number;
+ };
+ churn: {
+ /** Total VirtualItems emitted before the active last round */
+ settledVirtualItemCount: number;
+ /** Settled VirtualItems that kept exact `===` object identity from previous flush */
+ reusedSettledVirtualItems: number;
+ /** Settled VirtualItem reference reuse ratio (0..1) */
+ settledVirtualItemReuseRatio: number;
+ /** Total TimelineBlocks emitted before the active last round */
+ settledTimelineBlockCount: number;
+ /** Settled TimelineBlocks that kept exact `===` object identity from previous flush */
+ reusedSettledTimelineBlocks: number;
+ /** Settled TimelineBlock reference reuse ratio (0..1) */
+ settledTimelineBlockReuseRatio: number;
+ };
+}
+
+export interface LongRoundBenchmarkSummary {
+ roundCount: number;
+ totalFlushes: number;
+ totalPipelineMs: number;
+ avgFlushMs: number;
+ p50FlushMs: number;
+ p95FlushMs: number;
+ maxFlushMs: number;
+ earlyFlushAvgMs: number;
+ lateFlushAvgMs: number;
+ lateToEarlyScalingRatio: number;
+ stageTotalsMs: {
+ storeProjectionMs: number;
+ groupIndexAndFeedbackMs: number;
+ documentProjectionMs: number;
+ rhythmPassMs: number;
+ retainedBytesEstimateMs: number;
+ };
+ avgSettledVirtualItemReuseRatio: number;
+ avgSettledTimelineBlockReuseRatio: number;
+ steps: StreamingStepMetrics[];
+}
+
+export interface StoreProjectionBenchResult {
+ checkpoints: number[];
+ totalFlushes: number;
+ totalMs: number;
+ avgFlushMs: number;
+ earlyFlushAvgMs: number;
+ lateFlushAvgMs: number;
+ scalingRatio: number;
+ settledVirtualItemReuseRatio: number;
+}
+
+export interface TimelineDocumentBenchResult {
+ checkpoints: number[];
+ totalFlushes: number;
+ documentProjectionTotalMs: number;
+ rhythmPassTotalMs: number;
+ avgFlushMs: number;
+ earlyFlushAvgMs: number;
+ lateFlushAvgMs: number;
+ scalingRatio: number;
+ settledTimelineBlockReuseRatio: number;
+ /** TimelineBlock reuse when upstream VirtualItem references are held stable for settled rounds */
+ isolatedSettledTimelineBlockReuseRatio: number;
+ isolatedAvgFlushMs: number;
+}
+
+export interface GroupStateAndSearchBenchResult {
+ checkpoints: number[];
+ totalFlushes: number;
+ indexFlowGroupsTotalMs: number;
+ receiveFeedbackTotalMs: number;
+ searchPassTotalMs: number;
+ avgCombinedMs: number;
+ earlyCombinedAvgMs: number;
+ lateCombinedAvgMs: number;
+ scalingRatio: number;
+}
+
+export interface BackgroundBudgetAndPersistenceBenchResult {
+ checkpoints: number[];
+ iterationsPerCheckpoint: number;
+ retainedBytesTotalMs: number;
+ retainedBytesEarlyAvgMs: number;
+ retainedBytesLateAvgMs: number;
+ retainedBytesScalingRatio: number;
+ turnHashTotalMs: number;
+ turnHashEarlyAvgMs: number;
+ turnHashLateAvgMs: number;
+ estimatedActiveTurnBytesAtMaxRound: number;
+}
+
+const SAMPLE_TOOL_SEQUENCE = [
+ { toolName: 'Read', inputKey: 'file_path', valuePrefix: 'src/web-ui/src/flow_chat/Module' },
+ { toolName: 'Grep', inputKey: 'pattern', valuePrefix: 'useVirtualItems|sessionToVirtualItems' },
+ { toolName: 'Read', inputKey: 'file_path', valuePrefix: 'src/web-ui/src/flow_chat/timeline/Block' },
+ { toolName: 'Edit', inputKey: 'file_path', valuePrefix: 'src/web-ui/src/flow_chat/store/Store' },
+ { toolName: 'ExecCommand', inputKey: 'cmd', valuePrefix: 'pnpm --dir src/web-ui test' },
+] as const;
+
+export function buildCompletedRoundFixture(roundIndex: number, turnStartTime = 1_700_000_000_000): ModelRound {
+ const startTime = turnStartTime + roundIndex * 1_500;
+ const specA = SAMPLE_TOOL_SEQUENCE[roundIndex % SAMPLE_TOOL_SEQUENCE.length];
+ const specB = SAMPLE_TOOL_SEQUENCE[(roundIndex + 1) % SAMPLE_TOOL_SEQUENCE.length];
+ const items: AnyFlowItem[] = [];
+
+ if (roundIndex % 3 === 0) {
+ const thinking: FlowThinkingItem = {
+ id: `thinking-${roundIndex}`,
+ type: 'thinking',
+ content: `Analyzing step ${roundIndex}: checking component boundaries and virtual row stability.`,
+ isStreaming: false,
+ isCollapsed: true,
+ timestamp: startTime + 50,
+ status: 'completed',
+ };
+ items.push(thinking);
+ }
+
+ const toolA: FlowToolItem = {
+ id: `tool-${roundIndex}-a`,
+ type: 'tool',
+ toolName: specA.toolName,
+ timestamp: startTime + 120,
+ startTime: startTime + 120,
+ endTime: startTime + 450,
+ status: 'completed',
+ toolCall: {
+ id: `tool-${roundIndex}-a`,
+ input: { [specA.inputKey]: `${specA.valuePrefix}_${roundIndex}.ts` },
+ },
+ toolResult: {
+ success: true,
+ result: `Result payload for ${specA.toolName} in round ${roundIndex}: ` + 'line content\n'.repeat(12),
+ },
+ };
+ items.push(toolA);
+
+ if (roundIndex % 2 === 0) {
+ const toolB: FlowToolItem = {
+ id: `tool-${roundIndex}-b`,
+ type: 'tool',
+ toolName: specB.toolName,
+ timestamp: startTime + 480,
+ startTime: startTime + 480,
+ endTime: startTime + 820,
+ status: 'completed',
+ toolCall: {
+ id: `tool-${roundIndex}-b`,
+ input: { [specB.inputKey]: `${specB.valuePrefix}_${roundIndex}_b.ts` },
+ },
+ toolResult: {
+ success: true,
+ result: `Secondary payload for ${specB.toolName} in round ${roundIndex}: ` + 'match line\n'.repeat(8),
+ },
+ };
+ items.push(toolB);
+ }
+
+ if (roundIndex % 4 === 0) {
+ const text: FlowTextItem = {
+ id: `text-${roundIndex}`,
+ type: 'text',
+ content:
+ `### Round ${roundIndex} Summary\n\n` +
+ `Inspected \`${specA.valuePrefix}_${roundIndex}.ts\` and verified projection invariants.\n\n` +
+ `- Checked item references\n- Checked group boundaries\n`,
+ isStreaming: false,
+ isMarkdown: true,
+ timestamp: startTime + 900,
+ status: 'completed',
+ };
+ items.push(text);
+ }
+
+ return {
+ id: `round-${roundIndex}`,
+ index: roundIndex,
+ items,
+ isStreaming: false,
+ isComplete: true,
+ status: 'completed',
+ startTime,
+ endTime: startTime + 1_200,
+ firstChunkMs: startTime + 40,
+ firstVisibleOutputMs: startTime + 50,
+ ttftMs: 50,
+ streamDurationMs: 1_150,
+ };
+}
+
+export function buildLongRoundSessionFixture(options: LongRoundScenarioOptions): Session {
+ const sessionId = options.sessionId ?? 'perf-session-long-round';
+ const turnId = options.turnId ?? 'turn-active';
+ const priorCount = options.priorCompletedTurns ?? 1;
+ const baseTime = 1_700_000_000_000;
+
+ const priorTurns: DialogTurn[] = Array.from({ length: priorCount }, (_, idx) => ({
+ id: `turn-prior-${idx}`,
+ sessionId,
+ storageTurnIndex: idx,
+ userMessage: {
+ id: `user-prior-${idx}`,
+ content: `Prior user request ${idx}`,
+ timestamp: baseTime - (priorCount - idx) * 60_000,
+ },
+ modelRounds: [
+ buildCompletedRoundFixture(0, baseTime - (priorCount - idx) * 60_000 + 100),
+ buildCompletedRoundFixture(1, baseTime - (priorCount - idx) * 60_000 + 2_000),
+ ],
+ status: 'completed',
+ startTime: baseTime - (priorCount - idx) * 60_000,
+ endTime: baseTime - (priorCount - idx) * 60_000 + 5_000,
+ }));
+
+ const rounds: ModelRound[] = Array.from({ length: options.roundCount }, (_, idx) =>
+ buildCompletedRoundFixture(idx, baseTime)
+ );
+
+ const activeTurn: DialogTurn = {
+ id: turnId,
+ sessionId,
+ storageTurnIndex: priorCount,
+ userMessage: {
+ id: `user-${turnId}`,
+ content: 'Optimize long-round session scrolling and rendering performance.',
+ timestamp: baseTime - 100,
+ },
+ modelRounds: rounds,
+ status: 'processing',
+ startTime: baseTime - 100,
+ };
+
+ return {
+ sessionId,
+ sessionKind: 'normal',
+ dialogTurns: [...priorTurns, activeTurn],
+ status: 'active',
+ config: { workspaceId: 'workspace-perf', workspacePath: '/workspace/perf' },
+ createdAt: baseTime - 300_000,
+ lastActiveAt: baseTime + options.roundCount * 1_500,
+ error: null,
+ historyState: 'ready',
+ };
+}
+
+function buildStreamingChunkSession(
+ baseSession: Session,
+ chunkIdx: number,
+ chunksPerCheckpoint: number,
+): { session: Session; updatedTurn: DialogTurn; activeTailRound: ModelRound } {
+ const activeTurnIndex = baseSession.dialogTurns.length - 1;
+ const baseTurn = baseSession.dialogTurns[activeTurnIndex];
+ const settledRounds = baseTurn.modelRounds.slice(0, -1);
+ const tailRoundIndex = baseTurn.modelRounds.length - 1;
+ const tailStartTime = 1_700_000_000_000 + tailRoundIndex * 1_500;
+ const isLastChunk = chunkIdx === chunksPerCheckpoint - 1;
+
+ const streamingText: FlowTextItem = {
+ id: `stream-text-${tailRoundIndex}`,
+ type: 'text',
+ content: `Streaming response in round ${tailRoundIndex}: ` + 'chunk token payload '.repeat(chunkIdx + 1),
+ isStreaming: !isLastChunk,
+ isMarkdown: true,
+ timestamp: tailStartTime + 200 + chunkIdx * 32,
+ status: isLastChunk ? 'completed' : 'streaming',
+ };
+ const streamingTool: FlowToolItem = {
+ id: `stream-tool-${tailRoundIndex}`,
+ type: 'tool',
+ toolName: 'Read',
+ timestamp: tailStartTime + 50,
+ startTime: tailStartTime + 50,
+ endTime: tailStartTime + 180,
+ status: 'completed',
+ toolCall: {
+ id: `stream-tool-${tailRoundIndex}`,
+ input: { file_path: `src/file_${tailRoundIndex}.ts` },
+ },
+ toolResult: {
+ success: true,
+ result: 'file line\n'.repeat(10),
+ },
+ };
+
+ const activeTailRound: ModelRound = {
+ id: `round-${tailRoundIndex}`,
+ index: tailRoundIndex,
+ items: [streamingTool, streamingText],
+ isStreaming: !isLastChunk,
+ isComplete: isLastChunk,
+ status: isLastChunk ? 'completed' : 'streaming',
+ startTime: tailStartTime,
+ ...(isLastChunk ? { endTime: tailStartTime + 500 } : {}),
+ };
+
+ const updatedTurn: DialogTurn = {
+ ...baseTurn,
+ modelRounds: [...settledRounds, activeTailRound],
+ };
+ const session: Session = {
+ ...baseSession,
+ dialogTurns: [...baseSession.dialogTurns.slice(0, activeTurnIndex), updatedTurn],
+ lastActiveAt: tailStartTime + chunkIdx * 32,
+ };
+
+ return { session, updatedTurn, activeTailRound };
+}
+
+function percentile(sorted: number[], p: number): number {
+ if (sorted.length === 0) return 0;
+ const idx = Math.min(sorted.length - 1, Math.max(0, Math.floor(sorted.length * p)));
+ return sorted[idx];
+}
+
+/**
+ * Category 1: Store & Adjacent Group Projection (`projectSession` + `projectAdjacentFlowGroups`)
+ */
+export function benchStoreProjection(options?: {
+ checkpoints?: number[];
+ chunksPerCheckpoint?: number;
+ interleaveViews?: boolean;
+}): StoreProjectionBenchResult {
+ const checkpoints = options?.checkpoints ?? [10, 50, 100, 200, 300];
+ const chunksPerCheckpoint = options?.chunksPerCheckpoint ?? 5;
+
+ const projectLive = createSessionVirtualItemProjector();
+ const projectHistory = createSessionVirtualItemProjector();
+ const projectSide = createSessionVirtualItemProjector();
+ const side = buildLongRoundSessionFixture({ roundCount: 10, sessionId: 'side-session' });
+ let previousVirtualItems: VirtualItem[] = [];
+ const stepMs: Array<{ roundCount: number; ms: number; reuseRatio: number }> = [];
+
+ for (const roundCount of checkpoints) {
+ const baseSession = buildLongRoundSessionFixture({ roundCount });
+ for (let chunkIdx = 0; chunkIdx < chunksPerCheckpoint; chunkIdx += 1) {
+ const { session, activeTailRound } = buildStreamingChunkSession(
+ baseSession,
+ chunkIdx,
+ chunksPerCheckpoint,
+ );
+ if (options?.interleaveViews) {
+ projectHistory({ ...session, dialogTurns: session.dialogTurns.slice(0, -1) });
+ projectSide(buildStreamingChunkSession(side, chunkIdx, chunksPerCheckpoint).session);
+ }
+ const t0 = performance.now();
+ const virtualItems = projectLive(session);
+ const t1 = performance.now();
+
+ if (chunkIdx > 0) {
+ const settled = virtualItems.filter(
+ item => !(item.type === 'model-round' && item.data.id === activeTailRound.id),
+ );
+ const prevSet = new Set(previousVirtualItems);
+ const reused = settled.filter(item => prevSet.has(item)).length;
+ stepMs.push({
+ roundCount,
+ ms: t1 - t0,
+ reuseRatio: settled.length > 0 ? reused / settled.length : 1,
+ });
+ }
+ previousVirtualItems = virtualItems;
+ }
+ }
+
+ const totalMs = stepMs.reduce((s, x) => s + x.ms, 0);
+ const early = stepMs.filter(x => x.roundCount === checkpoints[0]);
+ const late = stepMs.filter(x => x.roundCount === checkpoints[checkpoints.length - 1]);
+ const earlyFlushAvgMs = early.reduce((s, x) => s + x.ms, 0) / Math.max(1, early.length);
+ const lateFlushAvgMs = late.reduce((s, x) => s + x.ms, 0) / Math.max(1, late.length);
+
+ return {
+ checkpoints,
+ totalFlushes: stepMs.length,
+ totalMs,
+ avgFlushMs: totalMs / Math.max(1, stepMs.length),
+ earlyFlushAvgMs,
+ lateFlushAvgMs,
+ scalingRatio: earlyFlushAvgMs > 0 ? lateFlushAvgMs / earlyFlushAvgMs : 1,
+ settledVirtualItemReuseRatio:
+ stepMs.reduce((s, x) => s + x.reuseRatio, 0) / Math.max(1, stepMs.length),
+ };
+}
+
+/**
+ * Category 2: Timeline Document Projection & Rhythm Spacing (`ConversationDocumentProjection.project` + `getNextVisibleVirtualItemIndexes`)
+ */
+export function benchTimelineDocument(options?: {
+ checkpoints?: number[];
+ chunksPerCheckpoint?: number;
+}): TimelineDocumentBenchResult {
+ const checkpoints = options?.checkpoints ?? [10, 50, 100, 200, 300];
+ const chunksPerCheckpoint = options?.chunksPerCheckpoint ?? 5;
+
+ const projectSession = createSessionVirtualItemProjector();
+ const reader = new FlowChatReaderState();
+ const docProjection = new ConversationDocumentProjection();
+ const docOptions: TimelineProjectionOptions = {
+ reader,
+ sessionId: 'perf-session-long-round',
+ groupStates: new Map(),
+ expandedToolCapsules: new Set(),
+ pendingPermissionToolCallIds: new Set(),
+ toolLabels: new Map(),
+ };
+
+ let previousTimelineBlocks: VirtualItem[] = [];
+ const steps: Array<{ roundCount: number; docMs: number; rhythmMs: number; reuseRatio: number }> = [];
+
+ for (const roundCount of checkpoints) {
+ const baseSession = buildLongRoundSessionFixture({ roundCount });
+ for (let chunkIdx = 0; chunkIdx < chunksPerCheckpoint; chunkIdx += 1) {
+ const { session, activeTailRound } = buildStreamingChunkSession(
+ baseSession,
+ chunkIdx,
+ chunksPerCheckpoint,
+ );
+ const virtualItems = projectSession(session);
+
+ const t0 = performance.now();
+ const timelineBlocks = docProjection.project(virtualItems, docOptions);
+ const t1 = performance.now();
+ getNextVisibleVirtualItemIndexes(timelineBlocks);
+ const t2 = performance.now();
+
+ if (chunkIdx > 0) {
+ const settled = timelineBlocks.filter(
+ block => !(block.type === 'model-round' && block.data.id === activeTailRound.id),
+ );
+ const prevSet = new Set(previousTimelineBlocks);
+ const reused = settled.filter(block => prevSet.has(block)).length;
+ steps.push({
+ roundCount,
+ docMs: t1 - t0,
+ rhythmMs: t2 - t1,
+ reuseRatio: settled.length > 0 ? reused / settled.length : 1,
+ });
+ }
+ previousTimelineBlocks = timelineBlocks;
+ }
+ }
+
+ // Also measure isolated document projection when settled VirtualItem references ARE held stable
+ const isolatedProjection = new ConversationDocumentProjection();
+ const maxRoundCount = checkpoints[checkpoints.length - 1];
+ const baseMaxSession = buildLongRoundSessionFixture({ roundCount: maxRoundCount });
+ const initialVirtualItems = projectSession(baseMaxSession);
+ const stableSettledPrefix = initialVirtualItems.slice(0, -1);
+ let prevIsolatedBlocks = isolatedProjection.project(initialVirtualItems, docOptions);
+ let isolatedTotalMs = 0;
+ let isolatedReuseSum = 0;
+ const isolatedFlushes = chunksPerCheckpoint - 1;
+
+ for (let chunkIdx = 1; chunkIdx < chunksPerCheckpoint; chunkIdx += 1) {
+ const { session, activeTailRound } = buildStreamingChunkSession(
+ baseMaxSession,
+ chunkIdx,
+ chunksPerCheckpoint,
+ );
+ const freshVirtualItems = projectSession(session);
+ const stabilizedInput = [...stableSettledPrefix, freshVirtualItems[freshVirtualItems.length - 1]];
+ const t0 = performance.now();
+ const nextBlocks = isolatedProjection.project(stabilizedInput, docOptions);
+ const t1 = performance.now();
+ isolatedTotalMs += t1 - t0;
+
+ const settled = nextBlocks.filter(
+ block => !(block.type === 'model-round' && block.data.id === activeTailRound.id),
+ );
+ const prevSet = new Set(prevIsolatedBlocks);
+ const reused = settled.filter(block => prevSet.has(block)).length;
+ isolatedReuseSum += settled.length > 0 ? reused / settled.length : 1;
+ prevIsolatedBlocks = nextBlocks;
+ }
+
+ const documentProjectionTotalMs = steps.reduce((s, x) => s + x.docMs, 0);
+ const rhythmPassTotalMs = steps.reduce((s, x) => s + x.rhythmMs, 0);
+ const early = steps.filter(x => x.roundCount === checkpoints[0]);
+ const late = steps.filter(x => x.roundCount === checkpoints[checkpoints.length - 1]);
+ const earlyFlushAvgMs =
+ early.reduce((s, x) => s + x.docMs + x.rhythmMs, 0) / Math.max(1, early.length);
+ const lateFlushAvgMs =
+ late.reduce((s, x) => s + x.docMs + x.rhythmMs, 0) / Math.max(1, late.length);
+
+ return {
+ checkpoints,
+ totalFlushes: steps.length,
+ documentProjectionTotalMs,
+ rhythmPassTotalMs,
+ avgFlushMs: (documentProjectionTotalMs + rhythmPassTotalMs) / Math.max(1, steps.length),
+ earlyFlushAvgMs,
+ lateFlushAvgMs,
+ scalingRatio: earlyFlushAvgMs > 0 ? lateFlushAvgMs / earlyFlushAvgMs : 1,
+ settledTimelineBlockReuseRatio:
+ steps.reduce((s, x) => s + x.reuseRatio, 0) / Math.max(1, steps.length),
+ isolatedSettledTimelineBlockReuseRatio: isolatedReuseSum / Math.max(1, isolatedFlushes),
+ isolatedAvgFlushMs: isolatedTotalMs / Math.max(1, isolatedFlushes),
+ };
+}
+
+/**
+ * Category 3: Container Group Indexing, Receive Feedback & Search Passes
+ * (`indexFlowGroups`, `captureFlowGroupFeedbackSnapshot`, `collectFlowGroupReceiveFeedback`, `buildFlowChatSearchMatches`)
+ */
+export function benchGroupStateAndSearch(options?: {
+ checkpoints?: number[];
+ chunksPerCheckpoint?: number;
+ activeSearchQuery?: string;
+}): GroupStateAndSearchBenchResult {
+ const checkpoints = options?.checkpoints ?? [10, 50, 100, 200, 300];
+ const chunksPerCheckpoint = options?.chunksPerCheckpoint ?? 5;
+ const activeSearchQuery = options?.activeSearchQuery ?? 'projection';
+ const projectSession = createSessionVirtualItemProjector();
+ const findMatches = createFlowChatSearchMatcher();
+
+ let feedbackSnapshot: ReturnType | undefined;
+
+ const steps: Array<{
+ roundCount: number;
+ indexMs: number;
+ feedbackMs: number;
+ searchMs: number;
+ }> = [];
+
+ for (const roundCount of checkpoints) {
+ const baseSession = buildLongRoundSessionFixture({ roundCount });
+ for (let chunkIdx = 0; chunkIdx < chunksPerCheckpoint; chunkIdx += 1) {
+ const { session } = buildStreamingChunkSession(baseSession, chunkIdx, chunksPerCheckpoint);
+ const virtualItems = projectSession(session);
+
+ const t0 = performance.now();
+ indexFlowGroups(virtualItems);
+ const t1 = performance.now();
+ collectFlowGroupReceiveFeedback(
+ feedbackSnapshot,
+ virtualItems,
+ session.sessionId,
+ );
+ feedbackSnapshot = captureFlowGroupFeedbackSnapshot(virtualItems, session.sessionId);
+ const t2 = performance.now();
+ findMatches(virtualItems, activeSearchQuery);
+ const t3 = performance.now();
+
+ if (chunkIdx > 0) {
+ steps.push({
+ roundCount,
+ indexMs: t1 - t0,
+ feedbackMs: t2 - t1,
+ searchMs: t3 - t2,
+ });
+ }
+ }
+ }
+
+ const indexFlowGroupsTotalMs = steps.reduce((s, x) => s + x.indexMs, 0);
+ const receiveFeedbackTotalMs = steps.reduce((s, x) => s + x.feedbackMs, 0);
+ const searchPassTotalMs = steps.reduce((s, x) => s + x.searchMs, 0);
+ const totalCombinedMs = indexFlowGroupsTotalMs + receiveFeedbackTotalMs + searchPassTotalMs;
+
+ const early = steps.filter(x => x.roundCount === checkpoints[0]);
+ const late = steps.filter(x => x.roundCount === checkpoints[checkpoints.length - 1]);
+ const earlyCombinedAvgMs =
+ early.reduce((s, x) => s + x.indexMs + x.feedbackMs + x.searchMs, 0) / Math.max(1, early.length);
+ const lateCombinedAvgMs =
+ late.reduce((s, x) => s + x.indexMs + x.feedbackMs + x.searchMs, 0) / Math.max(1, late.length);
+
+ return {
+ checkpoints,
+ totalFlushes: steps.length,
+ indexFlowGroupsTotalMs,
+ receiveFeedbackTotalMs,
+ searchPassTotalMs,
+ avgCombinedMs: totalCombinedMs / Math.max(1, steps.length),
+ earlyCombinedAvgMs,
+ lateCombinedAvgMs,
+ scalingRatio: earlyCombinedAvgMs > 0 ? lateCombinedAvgMs / earlyCombinedAvgMs : 1,
+ };
+}
+
+/**
+ * Category 4: Background Memory Budget & Persistence Hash Overhead
+ * (`estimateRetainedBytes(turn)` + `calculateTurnHash(turn)`)
+ */
+export function benchBackgroundBudgetAndPersistence(options?: {
+ checkpoints?: number[];
+ iterationsPerCheckpoint?: number;
+}): BackgroundBudgetAndPersistenceBenchResult {
+ const checkpoints = options?.checkpoints ?? [10, 50, 100, 200, 300];
+ const iterationsPerCheckpoint = options?.iterationsPerCheckpoint ?? 5;
+
+ const steps: Array<{ roundCount: number; bytesMs: number; hashMs: number; bytes: number }> = [];
+
+ for (const roundCount of checkpoints) {
+ const baseSession = buildLongRoundSessionFixture({ roundCount });
+ // Sample the initial turn before the later 500ms budget ticks. Production
+ // caches immutable whole Turns at the history owner, not round prefixes here.
+ const { updatedTurn: initialTurn } = buildStreamingChunkSession(baseSession, 0, iterationsPerCheckpoint + 1);
+ estimateRetainedBytes(initialTurn);
+ for (let i = 1; i <= iterationsPerCheckpoint; i += 1) {
+ const { updatedTurn } = buildStreamingChunkSession(baseSession, i, iterationsPerCheckpoint + 1);
+ const t0 = performance.now();
+ const bytes = estimateRetainedBytes(updatedTurn);
+ const t1 = performance.now();
+ calculateTurnHash(updatedTurn);
+ const t2 = performance.now();
+
+ steps.push({
+ roundCount,
+ bytesMs: t1 - t0,
+ hashMs: t2 - t1,
+ bytes,
+ });
+ }
+ }
+
+ const retainedBytesTotalMs = steps.reduce((s, x) => s + x.bytesMs, 0);
+ const turnHashTotalMs = steps.reduce((s, x) => s + x.hashMs, 0);
+ const early = steps.filter(x => x.roundCount === checkpoints[0]);
+ const late = steps.filter(x => x.roundCount === checkpoints[checkpoints.length - 1]);
+
+ const retainedBytesEarlyAvgMs =
+ early.reduce((s, x) => s + x.bytesMs, 0) / Math.max(1, early.length);
+ const retainedBytesLateAvgMs =
+ late.reduce((s, x) => s + x.bytesMs, 0) / Math.max(1, late.length);
+ const turnHashEarlyAvgMs = early.reduce((s, x) => s + x.hashMs, 0) / Math.max(1, early.length);
+ const turnHashLateAvgMs = late.reduce((s, x) => s + x.hashMs, 0) / Math.max(1, late.length);
+
+ return {
+ checkpoints,
+ iterationsPerCheckpoint,
+ retainedBytesTotalMs,
+ retainedBytesEarlyAvgMs,
+ retainedBytesLateAvgMs,
+ retainedBytesScalingRatio:
+ retainedBytesEarlyAvgMs > 0 ? retainedBytesLateAvgMs / retainedBytesEarlyAvgMs : 1,
+ turnHashTotalMs,
+ turnHashEarlyAvgMs,
+ turnHashLateAvgMs,
+ estimatedActiveTurnBytesAtMaxRound: late[late.length - 1]?.bytes ?? 0,
+ };
+}
+
+/**
+ * Runs a combined end-to-end multi-stage benchmark simulating streaming flushes
+ * at the tail of a growing long-round turn.
+ */
+export function runLongRoundPipelineBenchmark(options: {
+ checkpoints?: number[];
+ chunksPerCheckpoint?: number;
+ measureRetainedBytesEveryFlush?: boolean;
+}): LongRoundBenchmarkSummary {
+ const checkpoints = options.checkpoints ?? [10, 50, 100, 150, 200];
+ const chunksPerCheckpoint = options.chunksPerCheckpoint ?? 4;
+ const measureRetainedBytesEveryFlush = options.measureRetainedBytesEveryFlush ?? true;
+
+ const projectSession = createSessionVirtualItemProjector();
+ const reader = new FlowChatReaderState();
+ const docProjection = new ConversationDocumentProjection();
+ const groupStates = new Map();
+ const expandedToolCapsules = new Set();
+ const pendingPermissionToolCallIds = new Set();
+ const toolLabels = new Map();
+
+ let previousVirtualItems: VirtualItem[] = [];
+ let previousTimelineBlocks: VirtualItem[] = [];
+ let feedbackSnapshot: ReturnType | undefined;
+
+ const steps: StreamingStepMetrics[] = [];
+
+ for (const roundCount of checkpoints) {
+ const baseSession = buildLongRoundSessionFixture({ roundCount });
+ const tailRoundIndex = roundCount - 1;
+
+ for (let chunkIdx = 0; chunkIdx < chunksPerCheckpoint; chunkIdx += 1) {
+ const isLastChunk = chunkIdx === chunksPerCheckpoint - 1;
+ const { session, updatedTurn, activeTailRound } = buildStreamingChunkSession(
+ baseSession,
+ chunkIdx,
+ chunksPerCheckpoint,
+ );
+
+ // Stage 1: Store projection (projectSession + projectAdjacentFlowGroups)
+ const t0 = performance.now();
+ const virtualItems = projectSession(session);
+ const t1 = performance.now();
+
+ // Stage 2: Group indexing & receive feedback (useFlowGroupState equivalents)
+ const indexedGroups = indexFlowGroups(virtualItems);
+ collectFlowGroupReceiveFeedback(
+ feedbackSnapshot,
+ virtualItems,
+ session.sessionId,
+ );
+ feedbackSnapshot = captureFlowGroupFeedbackSnapshot(virtualItems, session.sessionId);
+ const t2 = performance.now();
+
+ // Stage 3: ConversationDocumentProjection.project
+ const docOptions: TimelineProjectionOptions = {
+ reader,
+ sessionId: session.sessionId,
+ groupStates,
+ expandedToolCapsules,
+ pendingPermissionToolCallIds,
+ toolLabels,
+ };
+ const timelineBlocks = docProjection.project(virtualItems, docOptions);
+ const t3 = performance.now();
+
+ // Stage 4: Rhythm visible-index pass
+ getNextVisibleVirtualItemIndexes(timelineBlocks);
+ const t4 = performance.now();
+
+ // Stage 5: Retained bytes estimation on active turn
+ if (measureRetainedBytesEveryFlush) {
+ estimateRetainedBytes(updatedTurn);
+ }
+ const t5 = performance.now();
+
+ // Audit reference stability of settled items (excluding the active tail round)
+ const activeRoundId = activeTailRound.id;
+ const settledVirtualItems = virtualItems.filter(
+ item => !(item.type === 'model-round' && item.data.id === activeRoundId)
+ );
+ const prevVirtualSet = new Set(previousVirtualItems);
+ const reusedSettledVirtualItems = settledVirtualItems.filter(item => prevVirtualSet.has(item)).length;
+
+ const settledTimelineBlocks = timelineBlocks.filter(
+ block => !(block.type === 'model-round' && block.data.id === activeRoundId)
+ );
+ const prevTimelineSet = new Set(previousTimelineBlocks);
+ const reusedSettledTimelineBlocks = settledTimelineBlocks.filter(block => prevTimelineSet.has(block)).length;
+
+ if (chunkIdx > 0) {
+ steps.push({
+ roundIndex: tailRoundIndex,
+ stepKind: isLastChunk ? 'round-complete' : 'text-chunk',
+ totalPipelineMs: t5 - t0,
+ stageMs: {
+ storeProjectionMs: t1 - t0,
+ groupIndexAndFeedbackMs: t2 - t1,
+ documentProjectionMs: t3 - t2,
+ rhythmPassMs: t4 - t3,
+ retainedBytesEstimateMs: t5 - t4,
+ },
+ counts: {
+ rounds: roundCount,
+ virtualItems: virtualItems.length,
+ timelineBlocks: timelineBlocks.length,
+ indexedGroups: indexedGroups.byId.size,
+ },
+ churn: {
+ settledVirtualItemCount: settledVirtualItems.length,
+ reusedSettledVirtualItems,
+ settledVirtualItemReuseRatio:
+ settledVirtualItems.length > 0 ? reusedSettledVirtualItems / settledVirtualItems.length : 1,
+ settledTimelineBlockCount: settledTimelineBlocks.length,
+ reusedSettledTimelineBlocks,
+ settledTimelineBlockReuseRatio:
+ settledTimelineBlocks.length > 0 ? reusedSettledTimelineBlocks / settledTimelineBlocks.length : 1,
+ },
+ });
+ }
+
+ previousVirtualItems = virtualItems;
+ previousTimelineBlocks = timelineBlocks;
+ }
+ }
+
+ const durations = steps.map(s => s.totalPipelineMs).sort((a, b) => a - b);
+ const totalPipelineMs = steps.reduce((sum, s) => sum + s.totalPipelineMs, 0);
+ const stageTotalsMs = steps.reduce(
+ (acc, s) => ({
+ storeProjectionMs: acc.storeProjectionMs + s.stageMs.storeProjectionMs,
+ groupIndexAndFeedbackMs: acc.groupIndexAndFeedbackMs + s.stageMs.groupIndexAndFeedbackMs,
+ documentProjectionMs: acc.documentProjectionMs + s.stageMs.documentProjectionMs,
+ rhythmPassMs: acc.rhythmPassMs + s.stageMs.rhythmPassMs,
+ retainedBytesEstimateMs: acc.retainedBytesEstimateMs + s.stageMs.retainedBytesEstimateMs,
+ }),
+ {
+ storeProjectionMs: 0,
+ groupIndexAndFeedbackMs: 0,
+ documentProjectionMs: 0,
+ rhythmPassMs: 0,
+ retainedBytesEstimateMs: 0,
+ },
+ );
+
+ const firstCheckpoint = checkpoints[0];
+ const lastCheckpoint = checkpoints[checkpoints.length - 1];
+ const earlySteps = steps.filter(s => s.roundIndex === firstCheckpoint - 1);
+ const lateSteps = steps.filter(s => s.roundIndex === lastCheckpoint - 1);
+ const earlyFlushAvgMs =
+ earlySteps.reduce((sum, s) => sum + s.totalPipelineMs, 0) / Math.max(1, earlySteps.length);
+ const lateFlushAvgMs =
+ lateSteps.reduce((sum, s) => sum + s.totalPipelineMs, 0) / Math.max(1, lateSteps.length);
+
+ const avgSettledVirtualItemReuseRatio =
+ steps.reduce((sum, s) => sum + s.churn.settledVirtualItemReuseRatio, 0) / Math.max(1, steps.length);
+ const avgSettledTimelineBlockReuseRatio =
+ steps.reduce((sum, s) => sum + s.churn.settledTimelineBlockReuseRatio, 0) / Math.max(1, steps.length);
+
+ return {
+ roundCount: lastCheckpoint,
+ totalFlushes: steps.length,
+ totalPipelineMs,
+ avgFlushMs: totalPipelineMs / Math.max(1, steps.length),
+ p50FlushMs: percentile(durations, 0.5),
+ p95FlushMs: percentile(durations, 0.95),
+ maxFlushMs: durations[durations.length - 1] ?? 0,
+ earlyFlushAvgMs,
+ lateFlushAvgMs,
+ lateToEarlyScalingRatio: earlyFlushAvgMs > 0 ? lateFlushAvgMs / earlyFlushAvgMs : 1,
+ stageTotalsMs,
+ avgSettledVirtualItemReuseRatio,
+ avgSettledTimelineBlockReuseRatio,
+ steps,
+ };
+}
+
+/**
+ * Formats a human-readable diagnostic table of the benchmark summary.
+ */
+export function formatBenchmarkReport(summary: LongRoundBenchmarkSummary): string {
+ const lines: string[] = [
+ `=== FlowChat Long-Round Harness Report (up to ${summary.roundCount} rounds, ${summary.totalFlushes} measured flushes) ===`,
+ `Total Pipeline Time : ${summary.totalPipelineMs.toFixed(2)} ms`,
+ `Flush Latency : avg=${summary.avgFlushMs.toFixed(2)}ms | p50=${summary.p50FlushMs.toFixed(2)}ms | p95=${summary.p95FlushMs.toFixed(2)}ms | max=${summary.maxFlushMs.toFixed(2)}ms`,
+ `Scaling (Late/Early): early=${summary.earlyFlushAvgMs.toFixed(2)}ms -> late=${summary.lateFlushAvgMs.toFixed(2)}ms (${summary.lateToEarlyScalingRatio.toFixed(2)}x)`,
+ `Stage Breakdown :`,
+ ` 1. Store Projection (projectSession + grouping): ${summary.stageTotalsMs.storeProjectionMs.toFixed(2)} ms`,
+ ` 2. Group Index & Feedback (useFlowGroupState) : ${summary.stageTotalsMs.groupIndexAndFeedbackMs.toFixed(2)} ms`,
+ ` 3. Document Timeline (ConversationDocumentProjection) : ${summary.stageTotalsMs.documentProjectionMs.toFixed(2)} ms`,
+ ` 4. Rhythm Spacing Pass (getNextVisibleIndexes) : ${summary.stageTotalsMs.rhythmPassMs.toFixed(2)} ms`,
+ ` 5. Retained Bytes Walk (estimateRetainedBytes) : ${summary.stageTotalsMs.retainedBytesEstimateMs.toFixed(2)} ms`,
+ `Reference Reuse :`,
+ ` - Settled VirtualItem Identity Reuse : ${(summary.avgSettledVirtualItemReuseRatio * 100).toFixed(1)}%`,
+ ` - Settled TimelineBlock Identity Reuse : ${(summary.avgSettledTimelineBlockReuseRatio * 100).toFixed(1)}%`,
+ ];
+ return lines.join('\n');
+}
+
+export { getVirtualItemStableKey, getVirtualItemFlowGroups };
diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.test.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.test.ts
index 58f169dff0..da2ecfcf32 100644
--- a/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.test.ts
+++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.test.ts
@@ -24,11 +24,16 @@ import { markOptimisticDispatchTurnMetadata } from '@/features/dispatch/optimist
import { interruptedTurnRecoveryGate } from '../interruptedTurnRecoveryGate';
import { agentAPI } from '@/infrastructure/api/service-api/AgentAPI';
import { localSessionDriver } from '../../session-drivers/local/LocalSessionDriver';
+import * as peerSessionRefresh from './PeerSessionRefreshModule';
import { chatInputSessionSubscriptionKey } from '../../utils/chatInputSessionSubscription';
import { selectInterruptedTurnRecovery } from '../../utils/interruptedTurnRecovery';
import { promptSuggestionKey, usePromptSuggestionStore } from '../../store/promptSuggestionStore';
import { clearAgentCanvasForPeerSwitch, switchAgentCanvasScope, useAgentCanvasStore } from '@/app/components/panels/content-canvas/stores';
import { activateSurface } from '@/infrastructure/peer-device/deviceSurface';
+import {
+ isRuntimeSessionProjectionStale,
+ resetRuntimeSessionEventGateForTest,
+} from '@/infrastructure/peer-device/runtimeSessionEventGate';
import { markCurrentTurnItemsAsCancelled } from '../../utils/turnCancellation';
import {
isManualCompactionPending,
@@ -1168,6 +1173,36 @@ describe('shouldProcessEvent', () => {
).toBe(false);
});
+ it.each(['local', 'peer-review'])('preserves replay repair for an unmaterialized session on %s', surfaceId => {
+ resetRuntimeSessionEventGateForTest();
+ activateSurface(surfaceId);
+ try {
+ expect(FlowChatStore.getInstance().getState().sessions.has(mockSessionId)).toBe(false);
+ expect(shouldProcessEvent(mockSessionId, mockTurnId, 'data', 'TextChunk')).toBe(false);
+ expect(isRuntimeSessionProjectionStale(surfaceId, mockSessionId)).toBe(true);
+ } finally {
+ activateSurface('local');
+ resetRuntimeSessionEventGateForTest();
+ }
+ });
+
+ it('coalesces an unknown session gap without suppressing repair after registration', () => {
+ resetRuntimeSessionEventGateForTest();
+ const repair = vi.spyOn(peerSessionRefresh, 'requestRuntimeProjectionRepair');
+ try {
+ expect(shouldProcessEvent('session-1', 'turn-1', 'data', 'TextChunk')).toBe(false);
+ expect(shouldProcessEvent('session-1', 'turn-1', 'data', 'TextChunk')).toBe(false);
+ expect(repair).toHaveBeenCalledTimes(1);
+ expect(isRuntimeSessionProjectionStale('local', 'session-1')).toBe(true);
+ createSessionWithTurn(createFinishingTurn());
+ expect(shouldProcessEvent('session-1', 'turn-1', 'data', 'TextChunk')).toBe(false);
+ expect(repair).toHaveBeenCalledTimes(2);
+ } finally {
+ repair.mockRestore();
+ resetRuntimeSessionEventGateForTest();
+ }
+ });
+
it('returns true for state_sync event even when no state machine exists', () => {
expect(
shouldProcessEvent(mockSessionId, mockTurnId, 'state_sync', 'SessionStateChanged'),
diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.ts
index 2b237edecf..7bb20a1b4b 100644
--- a/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.ts
+++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.ts
@@ -1,5 +1,6 @@
import { modelPoolAPI, supportsModelPools } from '@/infrastructure/api/service-api/ModelPoolAPI';
import { getActiveSurfaceScope } from '@/infrastructure/peer-device/deviceSurface';
+import { isRuntimeSessionProjectionStale } from '@/infrastructure/peer-device/runtimeSessionEventGate';
import { sessionWorkspaceId, sessionProjectWorkspacePath } from '../../utils/sessionWorkspace';
/**
* Event handling module
@@ -260,6 +261,11 @@ function logDroppedDataEvent(
turnId: string | null,
details: Record
): void {
+ // Missing UI state does not identify an internal background session. Preserve
+ // the first replay gap, then coalesce repeated drops until it materializes.
+ if (details.reason === 'missing_state_machine'
+ && !FlowChatStore.getInstance().getState().sessions.has(sessionId)
+ && isRuntimeSessionProjectionStale(getActiveSurfaceScope().surfaceId, sessionId)) return;
requestRuntimeProjectionRepair(sessionId);
log.debug('Dropped agentic data event', {
eventName,
diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts
index 6af88ef7c7..79c37b5264 100644
--- a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts
+++ b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { flowChatStore, mergeModelRoundAttemptDiagnostics } from './FlowChatStore';
-import { sessionToVirtualItems } from './modernFlowChatStore';
+import { createSessionVirtualItemProjector } from './modernFlowChatStore';
import { getTurnOutputDurationMs, getTurnUsageMetrics } from '../utils/turnUsageMetrics';
import { buildModelRoundItemGroups } from '../components/modern/modelRoundItemGrouping';
import { getVirtualItemFlowGroups } from '../grouping/selectors';
@@ -37,6 +37,9 @@ import {
askUserQuestionDraftStore,
} from './askUserQuestionDraftStore';
+let projectSession: ReturnType;
+beforeEach(() => { projectSession = createSessionVirtualItemProjector(); });
+
vi.mock('@/shared/notification-system', () => ({
notificationService: { error: vi.fn(), warning: vi.fn() },
}));
@@ -1406,7 +1409,7 @@ describe('FlowChatStore round attempts', () => {
}], { supersedeMatchingAttempts: true }));
flowChatStore.addModelRoundItem(session.sessionId, 'turn-1', tool('recovered', 2), 'retry');
- const groups = () => sessionToVirtualItems(flowChatStore.getState().sessions.get(session.sessionId)!)
+ const groups = () => projectSession(flowChatStore.getState().sessions.get(session.sessionId)!)
.flatMap(getVirtualItemFlowGroups);
expect(groups().map(group => group.allItems.map(item => item.id))).toEqual([['before-call'], ['recovered']]);
const owner = groups()[1].groupId;
@@ -1448,7 +1451,7 @@ describe('FlowChatStore round attempts', () => {
const reloaded = restore(JSON.parse(JSON.stringify(convertDialogTurnToBackendFormat(restored, 0))));
for (const turn of [restored, reloaded]) {
const session = createSession({ dialogTurns: [turn] });
- const groups = sessionToVirtualItems(session).flatMap(getVirtualItemFlowGroups);
+ const groups = projectSession(session).flatMap(getVirtualItemFlowGroups);
expect(groups.map(group => group.allItems.map(item => item.id))).toEqual(source ? [] : [['read', 'read-next']]);
expect(turn.modelRounds[0].attempts).toHaveLength(2);
expect(turn.modelRounds[0].attempts[0].diagnostic.rawError).toBe('Connection reset');
@@ -2935,7 +2938,7 @@ describe('FlowChatStore historical session hydration state', () => {
attemptId: scenario === 'diagnostic' ? 'runtime-interaction:round-live' : 'attempt-live', isParamsStreaming: false }),
]));
expect(round().items).toEqual(round().attempts!.flatMap(entry => entry.items));
- const visibleRound = sessionToVirtualItems(flowChatStore.getState().sessions.get('history-1')!)
+ const visibleRound = projectSession(flowChatStore.getState().sessions.get('history-1')!)
.find(item => item.type === 'model-round');
expect(visibleRound?.type).toBe('model-round');
if (visibleRound?.type === 'model-round') {
@@ -8754,9 +8757,9 @@ describe('FlowChatStore device surfaces', () => {
expect(result.composerText).toBe('test2');
}
expect(turnIds(sessionId)).toEqual(['turn-0']);
- expect(sessionToVirtualItems(flowChatStore.getState().sessions.get(sessionId)!))
+ expect(projectSession(flowChatStore.getState().sessions.get(sessionId)!))
.toEqual(expect.arrayContaining([expect.objectContaining({ turnId: 'turn-0' })]));
- expect(sessionToVirtualItems(flowChatStore.getState().sessions.get(sessionId)!)
+ expect(projectSession(flowChatStore.getState().sessions.get(sessionId)!)
.some(item => item.turnId === 'turn-1' || item.turnId === 'turn-2')).toBe(false);
expect(apiMocks.restoreSessionView).not.toHaveBeenCalled();
},
diff --git a/src/web-ui/src/flow_chat/store/modernFlowChatStore.test.ts b/src/web-ui/src/flow_chat/store/modernFlowChatStore.test.ts
index 69d7f6a783..db44b8f41e 100644
--- a/src/web-ui/src/flow_chat/store/modernFlowChatStore.test.ts
+++ b/src/web-ui/src/flow_chat/store/modernFlowChatStore.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { FlowTextItem, FlowThinkingItem, FlowToolItem, FlowUserSteeringItem, ModelRound, Session } from '../types/flow-chat';
vi.mock('./FlowChatStore', () => ({
@@ -10,12 +10,14 @@ vi.mock('./FlowChatStore', () => ({
},
}));
-import { sessionToVirtualItems, type VirtualItem } from './modernFlowChatStore';
+import { createModernFlowChatStore, createSessionVirtualItemProjector, type VirtualItem } from './modernFlowChatStore';
import { getVirtualItemFlowGroups } from '../grouping/selectors';
import { getVirtualItemStableKey } from '../components/modern/virtualItemIdentity';
import { getModelRoundExploreGroups, getProjectedModelRoundGroups } from '../components/modern/modelRoundItemGrouping';
type ModelRoundVirtualItem = Extract;
+let projectSession: ReturnType;
+beforeEach(() => { projectSession = createSessionVirtualItemProjector(); });
function makeTextItem(id: string, content: string): FlowTextItem {
return {
@@ -116,18 +118,216 @@ function makeSession(overrides: Partial = {}): Session {
};
}
-describe('sessionToVirtualItems unified work grouping', () => {
+describe('incremental projection cache contracts', () => {
+ function processingSession(rounds: ModelRound[]): Session {
+ const session = makeSession();
+ session.dialogTurns[0] = { ...session.dialogTurns[0], status: 'processing', modelRounds: rounds };
+ return session;
+ }
+
+ function updateTail(session: Session): Session {
+ const turn = session.dialogTurns[0];
+ return { ...session, dialogTurns: [{ ...turn, modelRounds: turn.modelRounds.map((round, index) => (
+ index === turn.modelRounds.length - 1 ? { ...round, items: [...round.items, makeTextItem('tail-chunk', 'next chunk')] } : round
+ )) }] };
+ }
+
+ it('keeps a user row stable while its only model round streams', () => {
+ const session = processingSession([makeRound({ items: [makeTextItem('text', 'Answer')] })]);
+ const before = projectSession(session);
+ const after = projectSession(updateTail(session));
+ expect(after[0]).toBe(before[0]);
+ });
+
+ it('shares immutable completed Turns across alternating streaming session revisions', () => {
+ const completed = makeSession().dialogTurns[0];
+ const session = { ...processingSession([makeRound()]), dialogTurns: [completed, {
+ ...completed, id: 'active', status: 'processing' as const,
+ }] };
+ const before = projectSession(session);
+ projectSession(makeSession({ sessionId: 'side' }));
+ const active = session.dialogTurns[1];
+ const after = projectSession({ ...session, dialogTurns: [completed, {
+ ...active, modelRounds: [...active.modelRounds, makeRound({ id: 'new' })],
+ }] });
+ expect(after.filter(item => item.turnId === completed.id).every((item, index) => item === before[index])).toBe(true);
+ });
+
+ it.each(['side session', 'history view'])('preserves live prefixes when a %s projects between flushes', other => {
+ let session = processingSession([
+ makeRound({ id: 'read', items: [makeReadTool('read')] }),
+ makeRound({ id: 'boundary', items: [makeTool('ask', 'AskUserQuestion')] }),
+ makeRound({ id: 'tail', items: [makeTextItem('tail', 'Answer')] }),
+ ]);
+ const live = createModernFlowChatStore(session);
+ const settled = live.getState().virtualItems.slice(0, 3);
+ const history = makeSession();
+ for (let step = 0; step < 4; step++) {
+ projectSession(other === 'side session'
+ ? makeSession({ sessionId: 'side' }) : history);
+ session = updateTail(session);
+ live.getState().setActiveSession(session);
+ expect(live.getState().virtualItems.slice(0, 3)).toEqual(settled);
+ expect(live.getState().virtualItems.slice(0, 3).every((item, index) => item === settled[index])).toBe(true);
+ }
+ live.getState().clear();
+ });
+
+ it('preserves settled rows and groups across tail updates', () => {
+ const session = processingSession([
+ makeRound({ id: 'read', items: [makeReadTool('read')] }),
+ makeRound({ id: 'boundary', items: [makeTool('ask', 'AskUserQuestion')] }),
+ makeRound({ id: 'tail', items: [makeTextItem('tail', 'Answer')] }),
+ ]);
+ const before = projectSession(session);
+ const after = projectSession(updateTail(session));
+ expect(after.slice(0, 3).every((item, index) => item === before[index])).toBe(true);
+ expect(getVirtualItemFlowGroups(after[1])[0]).toBe(getVirtualItemFlowGroups(before[1])[0]);
+ expect(after.at(-1)).not.toBe(before.at(-1));
+ });
+
+ it.each(['steering', 'retry', 'recovery'])('reuses immutable %s display rounds during tail streaming', variant => {
+ const special = makeRound({ id: 'special', items: [makeTextItem('special-text', 'Previous output')] });
+ const tail = makeRound({ id: 'tail', items: [makeTextItem('tail-text', 'Answer')] });
+ const rounds = variant === 'steering'
+ ? [{ ...special, items: [...special.items, makeSteeringItem('steer')] }, tail]
+ : variant === 'retry'
+ ? [makeRound({ id: 'failed', status: 'error', roundGroupId: 'retry' }), { ...special, roundGroupId: 'retry' }, tail]
+ : [makeRound({ id: 'cancelled', status: 'cancelled' }), special, tail];
+ const session = processingSession(rounds);
+ if (variant === 'recovery') session.dialogTurns[0].recoveryEpoch = 1;
+ const original = JSON.stringify(session);
+ const before = projectSession(session);
+ const updated = updateTail(session);
+ const after = projectSession(updated);
+ const row = (items: VirtualItem[]) => items.find((item): item is ModelRoundVirtualItem => (
+ item.type === 'model-round' && item.data.id === 'special'
+ ))!;
+ expect(row(after).data).toBe(row(before).data);
+ expect(JSON.stringify(session)).toBe(original);
+ projectSession(null);
+ expect(after).toEqual(projectSession(structuredClone(updated)));
+ });
+
+ it('restores exact warm projections while keeping equal session ids on separate sources isolated', () => {
+ const local = makeSession();
+ const peer = makeSession();
+ peer.dialogTurns[0].userMessage.content = 'Peer prompt';
+ const localItems = projectSession(local);
+ const peerItems = projectSession(peer);
+ expect(peerItems).not.toEqual(localItems);
+ expect(projectSession(local)).toBe(localItems);
+ expect(projectSession(peer)).toBe(peerItems);
+ });
+
+ it('invalidates cached warm sessions when the presentation store is cleared', () => {
+ const session = makeSession();
+ const store = createModernFlowChatStore(session);
+ const before = store.getState().virtualItems;
+ store.getState().clear();
+ expect(store.getState().activeSession).toBeNull();
+ expect(store.getState().virtualItems).toEqual([]);
+ store.getState().setActiveSession(session);
+ const after = store.getState().virtualItems;
+ expect(after).toEqual(before);
+ expect(after).not.toBe(before);
+ });
+
+ it('keeps every completed-turn row when a newer message is appended', () => {
+ const project = createSessionVirtualItemProjector();
+ const session = makeSession();
+ const before = project(session);
+ const after = project({ ...session, dialogTurns: [...session.dialogTurns, {
+ ...session.dialogTurns[0], id: 'new-turn', status: 'processing', modelRounds: [],
+ userMessage: { id: 'new-message', content: 'Continue', timestamp: 2000 },
+ }] });
+ const retained = after.filter(item => item.turnId === session.dialogTurns[0].id);
+ expect(retained).toEqual(before);
+ expect(retained.every((item, index) => item === before[index])).toBe(true);
+ });
+
+ it('matches fresh projections through repeated thinking, tool-parameter, interior, rollback and completion updates', () => {
+ let seed = 3778;
+ const random = (max: number) => {
+ seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
+ return (seed >>> 8) % max;
+ };
+ const names = ['Read', 'ExecCommand', 'Edit', 'AskUserQuestion', 'ToolSearch'];
+ const thinking = (id: string): FlowThinkingItem => ({
+ id, type: 'thinking', timestamp: 1000, content: `Thinking ${id}`,
+ status: 'streaming', isStreaming: true, isCollapsed: true,
+ });
+ const params = (id: string): FlowToolItem => ({
+ ...makeTool(id, 'Read', 'preparing'), isParamsStreaming: true,
+ toolCall: { id, input: { file_path: 'part' } },
+ });
+ for (let scenario = 0; scenario < 150; scenario++) {
+ const project = createSessionVirtualItemProjector();
+ const rounds = Array.from({ length: 4 + random(8) }, (_, index) => makeRound({
+ id: `round-${index}`, index,
+ items: Array.from({ length: 1 + random(6) }, (_, member) => {
+ const kind = random(9);
+ const id = `${index}-${member}`;
+ return kind < 5 ? makeTool(id, names[kind]) : kind === 5
+ ? makeTextItem(id, `Paragraph ${id}`) : kind === 6
+ ? makeSteeringItem(id) : kind === 7 ? thinking(id) : params(id);
+ }),
+ }));
+ let session = processingSession(rounds);
+ project(session);
+ for (let step = 0; step < 8; step++) {
+ const turn = session.dialogTurns[0];
+ let nextRounds = [...turn.modelRounds];
+ const lastIndex = nextRounds.length - 1;
+ const targetIndex = step === 3 ? random(lastIndex) : lastIndex;
+ const target = nextRounds[targetIndex];
+ if (step === 2 || step === 6) {
+ nextRounds.push(makeRound({ id: `added-${step}`, status: 'streaming', isComplete: false,
+ isStreaming: true, items: [makeTool(`ask-${step}`, 'AskUserQuestion'), thinking(`new-${step}`)] }));
+ } else if (step === 5) {
+ nextRounds = nextRounds.slice(0, -1);
+ } else if (step === 4 || step === 7) {
+ nextRounds = nextRounds.map(round => ({ ...round, status: 'completed', isComplete: true, isStreaming: false,
+ items: round.items.map(item => ({ ...item, status: 'completed',
+ ...(item.type === 'text' || item.type === 'thinking' ? { isStreaming: false } : {}),
+ ...(item.type === 'tool' ? { isParamsStreaming: false } : {}),
+ })),
+ }));
+ } else {
+ nextRounds[targetIndex] = { ...target, status: 'streaming', isComplete: false, isStreaming: true,
+ items: [...target.items.map(item => item.type === 'thinking'
+ ? { ...item, content: item.content + ' continued', isStreaming: true }
+ : item.type === 'tool' ? { ...item, isParamsStreaming: true,
+ toolCall: { ...item.toolCall, input: { file_path: `changed-${step}` } } } : item),
+ step === 0 ? thinking(`think-${step}`) : params(`params-${step}`)],
+ };
+ }
+ session = { ...session, dialogTurns: [{ ...turn, modelRounds: nextRounds,
+ status: step === 7 ? 'completed' : 'processing',
+ }] };
+ const original = JSON.stringify(session);
+ const cached = project(session);
+ const fresh = createSessionVirtualItemProjector()(structuredClone(session));
+ expect(cached, `scenario ${scenario}, step ${step}`).toEqual(fresh);
+ expect(JSON.stringify(session)).toBe(original);
+ }
+ }
+ });
+
+});
+
+describe('projectSession unified work grouping', () => {
it('omits host GenUI repair input rows while retaining repair output and stored diagnostics', () => {
const session = makeSession();
const turn = session.dialogTurns[0];
turn.userMessage = { ...turn.userMessage, content: 'Internal rendering diagnostics', metadata: { genUIHostRepair: true } };
turn.modelRounds = [makeRound({ items: [makeTextItem('repair-result', 'Repaired UI')] })];
const original = JSON.stringify(session);
- const items = sessionToVirtualItems(session);
+ const items = projectSession(session);
expect(items.some(item => item.type === 'user-message')).toBe(false);
expect(items.some(item => item.type === 'model-round' && item.data.items.some(value => value.id === 'repair-result'))).toBe(true);
expect(JSON.stringify(session)).toBe(original);
- expect(sessionToVirtualItems({ ...session })).toEqual(items);
+ expect(projectSession({ ...session })).toEqual(items);
});
it('projects quiet runs as stable execution receipts without losing raw output or catalog positions', () => {
const session = makeSession();
@@ -135,13 +335,13 @@ describe('sessionToVirtualItems unified work grouping', () => {
turn.userMessage.metadata = { backgroundDelivery: { schemaVersion: 1, source: 'scheduled_job', taskId: 'generic-monitor', runId: turn.id, policy: 'conditional', disposition: 'quiet', resolvedAtMs: 1 } };
turn.modelRounds = [makeRound({ items: [makeTextItem('raw', 'Nothing changed; remaining silent.')] })];
const original = JSON.stringify(session.dialogTurns);
- const first = sessionToVirtualItems(session);
+ const first = projectSession(session);
expect(first).toHaveLength(1);
expect(first[0]).toMatchObject({ type: 'background-run', turnId: turn.id, absoluteTurnIndex: 1 });
expect(JSON.stringify(session.dialogTurns)).toBe(original);
- const refreshed = sessionToVirtualItems({ ...session });
+ const refreshed = projectSession({ ...session });
expect(refreshed[0]).toBe(first[0]);
- const withAttention = sessionToVirtualItems({ ...session, needsUserAttention: 'ask_user' });
+ const withAttention = projectSession({ ...session, needsUserAttention: 'ask_user' });
expect(withAttention.some(item => item.type === 'model-round')).toBe(true);
});
it.each([undefined, 'Minimal', 'Standard', 'agentic', 'Ultimate', 'Ultra', 'Creative', 'Claw', 'acp:codex'])(
@@ -157,7 +357,7 @@ describe('sessionToVirtualItems unified work grouping', () => {
makeRound({ id: 'shell', items: [makeTextItem('progress', 'Inspecting the build'), ...calls] }),
makeRound({ id: 'after', items: [makeReadTool('after-read')] }),
] };
- const rows = sessionToVirtualItems(session);
+ const rows = projectSession(session);
expect(rows.flatMap(getVirtualItemFlowGroups).map(group => group.allItems.map(item => item.id)))
.toEqual([['before-read', 'progress', ...calls.map(item => item.id), 'after-read']]);
const shellRow = rows.find((row): row is ModelRoundVirtualItem => row.type === 'model-round' && row.data.id === 'shell')!;
@@ -173,7 +373,7 @@ describe('sessionToVirtualItems unified work grouping', () => {
makeRound({ id: 'read', items: [makeReadTool('read'), makeTool('poll', 'WriteStdin')] }),
] };
const recorded = JSON.stringify(session);
- const rows = sessionToVirtualItems(session);
+ const rows = projectSession(session);
expect(rows.flatMap(getVirtualItemFlowGroups)).toMatchObject([{
groupId: 'shell:shell:command', category: 'explore',
allItems: [{ id: 'command' }, { id: 'read' }, { id: 'poll' }],
@@ -181,7 +381,7 @@ describe('sessionToVirtualItems unified work grouping', () => {
expect(rows.map(getVirtualItemStableKey)).toEqual([
'user-message:turn-1:user-1', 'model-round:turn-1:shell', 'model-round:turn-1:read',
]);
- expect(sessionToVirtualItems({ ...session, mode: 'Creative' })).toBe(rows);
+ expect(projectSession({ ...session, mode: 'Creative' })).toBe(rows);
expect(JSON.stringify(session)).toBe(recorded);
});
@@ -189,13 +389,13 @@ describe('sessionToVirtualItems unified work grouping', () => {
const session = makeSession();
session.dialogTurns[0] = { ...session.dialogTurns[0], agentType: 'Minimal',
modelRounds: [makeRound({ items: [makeTool('command', 'ExecCommand')] })] };
- const minimalRows = sessionToVirtualItems(session);
+ const minimalRows = projectSession(session);
const creative = { ...session, dialogTurns: [{ ...session.dialogTurns[0], agentType: 'Creative' }] };
- const creativeRows = sessionToVirtualItems(creative);
+ const creativeRows = projectSession(creative);
expect(minimalRows.flatMap(getVirtualItemFlowGroups)).toHaveLength(1);
expect(creativeRows.flatMap(getVirtualItemFlowGroups)).toEqual(minimalRows.flatMap(getVirtualItemFlowGroups));
expect(creativeRows.map(getVirtualItemStableKey)).toEqual(minimalRows.map(getVirtualItemStableKey));
- expect(sessionToVirtualItems(session).flatMap(getVirtualItemFlowGroups)).toEqual(minimalRows.flatMap(getVirtualItemFlowGroups));
+ expect(projectSession(session).flatMap(getVirtualItemFlowGroups)).toEqual(minimalRows.flatMap(getVirtualItemFlowGroups));
});
it('keeps exploration, Shell calls and intervening prose in one group when historical mode hints are missing or false', () => {
@@ -212,7 +412,7 @@ describe('sessionToVirtualItems unified work grouping', () => {
makeRound({ id: 'verification', items: [progress, ...commands.slice(2), answer] }),
];
const recorded = JSON.stringify(session);
- const rows = sessionToVirtualItems(session);
+ const rows = projectSession(session);
const groups = rows.flatMap(getVirtualItemFlowGroups);
expect(groups).toHaveLength(1);
expect(groups[0]).toMatchObject({ category: 'explore', groupId: 'exploration:explore:read-0' });
@@ -227,7 +427,7 @@ describe('sessionToVirtualItems unified work grouping', () => {
});
});
-describe('sessionToVirtualItems explore grouping', () => {
+describe('projectSession explore grouping', () => {
it('keeps retry controls as a boundary even when the successful attempt only explored', () => {
const session = makeSession();
const read = makeReadTool('retry-read');
@@ -237,7 +437,7 @@ describe('sessionToVirtualItems explore grouping', () => {
} },
{ id: 'ok', index: 1, status: 'completed', items: [read] },
] })];
- const rows = sessionToVirtualItems(session);
+ const rows = projectSession(session);
expect(rows.map(item => item.type)).toEqual(['user-message', 'model-round', 'model-round']);
expect(rows[2]).toMatchObject({ data: { id: 'retry', attempts: session.dialogTurns[0].modelRounds[1].attempts } });
});
@@ -263,7 +463,7 @@ describe('sessionToVirtualItems explore grouping', () => {
retry, makeRound({ id: 'next', items: [operation('next-call')] }),
];
const recorded = JSON.stringify(session);
- const rows = sessionToVirtualItems(session);
+ const rows = projectSession(session);
const groups = rows.flatMap(getVirtualItemFlowGroups);
expect(groups.map(group => group.category)).toEqual([category, category]);
expect(groups.map(group => group.allItems.map(item => item.id)))
@@ -291,7 +491,7 @@ describe('sessionToVirtualItems explore grouping', () => {
const session = makeSession();
session.dialogTurns[0].modelRounds = [retry, makeRound({ id: 'next', items: [makeReadTool('next-call')] })];
const recorded = JSON.stringify(session);
- const groups = sessionToVirtualItems(session).flatMap(getVirtualItemFlowGroups);
+ const groups = projectSession(session).flatMap(getVirtualItemFlowGroups);
expect(groups.map(group => group.allItems.map(item => item.id)))
.toEqual(source ? [['next-call']] : [['recovered', 'next-call']]);
expect(JSON.stringify(session)).toBe(recorded);
@@ -307,7 +507,7 @@ describe('sessionToVirtualItems explore grouping', () => {
] });
const session = makeSession();
session.dialogTurns[0].modelRounds = [round];
- const rows = sessionToVirtualItems(session);
+ const rows = projectSession(session);
expect(rows.flatMap(getVirtualItemFlowGroups)).toEqual([]);
expect(getProjectedModelRoundGroups(rows[1] as ModelRoundVirtualItem))
.toEqual([{ type: 'critical', item: active }]);
@@ -324,7 +524,7 @@ describe('sessionToVirtualItems explore grouping', () => {
];
session.dialogTurns[0].modelRounds = rounds;
const snapshot = JSON.stringify(rounds);
- const rows = sessionToVirtualItems(session);
+ const rows = projectSession(session);
expect(rows.map(item => item.type)).toEqual(['user-message', ...rounds.map(() => 'model-round')]);
const modelRows = rows.filter((item): item is ModelRoundVirtualItem => item.type === 'model-round');
const groups = modelRows.flatMap(item => getModelRoundExploreGroups(item.data, item.projectedGroups));
@@ -349,7 +549,7 @@ describe('sessionToVirtualItems explore grouping', () => {
}],
});
});
- const rows = sessionToVirtualItems(session).filter((item): item is ModelRoundVirtualItem => item.type === 'model-round');
+ const rows = projectSession(session).filter((item): item is ModelRoundVirtualItem => item.type === 'model-round');
expect(rows.map(row => row.data.id)).toEqual(['round-0', 'round-1', 'round-2']);
expect(rows.map(row => !!row.data.renderHints?.continuedAfterInterruption)).toEqual([false, true, true]);
expect(rows.every(row => row.data.attempts?.[0].diagnostic === undefined)).toBe(true);
@@ -368,11 +568,11 @@ describe('sessionToVirtualItems explore grouping', () => {
} },
{ id: 'success', index: 2, status: 'completed', items: [makeTextItem('result', 'Result')] },
] }), makeRound({ id: 'next', items: [makeTextItem('next-text', 'Next')] })];
- const rows = sessionToVirtualItems(session).filter((item): item is ModelRoundVirtualItem => item.type === 'model-round');
+ const rows = projectSession(session).filter((item): item is ModelRoundVirtualItem => item.type === 'model-round');
expect(rows.map(row => !!row.data.renderHints?.continuedAfterInterruption)).toEqual([true, false]);
expect(rows[0].data.attempts?.[0].diagnostic?.rawError).toBe('Provider unavailable');
delete turn.recoveryEpoch;
- expect(sessionToVirtualItems({ ...session, dialogTurns: [{ ...turn }] }).filter((item): item is ModelRoundVirtualItem => item.type === 'model-round')
+ expect(projectSession({ ...session, dialogTurns: [{ ...turn }] }).filter((item): item is ModelRoundVirtualItem => item.type === 'model-round')
.every(row => !row.data.renderHints?.continuedAfterInterruption)).toBe(true);
});
@@ -383,7 +583,7 @@ describe('sessionToVirtualItems explore grouping', () => {
it('groups normal rounds containing only collapsible tools', () => {
const session = makeSession({ sessionId: 'normal-session' });
- const items = sessionToVirtualItems(session);
+ const items = projectSession(session);
expect(items.map(item => item.type)).toEqual(['user-message', 'model-round']);
expect(items.flatMap(getVirtualItemFlowGroups)).toHaveLength(1);
@@ -397,7 +597,7 @@ describe('sessionToVirtualItems explore grouping', () => {
};
const round = makeRound({ items: [thinking, makeReadTool('tool')] });
session.dialogTurns[0].modelRounds = [round];
- const rows = sessionToVirtualItems(session);
+ const rows = projectSession(session);
expect(rows.map(item => item.type)).toEqual(['user-message', 'model-round']);
const row = rows[1] as ModelRoundVirtualItem;
expect(row.data).toBe(round);
@@ -427,7 +627,7 @@ describe('sessionToVirtualItems explore grouping', () => {
}],
});
- const items = sessionToVirtualItems(session);
+ const items = projectSession(session);
expect(items.map(item => item.type)).toEqual(['user-message', 'model-round']);
expect(items[1]).toMatchObject({
@@ -464,7 +664,7 @@ describe('sessionToVirtualItems explore grouping', () => {
}],
});
- expect(sessionToVirtualItems(session).map(item => item.type)).toEqual([
+ expect(projectSession(session).map(item => item.type)).toEqual([
'user-message',
'model-round',
]);
@@ -489,7 +689,7 @@ describe('sessionToVirtualItems explore grouping', () => {
}],
});
- expect(sessionToVirtualItems(session).map(item => item.type)).toEqual([
+ expect(projectSession(session).map(item => item.type)).toEqual([
'user-message',
'model-round',
]);
@@ -517,7 +717,7 @@ describe('sessionToVirtualItems explore grouping', () => {
}],
});
- expect(sessionToVirtualItems(session).map(item => item.type)).toEqual([
+ expect(projectSession(session).map(item => item.type)).toEqual([
'user-message',
'model-round',
]);
@@ -558,7 +758,7 @@ describe('sessionToVirtualItems explore grouping', () => {
},
});
- const userMessage = sessionToVirtualItems(session).find(item => item.type === 'user-message');
+ const userMessage = projectSession(session).find(item => item.type === 'user-message');
expect(userMessage).toMatchObject({
type: 'user-message',
@@ -608,9 +808,9 @@ describe('sessionToVirtualItems explore grouping', () => {
},
});
- const initialUserMessage = sessionToVirtualItems(initialSession)
+ const initialUserMessage = projectSession(initialSession)
.find(item => item.type === 'user-message');
- const repairedUserMessage = sessionToVirtualItems(repairedSession)
+ const repairedUserMessage = projectSession(repairedSession)
.find(item => item.type === 'user-message');
expect(initialUserMessage).toMatchObject({ absoluteTurnIndex: 20 });
@@ -641,7 +841,7 @@ describe('sessionToVirtualItems explore grouping', () => {
}],
});
- const items = sessionToVirtualItems(session);
+ const items = projectSession(session);
expect(items.map(item => item.type)).toEqual(['user-message', 'model-round']);
});
@@ -677,7 +877,7 @@ describe('sessionToVirtualItems explore grouping', () => {
}],
});
- const modelItem = sessionToVirtualItems(session)
+ const modelItem = projectSession(session)
.find((item): item is ModelRoundVirtualItem => item.type === 'model-round');
expect(modelItem).toMatchObject({
@@ -721,7 +921,7 @@ describe('sessionToVirtualItems explore grouping', () => {
}],
});
- const modelRounds = sessionToVirtualItems(session)
+ const modelRounds = projectSession(session)
.filter((item): item is ModelRoundVirtualItem => item.type === 'model-round');
if (status === 'completed') {
@@ -742,7 +942,7 @@ describe('sessionToVirtualItems explore grouping', () => {
config: { agentType: 'acp:opencode' },
});
- const items = sessionToVirtualItems(session);
+ const items = projectSession(session);
expect(items.map(item => item.type)).toEqual(['user-message', 'model-round']);
});
@@ -768,7 +968,7 @@ describe('sessionToVirtualItems explore grouping', () => {
}],
});
- const items = sessionToVirtualItems(session);
+ const items = projectSession(session);
expect(items.map(item => item.type)).toEqual(['user-message', 'model-round']);
});
@@ -813,14 +1013,14 @@ describe('sessionToVirtualItems explore grouping', () => {
}],
});
- const modelRounds = sessionToVirtualItems(session)
+ const modelRounds = projectSession(session)
.filter((item): item is ModelRoundVirtualItem => item.type === 'model-round');
expect(modelRounds.map(item => item.layoutHints?.expandedThinkingItemIds)).toEqual([
[],
['thinking-1'],
]);
- const finished = sessionToVirtualItems({
+ const finished = projectSession({
...session,
dialogTurns: session.dialogTurns.map(turn => ({
...turn,
@@ -867,7 +1067,7 @@ describe('sessionToVirtualItems explore grouping', () => {
}],
});
- const modelRound = sessionToVirtualItems(session)
+ const modelRound = projectSession(session)
.find((item): item is ModelRoundVirtualItem => item.type === 'model-round');
expect(modelRound?.layoutHints?.expandedThinkingItemIds).toEqual([]);
@@ -890,7 +1090,7 @@ describe('sessionToVirtualItems explore grouping', () => {
}],
});
- const items = sessionToVirtualItems(session);
+ const items = projectSession(session);
expect(items.map(item => item.type)).toEqual([
'user-message',
@@ -922,7 +1122,7 @@ describe('sessionToVirtualItems explore grouping', () => {
}],
});
- const items = sessionToVirtualItems(session);
+ const items = projectSession(session);
expect(items.map(item => item.type)).toEqual(['user-message', 'model-round']);
});
@@ -949,7 +1149,7 @@ describe('sessionToVirtualItems explore grouping', () => {
}],
});
- const items = sessionToVirtualItems(session);
+ const items = projectSession(session);
expect(items.map(item => item.type)).toEqual(['user-message', 'turn-failure-notice']);
expect(items[1]).toMatchObject({
@@ -967,7 +1167,7 @@ describe('sessionToVirtualItems explore grouping', () => {
it('keeps a quiet tail group collecting until the Turn is terminal', () => {
const session = makeSession();
session.dialogTurns[0].status = 'processing';
- const items = sessionToVirtualItems(session);
+ const items = projectSession(session);
expect(items.map(item => item.type)).toEqual(['user-message', 'model-round']);
expect(items.flatMap(getVirtualItemFlowGroups)[0]).toMatchObject({
phase: 'collecting', isGroupStreaming: false,
@@ -979,7 +1179,7 @@ describe('sessionToVirtualItems explore grouping', () => {
session.dialogTurns[0].status = 'processing';
session.dialogTurns[0].modelRounds.push(makeRound({ id: 'round-2',
items: [makeTool('tool-2', 'Read', 'running')], isComplete: false, isStreaming: false }));
- const items = sessionToVirtualItems(session);
+ const items = projectSession(session);
expect(items.map(item => item.type)).toEqual(['user-message', 'model-round', 'model-round']);
expect(items.flatMap(getVirtualItemFlowGroups)[0]).toMatchObject({
phase: 'collecting', isGroupStreaming: true,
@@ -996,7 +1196,7 @@ describe('sessionToVirtualItems explore grouping', () => {
isStreaming: true, isCollapsed: false, status: 'streaming', timestamp: 1002 };
session.dialogTurns[0].modelRounds.push(makeRound({ id: 'round-2',
items: [thought, makeTextItem('answer', 'The answer')], isComplete: false, isStreaming: true }));
- const items = sessionToVirtualItems(session);
+ const items = projectSession(session);
expect(items.flatMap(getVirtualItemFlowGroups)[0].allItems.map(item => item.id)).toEqual(['tool-1']);
expect((items[2] as ModelRoundVirtualItem).projectedGroups).toBeUndefined();
expect((items[2] as ModelRoundVirtualItem).data.items.map(item => item.id)).toEqual(['thinking-2', 'answer']);
@@ -1009,9 +1209,9 @@ describe('sessionToVirtualItems explore grouping', () => {
session.dialogTurns[0].modelRounds.push(makeRound({ id: 'round-2', items: [makeReadTool('tool-2')] }));
vi.useFakeTimers();
vi.setSystemTime(10_200);
- const before = sessionToVirtualItems(session);
+ const before = projectSession(session);
vi.setSystemTime(999_999);
- const after = sessionToVirtualItems({ ...session, dialogTurns: [{ ...session.dialogTurns[0] }] });
+ const after = projectSession({ ...session, dialogTurns: [{ ...session.dialogTurns[0] }] });
expect(after.map(getVirtualItemStableKey)).toEqual(before.map(getVirtualItemStableKey));
expect(after.flatMap(getVirtualItemFlowGroups)[0]).toMatchObject({
phase: 'collecting', allItems: [expect.objectContaining({ id: 'tool-1' }), expect.objectContaining({ id: 'tool-2' })],
@@ -1051,7 +1251,7 @@ describe('sessionToVirtualItems explore grouping', () => {
}],
});
- const streamingItems = sessionToVirtualItems(session);
+ const streamingItems = projectSession(session);
expect(streamingItems.map(item => item.type)).toEqual(['user-message', 'model-round']);
expect(streamingItems[1]).toMatchObject({
type: 'model-round',
@@ -1077,7 +1277,7 @@ describe('sessionToVirtualItems explore grouping', () => {
status: 'completed',
}],
});
- const settledItems = sessionToVirtualItems(settledSession);
+ const settledItems = projectSession(settledSession);
expect(settledItems.map(item => item.type)).toEqual(['user-message', 'model-round']);
expect(settledItems[1]).toMatchObject({
type: 'model-round',
@@ -1094,11 +1294,11 @@ describe('sessionToVirtualItems explore grouping', () => {
const session = makeSession();
session.dialogTurns[0].status = 'processing';
session.dialogTurns[0].modelRounds.push(makeRound({ id: 'round-2', items: [makeTool('tool-2', 'Read', 'running')] }));
- const active = sessionToVirtualItems(session);
+ const active = projectSession(session);
const completedTurn = { ...session.dialogTurns[0], modelRounds: [session.dialogTurns[0].modelRounds[0],
makeRound({ id: 'round-2', items: [makeReadTool('tool-2')] })] };
- const completed = sessionToVirtualItems({ ...session, dialogTurns: [completedTurn] });
- const ended = sessionToVirtualItems({ ...session, dialogTurns: [{ ...completedTurn, status: 'completed' }] });
+ const completed = projectSession({ ...session, dialogTurns: [completedTurn] });
+ const ended = projectSession({ ...session, dialogTurns: [{ ...completedTurn, status: 'completed' }] });
const group = active.flatMap(getVirtualItemFlowGroups)[0];
for (const rows of [completed, ended]) {
expect(rows.map(getVirtualItemStableKey)).toEqual(active.map(getVirtualItemStableKey));
@@ -1111,7 +1311,7 @@ describe('sessionToVirtualItems explore grouping', () => {
});
it('settles the tail group when its Turn completes', () => {
- const items = sessionToVirtualItems(makeSession());
+ const items = projectSession(makeSession());
expect(items.flatMap(getVirtualItemFlowGroups)[0]).toMatchObject({
phase: 'settled', isGroupStreaming: false, isLastGroupInTurn: true,
});
@@ -1120,8 +1320,8 @@ describe('sessionToVirtualItems explore grouping', () => {
it('preserves a settled group across a new Turn without reopening it', () => {
const session = makeSession();
const firstTurn = session.dialogTurns[0];
- const initial = sessionToVirtualItems(session);
- const next = sessionToVirtualItems({ ...session, dialogTurns: [firstTurn, { ...firstTurn,
+ const initial = projectSession(session);
+ const next = projectSession({ ...session, dialogTurns: [firstTurn, { ...firstTurn,
id: 'turn-2', status: 'processing', modelRounds: [makeRound({ id: 'round-2', items: [makeReadTool('tool-2')] })] }] });
expect(next.flatMap(getVirtualItemFlowGroups).map(group => group.phase)).toEqual(['settled', 'collecting']);
expect(next.flatMap(getVirtualItemFlowGroups)[0].groupId).toBe(initial.flatMap(getVirtualItemFlowGroups)[0].groupId);
@@ -1134,7 +1334,7 @@ describe('sessionToVirtualItems explore grouping', () => {
makeRound({ id: 'round-2', items: [makeTool('todo', 'TodoWrite')] }),
makeRound({ id: 'round-3', items: [makeTool('tool-3', 'Read', 'running')] }),
);
- const items = sessionToVirtualItems(session);
+ const items = projectSession(session);
expect(items.map(item => item.type)).toEqual(['user-message', 'model-round', 'model-round', 'model-round']);
expect(items.flatMap(getVirtualItemFlowGroups).map(group => group.phase)).toEqual(['settled', 'collecting']);
expect((items[2] as ModelRoundVirtualItem).projectedGroups).toBeUndefined();
@@ -1167,7 +1367,7 @@ describe('sessionToVirtualItems explore grouping', () => {
}],
});
- const items = sessionToVirtualItems(session);
+ const items = projectSession(session);
expect(items.map(item => item.type)).toEqual([
'user-message',
@@ -1218,7 +1418,7 @@ describe('sessionToVirtualItems explore grouping', () => {
}],
});
- const items = sessionToVirtualItems(session);
+ const items = projectSession(session);
const modelItems = items.filter((item): item is ModelRoundVirtualItem => item.type === 'model-round');
expect(modelItems.map(item => item.data.id)).toEqual(['large-round', 'tail-round']);
@@ -1251,7 +1451,7 @@ describe('sessionToVirtualItems explore grouping', () => {
}],
});
- const items = sessionToVirtualItems(session);
+ const items = projectSession(session);
const modelItems = items.filter((item): item is ModelRoundVirtualItem => item.type === 'model-round');
expect(modelItems).toHaveLength(1);
@@ -1286,7 +1486,7 @@ describe('sessionToVirtualItems explore grouping', () => {
}],
});
- const items = sessionToVirtualItems(session);
+ const items = projectSession(session);
const modelItems = items.filter(item => item.type === 'model-round');
expect(items.map(item => item.type)).toEqual(['user-message', 'model-round']);
@@ -1366,11 +1566,12 @@ describe('sessionToVirtualItems explore grouping', () => {
],
});
- const firstItems = sessionToVirtualItems(firstSession);
- const secondItems = sessionToVirtualItems(secondSession);
+ const firstItems = projectSession(firstSession);
+ const secondItems = projectSession(secondSession);
expect(secondItems[0]).toBe(firstItems[0]);
expect(secondItems[1]).toBe(firstItems[1]);
- expect(secondItems[2]).not.toBe(firstItems[2]);
+ expect(secondItems[2]).toBe(firstItems[2]); // The unchanged user message is independent of its reply.
+ expect(secondItems[3]).not.toBe(firstItems[3]);
});
});
diff --git a/src/web-ui/src/flow_chat/store/modernFlowChatStore.ts b/src/web-ui/src/flow_chat/store/modernFlowChatStore.ts
index 8ac8537529..0f9f170516 100644
--- a/src/web-ui/src/flow_chat/store/modernFlowChatStore.ts
+++ b/src/web-ui/src/flow_chat/store/modernFlowChatStore.ts
@@ -12,7 +12,7 @@ import { flowChatStore } from './FlowChatStore';
import { getTurnCompletionNotice } from '../utils/turnCompletionNotice';
import { createAbsoluteSessionTurnIndexResolver } from '../utils/flowChatTurnOrdinal';
import { getTurnOutputDurationMs, getTurnTtftMs } from '../utils/turnUsageMetrics';
-import { projectAdjacentFlowGroups } from '../grouping/groupProjection';
+import { projectAdjacentFlowGroups, canStartFreshFlowGroupRunAt } from '../grouping/groupProjection';
import { hasModelRoundNarrative } from '../grouping/roundGroups';
import { isSuppressedBackgroundTurn } from '../utils/backgroundDelivery';
@@ -50,8 +50,13 @@ function steeringItemToUserMessage(item: FlowUserSteeringItem): NonNullable>();
+
function mergeRoundGroupForDisplay(currentRound: ModelRound, nextRound: ModelRound): ModelRound {
- return {
+ let byNext = mergedRoundDisplayCache.get(currentRound);
+ const cached = byNext?.get(nextRound);
+ if (cached) return cached;
+ const merged = {
...nextRound,
historyRounds: [
...(currentRound.historyRounds ?? []),
@@ -61,6 +66,38 @@ function mergeRoundGroupForDisplay(currentRound: ModelRound, nextRound: ModelRou
},
],
};
+ if (!byNext) mergedRoundDisplayCache.set(currentRound, byNext = new WeakMap());
+ byNext.set(nextRound, merged);
+ return merged;
+}
+
+const normalizedRoundDisplayCache = new WeakMap();
+
+/** Immutable recorded rounds own both display variants, including retry repair. */
+function normalizeRoundForDisplay(round: ModelRound, continuedAfterInterruption: boolean): ModelRound {
+ let entry = normalizedRoundDisplayCache.get(round);
+ const variant = continuedAfterInterruption ? 'continued' : 'ordinary';
+ const cached = entry?.[variant];
+ if (cached) return cached;
+ const nonSteeringItems = round.items.filter(item => item.type !== 'user-steering');
+ let normalized = nonSteeringItems.length === round.items.length ? round : { ...round, items: nonSteeringItems };
+ // Older runtimes recorded a cancelled stream as a superseded retry.
+ // Repair only that terminal attempt in the display projection.
+ const lastAttempt = round.attempts?.reduce(
+ (last, attempt) => !last || attempt.index > last.index ? attempt : last, undefined,
+ );
+ if (round.status === 'cancelled' && lastAttempt?.diagnostic?.category === 'stream_error'
+ && lastAttempt.diagnostic.rawError?.startsWith('Cancelled: ')) {
+ normalized = { ...normalized, attempts: round.attempts?.map(attempt => (
+ attempt === lastAttempt ? { ...attempt, status: 'cancelled', diagnostic: undefined } : attempt
+ )) };
+ }
+ if (continuedAfterInterruption) {
+ normalized = { ...normalized, renderHints: { ...normalized.renderHints, continuedAfterInterruption: true } };
+ }
+ if (!entry) normalizedRoundDisplayCache.set(round, entry = {});
+ entry[variant] = normalized;
+ return normalized;
}
function isTerminalTurnStatus(status: DialogTurn['status']): boolean {
@@ -108,78 +145,350 @@ function isStableTurnProjection(turn: DialogTurn): boolean {
);
}
-let cachedSession: Session | null = null;
-let cachedDialogTurnsRef: DialogTurn[] | null = null;
-let cachedTurnCatalogRef: Session['turnCatalog'] | undefined;
-let cachedIsPartial: boolean | undefined;
-let cachedTotalTurnCount: number | undefined;
-let cachedNeedsUserAttention: Session['needsUserAttention'];
-let cachedVirtualItems: VirtualItem[] = [];
-let cachedTurnItems = new WeakMap<
- DialogTurn,
- { items: VirtualItem[]; hasNewerDialogTurn: boolean; absoluteTurnIndex: number; backgroundCollapsed?: boolean }
->();
+interface SessionProjectionCache {
+ turnCatalogRef: Session['turnCatalog'] | undefined;
+ isPartial: boolean | undefined;
+ totalTurnCount: number | undefined;
+ needsUserAttention: Session['needsUserAttention'];
+ virtualItems: VirtualItem[];
+}
-/**
- * Convert Session to virtualized render items
- *
- * Performance optimizations:
- * 1. Uses references directly, relies on FlowChatStore immutable updates to detect reference changes
- * 2. Memoization cache: only recalculates when dialogTurns reference changes
- *
- * Stable model-round rows host category groups from first execution through completion.
- */
-export function sessionToVirtualItems(session: Session | null): VirtualItem[] {
- if (!session) {
- if (cachedSession !== null) {
- cachedSession = null;
- cachedDialogTurnsRef = null;
- cachedTurnCatalogRef = undefined;
- cachedIsPartial = undefined;
- cachedTotalTurnCount = undefined;
- cachedVirtualItems = [];
- cachedTurnItems = new WeakMap();
+// Settled source Turns can be shared by live, history and side views without
+// making any one view the owner of another view's streaming state or body.
+type StableTurnPresentation = 'background' | 'normal';
+const cachedTurnItems = new WeakMap>();
+
+function rememberStableTurnItems(
+ turn: DialogTurn,
+ presentation: StableTurnPresentation,
+ absoluteTurnIndex: number,
+ items: VirtualItem[],
+): void {
+ let variants = cachedTurnItems.get(turn);
+ if (!variants) cachedTurnItems.set(turn, variants = new Map());
+ variants.set(presentation, { items, absoluteTurnIndex });
+}
+
+interface CachedTurnPrefixProjection {
+ turnId: string;
+ isTurnComplete: boolean;
+ turnStartedAt: number;
+ turnEndedAt: number | undefined;
+ turnOutputDurationMs: number | undefined;
+ turnTtftMs: number | undefined;
+ turnTokenUsage: DialogTurn['tokenUsage'];
+ rawItems: VirtualItem[];
+ projectedItems: VirtualItem[];
+}
+
+function sameStringList(a: readonly string[] | undefined, b: readonly string[] | undefined): boolean {
+ if (a === b) return true;
+ if (!a || !b || a.length !== b.length) return false;
+ for (let i = 0; i < a.length; i += 1) {
+ if (a[i] !== b[i]) return false;
+ }
+ return true;
+}
+
+function sameFlowGroupData(
+ a: import('../grouping/types').FlowGroupData | undefined,
+ b: import('../grouping/types').FlowGroupData | undefined,
+): boolean {
+ if (a === b) return true;
+ if (!a || !b) return false;
+ if (
+ a.groupId !== b.groupId ||
+ a.category !== b.category ||
+ a.isGroupStreaming !== b.isGroupStreaming ||
+ a.phase !== b.phase ||
+ a.needsAttention !== b.needsAttention ||
+ a.isLastGroupInTurn !== b.isLastGroupInTurn ||
+ a.wasCutByCritical !== b.wasCutByCritical ||
+ a.allItems.length !== b.allItems.length ||
+ a.rounds.length !== b.rounds.length ||
+ !sameStringList(a.sourceGroupIds, b.sourceGroupIds)
+ ) {
+ return false;
+ }
+ for (let i = 0; i < a.allItems.length; i += 1) {
+ if (a.allItems[i] !== b.allItems[i]) return false;
+ }
+ for (let i = 0; i < a.rounds.length; i += 1) {
+ if (a.rounds[i] !== b.rounds[i]) return false;
+ }
+ return true;
+}
+
+function sameProjectedGroups(
+ a: readonly import('../grouping/types').ModelRoundItemGroup[] | undefined,
+ b: readonly import('../grouping/types').ModelRoundItemGroup[] | undefined,
+): boolean {
+ if (a === b) return true;
+ if (!a || !b || a.length !== b.length) return false;
+ for (let i = 0; i < a.length; i += 1) {
+ const ga = a[i];
+ const gb = b[i];
+ if (ga === gb) continue;
+ if (ga.type !== gb.type) return false;
+ if (ga.type === 'critical' && gb.type === 'critical') {
+ if (ga.item !== gb.item) return false;
+ continue;
+ }
+ if (ga.type !== 'critical' && gb.type !== 'critical') {
+ if (
+ ga.isLast !== gb.isLast ||
+ ga.items.length !== gb.items.length ||
+ !sameFlowGroupData(ga.projection, gb.projection)
+ ) {
+ return false;
+ }
+ for (let j = 0; j < ga.items.length; j += 1) {
+ if (ga.items[j] !== gb.items[j]) return false;
+ }
+ }
+ }
+ return true;
+}
+
+function canReuseVirtualItem(prev: VirtualItem, next: VirtualItem): boolean {
+ if (prev === next) return true;
+ if (prev.type !== next.type || prev.turnId !== next.turnId) return false;
+ switch (next.type) {
+ case 'user-message': {
+ const p = prev as typeof next;
+ return (
+ p.data === next.data &&
+ p.absoluteTurnIndex === next.absoluteTurnIndex &&
+ p.turnStatus === next.turnStatus &&
+ p.submissionPhase === next.submissionPhase &&
+ p.submissionError === next.submissionError &&
+ p.hostQueueStatus === next.hostQueueStatus &&
+ p.hostQueueAttachmentCount === next.hostQueueAttachmentCount
+ );
+ }
+ case 'user-steering-message': {
+ const p = prev as typeof next;
+ return (
+ p.steeringId === next.steeringId &&
+ p.steeringStatus === next.steeringStatus &&
+ p.data.id === next.data.id &&
+ p.data.content === next.data.content &&
+ p.data.timestamp === next.data.timestamp
+ );
+ }
+ case 'model-round': {
+ const p = prev as typeof next;
+ return (
+ p.data === next.data &&
+ p.isLastRound === next.isLastRound &&
+ p.isTurnComplete === next.isTurnComplete &&
+ p.turnStartedAt === next.turnStartedAt &&
+ p.turnEndedAt === next.turnEndedAt &&
+ p.turnDurationMs === next.turnDurationMs &&
+ p.turnOutputDurationMs === next.turnOutputDurationMs &&
+ p.turnTtftMs === next.turnTtftMs &&
+ p.turnTokenUsage === next.turnTokenUsage &&
+ sameStringList(p.layoutHints?.expandedThinkingItemIds, next.layoutHints?.expandedThinkingItemIds) &&
+ sameProjectedGroups(p.projectedGroups, next.projectedGroups)
+ );
}
- return cachedVirtualItems;
+ default:
+ return false;
}
-
+}
+
+function reconcileProjectedGroupsInPlace(
+ prevGroups: readonly import('../grouping/types').ModelRoundItemGroup[] | undefined,
+ nextGroups: import('../grouping/types').ModelRoundItemGroup[] | undefined,
+): import('../grouping/types').ModelRoundItemGroup[] | undefined {
+ if (!prevGroups || !nextGroups) return nextGroups;
+ let allSame = prevGroups.length === nextGroups.length;
+ const minLen = Math.min(prevGroups.length, nextGroups.length);
+ for (let i = 0; i < minLen; i += 1) {
+ const pg = prevGroups[i];
+ const ng = nextGroups[i];
+ if (pg === ng) continue;
+ if (pg.type === ng.type) {
+ if (pg.type === 'critical' && ng.type === 'critical') {
+ if (pg.item === ng.item) {
+ nextGroups[i] = pg;
+ continue;
+ }
+ } else if (pg.type !== 'critical' && ng.type !== 'critical') {
+ if (sameFlowGroupData(pg.projection, ng.projection)) {
+ ng.projection = pg.projection;
+ }
+ if (
+ pg.isLast === ng.isLast &&
+ pg.items.length === ng.items.length &&
+ pg.projection === ng.projection &&
+ pg.items.every((item, idx) => item === ng.items[idx])
+ ) {
+ nextGroups[i] = pg;
+ continue;
+ }
+ }
+ }
+ allSame = false;
+ }
+ return allSame ? (prevGroups as import('../grouping/types').ModelRoundItemGroup[]) : nextGroups;
+}
+
+function reconcileTurnVirtualItems(prevItems: VirtualItem[] | undefined, nextItems: VirtualItem[]): VirtualItem[] {
+ if (!prevItems || prevItems.length === 0) {
+ return nextItems;
+ }
+ for (let i = 0; i < nextItems.length; i += 1) {
+ const candidate = prevItems[i];
+ if (candidate && canReuseVirtualItem(candidate, nextItems[i])) {
+ nextItems[i] = candidate;
+ } else if (nextItems[i].type === 'model-round' && candidate?.type === 'model-round') {
+ const prevRound = candidate;
+ const nextRound = nextItems[i] as typeof prevRound;
+ nextRound.projectedGroups = reconcileProjectedGroupsInPlace(
+ prevRound.projectedGroups,
+ nextRound.projectedGroups,
+ );
+ }
+ }
+ return nextItems;
+}
+
+function projectTurnItemsWithPrefixCache(
+ turn: DialogTurn,
+ rawTurnItems: VirtualItem[],
+ isTurnComplete: boolean,
+ turnOutputDurationMs: number | undefined,
+ turnTtftMs: number | undefined,
+ cachedTurnPrefixById: Map,
+): VirtualItem[] {
+ const prev = cachedTurnPrefixById.get(turn.id);
+ let reuseCount = 0;
+
if (
- cachedSession?.sessionId === session.sessionId &&
- cachedDialogTurnsRef === session.dialogTurns &&
- cachedTurnCatalogRef === session.turnCatalog &&
- cachedIsPartial === session.isPartial &&
- cachedTotalTurnCount === session.totalTurnCount && cachedNeedsUserAttention === session.needsUserAttention
+ prev &&
+ prev.isTurnComplete === isTurnComplete &&
+ prev.turnStartedAt === turn.startTime &&
+ prev.turnEndedAt === turn.endTime &&
+ prev.turnOutputDurationMs === turnOutputDurationMs &&
+ prev.turnTtftMs === turnTtftMs &&
+ prev.turnTokenUsage === turn.tokenUsage &&
+ prev.rawItems.length === prev.projectedItems.length
) {
- return cachedVirtualItems;
+ const limit = Math.min(prev.rawItems.length, rawTurnItems.length) - 1;
+ let commonLen = 0;
+ while (
+ commonLen < limit &&
+ canReuseVirtualItem(prev.rawItems[commonLen], rawTurnItems[commonLen])
+ ) {
+ commonLen += 1;
+ }
+ for (let k = commonLen - 1; k >= 2; k -= 1) {
+ if (canStartFreshFlowGroupRunAt(rawTurnItems[k - 1], rawTurnItems[k])) {
+ reuseCount = k;
+ break;
+ }
+ }
}
-
- cachedSession = session;
- cachedDialogTurnsRef = session.dialogTurns;
- cachedTurnCatalogRef = session.turnCatalog;
- cachedIsPartial = session.isPartial;
- cachedTotalTurnCount = session.totalTurnCount;
- cachedNeedsUserAttention = session.needsUserAttention;
+ const projectedTurnItems = reuseCount > 1 && prev
+ ? [
+ prev.projectedItems[0],
+ ...prev.projectedItems.slice(1, reuseCount),
+ ...projectAdjacentFlowGroups(rawTurnItems.slice(reuseCount), { isTurnComplete }),
+ ]
+ : projectAdjacentFlowGroups(rawTurnItems, { isTurnComplete });
+
+ const reconciled = reconcileTurnVirtualItems(prev?.projectedItems, projectedTurnItems);
+ cachedTurnPrefixById.set(turn.id, {
+ turnId: turn.id,
+ isTurnComplete,
+ turnStartedAt: turn.startTime,
+ turnEndedAt: turn.endTime,
+ turnOutputDurationMs,
+ turnTtftMs,
+ turnTokenUsage: turn.tokenUsage,
+ rawItems: rawTurnItems,
+ projectedItems: reconciled,
+ });
+ return reconciled;
+}
+
+/** Each mounted projection owns its mutable streaming prefix and warm snapshots. */
+export function createSessionVirtualItemProjector(): (session: Session | null) => VirtualItem[] {
+ let sessionId: string | null = null;
+ let previousProjection: SessionProjectionCache | undefined;
+ let warmProjections = new WeakMap();
+ const cachedTurnPrefixById = new Map();
+ const emptyItems: VirtualItem[] = [];
+
+ return (session: Session | null): VirtualItem[] => {
+ if (!session) {
+ sessionId = null;
+ previousProjection = undefined;
+ warmProjections = new WeakMap();
+ cachedTurnPrefixById.clear();
+ return emptyItems;
+ }
+ if (sessionId !== session.sessionId) cachedTurnPrefixById.clear();
+ sessionId = session.sessionId;
+ const restored = warmProjections.get(session.dialogTurns);
+ if (restored
+ && restored.turnCatalogRef === session.turnCatalog
+ && restored.isPartial === session.isPartial
+ && restored.totalTurnCount === session.totalTurnCount
+ && restored.needsUserAttention === session.needsUserAttention) {
+ // Returning to another snapshot must release the previous window's body.
+ if (restored !== previousProjection) cachedTurnPrefixById.clear();
+ previousProjection = restored;
+ return restored.virtualItems;
+ }
+
+ // Paging and rollback can discard Turns while this same view stays mounted.
+ const turnIds = new Set(session.dialogTurns.map(turn => turn.id));
+ for (const turnId of cachedTurnPrefixById.keys()) {
+ if (!turnIds.has(turnId)) cachedTurnPrefixById.delete(turnId);
+ }
+
+ const items = projectSessionItems(session, cachedTurnPrefixById);
+ const projection = {
+ turnCatalogRef: session.turnCatalog,
+ isPartial: session.isPartial,
+ totalTurnCount: session.totalTurnCount,
+ needsUserAttention: session.needsUserAttention,
+ virtualItems: items,
+ };
+ warmProjections.set(session.dialogTurns, projection);
+ previousProjection = projection;
+ return items;
+ };
+}
+
+function projectSessionItems(
+ session: Session,
+ cachedTurnPrefixById: Map,
+): VirtualItem[] {
const items: VirtualItem[] = [];
const resolveAbsoluteTurnIndex = createAbsoluteSessionTurnIndexResolver(session);
session.dialogTurns.forEach((turn, turnIndex) => {
- const hasNewerDialogTurn = turnIndex < session.dialogTurns.length - 1;
const absoluteTurnIndex = resolveAbsoluteTurnIndex(turnIndex);
const backgroundCollapsed = isSuppressedBackgroundTurn(turn) && !session.needsUserAttention;
- const cachedItems = cachedTurnItems.get(turn);
- if (
- cachedItems &&
- cachedItems.hasNewerDialogTurn === hasNewerDialogTurn &&
- cachedItems.absoluteTurnIndex === absoluteTurnIndex && Boolean(cachedItems.backgroundCollapsed) === Boolean(backgroundCollapsed)
- ) {
+ const presentation = backgroundCollapsed ? 'background' : 'normal';
+ const cachedItems = cachedTurnItems.get(turn)?.get(presentation);
+ if (cachedItems?.absoluteTurnIndex === absoluteTurnIndex) {
+ cachedTurnPrefixById.delete(turn.id);
items.push(...cachedItems.items);
return;
}
if (backgroundCollapsed) {
+ cachedTurnPrefixById.delete(turn.id);
const backgroundItems: VirtualItem[] = [{ type: 'background-run', data: turn.userMessage, turn, turnId: turn.id, absoluteTurnIndex, turnStatus: turn.status }];
items.push(...backgroundItems);
- if (isStableTurnProjection(turn)) cachedTurnItems.set(turn, { items: backgroundItems, hasNewerDialogTurn, absoluteTurnIndex, backgroundCollapsed: true });
+ if (isStableTurnProjection(turn)) rememberStableTurnItems(turn, presentation, absoluteTurnIndex, backgroundItems);
return;
}
const turnItemStart = items.length;
@@ -212,27 +521,8 @@ export function sessionToVirtualItems(session: Session | null): VirtualItem[] {
const continuedAfterInterruption = hasRecovery && continuationPending;
continuationPending ||= round.status === 'cancelled';
if (!round.items || round.items.length === 0) return;
- const nonSteeringItems = round.items.filter(item => item.type !== 'user-steering');
- if (nonSteeringItems.length > 0) {
- let normalizedRound = nonSteeringItems.length === round.items.length
- ? round
- : { ...round, items: nonSteeringItems };
- // Older runtimes recorded a cancelled stream as a superseded retry.
- // Repair only that terminal attempt in the display projection.
- const lastAttempt = round.attempts?.reduce(
- (last, attempt) => !last || attempt.index > last.index ? attempt : last, undefined,
- );
- if (round.status === 'cancelled' && lastAttempt?.diagnostic?.category === 'stream_error'
- && lastAttempt.diagnostic.rawError?.startsWith('Cancelled: ')) {
- normalizedRound = { ...normalizedRound, attempts: round.attempts?.map(attempt => (
- attempt === lastAttempt ? { ...attempt, status: 'cancelled', diagnostic: undefined } : attempt
- )) };
- }
- if (continuedAfterInterruption) {
- normalizedRound = { ...normalizedRound, renderHints: {
- ...normalizedRound.renderHints, continuedAfterInterruption: true,
- } };
- }
+ const normalizedRound = normalizeRoundForDisplay(round, continuedAfterInterruption);
+ if (normalizedRound.items.length > 0) {
continuationPending = round.status === 'cancelled';
const lastRenderEntry = renderEntries[renderEntries.length - 1];
@@ -260,7 +550,7 @@ export function sessionToVirtualItems(session: Session | null): VirtualItem[] {
renderEntries.push({ type: 'steering', item });
});
});
-
+
const isTurnComplete = turn.status === 'completed' || turn.status === 'cancelled' || turn.status === 'error';
const turnOutputDurationMs = getTurnOutputDurationMs(turn.modelRounds);
const turnTtftMs = getTurnTtftMs(turn.modelRounds);
@@ -338,23 +628,26 @@ export function sessionToVirtualItems(session: Session | null): VirtualItem[] {
});
}
- const projectedTurnItems = projectAdjacentFlowGroups(items.slice(turnItemStart), { isTurnComplete });
+ const projectedTurnItems = projectTurnItemsWithPrefixCache(
+ turn,
+ items.slice(turnItemStart),
+ isTurnComplete,
+ turnOutputDurationMs,
+ turnTtftMs,
+ cachedTurnPrefixById,
+ );
items.splice(turnItemStart, items.length - turnItemStart, ...projectedTurnItems);
if (isStableTurnProjection(turn)) {
- cachedTurnItems.set(turn, {
- items: items.slice(turnItemStart),
- hasNewerDialogTurn,
- absoluteTurnIndex,
- });
+ cachedTurnPrefixById.delete(turn.id);
+ rememberStableTurnItems(turn, presentation, absoluteTurnIndex, projectedTurnItems);
}
});
- cachedVirtualItems = items;
return items;
}
-function getInitialModernState(): Pick<
+function getInitialModernState(projectSession: ReturnType): Pick<
ModernFlowChatState,
'activeSession' | 'virtualItems' | 'visibleTurnInfo'
> {
@@ -365,64 +658,60 @@ function getInitialModernState(): Pick<
return {
activeSession,
- virtualItems: sessionToVirtualItems(activeSession),
+ virtualItems: projectSession(activeSession),
visibleTurnInfo: null,
};
}
-export const createModernFlowChatStore = (initialSession?: Session | null) => create()(
- (set, get) => ({
- ...(initialSession === undefined ? getInitialModernState() : {
- activeSession: initialSession,
- virtualItems: sessionToVirtualItems(initialSession),
- visibleTurnInfo: null,
- }),
-
- setActiveSession: (session) => {
- const items = sessionToVirtualItems(session);
- set((state) => ({
- ...(state.activeSession?.sessionId !== session?.sessionId ? { visibleTurnInfo: null } : null),
- activeSession: session,
- virtualItems: items,
- }));
- },
-
- updateVirtualItems: () => {
- const session = get().activeSession;
- const items = sessionToVirtualItems(session);
-
- set((state) => ({
- ...state,
- virtualItems: items,
- }));
- },
-
- setVisibleTurnInfo: (info) => {
- set((state) => ({
- ...state,
- visibleTurnInfo: info,
- }));
- },
-
- clear: () => {
- cachedSession = null;
- cachedDialogTurnsRef = null;
- cachedTurnCatalogRef = undefined;
- cachedIsPartial = undefined;
- cachedTotalTurnCount = undefined;
- cachedVirtualItems = [];
- cachedTurnItems = new WeakMap();
- cachedNeedsUserAttention = undefined;
-
- set((state) => ({
- ...state,
- activeSession: null,
- virtualItems: [],
+export const createModernFlowChatStore = (initialSession?: Session | null) => {
+ const projectSession = createSessionVirtualItemProjector();
+ return create()(
+ (set, get) => ({
+ ...(initialSession === undefined ? getInitialModernState(projectSession) : {
+ activeSession: initialSession,
+ virtualItems: projectSession(initialSession),
visibleTurnInfo: null,
- }));
- },
- })
-);
+ }),
+
+ setActiveSession: (session) => {
+ const items = projectSession(session);
+ set((state) => ({
+ ...(state.activeSession?.sessionId !== session?.sessionId ? { visibleTurnInfo: null } : null),
+ activeSession: session,
+ virtualItems: items,
+ }));
+ },
+
+ updateVirtualItems: () => {
+ const session = get().activeSession;
+ const items = projectSession(session);
+
+ set((state) => ({
+ ...state,
+ virtualItems: items,
+ }));
+ },
+
+ setVisibleTurnInfo: (info) => {
+ set((state) => ({
+ ...state,
+ visibleTurnInfo: info,
+ }));
+ },
+
+ clear: () => {
+ projectSession(null);
+
+ set((state) => ({
+ ...state,
+ activeSession: null,
+ virtualItems: [],
+ visibleTurnInfo: null,
+ }));
+ },
+ })
+ );
+};
const defaultModernFlowChatStore = createModernFlowChatStore();
export const ModernFlowChatStoreContext = createContext | null>(null);
diff --git a/src/web-ui/src/flow_chat/timeline/document.test.ts b/src/web-ui/src/flow_chat/timeline/document.test.ts
index 0a201f8a27..bc5276c40e 100644
--- a/src/web-ui/src/flow_chat/timeline/document.test.ts
+++ b/src/web-ui/src/flow_chat/timeline/document.test.ts
@@ -7,6 +7,7 @@ import { estimateVirtualItemHeight } from '../components/modern/virtualItemHeigh
import { buildInlineToolGroupData } from '../grouping/roundGroups';
import { toolCapsuleStateKey } from '../tool-cards/toolCapsuleModel';
import { localizeMarkdownMatch } from './markdownSectionSearch';
+import { getVirtualItemBookmarkKey } from '../components/modern/virtualItemIdentity';
const tool = (id: string, status: FlowToolItem['status'] = 'completed'): FlowToolItem => ({
id, type: 'tool', toolName: 'Read', timestamp: 1, status,
@@ -22,6 +23,61 @@ const agent = (id: string, toolName = 'AgentSpawn', status: FlowToolItem['status
});
describe('desktop conversation document', () => {
+ it('keeps measured section keys while adopting durable narrative IDs and a missing suffix', () => {
+ const content = 'A paragraph with some text.\n\n'.repeat(600);
+ const thought = { id: 'thinking-live', type: 'thinking', content: 'Reasoning.\n\nMore.', status: 'completed' } as FlowItem;
+ const text = { id: 'text-live', type: 'text', content, isMarkdown: true, status: 'completed', isStreaming: false } as FlowItem;
+ const projection = new ConversationDocumentProjection(), opts = options();
+ const live = projection.project([source([thought, text])], opts).filter(row => row.timeline?.markdownSection);
+ const durable = [{ ...thought, id: 'round-thinking-0', content: 'Reasoning.\n\n\nMore.' },
+ { ...text, id: 'round-text-1', content: content + 'Recovered suffix.\n\n'.repeat(400) }] as FlowItem[];
+ const incoming = source(durable);
+ const before = JSON.stringify(incoming);
+ const settled = projection.project([incoming], opts).filter(row => row.timeline?.markdownSection);
+ expect(settled.slice(0, live.length).map(row => row.timeline?.key)).toEqual(live.map(row => row.timeline?.key));
+ expect(settled[0].timeline?.memberIds).toEqual(['round-thinking-0', 'round-text-1']);
+ expect(settled.every(row => row.type === 'model-round' && row.data.items.at(-1) === durable[1])).toBe(true);
+ expect(findTimelineBlockIndex(settled, 0, 'round-text-1', settled[1].timeline!.markdownSection!.start)).toBe(1);
+ expect(JSON.stringify(incoming)).toBe(before);
+ // A repeated host read retains the alias; another view starts from canonical IDs.
+ expect(projection.project([source(durable.map(item => ({ ...item })))], opts).map(row => row.timeline?.key))
+ .toEqual(projection.project([incoming], opts).map(row => row.timeline?.key));
+ const reopened = new ConversationDocumentProjection().project([incoming], options());
+ expect(reopened[0].timeline?.key).toBe('turn:round-thinking-0');
+ expect(reopened.filter(row => row.timeline?.markdownSection).map(getVirtualItemBookmarkKey))
+ .toEqual(settled.map(getVirtualItemBookmarkKey));
+ });
+
+ it.each(['retry', 'replacement', 'insertion', 'tool', 'round', 'turn', 'eviction'] as const)(
+ 'does not alias unrelated narrative during %s', change => {
+ const text = { id: 'live', type: 'text', content: 'Original answer', status: 'completed', attemptId: 'attempt', attemptIndex: 0 } as FlowItem;
+ const projection = new ConversationDocumentProjection(), opts = options();
+ const before = source([text, tool('tool')]);
+ projection.project([before], opts);
+ const replacement = { ...text, id: 'durable', ...(change === 'retry' ? { attemptId: 'retry', attemptIndex: 1 }
+ : change === 'replacement' ? { content: 'Different answer' } : {}) } as FlowItem;
+ const after = source([replacement, tool(change === 'tool' ? 'other-tool' : 'tool'),
+ ...(change === 'insertion' ? [tool('inserted')] : [])]);
+ if (change === 'round') after.data = { ...after.data, id: 'another-round' };
+ if (change === 'turn') after.turnId = 'another-turn';
+ if (change === 'eviction') projection.project([], opts);
+ const rows = projection.project([after], opts);
+ expect(rows[findTimelineBlockIndex(rows, 0, 'durable')].timeline?.key).toBe(`${after.turnId}:durable`);
+ });
+
+ it('avoids duplicate display keys when a later canonical item uses an earlier alias', () => {
+ const projection = new ConversationDocumentProjection(), opts = options();
+ const text = { id: 'live', type: 'text', content: 'Answer', status: 'completed' } as FlowItem;
+ projection.project([source([text])], opts);
+ const durable = { ...text, id: 'durable' };
+ const settledSource = source([durable]);
+ expect(projection.project([settledSource], opts)[0].timeline?.key).toBe('turn:live');
+ const rows = projection.project([source([durable, { ...text, content: 'New text' } as FlowItem])], opts);
+ expect(new Set(rows.map(row => row.timeline?.key)).size).toBe(rows.length);
+ expect(rows[0].timeline?.key).toBe('turn:durable');
+ expect(projection.project([settledSource], opts)[0].timeline?.key).toBe('turn:durable');
+ });
+
it('windows large Markdown with canonical identity, bounded estimates and exact search occurrences', () => {
const content = Array.from({ length: 300 }, (_, i) => `Paragraph ${i}: fixture **text**.\n\n`).join('')
+ '\n```ts\n' + 'const example = 1;\n'.repeat(100) + '```\n\n' + 'End fixture.\n\n'.repeat(400);
diff --git a/src/web-ui/src/flow_chat/timeline/document.ts b/src/web-ui/src/flow_chat/timeline/document.ts
index e24aafab7a..f46c490bcb 100644
--- a/src/web-ui/src/flow_chat/timeline/document.ts
+++ b/src/web-ui/src/flow_chat/timeline/document.ts
@@ -11,6 +11,7 @@ import { getConcurrentCapsuleRows } from '../tool-cards/toolCapsuleLayout';
import { AGENT_CARD_BATCH_SIZE, isAgentCardRun, isAgentLaunchCard } from './agentCardLayout';
import { markdownSections } from '@/infrastructure/markdown/markdownSections';
import { parseDeepResearchContent } from '../deep-research/deepResearchProtocol';
+import { TimelineItemIdentity } from './timelineItemIdentity';
export interface TimelineProjectionOptions {
reader: FlowChatReaderState;
@@ -89,6 +90,7 @@ const emptyItems: FlowItem[] = [];
* even when a different leaf in the same live round receives another token.
*/
export class ConversationDocumentProjection {
+ private itemIdentity = new TimelineItemIdentity();
private previous = new Map();
private sourceCache = new WeakMap();
private next = new Map();
@@ -132,6 +134,7 @@ export class ConversationDocumentProjection {
project(sources: readonly VirtualItem[], options: TimelineProjectionOptions): VirtualItem[] {
const started = isStartupRenderTraceEnabled() ? performance.now() : undefined;
+ if (this.itemIdentity.reconcile(sources)) this.sourceCache = new WeakMap();
if (this.labels !== options.toolLabels) {
this.labels = options.toolLabels;
this.sourceCache = new WeakMap();
@@ -231,8 +234,8 @@ export class ConversationDocumentProjection {
const sections = text && text.isMarkdown
&& options.reader.get('navigation:whole-text', '') !== identity
&& !parseDeepResearchContent(text.content).hasProtocol ? markdownSections(text.content) : undefined;
- if (!sections) { add(kind, run[0].id, run, extra); return; }
- sections.forEach((section, index) => add(kind, index === 0 ? run[0].id : `${text!.id}:markdown:${section.start}`, index === 0 ? run : [text!], {
+ if (!sections) { add(kind, this.itemIdentity.key(run[0]), run, extra); return; }
+ sections.forEach((section, index) => add(kind, index === 0 ? this.itemIdentity.key(run[0]) : `${this.itemIdentity.key(text!)}:markdown:${section.start}`, index === 0 ? run : [text!], {
...extra, first: extra.first && index === 0, last: extra.last && index === sections.length - 1,
markdownSection: section,
}));
diff --git a/src/web-ui/src/flow_chat/timeline/timelineItemIdentity.ts b/src/web-ui/src/flow_chat/timeline/timelineItemIdentity.ts
new file mode 100644
index 0000000000..bbedcfbb6d
--- /dev/null
+++ b/src/web-ui/src/flow_chat/timeline/timelineItemIdentity.ts
@@ -0,0 +1,58 @@
+import type { FlowItem } from '../types/flow-chat';
+import type { VirtualItem } from '../types/flow-chat-projection';
+
+function sameNarrative(previous: FlowItem, next: FlowItem): boolean {
+ if ((previous.type !== 'text' && previous.type !== 'thinking') || next.type !== previous.type) return false;
+ if (previous.attemptId !== next.attemptId || previous.attemptIndex !== next.attemptIndex) return false;
+ if (!('content' in previous) || typeof previous.content !== 'string'
+ || !('content' in next) || typeof next.content !== 'string') return false;
+ // Live chunks coalesce blank lines; host records may retain them. A host can
+ // also supply a missing suffix, but replacing/retrying prose is a new block.
+ const before = previous.content.replace(/\n{3,}/g, '\n\n');
+ const after = next.content.replace(/\n{3,}/g, '\n\n');
+ return before.length > 0 && after.startsWith(before);
+}
+
+/** Presentation aliases for a live-to-durable item-id handoff, scoped to this view. */
+export class TimelineItemIdentity {
+ private sources = new Map();
+ private keys = new WeakMap();
+
+ /** True only when an existing object's alias changed, invalidating cached rows. */
+ reconcile(sources: readonly VirtualItem[]): boolean {
+ let cachedKeysChanged = false;
+ const nextSources = new Map();
+ for (const source of sources) {
+ if (source.type !== 'model-round' && source.type !== 'explore-group') continue;
+ const owner = JSON.stringify([source.turnId, source.type,
+ source.type === 'model-round' ? source.data.id : source.data.groupId]);
+ const items = source.type === 'model-round' ? source.data.items : source.data.allItems;
+ const previous = this.sources.get(owner);
+ nextSources.set(owner, items);
+ if (items === previous) continue;
+ const previousById = new Map(previous?.map(item => [item.id, item]));
+ const ids = new Set(items.map(item => item.id));
+ // Only a one-to-one, ordered replacement inside the same source can
+ // bridge different canonical IDs. Insertions, removals, moved IDs and
+ // tool replacements must keep their own identity.
+ const handoff = previous?.length === items.length && items.every((item, index) => {
+ const before = previous[index];
+ return item.id === before.id && item.type === before.type
+ || (!ids.has(before.id) && !previousById.has(item.id) && sameNarrative(before, item));
+ });
+ items.forEach((item, index) => {
+ const before = previousById.get(item.id) ?? (handoff ? previous![index] : undefined);
+ const key = before && before.type === item.type ? this.key(before) : this.key(item);
+ const nextKey = key !== item.id && ids.has(key) ? item.id : key;
+ const cachedKey = this.keys.get(item);
+ if (cachedKey !== undefined && cachedKey !== nextKey) cachedKeysChanged = true;
+ this.keys.set(item, nextKey);
+ });
+ }
+ // Evicted Turns retain neither their old source bodies nor alias records.
+ this.sources = nextSources;
+ return cachedKeysChanged;
+ }
+
+ key(item: FlowItem): string { return this.keys.get(item) ?? item.id; }
+}
diff --git a/src/web-ui/src/infrastructure/markdown/MarkdownMathRenderer.tsx b/src/web-ui/src/infrastructure/markdown/MarkdownMathRenderer.tsx
index a45303ac57..a4a121a56b 100644
--- a/src/web-ui/src/infrastructure/markdown/MarkdownMathRenderer.tsx
+++ b/src/web-ui/src/infrastructure/markdown/MarkdownMathRenderer.tsx
@@ -2,6 +2,7 @@ import React from 'react';
import ReactMarkdown from 'react-markdown';
import type { Components } from 'react-markdown';
import remarkGfm from 'remark-gfm';
+import { markdownGfmOptions } from './markdownGfmOptions';
import { remarkAutolinkBoundaries } from './remarkAutolinkBoundaries';
import { remarkStreamingTableLinks } from './remarkStreamingTableLinks';
import remarkMath from 'remark-math';
@@ -40,7 +41,7 @@ export const MarkdownMathRenderer: React.FC = ({
}) => {
const content = (
{
vi.clearAllMocks();
});
+ it.each([false, true])('keeps range tildes literal with streaming=%s and after completion', async isStreaming => {
+ const content = String.raw`24~30°C, rain 1~2mm; \~escaped\~; ~~removed~~; \~~literal\~~; ` + '`~code~`';
+ for (const streaming of [isStreaming, false]) {
+ await act(async () => root.render());
+ expect([...container.querySelectorAll('del')].map(node => node.textContent)).toEqual(['removed']);
+ expect(container.textContent).toContain('24~30°C, rain 1~2mm; ~escaped~; removed; ~~literal~~; ~code~');
+ }
+ });
+
+ it('uses the same tilde rules for math Markdown and thinking', async () => {
+ const { MarkdownMathRenderer } = await vi.importActual('./MarkdownMathRenderer');
+ const content = '24~30°C, rain 1~2mm; ~~removed~~';
+ await act(async () => root.render( {}} urlTransform={value => value} />));
+ expect([...container.querySelectorAll('del')].map(node => node.textContent)).toEqual(['removed']);
+ expect(container.textContent).toContain('24~30°C, rain 1~2mm');
+ expect(container.querySelector('.katex')).not.toBeNull();
+ for (const isStreaming of [true, false]) {
+ await act(async () => root.render());
+ expect([...container.querySelectorAll('del')].every(node => node.textContent === 'removed')).toBe(true);
+ expect(container.textContent).toContain('24~30°C, rain 1~2mm');
+ }
+ });
+
it('isolates a mixed reply at its text leaf while retaining hidden bodies and native cross-message ranges', async () => {
const styles = document.createElement('style');
styles.textContent = compile(resolve('src/flow_chat/components/FlowTextBlock.scss')).css
diff --git a/src/web-ui/src/infrastructure/markdown/MarkdownRenderer.tsx b/src/web-ui/src/infrastructure/markdown/MarkdownRenderer.tsx
index 5cd054499c..00cd18e4fa 100644
--- a/src/web-ui/src/infrastructure/markdown/MarkdownRenderer.tsx
+++ b/src/web-ui/src/infrastructure/markdown/MarkdownRenderer.tsx
@@ -10,6 +10,7 @@ import React, { useState, useMemo, useCallback, useEffect, useLayoutEffect, useR
import ReactMarkdown, { defaultUrlTransform } from 'react-markdown';
import { Icon, IconButton, Tooltip } from '@openbitfun/ui';
import remarkGfm from 'remark-gfm';
+import { markdownGfmOptions } from './markdownGfmOptions';
import { remarkCachedParse } from './markdownParseCache';
import { remarkAutolinkBoundaries } from './remarkAutolinkBoundaries';
import { remarkStreamingTableLinks } from './remarkStreamingTableLinks';
@@ -1762,7 +1763,7 @@ const MarkdownSurface = React.memo) => {
try { self.postMessage({ tree: parser.parse(event.data) }); }
catch { self.postMessage({}); }
diff --git a/src/web-ui/src/infrastructure/markdown/markdownParseCache.test.ts b/src/web-ui/src/infrastructure/markdown/markdownParseCache.test.ts
index b2bb4d8dba..bd818c0a9c 100644
--- a/src/web-ui/src/infrastructure/markdown/markdownParseCache.test.ts
+++ b/src/web-ui/src/infrastructure/markdown/markdownParseCache.test.ts
@@ -2,13 +2,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { unified } from 'unified';
import remarkParse from 'remark-parse';
import remarkGfm from 'remark-gfm';
+import { markdownGfmOptions } from './markdownGfmOptions';
import remarkRehype from 'remark-rehype';
import rehypeRaw from 'rehype-raw';
import rehypeSanitize from 'rehype-sanitize';
import { remarkCachedParse } from './markdownParseCache';
describe('immutable Markdown parse cache', () => {
- const source = `# Cached document\n\n${'Paragraph with **emphasis**.\n\n'.repeat(90)}
+ const source = `# Cached document\n\n${'Paragraph with **emphasis**, 24~30°C, rain 1~2mm and ~~removed~~.\n\n'.repeat(90)}
[reference][target] and footnote[^1]
| a | b |
@@ -21,8 +22,8 @@ describe('immutable Markdown parse cache', () => {
`;
it('preserves whole-document GFM references, footnotes, positions and independent trees', () => {
- const expected = unified().use(remarkParse).use(remarkGfm).parse(source);
- const parse = () => unified().use(remarkParse).use(remarkGfm).use(remarkCachedParse).parse(source);
+ const expected = unified().use(remarkParse).use(remarkGfm, markdownGfmOptions).parse(source);
+ const parse = () => unified().use(remarkParse).use(remarkGfm, markdownGfmOptions).use(remarkCachedParse).parse(source);
const first = parse();
expect(first).toEqual(expected);
first.children.length = 0;
@@ -30,7 +31,7 @@ describe('immutable Markdown parse cache', () => {
});
it('runs raw HTML handling and sanitization after a cache hit', () => {
- const pipeline = () => unified().use(remarkParse).use(remarkGfm).use(remarkCachedParse)
+ const pipeline = () => unified().use(remarkParse).use(remarkGfm, markdownGfmOptions).use(remarkCachedParse)
.use(remarkRehype, { allowDangerousHtml: true }).use(rehypeRaw).use(rehypeSanitize);
const render = () => { const processor = pipeline(); return processor.runSync(processor.parse(source)); };
const first = render();
@@ -90,8 +91,8 @@ describe('Markdown worker prewarming', () => {
expect(workers).toHaveLength(1);
expect(workers[0].terminate).toHaveBeenCalledOnce();
expect(workers[0].postMessage).toHaveBeenCalledTimes(1);
- const processor = unified().use(remarkParse).use(remarkGfm).use(cachedParse);
- expect(processor.parse(text)).toEqual(unified().use(remarkParse).use(remarkGfm).parse(text));
+ const processor = unified().use(remarkParse).use(remarkGfm, markdownGfmOptions).use(cachedParse);
+ expect(processor.parse(text)).toEqual(unified().use(remarkParse).use(remarkGfm, markdownGfmOptions).parse(text));
});
it('does not retry a worker whose constructor throws', async () => {
@@ -117,10 +118,10 @@ describe('Markdown worker prewarming', () => {
it('caches successful replies and can restart after normal idle termination', async () => {
const { prewarmMarkdownParse, remarkCachedParse: cachedParse } = await import('./markdownParseCache');
- const tree = unified().use(remarkParse).use(remarkGfm).parse(text);
+ const tree = unified().use(remarkParse).use(remarkGfm, markdownGfmOptions).parse(text);
prewarmMarkdownParse(text);
workers[0].onmessage!({ data: { tree } });
- const processor = unified().use(remarkParse).use(remarkGfm).use(cachedParse);
+ const processor = unified().use(remarkParse).use(remarkGfm, markdownGfmOptions).use(cachedParse);
expect(processor.parse(text)).toEqual(tree);
prewarmMarkdownParse(text);
expect(workers[0].postMessage).toHaveBeenCalledOnce();
diff --git a/src/web-ui/src/infrastructure/markdown/thinkingPreview.ts b/src/web-ui/src/infrastructure/markdown/thinkingPreview.ts
index 4e1ed283f0..b0c3e33e47 100644
--- a/src/web-ui/src/infrastructure/markdown/thinkingPreview.ts
+++ b/src/web-ui/src/infrastructure/markdown/thinkingPreview.ts
@@ -2,6 +2,7 @@ import type { BaseNode, ParsedNode } from 'stream-markdown-parser';
import { unified } from 'unified';
import remarkParse from 'remark-parse';
import remarkGfm from 'remark-gfm';
+import { markdownGfmOptions } from './markdownGfmOptions';
import remarkRehype from 'remark-rehype';
import rehypeRaw from 'rehype-raw';
import rehypeSanitize from 'rehype-sanitize';
@@ -36,7 +37,7 @@ const htmlBlocks = new Set(['address', 'article', 'aside', 'blockquote', 'detail
// Only exceptional HTML/file-image fragments use the existing safe Markdown
// pipeline. Ordinary streaming text stays on the incremental parser's AST.
-const fragmentParser = unified().use(remarkParse).use(remarkGfm)
+const fragmentParser = unified().use(remarkParse).use(remarkGfm, markdownGfmOptions)
.use(remarkRehype, { allowDangerousHtml: true }).use(rehypeRaw).use(rehypeSanitize);
function fragmentNodes(source: string): ParsedNode[] {
diff --git a/src/web-ui/src/shared/utils/resourceBudget.test.ts b/src/web-ui/src/shared/utils/resourceBudget.test.ts
index 9b059545d1..bb71242620 100644
--- a/src/web-ui/src/shared/utils/resourceBudget.test.ts
+++ b/src/web-ui/src/shared/utils/resourceBudget.test.ts
@@ -40,4 +40,42 @@ describe('application resource budget', () => {
cycle.self = cycle;
expect(estimateRetainedBytes(cycle)).toBeGreaterThan(0);
});
+
+ const round = (id: string, content: string, status = 'completed') => ({
+ id, status, isStreaming: status === 'streaming', isComplete: status === 'completed',
+ items: [{ id: `${id}-text`, type: 'text', content }],
+ });
+
+ it.each(['cancelled', 'error'])('counts the completed prefix before a %s round in a resumed turn', status => {
+ const content = 'x'.repeat(1024 * 1024);
+ const turn = { id: 'resumed', modelRounds: [
+ round('first', content), round('interrupted', 'partial', status),
+ round('resumed', 'continued'), round('tail', 'streaming', 'streaming'),
+ ] };
+ const bytes = estimateRetainedBytes(turn);
+ expect(bytes).toBeGreaterThan(content.length * 2);
+ expect(estimateRetainedBytes(turn)).toBe(bytes);
+ });
+
+ it('accounts immutable updates to an interior completed round', () => {
+ const rounds = ['first', 'middle', 'last', 'tail'].map(id => round(id, '', id === 'tail' ? 'streaming' : 'completed'));
+ const turn = { id: 'updated', modelRounds: rounds };
+ const before = estimateRetainedBytes(turn);
+ const content = 'x'.repeat(1024 * 1024);
+ const updated = { ...turn, modelRounds: rounds.map((value, index) => index === 1
+ ? { ...value, items: [{ ...value.items[0], content }] } : value) };
+ expect(estimateRetainedBytes(updated) - before).toBe(content.length * 2);
+ });
+
+ it('counts shared completed-round contents once even after separate measurements', () => {
+ const shared = { content: 'x'.repeat(4096) };
+ const completed = { ...round('shared', ''), items: [shared] };
+ const first = estimateRetainedBytes({ shared, completed });
+ estimateRetainedBytes(completed);
+ expect(estimateRetainedBytes({ shared, completed })).toBe(first);
+ expect(estimateRetainedBytes({ completed, shared })).toBe(first);
+ const seen = new Set