The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(desktop-core): transcript oracle across every chat transition (C2)
teknium18fb196b3b6fa
diff --git a/apps/desktop/e2e/core/README.md b/apps/desktop/e2e/core/README.mdnew file mode 100644index 00000000000..7dd68d731ad--- /dev/null+++ b/apps/desktop/e2e/core/README.md@@ -0,0 +1,42 @@+# Desktop core suite (required CI lane)++A small, deterministic Electron suite that guards two issue classes end to end:++- **C2 transcript integrity** — `transcript-integrity.spec.ts`: one real app ++ one real `hermes serve`, only the LLM faked (`provider.ts`, scripted per turn+ by a unique marker, every streamed chunk recorded). After every transition —+ stream, tool-call turn, reasoning turn, steer, queued follow-up, session+ switch mid-stream, warm resume, reload, WebSocket drop + reconnect mid-stream,+ a non-default profile's chat, a forced second socket to the same backend,+ final reload — `oracle.ts` asserts:+ - every persisted user/assistant message is rendered exactly once, in order,+ and nothing unpersisted is rendered;+ - no marker is ever rendered twice, even transiently (in-page+ MutationObserver sampler — the #120005 garble healed on its own in the+ final DOM, so a final-state check alone misses it);+ - backend stream integrity: each turn's concatenated `message.delta` /+ `reasoning.delta` equals what the provider streamed, and+ `message.complete` equals the final completion.+- **C5 boot / process lifecycle** — `boot-lifecycle.spec.ts`: interactive+ composer + first turn, exactly one backend; `kill -9` backend → exactly one+ supervised respawn and a working turn; quit mid-turn with a running tool+ child → zero sandbox processes (/proc census on the sandbox `HERMES_HOME`,+ so orphans reparented to init are counted); relaunch the same home 3× → one+ backend per boot, zero after each quit, transcript cold-hydrates once.++Rules the suite keeps (why the old lane was disabled): no fixed sleeps as+synchronisation (every wait is on a frame, pid, DOM state or persisted row+with a deadline), no shared mock state between scenarios (replies are keyed+by the turn's own marker), no visual baselines, `retries: 0`, one worker,+sandboxed `HOME`/`HERMES_HOME`/user-data per test, all `HERMES_*` and+credential env stripped from the spawned app.++Run locally (Linux, after `npm run build` in `apps/desktop`):++```sh+cd apps/desktop+xvfb-run -a npx playwright test -c e2e/core/playwright.config.ts+```++`HERMES_E2E_CORE_ROOT` picks the sandbox parent dir (default: OS tmpdir);+`HERMES_E2E_CORE_KEEP=1` keeps sandboxes for post-mortem.diff --git a/apps/desktop/e2e/core/harness.ts b/apps/desktop/e2e/core/harness.tsnew file mode 100644index 00000000000..8042a45e6b2--- /dev/null+++ b/apps/desktop/e2e/core/harness.ts@@ -0,0 +1,580 @@+/**+ * Lane-private harness for the core Desktop suite: an isolated sandbox with a+ * fake HOME, a launch helper, a per-socket WebSocket recorder, a /proc-based+ * process census for the backend, and the transcript oracle.+ *+ * Synchronisation rule for every helper here: wait on an observable fact+ * (a frame, a DOM state, a persisted row, a pid) with a deadline — never a+ * fixed sleep.+ */++import * as fs from 'node:fs'+import * as net from 'node:net'+import * as os from 'node:os'+import * as path from 'node:path'+import { DatabaseSync } from 'node:sqlite'++import { _electron, type ElectronApplication, expect, type Page } from '@playwright/test'++import { resolveElectronBinary } from '../electron-binary'++export const DESKTOP_ROOT = path.resolve(import.meta.dirname, '..', '..')+export const REPO_ROOT = path.resolve(DESKTOP_ROOT, '..', '..')++// ─── Sandbox ────────────────────────────────────────────────────────────++export interface CoreSandbox {+ root: string+ /** Prepended to PATH: external-platform fakes (see createCoreSandbox). */+ bin: string+ home: string+ hermesHome: string+ userDataDir: string+ cleanup: () => void+}++/**+ * HOME is faked too, not just HERMES_HOME: profile roots are anchored to+ * `Path.home()/.hermes`, so a sandbox HERMES_HOME under the real ~/.hermes+ * would read and write the real install's profiles/.+ */+export function createCoreSandbox(label: string): CoreSandbox {+ const parent = process.env.HERMES_E2E_CORE_ROOT || os.tmpdir()+ fs.mkdirSync(parent, { recursive: true })+ const root = fs.mkdtempSync(path.join(parent, `core-${label}-`))+ const home = path.join(root, 'home')+ const hermesHome = path.join(home, '.hermes')+ const userDataDir = path.join(root, 'user-data')+ fs.mkdirSync(hermesHome, { recursive: true })+ fs.mkdirSync(userDataDir, { recursive: true })+ fs.writeFileSync(+ path.join(userDataDir, 'window-state.json'),+ JSON.stringify({ x: 0, y: 0, width: 1280, height: 860, isMaximized: false })+ )+ fs.writeFileSync(path.join(userDataDir, 'zoom-state.json'), JSON.stringify({ zoomLevel: 0 }))+ // External platform fake: a logged-out `gh`. The backend probes `gh auth+ // token` for GitHub credentials; with a sandbox HOME a real gh can block on+ // the desktop keyring for ~60 s, and a probe in flight at quit outlives the+ // backend (reported as a finding) — which would make the orphan census+ // depend on the runner's keyring rather than on Hermes.+ const bin = path.join(root, 'bin')+ fs.mkdirSync(bin, { recursive: true })+ fs.writeFileSync(path.join(bin, 'gh'), '#!/bin/sh\necho "no oauth token found for github.com" >&2\nexit 1\n', { mode: 0o755 })++ return {+ root,+ bin,+ home,+ hermesHome,+ userDataDir,+ cleanup: () => {+ if (!process.env.HERMES_E2E_CORE_KEEP) {+ fs.rmSync(root, { recursive: true, force: true })+ }+ }+ }+}++export function providerConfigYaml(providerUrl: string, extra = ''): string {+ return `model:+ default: mock-model+ provider: mock+providers:+ mock:+ api: ${providerUrl}/v1+ name: Mock+ api_mode: chat_completions+ key_env: MOCK_API_KEY+ models:+ mock-model: {}+ context_length: 64000+auxiliary:+ title_generation:+ enabled: false+approvals:+ mode: "off"+${extra}`+}++export function writeProviderHome(dir: string, providerUrl: string, extra = ''): void {+ fs.mkdirSync(dir, { recursive: true })+ fs.writeFileSync(path.join(dir, 'config.yaml'), providerConfigYaml(providerUrl, extra))+ fs.writeFileSync(path.join(dir, '.env'), 'MOCK_API_KEY=core-e2e-key\n')+}++const CREDENTIAL_RE = /(_API_KEY|_TOKEN|_SECRET|_PASSWORD|_CREDENTIALS|_ACCESS_KEY|_PRIVATE_KEY|_BASE_URL)$/++/**+ * The runner's own env minus credentials and every HERMES_* knob: an agent+ * shell exports HERMES_YOLO_MODE / _HERMES_GATEWAY, which the spawned backend+ * would inherit (auto-approving every command, changing the run under test).+ */+export function coreAppEnv(sandbox: CoreSandbox, extra: Record<string, string> = {}): Record<string, string> {+ const env: Record<string, string> = {}++ for (const [key, value] of Object.entries(process.env)) {+ if (!value || CREDENTIAL_RE.test(key) || /^_?HERMES_/.test(key) || key === 'VIRTUAL_ENV') {+ continue+ }++ env[key] = value+ }++ return {+ ...env,+ PATH: `${sandbox.bin}${path.delimiter}${env.PATH ?? ''}`,+ HOME: sandbox.home,+ HERMES_HOME: sandbox.hermesHome,+ HERMES_DESKTOP_USER_DATA_DIR: sandbox.userDataDir,+ HERMES_DESKTOP_IGNORE_EXISTING: '1',+ HERMES_DESKTOP_HERMES_ROOT: REPO_ROOT,+ HERMES_DESKTOP_APP_NAME: `HermesCoreE2E-${path.basename(sandbox.root)}`,+ HERMES_DESKTOP_SKIP_QUIT_CONFIRM: '1',+ HERMES_DESKTOP_CDP_PORT: 'off',+ ...extra+ }+}++export async function launchCoreApp(env: Record<string, string>): Promise<{ app: ElectronApplication; page: Page }> {+ if (!fs.existsSync(path.join(DESKTOP_ROOT, 'dist', 'electron-main.mjs'))) {+ throw new Error("Desktop dist not built: run 'npm run build' in apps/desktop first")+ }++ const app = await _electron.launch({+ executablePath: resolveElectronBinary([DESKTOP_ROOT, REPO_ROOT]),+ args: [DESKTOP_ROOT, '--disable-gpu', '--no-sandbox'],+ env,+ cwd: DESKTOP_ROOT+ })++ const page = await app.firstWindow()++ return { app, page }+}++// ─── Process census ─────────────────────────────────────────────────────++export interface ProcInfo {+ pid: number+ ppid: number+ cmdline: string+}++function readProc(pid: number): null | { environ: string; cmdline: string; ppid: number } {+ try {+ const environ = fs.readFileSync(`/proc/${pid}/environ`, 'utf8')+ const cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0').join(' ').trim()+ const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8')+ // Field 4 (ppid) follows the parenthesised comm, which may contain spaces.+ const ppid = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1])++ return { environ, cmdline, ppid }+ } catch {+ return null+ }+}++/** Every live process whose environment carries this sandbox's HERMES_HOME (orphans included). */+export function sandboxProcesses(sandbox: CoreSandbox): ProcInfo[] {+ const needle = `HERMES_HOME=${sandbox.hermesHome}\0`+ const out: ProcInfo[] = []++ for (const entry of fs.readdirSync('/proc')) {+ const pid = Number(entry)++ if (!Number.isInteger(pid) || pid === process.pid) {+ continue+ }++ const info = readProc(pid)++ if (!info || !(info.environ + '\0').includes(needle)) {+ continue+ }++ // Zombies have an empty cmdline and are already dead for our purposes.+ if (!info.cmdline) {+ continue+ }++ out.push({ pid, ppid: info.ppid, cmdline: info.cmdline })+ }++ return out+}++/** The `hermes serve` backend(s) spawned for this sandbox. */+export function backendProcesses(sandbox: CoreSandbox): ProcInfo[] {+ return sandboxProcesses(sandbox).filter(+ proc => / serve( |$)/.test(proc.cmdline) && !/electron/i.test(proc.cmdline.split(' ')[0])+ )+}++// ─── WebSocket recorder ─────────────────────────────────────────────────++export interface GatewayEventFrame {+ socket: number+ type: string+ sessionId: string+ seq: null | number+ payload: any+}++export interface WsRecorder {+ sockets: { id: number; url: string; closed: boolean }[]+ events: GatewayEventFrame[]+ sent: { socket: number; method: string; params: any }[]+}++export function recordWebSockets(page: Page): WsRecorder {+ const rec: WsRecorder = { sockets: [], events: [], sent: [] }++ page.on('websocket', ws => {+ if (!ws.url().includes('/api/ws')) {+ return+ }++ const id = rec.sockets.length+ const entry = { id, url: ws.url(), closed: false }+ rec.sockets.push(entry)+ ws.on('close', () => {+ entry.closed = true+ })+ ws.on('framereceived', frame => {+ try {+ const msg = JSON.parse(String(frame.payload))++ if (msg?.method === 'event' && msg.params) {+ rec.events.push({+ socket: id,+ type: String(msg.params.type ?? ''),+ sessionId: String(msg.params.session_id ?? ''),+ seq: typeof msg.params.seq === 'number' ? msg.params.seq : null,+ payload: msg.params.payload+ })+ }+ } catch {+ /* binary / non-JSON frames carry no gateway event */+ }+ })+ ws.on('framesent', frame => {+ try {+ const msg = JSON.parse(String(frame.payload))++ if (typeof msg?.method === 'string') {+ rec.sent.push({ socket: id, method: msg.method, params: msg.params })+ }+ } catch {+ /* ignore */+ }+ })+ })++ return rec+}++// ─── Network fault injection ────────────────────────────────────────────++export interface TcpProxy {+ port: number+ /** Live client connections through the proxy. */+ connections: () => number+ /** Reset every live connection (the renderer sees an abnormal close, as on a network drop). */+ dropAll: () => number+ close: () => Promise<void>+}++/** A loopback TCP proxy in the test process; the renderer's primary socket is routed through it. */+export function startTcpProxy(targetPort: number): Promise<TcpProxy> {+ const live = new Set<net.Socket>()++ const server = net.createServer(client => {+ const upstream = net.connect(targetPort, '127.0.0.1')+ live.add(client)+ const forget = () => {+ live.delete(client)+ client.destroy()+ upstream.destroy()+ }+ client.on('error', forget)+ upstream.on('error', forget)+ client.on('close', forget)+ upstream.on('close', forget)+ client.pipe(upstream)+ upstream.pipe(client)+ })++ return new Promise((resolve, reject) => {+ server.on('error', reject)+ server.listen(0, '127.0.0.1', () => {+ resolve({+ port: (server.address() as net.AddressInfo).port,+ connections: () => live.size,+ dropAll: () => {+ const count = live.size++ for (const socket of [...live]) {+ socket.resetAndDestroy()+ }++ return count+ },+ close: () =>+ new Promise<void>(done => {+ for (const socket of [...live]) {+ socket.destroy()+ }++ server.close(() => done())+ })+ })+ })+ })+}++/**+ * Rewrite the PRIMARY gateway WebSocket URL main hands the renderer (initial+ * connection and every reconnect mint) so it dials `proxyPort`. REST stays on+ * main's IPC bridge. Takes effect on the renderer's next dial (reload/reconnect).+ */+export async function routePrimaryWebSocket(app: ElectronApplication, backendPort: number, proxyPort: number) {+ await app.evaluate(+ ({ ipcMain }, { backendPort, proxyPort }) => {+ const handlers = (ipcMain as any)._invokeHandlers as Map<string, (...args: any[]) => Promise<any>>+ const from = `ws://127.0.0.1:${backendPort}/`+ const to = `ws://127.0.0.1:${proxyPort}/`+ const rewrite = (value: any): any => {+ if (typeof value === 'string') {+ return value.startsWith(from) ? to + value.slice(from.length) : value+ }++ if (Array.isArray(value)) {+ return value.map(rewrite)+ }++ if (value && typeof value === 'object') {+ return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, rewrite(inner)]))+ }++ return value+ }++ for (const channel of ['hermes:connection', 'hermes:gateway:ws-url']) {+ const original = handlers.get(channel)++ if (!original) {+ throw new Error(`no ipc handler ${channel}`)+ }++ ipcMain.removeHandler(channel)+ ipcMain.handle(channel, async (event: unknown, profile?: unknown, ...rest: unknown[]) => {+ const result = await original(event, profile, ...rest)+ const primary = profile === undefined || profile === null || profile === '' || profile === 'default'++ return primary ? rewrite(result) : result+ })+ }+ },+ { backendPort, proxyPort }+ )+}++/**+ * Make main stop tagging `profile`'s route as served by the shared primary+ * backend (while still pointing at that same backend). The renderer then dials+ * a SECOND WebSocket to the same process for that profile's session calls —+ * the #120005 topology — while calls made earlier keep the primary joined.+ */+export async function splitProfileRoute(app: ElectronApplication, profile: string): Promise<void> {+ await app.evaluate(({ ipcMain }, profile) => {+ const handlers = (ipcMain as any)._invokeHandlers as Map<string, (...args: any[]) => Promise<any>>+ const original = handlers.get('hermes:connection:for')++ if (!original) {+ throw new Error('no ipc handler hermes:connection:for')+ }++ ipcMain.removeHandler('hermes:connection:for')+ ipcMain.handle('hermes:connection:for', async (event: unknown, payload: any) => {+ const result = await original(event, payload)++ if (payload?.profile === profile && result && typeof result === 'object') {+ const { sharedPrimary: _shared, ...rest } = result++ return rest+ }++ return result+ })+ }, profile)+}++// ─── Renderer helpers ───────────────────────────────────────────────────++export function composer(page: Page) {+ return page.locator('[data-slot="composer-root"] [contenteditable="true"]').filter({ visible: true }).first()+}++/** Composer mounted, no full-viewport overlay above it, window visible. */+export async function waitForInteractive(app: ElectronApplication, page: Page, timeout = 180_000): Promise<void> {+ await expect(composer(page)).toBeVisible({ timeout })+ await page.waitForFunction(+ () => {+ const el = document.elementFromPoint(window.innerWidth / 2, window.innerHeight / 2)+ let node: Element | null = el++ if (!el) {+ return false+ }++ while (node) {+ const cs = window.getComputedStyle(node)++ if (cs.position === 'fixed') {+ const r = node.getBoundingClientRect()++ if (r.left <= 0 && r.top <= 0 && r.right >= window.innerWidth && r.bottom >= window.innerHeight) {+ return false+ }+ }++ node = node.parentElement+ }++ return true+ },+ undefined,+ { timeout, polling: 250 }+ )+ await expect+ .poll(+ () =>+ app+ .evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.isVisible() ?? false)+ .catch(() => false),+ { timeout, intervals: [250] }+ )+ .toBe(true)+}++/**+ * Enter submits (and steers a live turn); Control+Enter queues a follow-up+ * behind it. While the gateway is reconnecting the composer keeps the draft+ * and ignores Enter (by design), so the press is repeated until the draft is+ * accepted — but only while the draft is still in the composer AND no+ * prompt.submit carrying it went out on any socket, so a retry can never+ * double-submit.+ */+export async function send(+ page: Page,+ text: string,+ key: 'Control+Enter' | 'Enter' = 'Enter',+ ws?: WsRecorder+): Promise<void> {+ const box = composer(page)+ const probe = text.slice(0, 12)+ await box.click()+ await box.fill(text)+ await expect(box).toContainText(probe)+ const submitted = () => (ws?.sent ?? []).some(frame => JSON.stringify(frame.params ?? '').includes(probe))++ await expect+ .poll(+ async () => {+ const draft = (await box.textContent().catch(() => '')) ?? ''++ if (!draft.includes(probe)) {+ return 'accepted'+ }++ if (!submitted()) {+ await box.press(key)+ }++ return 'pending'+ },+ { timeout: 120_000, intervals: [1_000, 2_000, 4_000], message: `composer accepted ${probe}` }+ )+ .toBe('accepted')+}++export async function currentSessionId(page: Page): Promise<string> {+ return page.evaluate(() => decodeURIComponent(location.hash.replace(/^#\/?/, '').split('?')[0] ?? ''))+}++export interface PersistedMessage {+ role: string+ content: string+}++/**+ * The stored session id holding a user message with `marker`, read straight+ * from the profile's state.db (read-only) — independent of any renderer or+ * REST projection.+ */+export function storedSessionForMarker(sandbox: CoreSandbox, profile: string, marker: string): null | string {+ const dbPath =+ profile === 'default'+ ? path.join(sandbox.hermesHome, 'state.db')+ : path.join(sandbox.hermesHome, 'profiles', profile, 'state.db')++ if (!fs.existsSync(dbPath)) {+ return null+ }++ const db = new DatabaseSync(dbPath, { readOnly: true })++ try {+ const row = db+ .prepare("SELECT session_id FROM messages WHERE role = 'user' AND content LIKE ? ORDER BY id LIMIT 1")+ .get(`%${marker}%`) as undefined | { session_id: string }++ return row?.session_id ?? null+ } catch {+ // Mid-WAL-checkpoint reads can fail transiently; the caller polls.+ return null+ } finally {+ db.close()+ }+}++/** The backend's persisted display transcript (REST, the same read the renderer hydrates from). */+export async function persistedTranscript(page: Page, sessionId: string, profile?: string): Promise<PersistedMessage[]> {+ const query = profile ? `&profile=${encodeURIComponent(profile)}` : ''++ const result = await page.evaluate(+ async ({ sessionId, query }) =>+ (window as any).hermesDesktop.api({ path: `/api/sessions/${sessionId}/messages?order=oldest&limit=500${query}` }),+ { sessionId, query }+ )++ return (result?.messages ?? []).map((m: any) => ({+ role: String(m.role ?? ''),+ content: typeof m.content === 'string' ? m.content : JSON.stringify(m.content ?? '')+ }))+}++export interface RenderedMessage {+ role: 'assistant' | 'user'+ text: string+}++/** Every user/assistant bubble in the visible thread, in DOM order. */+export async function renderedTranscript(page: Page): Promise<{ bubbles: RenderedMessage[]; fullText: string }> {+ return page.evaluate(() => {+ const viewport = document.querySelector('[data-slot="aui_thread-viewport"]')++ if (!viewport) {+ return { bubbles: [], fullText: '' }+ }++ const bubbles = [+ ...viewport.querySelectorAll('[data-slot="aui_user-message-root"], [data-slot="aui_assistant-message-root"]')+ ].map(el => ({+ role: (el.getAttribute('data-slot') === 'aui_user-message-root' ? 'user' : 'assistant') as 'assistant' | 'user',+ text: (el as HTMLElement).innerText.replace(/\s+/g, ' ').trim()+ }))++ return { bubbles, fullText: (viewport as HTMLElement).innerText.replace(/\s+/g, ' ') }+ })+}diff --git a/apps/desktop/e2e/core/oracle.ts b/apps/desktop/e2e/core/oracle.tsnew file mode 100644index 00000000000..0680e711440--- /dev/null+++ b/apps/desktop/e2e/core/oracle.ts@@ -0,0 +1,439 @@+/**+ * The transcript oracle.+ *+ * Invariant, checked after every transition: each persisted user/assistant+ * message is rendered EXACTLY ONCE, in persisted order; nothing scenario-made+ * is rendered that is not persisted; the persisted assistant rows are exactly+ * what the provider streamed; and on the wire, each turn's concatenated+ * message.delta text equals what the provider streamed for that turn (and its+ * message.complete text equals the final completion).+ *+ * Every scenario text carries a unique marker (`U<n>-<nonce>` for the user,+ * `A<n>-<nonce>` / `A<n>i-<nonce>` for replies, `R<n>-<nonce>` for reasoning),+ * so "exactly once" is a count over rendered text, independent of how the+ * renderer groups bubbles (live vs hydrated grouping legitimately differs).+ *+ * Final-state checks converge with a deadline (hydration is asynchronous);+ * transient duplicates are caught separately by an in-page MutationObserver+ * sampler that is never allowed to see a marker twice.+ */++import { expect, type Page } from '@playwright/test'++import type { GatewayEventFrame, PersistedMessage, WsRecorder } from './harness'+import { persistedTranscript } from './harness'+import type { RecordedCompletion, ScriptedProvider } from './provider'++export const ANY_MARKER_RE = /\b[UAR]\d+i?-[a-z0-9]{3,}\b/g+const FIRST_MARKER_RE = /\b[UAR]\d+i?-[a-z0-9]{3,}\b/++const norm = (text: string) => text.replace(/\s+/g, ' ').trim()++function countOccurrences(haystack: string, needle: string): number {+ if (!needle) {+ return 0+ }++ let count = 0+ let at = haystack.indexOf(needle)++ while (at !== -1) {+ count+++ at = haystack.indexOf(needle, at + needle.length)+ }++ return count+}++function countMarker(haystack: string, marker: string): number {+ return (haystack.match(new RegExp(`\\b${marker}\\b`, 'g')) ?? []).length+}++/** The user marker a reply/reasoning marker answers: A3-x / A3i-x / R3-x → U3-x. */+export function userMarkerFor(marker: string): string {+ return marker.replace(/^[AR](\d+)i?-/, 'U$1-')+}++// ─── Transient-duplicate sampler ────────────────────────────────────────++/** Idempotent; re-run after every reload (the observer dies with the document). */+export async function installDuplicateSampler(page: Page): Promise<void> {+ await page.evaluate(source => {+ const w = window as any++ if (w.__coreSampler) {+ return+ }++ const re = new RegExp(source, 'g')+ w.__coreSampler = { samples: 0, violations: [] as { marker: string; count: number; text: string }[] }+ let scheduled = false++ const sample = () => {+ scheduled = false+ const viewports = [...document.querySelectorAll('[data-slot="aui_thread-viewport"]')] as HTMLElement[]++ for (const viewport of viewports) {+ if (viewport.getClientRects().length === 0) {+ continue+ }++ const text = viewport.innerText+ w.__coreSampler.samples+++ const counts = new Map<string, number>()++ for (const match of text.match(re) ?? []) {+ counts.set(match, (counts.get(match) ?? 0) + 1)+ }++ for (const [marker, count] of counts) {+ if (count > 1 && w.__coreSampler.violations.length < 20) {+ w.__coreSampler.violations.push({ marker, count, text: text.replace(/\s+/g, ' ').slice(0, 600) })+ }+ }+ }+ }++ new MutationObserver(() => {+ if (!scheduled) {+ scheduled = true+ requestAnimationFrame(sample)+ }+ }).observe(document.body, { childList: true, subtree: true, characterData: true })+ }, ANY_MARKER_RE.source)+}++async function samplerViolations(page: Page): Promise<{ samples: number; violations: any[] }> {+ return page.evaluate(() => (window as any).__coreSampler ?? { samples: 0, violations: [] })+}++// ─── Rendered view ──────────────────────────────────────────────────────++interface RenderedView {+ text: string+ userBubbles: string[]+}++async function renderedView(page: Page): Promise<RenderedView> {+ return page.evaluate(() => {+ const viewport = ([...document.querySelectorAll('[data-slot="aui_thread-viewport"]')] as HTMLElement[]).find(+ el => el.getClientRects().length > 0+ )++ if (!viewport) {+ return { text: '', userBubbles: [] }+ }++ return {+ text: viewport.innerText.replace(/\s+/g, ' '),+ userBubbles: ([...viewport.querySelectorAll('[data-slot="aui_user-message-root"]')] as HTMLElement[]).map(el =>+ el.innerText.replace(/\s+/g, ' ').trim()+ )+ }+ })+}++// ─── Wire check ─────────────────────────────────────────────────────────++interface WireTurn {+ sessionId: string+ deltas: string+ reasoning: string+ complete: null | string+}++/**+ * Backend-truth turns: events deduplicated by (runtime session, seq) across+ * every socket (the backend stamps seq once before fan-out), split at+ * message.start, in seq order.+ */+export function wireTurns(events: GatewayEventFrame[]): WireTurn[] {+ const unique = new Map<string, GatewayEventFrame>()++ for (const event of events) {+ if (event.seq === null || !event.sessionId) {+ continue+ }++ const key = `${event.sessionId}#${event.seq}`++ if (!unique.has(key)) {+ unique.set(key, event)+ }+ }++ const bySession = new Map<string, GatewayEventFrame[]>()++ for (const event of unique.values()) {+ const list = bySession.get(event.sessionId) ?? []+ list.push(event)+ bySession.set(event.sessionId, list)+ }++ const turns: WireTurn[] = []++ for (const [sessionId, list] of bySession) {+ list.sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0))+ let turn: null | WireTurn = null++ for (const event of list) {+ if (event.type === 'message.start') {+ turn = { sessionId, deltas: '', reasoning: '', complete: null }+ turns.push(turn)+ } else if (!turn) {+ continue+ } else if (event.type === 'message.delta') {+ turn.deltas += String(event.payload?.text ?? '')+ } else if (event.type === 'reasoning.delta') {+ turn.reasoning += String(event.payload?.text ?? '')+ } else if (event.type === 'message.complete') {+ turn.complete = String(event.payload?.text ?? '')+ }+ }+ }++ return turns+}++/**+ * Split a turn's streamed text at scenario markers: every scripted completion+ * starts with its own marker, so each segment is one completion's output.+ */+function segments(text: string, re: RegExp): { marker: string; text: string }[] {+ const out: { marker: string; text: string }[] = []+ const flat = norm(text)+ const hits = [...flat.matchAll(new RegExp(re.source, 'g'))]++ hits.forEach((hit, i) => {+ const end = i + 1 < hits.length ? hits[i + 1]!.index : flat.length+ out.push({ marker: hit[0], text: flat.slice(hit.index, end).trim() })+ })++ return out+}++/**+ * Backend stream integrity per turn: the concatenated message.delta (and+ * reasoning.delta) text is exactly the provider's output, segment by segment —+ * each completion once, whole (or a prefix when the backend itself hung up on+ * it, e.g. a steer), in order — and message.complete equals the final+ * completion. Only whitespace between tool-iteration segments may differ.+ */+function isSubsequence(words: string[], of: string[]): boolean {+ let i = 0++ for (const word of of) {+ if (i < words.length && words[i] === word) {+ i+++ }+ }++ return i === words.length+}++function wireViolations(+ ws: WsRecorder,+ provider: ScriptedProvider,+ userMarkers: Set<string>,+ lossy: Set<string>+): string[] {+ const problems: string[] = []+ const byOpening = new Map<string, RecordedCompletion>()++ for (const completion of provider.completions) {+ const opening = FIRST_MARKER_RE.exec(completion.sentText)?.[0]+ const reasoningOpening = FIRST_MARKER_RE.exec(completion.sentReasoning)?.[0]++ if (opening) {+ byOpening.set(opening, completion)+ }++ if (reasoningOpening) {+ byOpening.set(reasoningOpening, completion)+ }+ }++ for (const turn of wireTurns(ws.events)) {+ const textSegments = segments(turn.deltas, /\bA\d+i?-[a-z0-9]{3,}\b/)++ if (textSegments.length === 0 || !userMarkers.has(userMarkerFor(textSegments.at(-1)!.marker))) {+ continue+ }++ // A turn that straddled an injected socket drop may have frames that went+ // to the dead socket (the renderer recovers them from the persisted+ // transcript, which the render oracle checks). Its frames must still be an+ // in-order subsequence of what was streamed — never doubled or foreign.+ const gapped = lossy.has(userMarkerFor(textSegments.at(-1)!.marker))++ if (turn.complete === null && !gapped) {+ problems.push(`wire ${textSegments.at(-1)!.marker}: turn never completed`)+ continue+ }++ const seen = new Set<string>()+ const check = (kind: string, segs: { marker: string; text: string }[], pick: (c: RecordedCompletion) => string) => {+ segs.forEach((seg, i) => {+ const completion = byOpening.get(seg.marker)++ if (!completion) {+ problems.push(`wire: ${kind} segment ${seg.marker} was never streamed by the provider`)+ return+ }++ if (seen.has(`${kind}:${seg.marker}`)) {+ problems.push(`wire: ${kind} segment ${seg.marker} delivered twice in one turn`)+ }++ seen.add(`${kind}:${seg.marker}`)+ const sent = norm(pick(completion))+ const partialAllowed = completion.aborted && i < segs.length - 1++ if (gapped) {+ if (!isSubsequence(seg.text.split(' '), sent.split(' '))) {+ problems.push(`wire: ${kind} ${JSON.stringify(seg.text)} is not an in-order subsequence of ${JSON.stringify(sent)}`)+ }+ } else if (partialAllowed ? !sent.startsWith(seg.text) : seg.text !== sent) {+ problems.push(`wire: ${kind} ${JSON.stringify(seg.text)} != provider ${JSON.stringify(sent)}${completion.aborted ? ' (aborted)' : ''}`)+ }+ })+ }++ check('message.delta', textSegments, c => c.sentText)+ check('reasoning.delta', segments(turn.reasoning, /\bR\d+-[a-z0-9]{3,}\b/), c => c.sentReasoning)++ const final = byOpening.get(textSegments.at(-1)!.marker)++ if (final && turn.complete !== null && norm(turn.complete) !== norm(final.sentText)) {+ problems.push(`wire: message.complete ${JSON.stringify(turn.complete)} != final completion ${JSON.stringify(final.sentText)}`)+ }+ }++ return problems+}++// ─── The oracle ─────────────────────────────────────────────────────────++export interface OracleTarget {+ /** Stored session id (the route id). */+ sessionId: string+ profile?: string+ /** User markers this session must contain (guards against an empty/wrong session passing vacuously). */+ expectUserMarkers: string[]+ /** User markers whose turn straddled an injected socket drop (wire frames may be gapped, never doubled). */+ lossyWire?: string[]+}++function transcriptViolations(persisted: PersistedMessage[], view: RenderedView, target: OracleTarget): string[] {+ const problems: string[] = []+ const rows = persisted.filter(m => (m.role === 'user' || m.role === 'assistant') && norm(m.content))+ const persistedMarkers = new Set<string>()++ for (const marker of target.expectUserMarkers) {+ if (!rows.some(row => row.role === 'user' && countMarker(row.content, marker) === 1)) {+ problems.push(`persisted: user message ${marker} missing from the session`)+ }+ }++ for (const marker of target.expectUserMarkers) {+ if (rows.filter(row => row.role === 'user' && row.content.includes(marker)).length > 1) {+ problems.push(`persisted: user message ${marker} stored more than once`)+ }+ }++ let cursor = -1++ for (const row of rows) {+ const content = norm(row.content)++ for (const marker of content.match(ANY_MARKER_RE) ?? []) {+ persistedMarkers.add(marker)+ }++ const occurrences = countOccurrences(view.text, content)++ if (occurrences !== 1) {+ problems.push(`rendered ${occurrences}x (want 1): ${row.role} ${JSON.stringify(content.slice(0, 80))}`)+ continue+ }++ const at = view.text.indexOf(content)++ if (at < cursor) {+ problems.push(`order: ${row.role} ${JSON.stringify(content.slice(0, 40))} rendered before an earlier message`)+ }++ cursor = at+ }++ const renderedMarkers = view.text.match(ANY_MARKER_RE) ?? []+ const counts = new Map<string, number>()++ for (const marker of renderedMarkers) {+ counts.set(marker, (counts.get(marker) ?? 0) + 1)+ }++ for (const [marker, count] of counts) {+ if (count > 1) {+ problems.push(`marker ${marker} rendered ${count}x`)+ }++ // Reasoning is not part of the display content; every other marker must be persisted.+ if (!marker.startsWith('R') && !persistedMarkers.has(marker)) {+ problems.push(`rendered but not persisted: ${marker}`)+ }+ }++ const userRows = rows.filter(row => row.role === 'user').map(row => norm(row.content))++ if (view.userBubbles.length !== userRows.length) {+ problems.push(`user bubbles ${view.userBubbles.length} != persisted user rows ${userRows.length}`)+ }++ return problems+}++/**+ * Assert the invariant for the session currently on screen. Converges on the+ * final state (deadline), then requires zero transient duplicates since the+ * sampler was installed and a clean wire.+ */+export async function assertTranscriptOracle(+ page: Page,+ ws: WsRecorder,+ provider: ScriptedProvider,+ target: OracleTarget,+ label: string+): Promise<void> {+ let last: { problems: string[]; persisted: PersistedMessage[]; view: RenderedView } = {+ problems: ['not evaluated'],+ persisted: [],+ view: { text: '', userBubbles: [] }+ }++ await expect+ .poll(+ async () => {+ const persisted = await persistedTranscript(page, target.sessionId, target.profile)+ const view = await renderedView(page)+ last = { problems: transcriptViolations(persisted, view, target), persisted, view }++ return last.problems+ },+ { timeout: 60_000, intervals: [250, 500, 1000], message: `transcript oracle [${label}]` }+ )+ .toEqual([])+ .catch(error => {+ throw new Error(+ `transcript oracle [${label}] failed:\n ${last.problems.join('\n ')}\n` ++ `persisted: ${JSON.stringify(last.persisted.map(m => [m.role, m.content.slice(0, 60)]))}\n` ++ `rendered: ${JSON.stringify(last.view.text.slice(0, 1500))}\n(${(error as Error).message.split('\n')[0]})`+ )+ })++ const transient = await samplerViolations(page)+ expect(transient.violations, `transient duplicate render during [${label}] (${transient.samples} samples)`).toEqual([])++ const wire = wireViolations(ws, provider, new Set(target.expectUserMarkers), new Set(target.lossyWire ?? []))+ expect(wire, `wire integrity [${label}]`).toEqual([])+}diff --git a/apps/desktop/e2e/core/playwright.config.ts b/apps/desktop/e2e/core/playwright.config.tsnew file mode 100644index 00000000000..3a28ac90b80--- /dev/null+++ b/apps/desktop/e2e/core/playwright.config.ts@@ -0,0 +1,31 @@+import '../fix-electron-tracing'++import { defineConfig } from '@playwright/test'++/**+ * The core Desktop suite: a small, deterministic, REQUIRED lane.+ *+ * Deliberately different from ../../playwright.config.ts:+ * - retries: 0 — a required job that retries hides exactly the flake it+ * should expose (the old lane retried and still went red for weeks).+ * - no visual baselines / always-on screenshots; artifacts only on failure.+ * - one worker: every spec owns a real Electron + `hermes serve`; running+ * them concurrently on a loaded runner is the timing margin we refuse.+ * - generous per-test timeout; every wait inside is event-driven with its+ * own deadline, so a long timeout never slows a green run.+ */+export default defineConfig({+ testDir: '.',+ testMatch: '*.spec.ts',+ timeout: 600_000,+ expect: { timeout: 60_000 },+ retries: 0,+ workers: 1,+ fullyParallel: false,+ reporter: [['list'], ['html', { open: 'never', outputFolder: '../../playwright-report/core' }]],+ outputDir: '../../test-results/core',+ use: {+ screenshot: 'only-on-failure',+ trace: 'retain-on-failure'+ }+})diff --git a/apps/desktop/e2e/core/provider.ts b/apps/desktop/e2e/core/provider.tsnew file mode 100644index 00000000000..15d61057217--- /dev/null+++ b/apps/desktop/e2e/core/provider.ts@@ -0,0 +1,317 @@+/**+ * Scripted, recording OpenAI-compatible provider for the core Desktop suite.+ *+ * Unlike the shared tests-js mock (trigger keywords + module-global counters,+ * one of the reasons the old lane drifted), every reply here is keyed by the+ * unique marker in the turn's own user message, and the step within a turn is+ * derived from the request itself (assistant messages after the last user+ * message). Two scenarios can never consume each other's script, and a replay+ * or retry of the same request gets the same answer.+ *+ * Every chunk actually written is recorded so the oracle can assert+ * "rendered == persisted == what the provider streamed".+ */++import http from 'node:http'+import type { AddressInfo } from 'node:net'++export interface Gate {+ open: () => void+ opened: Promise<void>+}++export function gate(): Gate {+ let open = () => {}+ const opened = new Promise<void>(resolve => {+ open = resolve+ })++ return { open, opened }+}++export interface ToolCallSpec {+ name: string+ args: Record<string, unknown>+}++/** One provider completion. Chunks are streamed in order: reasoning, text, tool calls. */+export interface Step {+ reasoning?: string[]+ text?: string[]+ toolCalls?: ToolCallSpec[]+ /** Hold the stream after the first text (or reasoning) chunk until the gate opens. */+ holdAfterFirstChunk?: Gate+}++export interface RecordedCompletion {+ marker: null | string+ step: number+ stream: boolean+ sentText: string+ sentReasoning: string+ toolCalls: string[]+ finished: boolean+ /** The client (the backend) hung up before the stream ended, e.g. an interrupt/steer. */+ aborted: boolean+ body: any+}++export interface ScriptedProvider {+ url: string+ /** Register the steps a turn keyed by `marker` answers with (step i = i-th completion of that turn). */+ script: (marker: string, steps: Step[]) => void+ completions: RecordedCompletion[]+ /** Resolves once the first chunk of `marker`'s step has been written to the wire. */+ streamStarted: (marker: string, step?: number) => Promise<void>+ close: () => Promise<void>+}++const MARKER_RE = /\bU\d+-[a-z0-9]+\b/++function textOf(content: unknown): string {+ if (typeof content === 'string') {+ return content+ }++ if (Array.isArray(content)) {+ return content.map(part => (typeof part?.text === 'string' ? part.text : '')).join('')+ }++ return ''+}++function turnPosition(messages: any[]): { marker: null | string; step: number } {+ let lastUser = -1++ for (let i = messages.length - 1; i >= 0; i--) {+ if (messages[i]?.role === 'user') {+ lastUser = i+ break+ }+ }++ if (lastUser < 0) {+ return { marker: null, step: 0 }+ }++ const marker = MARKER_RE.exec(textOf(messages[lastUser].content))?.[0] ?? null+ const step = messages.slice(lastUser + 1).filter(m => m?.role === 'assistant').length++ return { marker, step }+}++function chunk(model: string, delta: Record<string, unknown>, finish: null | string = null): string {+ return `data: ${JSON.stringify({+ id: 'core-e2e',+ object: 'chat.completion.chunk',+ created: 0,+ model,+ choices: [{ index: 0, delta, finish_reason: finish }]+ })}\n\n`+}++const tick = () => new Promise(resolve => setTimeout(resolve, 15))++export function startScriptedProvider(): Promise<ScriptedProvider> {+ const scripts = new Map<string, Step[]>()+ const completions: RecordedCompletion[] = []+ const started = new Map<string, Gate>()++ const startedGate = (key: string) => {+ let g = started.get(key)++ if (!g) {+ g = gate()+ started.set(key, g)+ }++ return g+ }++ async function streamStep(res: http.ServerResponse, model: string, step: Step, rec: RecordedCompletion) {+ res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' })+ res.on('close', () => {+ if (!res.writableFinished) {+ rec.aborted = true+ }+ })+ let first = true++ const afterChunk = async () => {+ if (first) {+ first = false+ startedGate(`${rec.marker}#${rec.step}`).open()++ if (step.holdAfterFirstChunk) {+ await step.holdAfterFirstChunk.opened+ }+ }++ await tick()+ }++ for (const piece of step.reasoning ?? []) {+ if (rec.aborted) {+ return+ }++ res.write(chunk(model, { reasoning_content: piece }))+ rec.sentReasoning += piece+ await afterChunk()+ }++ for (const piece of step.text ?? []) {+ if (rec.aborted) {+ return+ }++ res.write(chunk(model, { content: piece }))+ rec.sentText += piece+ await afterChunk()+ }++ const calls = step.toolCalls ?? []++ if (rec.aborted) {+ return+ }++ if (calls.length > 0) {+ res.write(+ chunk(model, {+ tool_calls: calls.map((call, index) => ({+ index,+ id: `call_core_${rec.marker}_${rec.step}_${index}`,+ type: 'function',+ function: { name: call.name, arguments: JSON.stringify(call.args) }+ }))+ })+ )+ rec.toolCalls.push(...calls.map(call => call.name))+ await afterChunk()+ }++ res.write(chunk(model, {}, calls.length > 0 ? 'tool_calls' : 'stop'))+ res.write('data: [DONE]\n\n')+ res.end()+ rec.finished = true+ }++ function plainJson(res: http.ServerResponse, model: string, step: Step, rec: RecordedCompletion) {+ const text = (step.text ?? []).join('')+ const calls = step.toolCalls ?? []+ rec.sentText = text+ rec.sentReasoning = (step.reasoning ?? []).join('')+ rec.toolCalls.push(...calls.map(call => call.name))+ rec.finished = true+ startedGate(`${rec.marker}#${rec.step}`).open()+ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(+ JSON.stringify({+ id: 'core-e2e',+ object: 'chat.completion',+ created: 0,+ model,+ choices: [+ {+ index: 0,+ finish_reason: calls.length > 0 ? 'tool_calls' : 'stop',+ message: {+ role: 'assistant',+ content: text || null,+ ...(rec.sentReasoning ? { reasoning_content: rec.sentReasoning } : {}),+ ...(calls.length > 0+ ? {+ tool_calls: calls.map((call, index) => ({+ id: `call_core_${rec.marker}_${rec.step}_${index}`,+ type: 'function',+ function: { name: call.name, arguments: JSON.stringify(call.args) }+ }))+ }+ : {})+ }+ }+ ],+ usage: { prompt_tokens: 10, completion_tokens: 10, total_tokens: 20 }+ })+ )+ }++ const server = http.createServer((req, res) => {+ if (req.method === 'GET' && req.url?.startsWith('/v1/models')) {+ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ object: 'list', data: [{ id: 'mock-model', object: 'model', created: 0, owned_by: 'core' }] }))++ return+ }++ if (req.method !== 'POST' || !req.url?.startsWith('/v1/chat/completions')) {+ res.writeHead(404, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'not found' }))++ return+ }++ let raw = ''+ req.on('data', (data: Buffer) => {+ raw += data.toString()+ })+ req.on('end', () => {+ let body: any = {}++ try {+ body = JSON.parse(raw)+ } catch {+ body = {}+ }++ const messages: any[] = Array.isArray(body.messages) ? body.messages : []+ const { marker, step: stepIndex } = turnPosition(messages)+ const steps = marker ? scripts.get(marker) : undefined+ // Unscripted traffic (auxiliary calls, a marker-less prompt) gets a+ // fixed short answer; it is recorded, never matched to a scenario.+ const step: Step = steps?.[Math.min(stepIndex, steps.length - 1)] ?? { text: ['ok'] }+ const model = typeof body.model === 'string' ? body.model : 'mock-model'++ const rec: RecordedCompletion = {+ marker: steps ? marker : null,+ step: stepIndex,+ stream: body.stream === true,+ sentText: '',+ sentReasoning: '',+ toolCalls: [],+ finished: false,+ aborted: false,+ body+ }++ completions.push(rec)++ if (rec.stream) {+ void streamStep(res, model, step, rec).catch(() => res.destroy())+ } else {+ plainJson(res, model, step, rec)+ }+ })+ })++ return new Promise((resolve, reject) => {+ server.on('error', reject)+ server.listen(0, '127.0.0.1', () => {+ const { port } = server.address() as AddressInfo+ resolve({+ url: `http://127.0.0.1:${port}`,+ script: (marker, steps) => {+ scripts.set(marker, steps)+ },+ completions,+ streamStarted: (marker, step = 0) => startedGate(`${marker}#${step}`).opened,+ close: () =>+ new Promise<void>(done => {+ server.closeAllConnections?.()+ server.close(() => done())+ })+ })+ })+ })+}diff --git a/apps/desktop/e2e/core/transcript-integrity.spec.ts b/apps/desktop/e2e/core/transcript-integrity.spec.tsnew file mode 100644index 00000000000..e8cc0333d59--- /dev/null+++ b/apps/desktop/e2e/core/transcript-integrity.spec.ts@@ -0,0 +1,292 @@+/**+ * C2 core: transcript integrity across every transition that has shipped a+ * duplicate / vanishing / reordered message bug.+ *+ * One real Electron app + one real `hermes serve` backend (only the LLM is+ * faked, by a scripted recording provider). After every transition the+ * transcript oracle (./oracle.ts) asserts: each persisted user/assistant+ * message is rendered exactly once, in order, nothing unpersisted is+ * rendered, no marker was ever rendered twice even transiently, and the+ * backend's concatenated deltas equal what the provider streamed.+ *+ * Transitions (in order, sharing the app so each builds on the last):+ * stream → tool-call turn → reasoning turn → steer mid-stream →+ * queued follow-up →+ * session switch mid-stream → warm resume → reload →+ * WebSocket drop + reconnect mid-stream → second socket to the same+ * backend (#120005 topology) → final reload re-checks every session.+ */++import * as path from 'node:path'++import { expect, type Page, test } from '@playwright/test'++import {+ coreAppEnv,+ createCoreSandbox,+ currentSessionId,+ launchCoreApp,+ recordWebSockets,+ routePrimaryWebSocket,+ send,+ splitProfileRoute,+ startTcpProxy,+ storedSessionForMarker,+ waitForInteractive,+ writeProviderHome+} from './harness'+import { assertTranscriptOracle, installDuplicateSampler, type OracleTarget } from './oracle'+import { gate, startScriptedProvider } from './provider'++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 AI = (n: number) => `A${n}i-${nonce}`+const R = (n: number) => `R${n}-${nonce}`++const words = (marker: string, ...rest: string[]) => [`${marker} `, ...rest.map((w, i) => (i === rest.length - 1 ? w : `${w} `))]++function viewport(page: Page) {+ return page.locator('[data-slot="aui_thread-viewport"]').filter({ visible: true }).first()+}++async function openSession(page: Page, sessionId: string, mustShow: string) {+ await page.evaluate(id => {+ window.location.hash = `#/${encodeURIComponent(id)}`+ }, sessionId)+ await expect.poll(() => currentSessionId(page)).toBe(sessionId)+ await expect(viewport(page)).toContainText(mustShow, { timeout: 60_000 })+}++test('transcript oracle holds across every transition', async () => {+ const provider = await startScriptedProvider()+ const sandbox = createCoreSandbox('transcript')+ writeProviderHome(sandbox.hermesHome, provider.url)+ writeProviderHome(path.join(sandbox.hermesHome, 'profiles', 'p2'), provider.url)+ const { app, page } = await launchCoreApp(coreAppEnv(sandbox))+ const ws = recordWebSockets(page)+ const proxies: { close: () => Promise<void> }[] = []++ const finished = (marker: string, step = 0) =>+ expect+ .poll(() => provider.completions.some(c => c.marker === marker && c.step === step && c.finished), {+ timeout: 120_000,+ message: `provider finished ${marker} step ${step}`+ })+ .toBe(true)++ const sessionA: OracleTarget = { sessionId: '', expectUserMarkers: [] }+ const sessionB: OracleTarget = { sessionId: '', expectUserMarkers: [] }++ try {+ await waitForInteractive(app, page)+ await installDuplicateSampler(page)++ await test.step('stream: multi-chunk reply', async () => {+ provider.script(U(1), [{ text: words(A(1), 'alpha', 'bravo', 'charlie', 'delta', 'echo') }])+ await send(page, `${U(1)} hello`, 'Enter', ws)+ await finished(U(1))+ await expect.poll(() => currentSessionId(page)).not.toBe('')+ sessionA.sessionId = await currentSessionId(page)+ sessionA.expectUserMarkers.push(U(1))+ await assertTranscriptOracle(page, ws, provider, sessionA, 'stream')+ })++ await test.step('tool-call turn: interim text + real terminal tool + final', async () => {+ provider.script(U(2), [+ { text: words(AI(2), 'checking', 'first'), toolCalls: [{ name: 'terminal', args: { command: 'echo core-tool-ok' } }] },+ { text: words(A(2), 'tool', 'said', 'ok') }+ ])+ await send(page, `${U(2)} run a tool`, 'Enter', ws)+ await finished(U(2), 1)+ sessionA.expectUserMarkers.push(U(2))+ await assertTranscriptOracle(page, ws, provider, sessionA, 'tool-call turn')+ })++ await test.step('reasoning turn: reasoning deltas never leak into or double the reply', async () => {+ provider.script(U(3), [{ reasoning: words(R(3), 'weighing', 'options'), text: words(A(3), 'reasoned', 'answer') }])+ await send(page, `${U(3)} think first`, 'Enter', ws)+ await finished(U(3))+ sessionA.expectUserMarkers.push(U(3))+ await assertTranscriptOracle(page, ws, provider, sessionA, 'reasoning turn')+ })++ await test.step('steer mid-stream: Enter while busy redirects the live turn', async () => {+ const hold = gate()+ provider.script(U(4), [{ text: words(A(4), 'slow', 'first', 'reply'), holdAfterFirstChunk: hold }])+ provider.script(U(5), [{ text: words(A(5), 'steered', 'reply') }])+ await send(page, `${U(4)} slow one`, 'Enter', ws)+ await provider.streamStarted(U(4))+ await expect(viewport(page)).toContainText(A(4))+ await send(page, `${U(5)} change course`, 'Enter', ws)+ await finished(U(5))+ hold.open()+ sessionA.expectUserMarkers.push(U(4), U(5))+ await assertTranscriptOracle(page, ws, provider, sessionA, 'steer mid-stream')+ })++ await test.step('queued follow-up: Ctrl+Enter while busy runs after the live turn, once', async () => {+ const hold = gate()+ provider.script(U(11), [{ text: words(A(11), 'long', 'running', 'reply'), holdAfterFirstChunk: hold }])+ provider.script(U(12), [{ text: words(A(12), 'queued', 'reply') }])+ await send(page, `${U(11)} long one`, 'Enter', ws)+ await provider.streamStarted(U(11))+ await expect(viewport(page)).toContainText(A(11))+ await send(page, `${U(12)} after that`, 'Control+Enter', ws)+ hold.open()+ await finished(U(11))+ await finished(U(12))+ // The queued message is a turn of its own, strictly after the first.+ const u11 = provider.completions.findIndex(c => c.marker === U(11))+ const u12 = provider.completions.findIndex(c => c.marker === U(12))+ expect(u12).toBeGreaterThan(u11)+ sessionA.expectUserMarkers.push(U(11), U(12))+ await assertTranscriptOracle(page, ws, provider, sessionA, 'queued follow-up')+ })++ await test.step('session switch mid-stream: the away session completes exactly once', async () => {+ // NEW_CHAT_ROUTE ('/') — the route the sidebar's New session button opens.+ await page.evaluate(() => {+ window.location.hash = '#/'+ })+ await expect.poll(() => currentSessionId(page)).toBe('')+ await expect(viewport(page)).not.toContainText(U(1))+ const hold = gate()+ provider.script(U(6), [{ text: words(A(6), 'finished', 'while', 'away'), holdAfterFirstChunk: hold }])+ await send(page, `${U(6)} in session b`, 'Enter', ws)+ await provider.streamStarted(U(6))+ await expect.poll(() => currentSessionId(page)).not.toBe('')+ sessionB.sessionId = await currentSessionId(page)+ expect(sessionB.sessionId).not.toBe(sessionA.sessionId)+ sessionB.expectUserMarkers.push(U(6))+ await openSession(page, sessionA.sessionId, A(12))+ hold.open()+ await finished(U(6))+ await assertTranscriptOracle(page, ws, provider, sessionA, 'switch: session A while B streams')+ await openSession(page, sessionB.sessionId, U(6))+ await assertTranscriptOracle(page, ws, provider, sessionB, 'switch: back to B after it completed away')+ })++ await test.step('warm resume: revisit cached sessions and continue one', async () => {+ await openSession(page, sessionA.sessionId, A(12))+ await assertTranscriptOracle(page, ws, provider, sessionA, 'warm resume A')+ await openSession(page, sessionB.sessionId, A(6))+ provider.script(U(7), [{ text: words(A(7), 'warm', 'continue') }])+ await send(page, `${U(7)} continue b`, 'Enter', ws)+ await finished(U(7))+ sessionB.expectUserMarkers.push(U(7))+ await assertTranscriptOracle(page, ws, provider, sessionB, 'warm resume B + new turn')+ })++ // From here on the primary socket dials through a loopback proxy the test+ // controls, so a network drop can be injected mid-stream.+ const backendPort = Number(new URL(ws.sockets[0]!.url).port)+ const proxy = await startTcpProxy(backendPort)+ proxies.push(proxy)+ await routePrimaryWebSocket(app, backendPort, proxy.port)++ await test.step('reload: hydrated transcript equals persisted', async () => {+ await page.reload()+ await waitForInteractive(app, page)+ await installDuplicateSampler(page)+ await expect.poll(() => proxy.connections()).toBeGreaterThan(0)+ await openSession(page, sessionB.sessionId, A(7))+ await assertTranscriptOracle(page, ws, provider, sessionB, 'reload B')+ await openSession(page, sessionA.sessionId, A(12))+ await assertTranscriptOracle(page, ws, provider, sessionA, 'reload A')+ })++ await test.step('WebSocket drop + reconnect mid-stream: no lost, doubled or replayed text', async () => {+ const hold = gate()+ provider.script(U(8), [{ text: words(A(8), 'survives', 'the', 'drop'), holdAfterFirstChunk: hold }])+ await send(page, `${U(8)} across a drop`, 'Enter', ws)+ await provider.streamStarted(U(8))+ await expect(viewport(page)).toContainText(A(8))+ const socketsBefore = ws.sockets.length+ expect(proxy.dropAll()).toBeGreaterThan(0)+ // The renderer must dial a fresh socket (through the proxy) on its own.+ await expect.poll(() => ws.sockets.length, { timeout: 60_000 }).toBeGreaterThan(socketsBefore)+ await expect.poll(() => proxy.connections(), { timeout: 60_000 }).toBeGreaterThan(0)+ hold.open()+ await finished(U(8))+ sessionA.expectUserMarkers.push(U(8))+ sessionA.lossyWire = [U(8)]+ await assertTranscriptOracle(page, ws, provider, sessionA, 'ws drop + reconnect')+ })++ // Sockets that delivered the message.complete of the turn whose reply opens with `marker`.+ const completeSockets = (marker: string) =>+ new Set(ws.events.filter(e => e.type === 'message.complete' && String(e.payload?.text ?? '').startsWith(marker)).map(e => e.socket))++ let sessionP2: OracleTarget = { sessionId: '', profile: 'p2', expectUserMarkers: [] }++ await test.step('non-default profile on the shared host backend: one socket per session', async () => {+ await page.getByRole('button', { name: 'Bots', exact: true }).or(page.getByRole('tab', { name: 'Bots', exact: true })).first().click()+ const row = page.locator('[data-slot="bots-roster"] [data-roster-key="local::p2"]')+ await expect(row).toBeVisible({ timeout: 60_000 })+ await row.click()+ await expect(page.getByRole('tab', { name: /Draft/ })).toBeVisible({ timeout: 60_000 })+ provider.script(U(9), [{ text: words(A(9), 'profile', 'two', 'first') }])+ await send(page, `${U(9)} on p2`, 'Enter', ws)+ await finished(U(9))+ await expect(viewport(page)).toContainText(A(9))+ let p2Session: null | string = null+ await expect+ .poll(() => (p2Session = storedSessionForMarker(sandbox, 'p2', U(9))), { message: 'p2 turn persisted in the p2 state.db' })+ .not.toBeNull()+ sessionP2 = { sessionId: p2Session!, profile: 'p2', expectUserMarkers: [U(9)] }+ await assertTranscriptOracle(page, ws, provider, sessionP2, 'p2 first turn')++ // #120005: the SECOND message of a non-default-profile chat is where a+ // session-owner call used to dial a second socket to the same process.+ provider.script(U(13), [{ text: words(A(13), 'profile', 'two', 'second') }])+ await send(page, `${U(13)} again on p2`, 'Enter', ws)+ await finished(U(13))+ sessionP2.expectUserMarkers.push(U(13))+ await assertTranscriptOracle(page, ws, provider, sessionP2, 'p2 second turn')+ expect([...completeSockets(A(9))].length, 'p2 turn 1 delivered on exactly one socket').toBe(1)+ expect([...completeSockets(A(13))].length, 'p2 turn 2 delivered on exactly one socket (no 2nd socket to one backend)').toBe(1)+ })++ await test.step('forced second socket to the same backend: every event still renders once', async () => {+ // Force the #120005 topology regardless of routing: from the next+ // session call on, the p2 route is served by a second socket to the same+ // backend while the primary stays joined. The renderer must still apply+ // every event exactly once (tool turn → interim bubble + final).+ const socketsBefore = ws.sockets.length+ await splitProfileRoute(app, 'p2')+ provider.script(U(10), [+ { text: words(AI(10), 'looking', 'it', 'up'), toolCalls: [{ name: 'terminal', args: { command: 'echo core-two-sockets' } }] },+ { text: words(A(10), 'two', 'sockets', 'one', 'render') }+ ])+ await send(page, `${U(10)} tool on p2`, 'Enter', ws)+ await finished(U(10), 1)+ await expect.poll(() => ws.sockets.length).toBeGreaterThan(socketsBefore)+ // Precondition of the scenario: the turn really was fanned out to 2+ sockets.+ await expect+ .poll(() => completeSockets(A(10)).size, { timeout: 60_000, message: 'the forced turn reached more than one socket' })+ .toBeGreaterThan(1)+ sessionP2.expectUserMarkers.push(U(10))+ await assertTranscriptOracle(page, ws, provider, sessionP2, 'p2 tool turn over two sockets')+ })++ await test.step('final reload: every session re-hydrates exactly once', async () => {+ await page.reload()+ await waitForInteractive(app, page)+ await installDuplicateSampler(page)+ await openSession(page, sessionA.sessionId, A(8))+ await assertTranscriptOracle(page, ws, provider, sessionA, 'final reload A')+ await openSession(page, sessionB.sessionId, A(7))+ await assertTranscriptOracle(page, ws, provider, sessionB, 'final reload B')+ })+ } finally {+ await app.close().catch(() => undefined)++ for (const proxy of proxies) {+ await proxy.close()+ }++ await provider.close()+ sandbox.cleanup()+ }+})