Files
orca/config/scripts/mobile-web-app/mobile-web-app-terminal-render.test.mjs
T
OrcaWinandOrcaWin 7d6603aa17 [comment audit] Complete repository-wide comment cleanup (#33249)
* [comment audit] Align legacy failure-read counts with cached display

* [comment audit] Condense shared provider lifecycle and browser recovery comments [skip ci]

* [comment audit] Condense shared generation, path and preview comments [skip ci]

* [comment audit] Condense host, file and Git contract rationale [skip ci]

* [comment audit] Tighten Git lifecycle and provider contract comments [skip ci]

* [comment audit] Clarify shared host authority and launch isolation [skip ci]

* [comment audit] simplify local access mobile and native chat contracts [skip ci]

* [comment audit] simplify native chat presentation and state contracts [skip ci]

* [comment audit] simplify native runtime and provider contracts [skip ci]

* [comment audit] simplify migration and orchestration contracts [skip ci]

* [comment audit] simplify plugin trust and process capture rationale [skip ci]

* [comment audit] simplify terminal delivery and remote compatibility rationale [skip ci]

* [comment audit] clarify remote recovery and launch wire rationale [skip ci]

* [comment audit] shorten shared RPC compatibility and runtime evidence comments [skip ci]

* [comment audit] simplify secure storage shell startup and sidebar rationale [skip ci]

* [comment audit] clarify sidebar, skill and SSH invariants [skip ci]

* [comment audit] condense structured chat delivery and timing rationale [skip ci]

* [comment audit] condense terminal replay and telemetry invariants [skip ci]

* [comment audit] clarify launch permission and terminal delivery rationale [skip ci]

* [comment audit] clarify workspace ownership and layout contracts [skip ci]

* [comment audit] wait for fitted and painted SSH terminal links

* [comment audit] clarify layout persistence and session ownership [skip ci]

* [comment audit] clarify host routing and workspace lifecycle contracts [skip ci]

* [comment audit] clarify startup persistence and app lifetime comments [skip ci]

* [comment audit] clarify recovery and activity boundaries [skip ci]

* [comment audit] condense activity and artifact invariants [skip ci]

* [comment audit] condense automation authority contracts [skip ci]

* [comment audit] simplify automation scheduling and history contracts [skip ci]

* [comment audit] clarify browser chrome and annotation lifecycles [skip ci]

* [comment audit] clarify browser routing and retained guest ownership [skip ci]

* [comment audit] clarify browser recovery and document ownership comments [skip ci]

* [comment audit] restore hosted runners required by native IME fixtures

* [comment audit] shorten preview, palette and dashboard invariants [skip ci]

* [comment audit] clarify terminal preview, dashboard and retention comments [skip ci]

* [comment audit] clarify diff-note recovery and editor lifecycle comments [skip ci]

* [comment audit] shorten rich-text and combined-diff ownership comments [skip ci]

* [comment audit] shorten autosave, draft recovery and model ownership comments [skip ci]

* [comment audit] shorten save-queue, notebook and Markdown constraints [skip ci]

* [comment audit] shorten Monaco, PDF and rich Markdown safeguards [skip ci]

* [comment audit] clarify rich Markdown source and selection safeguards [skip ci]

* [comment audit] clarify editor loading and emulator stream lifetimes [skip ci]

* [comment audit] trim emulator and feature tour narration [skip ci]

* [comment audit] clarify floating workspace and GitHub cache ownership [skip ci]

* [comment audit] trim provider controls and Linear filter explanations [skip ci]

* [comment audit] clarify pairing and chat resume lifetimes [skip ci]

* [comment audit] clarify chat delivery and transcript lifetimes [skip ci]

* [comment audit] clarify session options and host-owned status [skip ci]

* [comment audit] clarify draft durability and live-status precedence [skip ci]

* [comment audit] Trim chat send and model ownership explanations [skip ci]

* [comment audit] Shorten transcript ownership and send recovery comments [skip ci]

* [comment audit] Simplify native chat composer and transcript hook comments [skip ci]

* [comment audit] Shorten native chat scroll and structured session explanations [skip ci]

* [comment audit] Trim workspace picker and onboarding commentary [skip ci]

* [comment audit] Simplify pet rendering, review cache and quick open comments [skip ci]

* [comment audit] Trim sidebar and session history explanations [skip ci]

* [comment audit] Condense session resume and review checks comments [skip ci]

* [comment audit] Shorten checks state and file explorer refresh comments [skip ci]

* [comment audit] Trim plugin bridge and source-control action rationale [skip ci]

* [comment audit] Trim source-control listing and review rationale [skip ci]

* [comment audit] Shorten sidebar lifecycle and explorer safeguards [skip ci]

* [comment audit] Condense Settings account and appearance rationale [skip ci]

* [comment audit] Trim pairing and repository Settings explanations [skip ci]

* [comment audit] Condense Settings search SSH and terminal safeguards [skip ci]

* [comment audit] Shorten Settings voice and provider ownership comments [skip ci]

* [comment audit] Condense Settings draft persistence and host-state rationale [skip ci]

* [comment audit] Trim Settings hooks and sidebar setup rationale [skip ci]

* [comment audit] Condense sidebar deletion and board-filter safeguards [skip ci]

* [comment audit] Condense worktree cards, host ownership and Markdown contracts [skip ci]

* [comment audit] Condense sidebar drag, folder and filtering contracts [skip ci]

* [comment audit] Condense sidebar parity, sleep and host ownership contracts [skip ci]

* [comment audit] Prune focus-read baseline after comment cleanup

* [comment audit] Clarify sidebar visibility, board drops and agent evidence [skip ci]

* [comment audit] Tighten sidebar listing, drag and reveal contracts [skip ci]

* [comment audit] Clarify viewport geometry and skill update safeguards [skip ci]

* [comment audit] Tighten skill inventory, usage and host status comments [skip ci]

* [comment audit] Clarify usage ownership and resource kill safeguards [skip ci]

* [comment audit] Tighten tab selection, rename and search contracts [skip ci]

* [comment audit] Tighten tab-strip geometry and drag ownership comments [skip ci]

* [comment audit] Tighten Tasks recovery, pagination and mutation comments [skip ci]

* [comment audit] Tighten provider loading and terminal recovery comments [skip ci]

* [comment audit] Tighten completion, cadence and PTY ownership comments [skip ci]

* [comment audit] Clarify terminal restore and parked-pane boundaries [skip ci]

* [comment audit] Tighten PTY startup and replay explanations [skip ci]

* [comment audit] Clarify PTY identity and delivery ownership [skip ci]

* [comment audit] Shorten remote reconnect and input replay rationale [skip ci]

* [comment audit] Condense terminal parking clipboard and file link comments [skip ci]

* [comment audit] Clarify IME ownership and trim trace history [skip ci]

* [comment audit] Shorten pane recovery and parked watcher explanations [skip ci]

* [comment audit] Condense snapshot replay and visibility recovery rationale [skip ci]

* [comment audit] Shorten terminal parking and keyboard ownership rationale [skip ci]

* [comment audit] Trim renderer lifecycle and menu rationale [skip ci]

* [comment audit] Condense workspace cleanup ownership and settlement notes [skip ci]

* [comment audit] Clarify renderer hook evidence and source ownership [skip ci]

* [comment audit] Tighten IPC ownership and reconnect explanations [skip ci]

* [comment audit] Trim renderer focus, paste and attention comments [skip ci]

* [comment audit] Shorten scroll, locale and agent lifecycle comments [skip ci]

* [comment audit] Trim agent launch, resume and ownership commentary [skip ci]

* [comment audit] Shorten account, browser and editor comments [skip ci]

* [comment audit] Clarify host-mirror waits, previews and input ownership [skip ci]

* [comment audit] Condense launch recovery and editor tokenization comments [skip ci]

* [comment audit] Condense workspace selection and terminal pane rationale [skip ci]

* [comment audit] Condense terminal fitting and rendering recovery comments [skip ci]

* [comment audit] Condense terminal input and host routing explanations [skip ci]

* [comment audit] Condense ownership and sleeping-session recovery rationale [skip ci]

* [comment audit] Condense structured launch and terminal link explanations [skip ci]

* [comment audit] Condense terminal ownership and workspace file routing rationale [skip ci]

* [comment audit] Condense session persistence and workspace activation rationale [skip ci]

* [comment audit] Condense workspace routing and browser ownership rationale [skip ci]

* [comment audit] Condense mirror recovery and layout authority rationale [skip ci]

* [comment audit] Condense runtime transport and file safety rationale [skip ci]

* [comment audit] Condense runtime graph and structured session rationale [skip ci]

* [comment audit] Condense browser creation and remote tab recovery rationale [skip ci]

* [comment audit] Condense snapshot authority and publisher recovery rationale [skip ci]

* [comment audit] Condense frame, startup and provider cache rationale [skip ci]

* [comment audit] Condense host twin and agent lifecycle rationale [skip ci]

* [comment audit] Condense browser authority and editor cleanup rationale [skip ci]

* [comment audit] Condense editor buffer identity and review cache rationale [skip ci]

* [comment audit] Condense provider lifetime and repository ownership rationale [skip ci]

* [comment audit] Condense reconnect, hydration and terminal retirement rationale [skip ci]

* [comment audit] Condense recovery, reconciliation and persistence rationale [skip ci]

* [comment audit] Condense cleanup ownership and listing admission rationale [skip ci]

* [comment audit] Condense teardown ordering and terminal ownership rationale [skip ci]

* [comment audit] Condense recovery ledger and web host-boundary rationale [skip ci]

* [comment audit] Condense web reconnect and credential lifecycle rationale [skip ci]

* [comment audit] Condense cloud rollout and assignment safety rationale [skip ci]

* [comment audit] Condense relay session and database recovery rationale [skip ci]

* [comment audit] Condense relay placement and protocol compatibility rationale [skip ci]

* [comment audit] Condense build and packaging constraints [skip ci]

* [comment audit] Condense CI gates and validation isolation rationale [skip ci]

* [comment audit] Condense catalog identity and browser validation rationale [skip ci]

* [comment audit] Condense mobile browser and frame-budget rationale [skip ci]

* [comment audit] Shorten mobile route and browser test explanations [skip ci]

* [comment audit] Condense editor and session seam test rationale [skip ci]

* [comment audit] Trim session and terminal closure history [skip ci]

* [comment audit] Shorten terminal browser and census explanations [skip ci]

* [comment audit] Preserve root-only E2E diagnostic baseline

* [comment audit] Condense mobile seam and HTML preview test rationale [skip ci]

* [comment audit] Condense preview instrumentation and render harness rationale [skip ci]

* [comment audit] Condense bundle contracts and native-build constraints [skip ci]

* [comment audit] Shorten native packaging and CI routing rationale [skip ci]

* [comment audit] Condense release tooling and benchmark constraints [skip ci]

* [comment audit] Condense packaging and platform gate rationale [skip ci]

* [comment audit] Shorten mobile route and history rationale [skip ci]

* [comment audit] Condense mobile browser and component rationale [skip ci]

* [comment audit] Shorten drawer and workspace-form rationale [skip ci]

* [comment audit] Trim mobile review and editor-document explanations [skip ci]

* [comment audit] Condense editor lifecycle and Markdown explanations [skip ci]

* [comment audit] Trim mobile file, diagnostics and dictation commentary [skip ci]

* [comment audit] Simplify mobile host-list and workspace-view explanations [skip ci]

* [comment audit] Clarify mobile shell lifetime and bridge delivery constraints [skip ci]

* [comment audit] Condense bridge stream, native request and audio rationale [skip ci]

* [comment audit] Reduce bridge schema and page-client commentary [skip ci]

* [comment audit] Tighten mobile page bridge contracts [skip ci]

* [comment audit] Clarify mobile cache and session constraints [skip ci]

* [comment audit] Condense mobile route and lifecycle rationale [skip ci]

* [comment audit] Tighten mobile shell hook timing rationale [skip ci]

* [comment audit] Clarify route handoff and notification compatibility [skip ci]

* [comment audit] Clarify push registration and dictation cleanup constraints [skip ci]

* [comment audit] Condense keyboard geometry and native media ownership rationale [skip ci]

* [comment audit] Tighten mobile chat scroll and composer concurrency rationale [skip ci]

* [comment audit] Condense mobile reply compatibility and upload ownership rationale [skip ci]

* [comment audit] Condense optimistic echo and scroll ownership rationale [skip ci]

* [comment audit] Tighten stream replay and queued session ownership rationale [skip ci]

* [comment audit] Condense mobile composer and reply-schema constraints [skip ci]

* [comment audit] Clarify mobile transcript recovery and session ownership [skip ci]

* [comment audit] Clarify mobile queue and source-control compatibility [skip ci]

* [comment audit] Condense storage and task launch constraints [skip ci]

* [comment audit] Clarify task schemas and terminal document ownership [skip ci]

* [comment audit] Tighten terminal input and viewport rationale [skip ci]

* [comment audit] Shorten terminal and RPC recorder contracts [skip ci]

* [comment audit] Condense recorder engine and connection contracts [skip ci]

* [comment audit] Shorten host credential and relay recovery comments [skip ci]

* [comment audit] Tighten pairing recovery and bundle transport rationale [skip ci]

* [comment audit] Clarify RPC delivery and workspace catalog boundaries [skip ci]

* [comment audit] Condense catalog and relay entry contracts [skip ci]

* [comment audit] Shorten shutdown and SSH relay delivery contracts [skip ci]

* [comment audit] Condense WSL relay and E2E regression rationale [skip ci]

* [comment audit] Shorten cross-version harness and renderer fixture explanations [skip ci]

* [comment audit] Condense paired-host and E2E lifecycle rationale [skip ci]

* [comment audit] Shorten layout oracle and regression explanations [skip ci]

* [comment audit] Condense paired recovery and ownership regression contracts [skip ci]

* [comment audit] Shorten restart, sidebar and SSH lifecycle contracts [skip ci]

* [comment audit] Condense terminal rendering and IME regression rationale [skip ci]

* [comment audit] Shorten terminal recovery and benchmark contracts [skip ci]

* [comment audit] Condense tooling and Windows lifecycle proof rationale [skip ci]

* [comment audit] Condense workflow routing and release rationale [skip ci]

* [comment audit] Condense mobile security and installer contracts [skip ci]

* [comment audit] Shorten native rationale and stylesheet workarounds [skip ci]

* [comment audit] Shorten Windows visibility probe rationale [skip ci]

* [comment audit] Condense embedded release and signing rationale [skip ci]

* [comment audit] Retain current main test behavior in final reconciliation [skip ci]

* [comment audit] Complete final comment review across current source inventory

* [comment audit] Handle consolidated audit reports before final CI

* [comment audit] Preserve credential storage census detail [skip ci]

* [comment audit] Scale broad changed E2E selections with verified timing shards

* [comment audit] Align E2E assertions with browser close and settled session metadata

* [comment audit] Match existing E2Es to current resource and windowing contracts

* [comment audit] Observe the shared server outage notice in reconnect coverage

* [comment audit] Make existing renderer probes measure settled tab and PTY work

* [comment audit] Align palette E2E selector with task search

* [comment audit] Refresh remaining palette search selectors

* [comment audit] Keep selector correction within selected audit specs

* [comment audit] Await emoji fixture settings inside renderer evaluation

* [comment audit] Cancel fixture fit retries between terminal tests

---------

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
2026-10-25 04:05:46 -07:00

618 lines
27 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { mobileWebAppDependenciesPresent } from './mobile-web-app-bundle-dependencies.mjs'
import {
escapeDenseStream,
FIRST_MARKER,
LAST_MARKER,
MIN_STREAM_BYTES
} from './preview/mobile-web-app-terminal-probe-route.mjs'
import {
CONTROL_ROUTE,
openProbeTerminal,
PROBE_ROUTE,
startTerminalRenderFixture
} from './mobile-web-app-terminal-render-fixture.mjs'
import {
readRootComputedStyles,
terminalStyleReach
} from './preview/mobile-web-app-render-harness.mjs'
// Render real terminal modules/xterm under script-src self without unsafe-inline/eval; module tests cannot prove paint or CSP.
// Escape-dense TUI bytes stress transport; read exact transcript through real selection/Copy/onSelectionCopy path.
// Scratch route mounts terminal without scripting session’s full host handshake.
const bundles = mobileWebAppDependenciesPresent()
const describeRender = bundles ? describe : describe.skip
let fixture = null
let controlCspViolations = []
const stream = escapeDenseStream()
const openPage = (pathname, options) => fixture.openPage(pathname, options)
const openTerminal = (options) => fixture.openTerminal(options)
beforeAll(async () => {
if (!bundles) {
return
}
fixture = await startTerminalRenderFixture()
}, 600_000)
afterAll(async () => {
await fixture?.close()
})
// Subtract control CSP violations to attribute terminal’s own effects.
async function terminalCspViolations(page) {
const seen = await page.evaluate(() => globalThis.__orcaCspViolations)
const shared = new Set(controlCspViolations.map(stripAssetPath))
return seen.map(stripAssetPath).filter((entry) => !shared.has(entry))
}
// Normalize per-run port/content-hash asset names out of findings.
function stripAssetPath(entry) {
return entry.replace(/ @ .*$/, '')
}
describeRender(
'the terminal on the page',
() => {
it('records what the page refuses before any terminal is on it', async () => {
// Run control first and require marker paint before subtracting it; unmounted control cannot validate zero terminal violations.
const { page } = await openPage(CONTROL_ROUTE)
await page.waitForFunction(() => globalThis.__orcaTerminalControlMounted === true, {
timeout: 60_000,
polling: 100
})
controlCspViolations = await page.evaluate(() => globalThis.__orcaCspViolations)
console.log('[c7.5][csp-control]', JSON.stringify(controlCspViolations.map(stripAssetPath)))
// Control is now clean after jitless banner stopped Zod’s swallowed new Function probe; keep subtraction for terminal-specific attribution.
expect(controlCspViolations.map(stripAssetPath)).toEqual([])
await page.close()
}, 300_000)
it('opens xterm under the shipped policy and paints a dense stream into its buffer', async () => {
const fonts = []
const { errors, page } = await openTerminal({
beforeNavigate: async (page) => {
page.on('response', (response) => {
if (response.url().endsWith('.woff2')) {
fonts.push(response)
}
})
}
})
await openProbeTerminal(page)
expect(fonts).toHaveLength(1)
expect(fonts[0].status()).toBe(200)
expect(fonts[0].headers()['content-type']).toBe('font/woff2')
const fontUrl = new URL(fonts[0].url())
expect(fontUrl.origin).toBe(new URL(page.url()).origin)
expect(fontUrl.pathname).toMatch(/^\/assets\/[^/]+\.woff2$/)
expect(
await page.evaluate(() => document.fonts.check('13px "Orca Nerd Font Symbols"', '\ue0b0'))
).toBe(true)
const applied = await page.evaluate((data) => {
globalThis.__orcaTerminalProbe.write(data)
return data.length
}, stream)
expect(applied).toBeGreaterThanOrEqual(MIN_STREAM_BYTES)
// Read through real select-all/Copy overlay into onSelectionCopy, not private xterm state.
await page.evaluate(() => globalThis.__orcaTerminalProbe.selectAll())
await page.waitForFunction(
() => document.getElementById('selection-overlay')?.classList.contains('active') === true,
{ timeout: 30_000, polling: 100 }
)
await page.evaluate(() => document.getElementById('sel-menu-copy').click())
await page.waitForFunction(() => typeof globalThis.__orcaTerminalCopied === 'string', {
timeout: 30_000,
polling: 100
})
const copied = await page.evaluate(() => globalThis.__orcaTerminalCopied)
console.log(
'[c7.5][stream]',
JSON.stringify({ appliedBytes: applied, readBackChars: copied.length })
)
expect(copied).toContain(FIRST_MARKER)
expect(copied).toContain(LAST_MARKER)
// Escape bytes must affect terminal, not print literally.
expect(copied).not.toContain('\u001b')
expect(copied).not.toContain('[31;1m')
expect(await terminalCspViolations(page)).toEqual([])
expect(await page.evaluate(() => globalThis.__orcaTerminalEngineErrors)).toEqual([])
expect(errors).toEqual([])
await page.close()
}, 300_000)
it('leaves the page its own window.onerror across mount and dispose', async () => {
// Preserve preexisting page error-handler identity through mount/dispose; non-null/same-shape checks would miss replacement.
const { page } = await openTerminal({ errorSentinel: true })
expect(await page.evaluate(() => window.onerror === globalThis.__orcaSentinel)).toBe(true)
await openProbeTerminal(page)
expect(await page.evaluate(() => window.onerror === globalThis.__orcaSentinel)).toBe(true)
// Require both page and terminal error reporters work; preserved page handler alone could hide broken terminal reporting.
await page.evaluate(() => {
setTimeout(() => {
throw new Error('orca-terminal-render-uncaught')
}, 0)
})
const sawIt = (entries) =>
entries.some((entry) => entry.includes('orca-terminal-render-uncaught'))
await page.waitForFunction(
() =>
globalThis.__orcaTerminalEngineErrors.some((entry) =>
entry.includes('orca-terminal-render-uncaught')
),
{ timeout: 30_000, polling: 100 }
)
expect(sawIt(await page.evaluate(() => globalThis.__orcaSentinelCalls))).toBe(true)
// Dispose removes terminal listener while retaining page handler.
await page.evaluate(() => globalThis.__orcaTerminalProbe.setMounted(false))
await page.locator('#terminal-container').waitFor({ state: 'detached', timeout: 30_000 })
expect(await page.evaluate(() => window.onerror === globalThis.__orcaSentinel)).toBe(true)
const before = await page.evaluate(() => {
setTimeout(() => {
throw new Error('orca-terminal-render-after-dispose')
}, 0)
return globalThis.__orcaTerminalEngineErrors.length
})
await page.waitForFunction(
() =>
globalThis.__orcaSentinelCalls.some((entry) =>
entry.includes('orca-terminal-render-after-dispose')
),
{ timeout: 30_000, polling: 100 }
)
// Page must receive error after terminal reporter is disposed.
expect(await page.evaluate(() => globalThis.__orcaTerminalEngineErrors.length)).toBe(before)
await page.close()
}, 300_000)
it('installs no window.onerror on a page that had none', async () => {
// With no initial handler, dispose must leave slot free for later consumer.
const { page } = await openTerminal()
expect(await page.evaluate(() => window.onerror)).toBe(null)
await openProbeTerminal(page)
expect(await page.evaluate(() => window.onerror)).toBe(null)
await page.evaluate(() => globalThis.__orcaTerminalProbe.setMounted(false))
await page.locator('#terminal-container').waitFor({ state: 'detached', timeout: 30_000 })
expect(await page.evaluate(() => window.onerror)).toBe(null)
await page.close()
}, 300_000)
// ES module bodies run once; remount must reacquire live DOM/listeners rather than retain detached first-mount elements.
// Read live behavior: component readiness handshake alone does not prove engine uses current nodes.
/** The listeners the page holds with no terminal on it, which is what two mounts can differ by. */
async function listenersWithNoTerminal(page) {
await page.evaluate(() => globalThis.__orcaTerminalProbe.setMounted(false))
await page.locator('#terminal-container').waitFor({ state: 'detached', timeout: 30_000 })
return page.evaluate(() => globalThis.__orcaListeners.snapshot())
}
async function assertLiveTerminal(page, label) {
await page.locator('#terminal-surface .xterm').waitFor({ state: 'attached', timeout: 30_000 })
expect(
await page.evaluate(() => document.querySelectorAll('#terminal-surface .xterm').length),
`${label}: xterm elements in the live DOM`
).toBeGreaterThan(0)
// Overlay through handle proves message path targets current mounted elements.
await page.evaluate(() => globalThis.__orcaTerminalProbe.selectAll())
await page.waitForFunction(
() => document.getElementById('selection-overlay')?.classList.contains('active') === true,
{ timeout: 30_000, polling: 100 }
)
// Error reporter must reinstall per mount.
const marker = `orca-remount-${label}`
await page.evaluate((thrown) => {
globalThis.__orcaTerminalEngineErrors = []
setTimeout(() => {
throw new Error(thrown)
}, 0)
}, marker)
await page.waitForFunction(
(thrown) => globalThis.__orcaTerminalEngineErrors.some((entry) => entry.includes(thrown)),
marker,
{ timeout: 30_000, polling: 100 }
)
}
it('is a live terminal again after an unmount and a remount', async () => {
const { page } = await openTerminal()
await openProbeTerminal(page)
await assertLiveTerminal(page, 'first-mount')
await page.evaluate(() => globalThis.__orcaTerminalProbe.setMounted(false))
await page.locator('#terminal-container').waitFor({ state: 'detached', timeout: 30_000 })
await page.evaluate(() => {
globalThis.__orcaTerminalReady = false
globalThis.__orcaTerminalProbe.setMounted(true)
})
await page.waitForFunction(() => globalThis.__orcaTerminalReady === true, {
timeout: 60_000,
polling: 100
})
await openProbeTerminal(page)
await assertLiveTerminal(page, 'remount')
await page.close()
}, 300_000)
it('is a live terminal again after the user reloads a failed one', async () => {
// Drive pre-init uncaught error through real fatal overlay/Reload; this user remount path must rebuild document inside same component.
const { page } = await openTerminal()
await page.locator('#terminal-container').waitFor({ state: 'attached', timeout: 30_000 })
await page.evaluate(() => {
setTimeout(() => {
throw new Error('orca-terminal-render-fatal')
}, 0)
})
const reload = page.getByText('Reload')
await reload.waitFor({ timeout: 30_000 })
await page.evaluate(() => {
globalThis.__orcaTerminalReady = false
})
await reload.click()
await page.waitForFunction(() => globalThis.__orcaTerminalReady === true, {
timeout: 60_000,
polling: 100
})
await openProbeTerminal(page)
await assertLiveTerminal(page, 'after-reload')
await page.close()
}, 300_000)
it('leaves the page the listeners it found, across a mount and a dispose', async () => {
// Compare listener snapshots after two unmounted cycles: component provides no bare-page moment, and a leak must grow on second cycle.
// Include window/document resize, error, gesture and tap listeners; retained listeners may have no visible immediate failure.
const { page } = await openTerminal({ listeners: true })
await openProbeTerminal(page)
const before = await listenersWithNoTerminal(page)
await page.evaluate(() => {
globalThis.__orcaTerminalReady = false
globalThis.__orcaTerminalProbe.setMounted(true)
})
await page.waitForFunction(() => globalThis.__orcaTerminalReady === true, {
timeout: 60_000,
polling: 100
})
await openProbeTerminal(page)
const whileLive = await page.evaluate(() => globalThis.__orcaListeners.snapshot())
const after = await listenersWithNoTerminal(page)
// Require recorder observed listener installs or empty baseline could pass leak equality.
expect(whileLive, 'the mount installed listeners the dispose has to take back').not.toEqual(
before
)
expect(after).toEqual(before)
await page.close()
}, 300_000)
it('still reports runtime errors after a first mount spent the non-fatal budget', async () => {
// Nonfatal error cap is per document instance: first mount spending five notifications must not mute replacement.
const { page } = await openTerminal()
await openProbeTerminal(page)
await page.evaluate(() => {
for (let index = 0; index < 6; index++) {
setTimeout(() => {
throw new Error(`orca-budget-burn-${String(index)}`)
}, 0)
}
})
await page.waitForFunction(
() =>
globalThis.__orcaTerminalEngineErrors.filter((entry) =>
entry.includes('orca-budget-burn')
).length >= 5,
{ timeout: 30_000, polling: 100 }
)
await page.evaluate(() => globalThis.__orcaTerminalProbe.setMounted(false))
await page.locator('#terminal-container').waitFor({ state: 'detached', timeout: 30_000 })
await page.evaluate(() => {
globalThis.__orcaTerminalReady = false
globalThis.__orcaTerminalProbe.setMounted(true)
})
await page.waitForFunction(() => globalThis.__orcaTerminalReady === true, {
timeout: 60_000,
polling: 100
})
await openProbeTerminal(page)
await page.evaluate(() => {
globalThis.__orcaTerminalEngineErrors = []
setTimeout(() => {
throw new Error('orca-second-mount-error')
}, 0)
})
await page.waitForFunction(
() =>
globalThis.__orcaTerminalEngineErrors.some((entry) =>
entry.includes('orca-second-mount-error')
),
{ timeout: 30_000, polling: 100 }
)
await page.close()
}, 300_000)
it('cancels the timers it armed, so none of the first mount fires into the second', async () => {
// Disposed timers/frames must not act on replacement; test each on its own witness.
// Attribute schedules to document chunk identified by host-notify literal; xterm renderer owns unrelated harmless callbacks.
let documentChunk = null
const { page } = await openPage(PROBE_ROUTE, {
scheduler: true,
beforeNavigate: async (opened) => {
await opened.route('**/*.js', async (route) => {
const response = await route.fetch()
const body = await response.text()
if (body.includes('terminal runtime error')) {
documentChunk = new URL(route.request().url()).pathname
}
await route.fulfill({ response, body })
})
}
})
await page.waitForFunction(() => globalThis.__orcaTerminalReady === true, {
timeout: 60_000,
polling: 100
})
await openProbeTerminal(page)
expect(documentChunk, 'the document was served as its own chunk').not.toBe(null)
// Arm document’s 550ms scroll-indicator timer, smooth-scroll frame and 500ms long-press in disposal task.
// Long-press needs no engine paint; precondition proves provocation landed without racing renderer.
await page.evaluate(() => {
globalThis.__orcaScheduler.watching = true
const surface = document.getElementById('terminal-surface')
surface.dispatchEvent(
new TouchEvent('touchstart', {
bubbles: true,
cancelable: true,
touches: [new Touch({ identifier: 1, target: surface, clientX: 100, clientY: 400 })],
changedTouches: [
new Touch({ identifier: 1, target: surface, clientX: 100, clientY: 400 })
]
})
)
globalThis.__orcaTerminalProbe.setMounted(false)
})
await page.locator('#terminal-container').waitFor({ state: 'detached', timeout: 30_000 })
await page.evaluate(() => {
globalThis.__orcaTerminalReady = false
globalThis.__orcaTerminalProbe.setMounted(true)
})
await page.waitForFunction(() => globalThis.__orcaTerminalReady === true, {
timeout: 60_000,
polling: 100
})
await openProbeTerminal(page)
// Wait beyond longest first-mount timer so surviving work would execute.
await page.evaluate(() => new Promise((resolve) => globalThis.setTimeout(resolve, 3000)))
const scheduler = await page.evaluate(() => globalThis.__orcaScheduler)
// Require pending work existed or empty leak list proves nothing.
expect(
scheduler.scheduled.filter(
(entry) => entry.owned && entry.kind === 'timer' && entry.caller.includes(documentChunk)
).length
).toBeGreaterThan(0)
expect(
scheduler.leaked.filter(
(entry) => entry.startsWith('timer ') && entry.includes(documentChunk)
)
).toEqual([])
await page.unrouteAll({ behavior: 'ignoreErrors' })
await page.close()
}, 300_000)
it.each([
{ name: 'takes back the frames it is owed, not only the timers', cancelFrames: true },
{ name: 'detects leaked frames when disposal cannot cancel them', cancelFrames: false }
])(
'$name',
async ({ cancelFrames }) => {
// Hold real refit frame across disposal so ResizeObserver cannot race witness.
let documentChunk = null
const { page } = await openPage(PROBE_ROUTE, {
scheduler: true,
beforeNavigate: async (opened) => {
await opened.route('**/*.js', async (route) => {
const response = await route.fetch()
const body = await response.text()
if (body.includes('terminal runtime error')) {
documentChunk = new URL(route.request().url()).pathname
}
await route.fulfill({ response, body })
})
}
})
try {
await page.waitForFunction(() => globalThis.__orcaTerminalReady === true, {
timeout: 60_000,
polling: 100
})
await openProbeTerminal(page)
expect(documentChunk, 'the document was served as its own chunk').not.toBe(null)
// Settle ready’s pending replay-fit first; otherwise it consumes resize before observer can schedule frame under test.
await page.evaluate(
() =>
new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))
)
await page.evaluate((chunk) => {
const state = globalThis.__orcaScheduler
state.disposed = null
state.watching = true
state.holdFramesFrom = chunk
const host = document.querySelector('.orca-terminal-document-host')
// Dispose removes class after cancelling frames; DOM detachment occurs before cleanup.
const observer = new MutationObserver(() => {
if (
state.disposed !== null ||
host.classList.contains('orca-terminal-document-host')
) {
return
}
state.disposed = {
owed: state.scheduled.filter(
(entry) => entry.kind === 'frame' && !entry.fired && entry.caller.includes(chunk)
).length,
leakedBefore: state.leaked.length
}
observer.disconnect()
})
observer.observe(host, { attributes: true, attributeFilter: ['class'] })
host.style.width = '80%'
}, documentChunk)
await page.waitForFunction(() => globalThis.__orcaScheduler.heldFrames > 0, undefined, {
timeout: 30_000
})
await page.evaluate((cancelFrames) => {
globalThis.__orcaRestoreFrameCancellation = globalThis.cancelAnimationFrame
if (!cancelFrames) {
// Negative control must expose held callbacks after real document disposal.
globalThis.cancelAnimationFrame = () => {}
}
globalThis.__orcaTerminalProbe.setMounted(false)
}, cancelFrames)
await page.locator('#terminal-container').waitFor({ state: 'detached', timeout: 30_000 })
await page.waitForFunction(() => globalThis.__orcaScheduler.disposed !== null)
await page.evaluate(() => {
globalThis.cancelAnimationFrame = globalThis.__orcaRestoreFrameCancellation
globalThis.__orcaScheduler.holdFramesFrom = null
globalThis.__orcaTerminalReady = false
globalThis.__orcaTerminalProbe.setMounted(true)
})
await page.waitForFunction(() => globalThis.__orcaTerminalReady === true, {
timeout: 60_000,
polling: 100
})
await openProbeTerminal(page)
// Require uncancelled work runs on replacement; hold mechanism must not itself hide leaks.
await page.evaluate(
() =>
new Promise((resolve) => {
globalThis.__orcaReleaseFrames()
requestAnimationFrame(() => requestAnimationFrame(resolve))
})
)
const scheduler = await page.evaluate(() => globalThis.__orcaScheduler)
expect(
scheduler.disposed?.owed,
'the document owed a frame at the moment dispose returned'
).toBeGreaterThan(0)
const leakedFrames = scheduler.leaked
.slice(scheduler.disposed.leakedBefore)
.filter((entry) => entry.startsWith('frame ') && entry.includes(documentChunk))
if (cancelFrames) {
expect(leakedFrames).toEqual([])
} else {
expect(
leakedFrames.length,
'the recorder must expose uncancelled work'
).toBeGreaterThan(0)
}
} finally {
await page.unrouteAll({ behavior: 'ignoreErrors' }).finally(() => page.close())
}
},
300_000
)
it('styles what it owns, and only that', async () => {
// WebView sheet owns *, html and body, but page terminal owns only its host: omit document rules and scope remaining selectors.
// Compare same app without terminal; unscoped rules would alter all screens even after terminal disposal.
const control = await openPage(CONTROL_ROUTE)
const expected = await readRootComputedStyles(control.page)
await control.page.close()
const { page } = await openTerminal()
await openProbeTerminal(page)
expect(await readRootComputedStyles(page), 'roots while the terminal is mounted').toEqual(
expected
)
// Check every selector stays under host; body-only comparison misses other escaped targets.
const mounted = await terminalStyleReach(page)
// Require stylesheet rules exist so empty sheet cannot pass scoping checks.
expect(mounted.rules).toBeGreaterThan(0)
expect(mounted.outside).toEqual([])
// Positive control reads live xterm/document styles; sheet matching nothing would satisfy all isolation checks.
expect(
await page.evaluate(() => {
const host = document.querySelector('.orca-terminal-document-host')
const xterm = host.querySelector('.xterm')
const viewport = host.querySelector('.xterm-viewport')
const overlay = host.querySelector('#selection-overlay')
return {
xtermPosition: getComputedStyle(xterm).position,
// Terminal owns scrolling; viewport must not reserve width for browser scrollbar.
viewportOverflowY: getComputedStyle(viewport).overflowY,
viewportReservesScrollbar: viewport.offsetWidth !== viewport.clientWidth,
// Overlay uses host-local unscaled coordinates; fixed would cover page header.
overlayPosition: getComputedStyle(overlay).position
}
})
).toEqual({
xtermPosition: 'relative',
viewportOverflowY: 'hidden',
viewportReservesScrollbar: false,
overlayPosition: 'absolute'
})
await page.evaluate(() => globalThis.__orcaTerminalProbe.setMounted(false))
await page.locator('#terminal-container').waitFor({ state: 'detached', timeout: 30_000 })
expect(await readRootComputedStyles(page), 'roots after dispose').toEqual(expected)
// Retain stylesheet across mounts; without host it must match nothing.
const disposed = await terminalStyleReach(page)
expect(disposed.rules).toBe(mounted.rules)
expect(disposed.outside).toEqual([])
await page.close()
}, 300_000)
it('fits through the handle from the ready box and records what beforeinput reports', async () => {
const { page } = await openTerminal()
await openProbeTerminal(page)
// Fit uses actual cell box from web-ready and RN frame; null means missing/too-small measurable grid.
const fit = await page.evaluate(() => globalThis.__orcaTerminalProbe.fit())
expect(fit).not.toBeNull()
expect(fit.cols).toBeGreaterThanOrEqual(20)
expect(fit.rows).toBeGreaterThanOrEqual(8)
// xterm helper textarea is readonly/untabbable/inputmode-none; keyboard input belongs to screen field tested below.
const textarea = await page.evaluate(() => {
const element = document.querySelector('#terminal-surface .xterm-helper-textarea')
return element === null
? null
: {
readOnly: element.readOnly,
tabIndex: element.tabIndex,
inputMode: element.getAttribute('inputmode')
}
})
expect(textarea).toEqual({ readOnly: true, tabIndex: -1, inputMode: 'none' })
// Browser covers ordinary text entry; real composing soft-keyboard behavior remains device proof.
await page.getByTestId('terminal-live-input').focus()
await page.keyboard.type('ab')
await page.waitForFunction(() => globalThis.__orcaTerminalBeforeInput.length >= 2, {
timeout: 30_000,
polling: 100
})
const beforeInput = await page.evaluate(() => globalThis.__orcaTerminalBeforeInput)
console.log('[c7.5][beforeinput]', JSON.stringify(beforeInput.slice(0, 4)))
expect(beforeInput.map((entry) => entry.inputType)).toContain('insertText')
expect(beforeInput.map((entry) => entry.data)).toContain('a')
expect(beforeInput.every((entry) => entry.isComposing === false)).toBe(true)
expect(await terminalCspViolations(page)).toEqual([])
await page.close()
}, 300_000)
},
900_000
)