Skip to content

The agent that grows with you

test(desktop): real compaction lineages — rotated rows (#121148) and in-turn compaction handoff (#121088) as merge-order-safe KNOWN cells

teknium1552704e26d4c
diff --git a/apps/desktop/e2e/core/known.ts b/apps/desktop/e2e/core/known.ts
new file mode 100644
index 00000000000..2771f5bcbba
--- /dev/null
+++ b/apps/desktop/e2e/core/known.ts
@@ -0,0 +1,50 @@
+/**
+ * KNOWN bugs for the core suite: merge-order-safe expected failures, the
+ * Playwright twin of tests/e2e/core/_pending_fixes.py::known_failure.
+ *
+ * A strict marker (`test.fail()` up front, or an XPASS error) turns main red
+ * the moment the fix merges before this suite does, and accepts ANY failure
+ * (a dead backend, a timeout) as "the bug is still there". Instead only the
+ * final symptom assertion is wrapped (`expectNoSymptom`): when it fails with the bug's own
+ * message the test is marked expected-failing at run time; any other failure
+ * propagates; a clean pass stays a pass once the fix lands (then delete the
+ * KNOWN entry). Every wait must have settled before the wrapped assertion.
+ */
+
+import { expect, test } from '@playwright/test'
+
+/**
+ * The symptom assertion of a scenario. `symptom` is true when the bug's
+ * user-visible symptom was observed. With no KNOWN entry this is a plain
+ * `expect(symptom).toBe(false)`; with one (`known` = issue ref + one line),
+ * that same failure — and only it — becomes an expected failure.
+ */
+export function expectNoSymptom(known: string | undefined, symptom: boolean, what: string, detail = ''): void {
+ const check = () => expect(symptom, `${what}${detail ? `\n${detail}` : ''}`).toBe(false)
+
+ if (!known) {
+ check()
+
+ return
+ }
+
+ try {
+ check()
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error)
+
+ if (!message.includes(what)) {
+ throw error
+ }
+
+ test
+ .info()
+ .annotations.push({
+ type: 'known-bug',
+ description: `${known} [observed: ${what}${detail ? ` — ${detail.slice(0, 200)}` : ''}]`
+ })
+ test.fail(true, known)
+
+ throw error
+ }
+}
diff --git a/apps/desktop/e2e/core/lineage-compaction-prompt.spec.ts b/apps/desktop/e2e/core/lineage-compaction-prompt.spec.ts
new file mode 100644
index 00000000000..83088166131
--- /dev/null
+++ b/apps/desktop/e2e/core/lineage-compaction-prompt.spec.ts
@@ -0,0 +1,340 @@
+/**
+ * #121088 — an acknowledged Desktop prompt is appended a second time, after its
+ * own reply, when refreshed history carries synthetic user-role rows written by
+ * an in-place compaction inside that prompt's turn.
+ *
+ * Mechanism (apps/desktop/src/app/session/hooks/use-session-actions/utils.ts ::
+ * preserveLocalPendingTurnMessages): an optimistic prompt without a row-id
+ * receipt survives a refresh unless (a) its text equals `latestAuthoritativeUser`
+ * — the LAST user-role row of the refreshed tail — or (b) the user row at the
+ * same role ordinal pairs with it. Real processes produce both misses here:
+ *
+ * U3 turn: tool round (todo_list) pushes the request over threshold_tokens
+ * -> in-place compaction #1 appends the todo-snapshot user row S1
+ * -> the resumed stream is still running when …
+ * U4: … the user redirects (busy submit = correction, optimistic row, no
+ * row-id receipt) -> tool round -> in-place compaction #2 appends
+ * snapshot S2 after the committed U4 -> final reply A6.
+ *
+ * The live view never shows S1/S2 (not streamed). On the next refresh the
+ * stored history is [.., U3, A3i, S1, A5, U4, A4i, S2, A6]: S1 shifts U4's role
+ * ordinal onto S1 (miss b) and S2 is the latest user row (miss a), so the
+ * optimistic U4 is re-appended after A6.
+ *
+ * Compaction threshold is calibrated from a first throwaway session's real
+ * request size, so the config (written before the scenario session's agent is
+ * built) crosses threshold exactly at the two tool rounds regardless of how big
+ * the system prompt / tool schemas are on this commit.
+ */
+import fs from 'node:fs'
+import path from 'node:path'
+import { DatabaseSync } from 'node:sqlite'
+
+import { expect, type Page, test } from '@playwright/test'
+
+import {
+ coreAppEnv,
+ createCoreSandbox,
+ currentSessionId,
+ launchCoreApp,
+ recordWebSockets,
+ renderedTranscript,
+ send,
+ waitForInteractive,
+ writeProviderHome
+} from './harness'
+import { expectNoSymptom } from './known'
+import { installDuplicateSampler } from './oracle'
+import { gate, startScriptedProvider } from './provider'
+
+const KNOWN: Record<string, string | undefined> = {
+ dupPrompt:
+ '#121088 acknowledged redirect prompt re-appended after its reply when in-place compaction wrote synthetic user rows inside its turn'
+}
+
+const nonce = Math.random()
+ .toString(36)
+ .slice(2, 8)
+ .replace(/[^a-z0-9]/g, 'x')
+ .padEnd(4, 'q')
+
+const U = (n: number) => `U${n}-${nonce}`
+const A = (n: number) => `A${n}-${nonce}`
+const SNAPSHOT = '[Your active task list was preserved across context compression]'
+
+// Token budget (rough estimator ≈ chars/4) above the calibrated base request:
+// history 2×24k chars ≈ 12k < X=18k (turn-start preflight must NOT fire)
+// history + round ≈ 24k >= X (compaction #1 after the U3 tool round)
+// summary + tail(round) ≈ 13.5k < X (no re-fire after #1 / at the redirect)
+// 2 rounds ≈ 25.5k >= X (compaction #2 after the U4 tool round)
+const HISTORY_CHARS = 24_000
+const ROUND_CHARS = 48_000
+const HEADROOM_TOKENS = 18_000
+
+function filler(tag: string, chars: number): string {
+ const out: string[] = []
+ let len = 0
+
+ for (let i = 0; len < chars; i++) {
+ const word = `${tag}${i}`
+ out.push(word)
+ len += word.length + 1
+ }
+
+ return out.join(' ')
+}
+
+const compressionYaml = (thresholdTokens: number) =>
+ [
+ 'compression:',
+ ' in_place: true',
+ ` threshold_tokens: ${thresholdTokens}`,
+ ' tail_mode: legacy',
+ ' protect_first_n: 0',
+ ' protect_last_n: 2',
+ // todo_list is deferred behind tool_search by default; the scripted model calls it directly.
+ 'tools:',
+ ' tool_search:',
+ ' defer: []',
+ ''
+ ].join('\n')
+
+function viewport(page: Page) {
+ return page.locator('[data-slot="aui_thread-viewport"]').filter({ visible: true }).first()
+}
+
+async function settled(page: Page) {
+ await expect
+ .poll(() => page.locator('[data-slot="composer-root"] button[aria-label="Stop"]').count(), {
+ timeout: 90_000,
+ message: 'turn never settled'
+ })
+ .toBe(0)
+}
+
+async function openSession(page: Page, id: string) {
+ await page.evaluate(sid => {
+ window.location.hash = sid ? `#/${encodeURIComponent(sid)}` : '#/'
+ }, id)
+ await expect.poll(() => currentSessionId(page)).toBe(id)
+}
+
+interface Row {
+ active: number
+ content: string
+ id: number
+ role: string
+}
+
+function sessionRows(hermesHome: string, sid: string): Row[] {
+ const db = new DatabaseSync(path.join(hermesHome, 'state.db'), { readOnly: true })
+
+ try {
+ return db
+ .prepare(
+ "SELECT id, role, COALESCE(active, 1) AS active, COALESCE(content, '') AS content FROM messages WHERE session_id = ? ORDER BY id"
+ )
+ .all(sid) as unknown as Row[]
+ } finally {
+ db.close()
+ }
+}
+
+/** U4 as more than one user bubble, or a U4 user bubble after the final reply A6. */
+function dupShape(bubbles: { role: string; text: string }[]) {
+ const lastA6 = bubbles.findLastIndex(b => b.role === 'assistant' && b.text.includes(A(6)))
+ const afterReply = lastA6 >= 0 && bubbles.slice(lastA6 + 1).some(b => b.role === 'user' && b.text.includes(U(4)))
+ const userCopies = bubbles.filter(b => b.role === 'user' && b.text.includes(U(4))).length
+
+ return {
+ dup: afterReply || userCopies > 1,
+ afterReply,
+ userCopies,
+ tail: bubbles.slice(-4).map(b => `${b.role}: ${b.text.slice(0, 40)}`)
+ }
+}
+
+async function samplerHits(page: Page, marker: string): Promise<{ bubbles: string[]; count: number }[]> {
+ return page.evaluate(
+ m =>
+ ((window as any).__coreSampler?.violations ?? [])
+ .filter((v: any) => v.marker === m)
+ .map((v: any) => ({ bubbles: v.bubbles, count: v.count })),
+ marker
+ )
+}
+
+test('an acknowledged redirect prompt renders once after in-place compaction inside its turn (#121088)', async () => {
+ test.setTimeout(180_000)
+ const provider = await startScriptedProvider()
+ const sandbox = createCoreSandbox('lcp')
+ writeProviderHome(sandbox.hermesHome, provider.url, compressionYaml(250_000))
+ const { app, page } = await launchCoreApp(coreAppEnv(sandbox))
+ const ws = recordWebSockets(page)
+
+ try {
+ await waitForInteractive(app, page)
+ await installDuplicateSampler(page)
+
+ // ── Calibration session: measure the real base request, then write the threshold.
+ provider.script(U(0), [{ text: [`${A(0)} `, 'calibrated'] }])
+ await send(page, `${U(0)} calibrate`, 'Enter', ws)
+ await expect(viewport(page)).toContainText(A(0), { timeout: 60_000 })
+ await settled(page)
+ const calibration = provider.completions.find(c => c.marker === U(0))
+ expect(calibration, 'calibration request reached the provider').toBeTruthy()
+ const base = Math.ceil(JSON.stringify({ m: calibration!.body.messages, t: calibration!.body.tools }).length / 4)
+ writeProviderHome(sandbox.hermesHome, provider.url, compressionYaml(base + HEADROOM_TOKENS))
+
+ // ── Scenario session (fresh agent reads the calibrated config).
+ await openSession(page, '')
+ await expect(viewport(page)).not.toContainText(A(0))
+
+ // Summary requests are keyed by their first marker (U1 / U2 here), so these
+ // text-only replies double as the compaction summaries.
+ provider.script(U(1), [{ text: [`${A(1)} `, 'short ', 'reply'] }])
+ provider.script(U(2), [{ text: [`${A(2)} `, 'short ', 'reply'] }])
+
+ for (const n of [1, 2]) {
+ await send(page, `${U(n)} ${filler(`f${n}w`, HISTORY_CHARS)}`, 'Enter', ws)
+ await expect(viewport(page)).toContainText(A(n), { timeout: 60_000 })
+ await settled(page)
+ }
+
+ const sid = await currentSessionId(page)
+ expect(sid, 'scenario session id').not.toBe('')
+
+ const hold = gate()
+ provider.script(U(3), [
+ {
+ text: [`${A(3)}i `, filler('p', ROUND_CHARS)],
+ toolCalls: [
+ {
+ name: 'todo_list',
+ args: { todos: [{ id: '1', content: `${U(5)} draft the report`, status: 'in_progress' }] }
+ }
+ ]
+ },
+ { text: [`${A(3)} `, 'compaction ', 'one ', 'missed'] }
+ ])
+ // After compaction #1 the last user row is snapshot S1 (first marker U5).
+ provider.script(U(5), [{ text: [`${A(5)} `, 'slow ', 'after ', 'compaction'], holdAfterFirstChunk: hold }])
+ provider.script(U(4), [
+ {
+ text: [`${A(4)}i `, filler('q', ROUND_CHARS)],
+ toolCalls: [
+ {
+ name: 'todo_list',
+ args: { todos: [{ id: '1', content: `${U(6)} ship the report`, status: 'in_progress' }] }
+ }
+ ]
+ },
+ { text: [`${A(4)} `, 'compaction ', 'two ', 'missed'] }
+ ])
+ // After compaction #2 the last user row is snapshot S2 (first marker U6).
+ provider.script(U(6), [{ text: [`${A(6)} `, 'after ', 'second ', 'compaction'] }])
+
+ await send(page, `${U(3)} plan it`, 'Enter', ws)
+ await provider.streamStarted(U(5))
+ await expect(viewport(page)).toContainText(A(5), { timeout: 60_000 })
+
+ // Busy submit: the redirect correction, an optimistic row with no row-id receipt.
+ await send(page, `${U(4)} change course`, 'Enter', ws)
+ await expect
+ .poll(() => provider.completions.some(c => c.marker === U(6) && c.finished), {
+ timeout: 90_000,
+ message: 'post-compaction-#2 reply (keyed on snapshot S2) never finished'
+ })
+ .toBe(true)
+ hold.open()
+ await settled(page)
+ await expect(viewport(page)).toContainText(A(6), { timeout: 30_000 })
+
+ // ── Preconditions (ordinary): two in-place compactions committed inside the
+ // turn; stored history = committed U4, synthetic S1 before it, S2 after it.
+ const agentLog = fs.readFileSync(path.join(sandbox.hermesHome, 'logs', 'agent.log'), 'utf8')
+
+ const committed = agentLog
+ .split('\n')
+ .filter(l => l.includes(sid) && l.includes('"commit_status":"committed"') && l.includes('in_place_committed'))
+
+ expect(committed.length, 'two in-place compactions committed for the scenario session').toBe(2)
+
+ const summaries = provider.completions.filter(c =>
+ JSON.stringify(c.body.messages ?? '').includes('context checkpoint')
+ )
+
+ expect(
+ summaries.map(c => c.finished && !c.aborted),
+ 'two summary requests answered'
+ ).toEqual([true, true])
+ expect(
+ provider.completions.some(c => (c.marker === U(3) || c.marker === U(4)) && c.step === 1),
+ 'no un-compacted continuation'
+ ).toBe(false)
+
+ const active = sessionRows(sandbox.hermesHome, sid).filter(r => r.active === 1)
+ const users = active.filter(r => r.role === 'user')
+ const committedU4 = users.filter(r => r.content === `${U(4)} change course`)
+ expect(committedU4.length, 'the correction is committed exactly once in active history').toBe(1)
+ const s2 = users.find(r => r.content.startsWith(SNAPSHOT) && r.content.includes(U(6)))
+ expect(s2, 'snapshot S2 (synthetic user row) is active').toBeTruthy()
+ const a6 = active.find(r => r.role === 'assistant' && r.content.startsWith(A(6)))
+ expect(a6, 'final reply A6 is stored').toBeTruthy()
+ expect(committedU4[0].id < s2!.id && s2!.id < a6!.id, 'stored order: U4 < S2 < A6').toBe(true)
+ const all = sessionRows(sandbox.hermesHome, sid)
+
+ expect(
+ all.some(r => r.role === 'user' && r.content.startsWith(SNAPSHOT) && r.content.includes(U(5))),
+ 'snapshot S1 from compaction #1 is stored'
+ ).toBe(true)
+
+ // Observation 1: the settled live view. A turn-settle refresh may already
+ // have reconciled the stored history (timing-dependent), so it is part of
+ // the symptom window rather than an ordinary expect.
+ const live = dupShape((await renderedTranscript(page)).bubbles)
+
+ // ── Refresh through preserveLocalPendingTurnMessages: switch away and back.
+ await openSession(page, '')
+ await expect(viewport(page)).not.toContainText(A(6))
+ await openSession(page, sid)
+ // Refreshed stored history landed (only it carries S2), so the reconcile ran.
+ await expect(viewport(page).getByText(U(6)).first(), 'refreshed history renders snapshot S2').toBeVisible({
+ timeout: 60_000
+ })
+ await expect(viewport(page)).toContainText(A(6))
+
+ // Observation 2: the switch-back view; observation 3: every sampled frame
+ // since the redirect (the in-page sampler records transient duplicates).
+ const switched = dupShape((await renderedTranscript(page)).bubbles)
+ const hits = await samplerHits(page, U(4))
+ const symptom = live.dup || switched.dup || hits.some(h => h.bubbles.length > 1)
+ // ── Reload (no local optimistic state): stored history alone renders U4 once.
+ await page.reload()
+ await waitForInteractive(app, page)
+ await expect(viewport(page)).toContainText(A(6), { timeout: 60_000 })
+ const reloaded = await renderedTranscript(page)
+ expect(
+ reloaded.bubbles.filter(b => b.role === 'user' && b.text.includes(U(4))).length,
+ 'after reload, stored history renders U4 once'
+ ).toBe(1)
+ expect(
+ reloaded.bubbles
+ .slice(reloaded.bubbles.findLastIndex(b => b.text.includes(A(6))) + 1)
+ .some(b => b.role === 'user'),
+ 'after reload, no user bubble after the final reply'
+ ).toBe(false)
+
+ // Last: the KNOWN symptom (an expected failure while #121088 is open, a pass once fixed).
+ expectNoSymptom(
+ KNOWN.dupPrompt,
+ symptom,
+ 'the redirect prompt U4 renders as two user bubbles / a user bubble after its reply A6',
+ JSON.stringify({ live, switched, sampler: hits.slice(0, 2) })
+ )
+ } finally {
+ await app.close().catch(() => undefined)
+ await provider.close()
+ sandbox.cleanup()
+ }
+})
diff --git a/apps/desktop/e2e/core/lineage-rotation.spec.ts b/apps/desktop/e2e/core/lineage-rotation.spec.ts
new file mode 100644
index 00000000000..7f1855af012
--- /dev/null
+++ b/apps/desktop/e2e/core/lineage-rotation.spec.ts
@@ -0,0 +1,276 @@
+/**
+ * #121148 with REAL rotated session rows: one Electron app + one `hermes serve`,
+ * only the LLM is faked. `compression.in_place: false` + a low
+ * `threshold_tokens` make the backend's own auto-compaction rotate the live
+ * conversation mid-turn (parent sealed with end_reason='compression', a
+ * continuation row with parent_session_id = parent) — verified from state.db
+ * before anything is asserted about the sidebar.
+ *
+ * The sidebar runs in Project grouping (the persisted preference the grouping
+ * menu writes). The sandbox holds exactly one conversation, so every visible
+ * session row belongs to that one compression lineage.
+ *
+ * - KNOWN #121148 (last assertion, merge-order safe): while the conversation is live, the continuation renders
+ * as a `└─` branch row nested under its sealed parent (same shape as a
+ * user branch) — observed in a bounded window around the rotating turn.
+ * - Plain regression: after a reload the lineage is ONE sidebar row, it is
+ * the live tip (clicking it routes to the tip id from state.db) and it
+ * opens the continuation transcript.
+ *
+ * Not covered here: collapseCompressionLineages (session-branch-tree.ts). No
+ * real sequence tried (manual /compress, mid-turn auto-compaction, flat and
+ * Project grouping, pinned root, reload) ever put two rows with the same
+ * lineage key into the sidebar pool — the backend tip projection,
+ * mergeSessionPage's lineage dedupe and upsertResolvedSession already remove
+ * them — so sabotaging it does not turn this spec red.
+ */
+
+import { expect, type Page, test } from '@playwright/test'
+
+import {
+ coreAppEnv,
+ createCoreSandbox,
+ currentSessionId,
+ launchCoreApp,
+ recordWebSockets,
+ send,
+ storedSessionForMarker,
+ waitForInteractive,
+ writeProviderHome
+} from './harness'
+import { expectNoSymptom } from './known'
+import { startScriptedProvider } from './provider'
+import { messageRows, type SessionRow, sessionRows } from './remote-helpers'
+
+const KNOWN: Record<string, string> = {
+ continuationAsBranch:
+ '#121148 a compression continuation renders as a nested └─ branch row under its sealed parent (Project grouping)'
+}
+
+const nonce = Math.random()
+ .toString(36)
+ .slice(2, 8)
+ .replace(/[^a-z0-9]/g, 'x')
+ .padEnd(4, 'q')
+
+const U = (n: number) => `U${n}-${nonce}`
+const A = (n: number) => `A${n}-${nonce}`
+
+/** Bulky assistant prose: compaction only shrinks the transcript (and commits) when the replaced turns outweigh the summary wrapper. */
+const bulk = (tag: string) => Array.from({ length: 1500 }, (_, i) => `${tag}w${i}${'abcdefghij'[i % 10]}`).join(' ')
+
+function viewport(page: Page) {
+ return page.locator('[data-slot="aui_thread-viewport"]').filter({ visible: true }).first()
+}
+
+const ROW = '*:has(> [data-row-actions])'
+
+/** Visible sidebar SESSION rows (outermost [data-row-actions] owners that name this run's conversation, not project headers). */
+function sessionRowsInSidebar(page: Page) {
+ return page
+ .locator(`${ROW}:not(${ROW} *)`)
+ .filter({ visible: true })
+ .filter({ hasText: new RegExp(`-${nonce}\\b|Untitled`) })
+}
+
+/** In-page MutationObserver: the most session rows ever rendered at once, and their texts. */
+async function installRowCountSampler(page: Page) {
+ await page.evaluate(
+ ({ row, nonce }) => {
+ const re = new RegExp(`-${nonce}\\b|Untitled`)
+
+ const rec = { max: 0, atMax: [] as string[], samples: 0 }
+
+ ;(window as unknown as { __rotationRows: typeof rec }).__rotationRows = rec
+
+ const sample = () => {
+ rec.samples++
+
+ const texts = [...document.querySelectorAll<HTMLElement>(`${row}:not(${row} *)`)]
+ .filter(el => el.offsetParent !== null)
+ .map(el => el.innerText.replace(/\s+/g, ' ').trim())
+ .filter(text => re.test(text))
+
+ if (texts.length > rec.max) {
+ rec.max = texts.length
+ rec.atMax = texts.map(text => text.slice(0, 60))
+ }
+ }
+
+ new MutationObserver(sample).observe(document.body, {
+ attributes: true,
+ characterData: true,
+ childList: true,
+ subtree: true
+ })
+ sample()
+ },
+ { row: ROW, nonce }
+ )
+}
+
+async function readRowCountSampler(page: Page): Promise<{ max: number; atMax: string[]; samples: number }> {
+ return page.evaluate(
+ () => (window as unknown as { __rotationRows: { max: number; atMax: string[]; samples: number } }).__rotationRows
+ )
+}
+
+async function settled(page: Page) {
+ await expect
+ .poll(() => page.locator('[data-slot="composer-root"] button[aria-label="Stop"]').count(), {
+ timeout: 60_000,
+ message: 'turn settled'
+ })
+ .toBe(0)
+}
+
+/** The live tip of `rootId`'s compression lineage, walking state.db's compression edges. */
+function lineageFromDb(rows: SessionRow[], rootId: string): string[] {
+ const chain = [rootId]
+
+ for (;;) {
+ const cur = rows.find(r => r.id === chain[chain.length - 1])
+ const next = cur?.end_reason === 'compression' ? rows.find(r => r.parent_session_id === cur.id) : undefined
+
+ if (!next) {
+ return chain
+ }
+
+ chain.push(next.id)
+ }
+}
+
+test('lineage: a real compression rotation is one sidebar row per conversation (#121148)', async () => {
+ const provider = await startScriptedProvider()
+ const sandbox = createCoreSandbox('rotation')
+ writeProviderHome(
+ sandbox.hermesHome,
+ provider.url,
+ 'compression:\n in_place: false\n protect_first_n: 1\n protect_last_n: 1\n threshold_tokens: 24000\n'
+ )
+ const { app, page } = await launchCoreApp(coreAppEnv(sandbox))
+ const ws = recordWebSockets(page)
+
+ const turn = async (n: number, words: string) => {
+ provider.script(U(n), [{ text: [`${A(n)} `, `${bulk(`a${n}`)} `, 'done'] }])
+ await send(page, `${U(n)} ${words}`, 'Enter', ws)
+ await expect(viewport(page)).toContainText(A(n), { timeout: 60_000 })
+ await settled(page)
+ }
+
+ try {
+ await waitForInteractive(app, page)
+ // Project grouping, as the sidebar's grouping menu persists it.
+ await page.evaluate(() => localStorage.setItem('hermes.desktop.agentsGroupedByWorkspace', 'true'))
+ await page.reload()
+ await waitForInteractive(app, page)
+
+ let rootId = ''
+ let last = 0
+
+ await test.step('auto-compaction really rotates the live conversation (state.db)', async () => {
+ await turn(1, 'first question')
+ rootId = storedSessionForMarker(sandbox, 'default', U(1)) ?? ''
+ expect(rootId, 'U1 persisted').not.toBe('')
+ await expect(page.locator('[data-sessions-mode]').first()).toHaveAttribute('data-sessions-mode', 'projects', {
+ timeout: 30_000
+ })
+ await expect(sessionRowsInSidebar(page)).toHaveCount(1)
+ await installRowCountSampler(page)
+
+ for (last = 2; last <= 9; last++) {
+ await turn(last, `question number ${last}`)
+
+ if (sessionRows(sandbox).some(r => r.id === rootId && r.end_reason === 'compression')) {
+ break
+ }
+ }
+
+ const rows = sessionRows(sandbox)
+ expect(rows.find(r => r.id === rootId)?.end_reason, 'root sealed by compression').toBe('compression')
+ const continuation = rows.find(r => r.parent_session_id === rootId)
+ expect(continuation, 'continuation row with parent_session_id = root').toBeTruthy()
+ })
+
+ let seen = { max: 0, atMax: [] as string[], samples: 0 }
+
+ await test.step('observe the live sidebar around the rotation (#121148 window)', async () => {
+ // Bounded observation window (not synchronization): the rotating turn,
+ // 3 s idle, the follow-up turn (which normally rotates again), 3 s idle.
+ await page.waitForTimeout(3_000)
+ await turn(last + 1, 'after the rotation')
+ await page.waitForTimeout(3_000)
+ seen = await readRowCountSampler(page)
+ expect(seen.samples, 'row sampler observed the sidebar').toBeGreaterThan(0)
+ })
+
+ await test.step('after reload the lineage is one row: the live tip, opening the continuation', async () => {
+ const tip = lineageFromDb(sessionRows(sandbox), rootId).at(-1)!
+ expect(tip, 'rotation moved the tip off the root').not.toBe(rootId)
+ expect(
+ messageRows(sandbox, tip).some(m => m.role === 'user' && m.content.includes(U(last + 1))),
+ 'follow-up persisted on the tip'
+ ).toBe(true)
+
+ await page.reload()
+ await waitForInteractive(app, page)
+ await expect
+ .poll(async () => (await sessionRowsInSidebar(page).allInnerTexts()).map(t => t.replace(/\s+/g, ' ').trim()), {
+ timeout: 30_000,
+ message: 'one conversation → one sidebar row after rotation + reload'
+ })
+ .toHaveLength(1)
+
+ // Record every route the click produces: a stale root row would route to
+ // the sealed root first (the backend then redirects the resume to the tip).
+ await page.evaluate(() => {
+ window.location.hash = '#/'
+ })
+ await expect.poll(() => currentSessionId(page)).toBe('')
+ await page.evaluate(() => {
+ const w = window as unknown as { __routes: string[] }
+ w.__routes = []
+
+ const record = () => {
+ const id = decodeURIComponent(location.hash.replace(/^#\/?/, '').split('?')[0] ?? '')
+
+ if (w.__routes.at(-1) !== id) {
+ w.__routes.push(id)
+ }
+ }
+
+ for (const method of ['pushState', 'replaceState'] as const) {
+ const original = history[method].bind(history)
+
+ history[method] = (...args: Parameters<History['pushState']>) => {
+ original(...args)
+ record()
+ }
+ }
+
+ window.addEventListener('hashchange', record)
+ })
+ await sessionRowsInSidebar(page).first().click()
+ await expect
+ .poll(() => page.evaluate(() => (window as unknown as { __routes: string[] }).__routes.filter(Boolean)), {
+ timeout: 30_000,
+ message: 'the sidebar row IS the live tip: clicking it routes straight to the tip id'
+ })
+ .toEqual([tip])
+ await expect(viewport(page)).toContainText(A(last + 1), { timeout: 60_000 })
+ await expect(sessionRowsInSidebar(page)).toHaveCount(1)
+ })
+
+ // Last: the KNOWN symptom (an expected failure while #121148 is open, a pass once fixed).
+ expectNoSymptom(
+ KNOWN.continuationAsBranch,
+ seen.max > 1,
+ 'one conversation rendered as more than one sidebar row after a compression rotation',
+ `max ${seen.max} rows at once: ${JSON.stringify(seen.atMax)}`
+ )
+ } finally {
+ await app.close().catch(() => undefined)
+ await provider.close()
+ sandbox.cleanup()
+ }
+})
diff --git a/apps/desktop/e2e/core/lineage-sidebar.spec.ts b/apps/desktop/e2e/core/lineage-sidebar.spec.ts
index ce295c10032..edf7267c84a 100644
--- a/apps/desktop/e2e/core/lineage-sidebar.spec.ts
+++ b/apps/desktop/e2e/core/lineage-sidebar.spec.ts
@@ -1,19 +1,16 @@
/**
- * Session lineage and sidebar integrity after compaction and branching.
- * One real Electron app + one real `hermes serve`; only the LLM is faked.
+ * Session lineage and sidebar integrity for branches. One real Electron app +
+ * one real `hermes serve`; only the LLM is faked.
*
- * - compaction that rotates the session (compression.in_place: false) is a
- * CONTINUATION: the sidebar keeps one row for the conversation, never a
- * parent + child branch pair (#121148);
- * - the prompt acknowledged right after compaction renders exactly once,
- * live and after a reload (#121088);
* - a branch child is born with a title (#121062) and is a sidebar row of
* its own;
- * - switching between the branch and its parent never renders the other
- * session's (stale) turns or duplicates a part (#121096).
+ * - switching between the branch and its parent (3 round trips, then a
+ * reload) never renders the other session's turns or duplicates a part.
*
- * No KNOWN entries: every scenario is green on main. A bug found later is
- * marked with test.fail() + the issue ref (strict: red once fixed).
+ * Compaction lineages live in lineage-rotation.spec.ts (#121148) and
+ * lineage-compaction-prompt.spec.ts (#121088). The #121096 mechanism
+ * (index-keyed response-group children) is NOT reached by this switching
+ * scenario — see the PR's NOT COVERED list.
*/
import { expect, type Page, test } from '@playwright/test'
@@ -54,10 +51,6 @@ function sidebarRows(page: Page) {
return page.locator(`${row}:not(${row} *)`).filter({ visible: true })
}
-async function sidebarRowTexts(page: Page): Promise<string[]> {
- return (await sidebarRows(page).allInnerTexts()).map(text => text.replace(/\s+/g, ' ').trim())
-}
-
/** Markers of every user bubble, in order, and how often each assistant marker renders. */
async function renderedMarkers(page: Page): Promise<{ users: string[]; assistants: string[] }> {
const { bubbles } = await renderedTranscript(page)
@@ -70,16 +63,6 @@ async function renderedMarkers(page: Page): Promise<{ users: string[]; assistant
}
}
-const isSummary = (c: { body: any }) => JSON.stringify(c.body?.messages ?? '').includes('context checkpoint')
-
-async function composeSlash(page: Page, command: string) {
- const box = page.locator('[data-slot="composer-root"] [contenteditable="true"]').filter({ visible: true }).first()
- await box.click()
- await page.keyboard.insertText(command)
- await expect.poll(() => box.textContent()).toContain(command.slice(1))
- await page.getByRole('button', { name: 'Send', exact: true }).click()
-}
-
async function settled(page: Page) {
await expect
.poll(() => page.locator('[data-slot="composer-root"] button[aria-label="Stop"]').count(), {
@@ -97,14 +80,10 @@ async function openSession(page: Page, sessionId: string, mustShow: string) {
await expect(viewport(page)).toContainText(mustShow, { timeout: 60_000 })
}
-test('lineage: compaction continuation and branch children keep one coherent sidebar', async () => {
+test('lineage: a branch child is its own titled row and switching never leaks turns', async () => {
const provider = await startScriptedProvider()
const sandbox = createCoreSandbox('lineage')
- writeProviderHome(
- sandbox.hermesHome,
- provider.url,
- 'compression:\n in_place: false\n protect_first_n: 1\n protect_last_n: 1\n'
- )
+ writeProviderHome(sandbox.hermesHome, provider.url)
const { app, page } = await launchCoreApp(coreAppEnv(sandbox))
const ws = recordWebSockets(page)
@@ -128,68 +107,10 @@ test('lineage: compaction continuation and branch children keep one coherent sid
await waitForInteractive(app, page)
await installDuplicateSampler(page)
- let rootId = ''
-
- await test.step('compaction continuation stays one sidebar row (#121148)', async () => {
+ await test.step('a parent conversation with two turns', async () => {
await turn(1, 'first question here')
- rootId = storedSessionForMarker(sandbox, 'default', U(1)) ?? ''
- expect(rootId).not.toBe('')
await turn(2, 'second question here')
- await turn(3, 'third question here')
await expect.poll(() => sidebarRows(page).count()).toBe(1)
-
- const summariesBefore = provider.completions.filter(isSummary).length
- await composeSlash(page, '/compress keep the question markers')
- await expect
- .poll(() => provider.completions.filter(c => isSummary(c) && c.finished).length, {
- timeout: 90_000,
- message: 'the compaction summary was generated'
- })
- .toBeGreaterThan(summariesBefore)
- await settled(page)
- await turn(4, 'after the compaction')
- const continuation = storedSessionForMarker(sandbox, 'default', U(4))
- expect(continuation, 'follow-up persisted').not.toBeNull()
- const rotated = continuation !== rootId
- test.info().annotations.push({ type: 'compaction', description: rotated ? 'rotated' : 'in place' })
-
- if (rotated) {
- expect(sessionRows(sandbox).find(r => r.id === continuation)?.parent_session_id).toBe(rootId)
- }
-
- await expect
- .poll(() => sidebarRowTexts(page), {
- timeout: 30_000,
- message: 'one conversation → one sidebar row after compaction'
- })
- .toHaveLength(1)
- })
-
- await test.step('the prompt acknowledged after compaction renders once (#121088)', async () => {
- const live = await renderedMarkers(page)
- expect(
- live.users.filter(m => m === U(4)),
- 'live: U4 rendered once'
- ).toHaveLength(1)
- expect(
- live.assistants.filter(m => m === A(4)),
- 'live: A4 rendered once'
- ).toHaveLength(1)
- expect(live.users.indexOf(U(4)), 'U4 is the last user bubble').toBe(live.users.length - 1)
-
- await page.reload()
- await waitForInteractive(app, page)
- await installDuplicateSampler(page)
- await expect(viewport(page)).toContainText(A(4), { timeout: 60_000 })
- const cold = await renderedMarkers(page)
- expect(
- cold.users.filter(m => m === U(4)),
- 'reload: U4 rendered once'
- ).toHaveLength(1)
- expect(
- cold.assistants.filter(m => m === A(4)),
- 'reload: A4 rendered once'
- ).toHaveLength(1)
})
let branchId = ''
@@ -225,9 +146,9 @@ test('lineage: compaction continuation and branch children keep one coherent sid
await expect.poll(() => sidebarRows(page).count(), { timeout: 30_000 }).toBe(2)
})
- await test.step('switching branch ↔ parent never renders stale or duplicated parts (#121096)', async () => {
+ await test.step("switching branch ↔ parent never renders the other session's turn or a duplicate part", async () => {
for (let round = 0; round < 3; round++) {
- await openSession(page, parentId, A(4))
+ await openSession(page, parentId, A(2))
const parent = await renderedMarkers(page)
expect(parent.users, `round ${round}: parent never shows the branch turn`).not.toContain(U(5))
expect(new Set(parent.assistants).size, `round ${round}: parent assistant parts unique`).toBe(
@@ -245,6 +166,10 @@ test('lineage: compaction continuation and branch children keep one coherent sid
)
}
+ // Every frame sampled across the switches (transient duplicates included).
+ const violations = await page.evaluate(() => (window as any).__coreSampler?.violations ?? [])
+ expect(violations, 'no marker rendered twice in any sampled frame').toEqual([])
+
await page.reload()
await waitForInteractive(app, page)
await expect.poll(() => sidebarRows(page).count(), { timeout: 30_000 }).toBe(2)