Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.
TypeScript adeagent-ideai-agentsautomationbotclaude-codecodexghosttygrok-bothermes-agentmobile-appmuseopenclawopencodeorchestrationpiruntimeterminalworktreesyc-backed
// @vitest-environment happy-dom
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { Script } from 'node:vm'
import { parse } from 'acorn'
import { describe, expect, it, vi } from 'vitest'
import { TERMINAL_NERD_FONT_CSS, XTERM_ENGINE_CSS } from './terminal-webview-engine-css.generated'
import { XTERM_ENGINE_JS } from './terminal-webview-engine.generated'
import { createTerminalDocumentScope } from './document/document-scope'
import { attachWebglAddon, startWebglRecovery } from './document/webgl-recovery'
import { XTERM_HTML } from './terminal-webview-html'
import { applyTerminalTheme } from './document/terminal-theme'
function createWebglRecoveryHarness(failSecondAttach = false) {
const timers: Array<() => void> = []
const addons: Array<{
clearTextureAtlas: ReturnType<typeof vi.fn>
dispose: ReturnType<typeof vi.fn>
fireContextLoss: () => void
}> = []
const term = {
rows: 24,
options: { theme: {}, minimumContrastRatio: 0, fontSize: 13 },
refresh: vi.fn(),
loadAddon: vi.fn(() => {
if (failSecondAttach && addons.length === 2) {
throw new Error('retry unavailable')
}
})
}
function WebglAddon() {
let contextLoss = () => {}
const addon = {
clearTextureAtlas: vi.fn(),
dispose: vi.fn(),
fireContextLoss: () => contextLoss()
}
addons.push(addon)
return Object.assign(addon, {
onContextLoss: (listener: () => void) => {
contextLoss = listener
}
})
}
const logged: Record<string, unknown>[] = []
const terminalThemeInput = { mode: 'dark' }
vi.spyOn(globalThis, 'setTimeout').mockImplementation((callback: TimerHandler) => {
if (typeof callback === 'function') {
timers.push(() => {
callback()
})
}
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the document holds this only to clear it, and nothing here clears a timer.
return timers.length as unknown as ReturnType<typeof setTimeout>
})
const scope = createTerminalDocumentScope({
createWebglAddon: () => WebglAddon(),
postToHost: (message) => logged.push(message)
})
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the double implements the members the recovery path reaches, which is what each case asserts about.
scope.term = term as unknown as typeof scope.term
scope.terminalGeneration = 1
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the recovery only re-applies this value through the theme path; its shape is that path's own input.
scope.terminalThemeInput = terminalThemeInput as unknown as typeof scope.terminalThemeInput
startWebglRecovery(scope)
attachWebglAddon(scope, true)
return {
addons,
appliedThemes: () => term.options.theme,
fireVisibilityChange: () => {
document.dispatchEvent(new Event('visibilitychange'))
},
logged,
scope,
term,
terminalThemeInput,
timers
}
}
describe('terminal WebView bundled engine', () => {
it('keeps the assembled terminal HTML free of external engine URLs', () => {
expect(XTERM_HTML).not.toMatch(/\bhttps?:\/\//)
expect(XTERM_HTML).not.toContain('cdn.jsdelivr.net')
expect(XTERM_HTML).not.toContain('<script src=')
expect(XTERM_HTML).not.toContain('rel="stylesheet" href=')
})
it('ships the licensed desktop symbol font offline without covering normal text', () => {
const encoded = TERMINAL_NERD_FONT_CSS.match(/base64,([^']+)'/)?.[1]
expect(encoded).toBeTruthy()
const bundled = readFileSync(
path.resolve(import.meta.dirname, '../../assets/fonts/SymbolsNerdFontMono-Regular.woff2')
)
expect(Buffer.from(encoded ?? '', 'base64').equals(bundled)).toBe(true)
expect(
bundled.equals(
readFileSync(
path.resolve(
import.meta.dirname,
'../../../src/renderer/src/assets/fonts/SymbolsNerdFontMono-Regular.woff2'
)
)
)
).toBe(true)
expect(TERMINAL_NERD_FONT_CSS).toContain(
'unicode-range:U+E000-F8FF,U+F0000-FFFFD,U+100000-10FFFD'
)
expect(XTERM_HTML).toContain(`<style>${TERMINAL_NERD_FONT_CSS}</style>`)
expect(XTERM_HTML).toContain(
'"Liberation Mono", "Orca Nerd Font Symbols", "Symbols Nerd Font Mono"'
)
expect(TERMINAL_NERD_FONT_CSS).not.toMatch(/<\/style/i)
})
it('parses the bundled engine at the Chrome 74 syntax floor', () => {
expect(() => parse(XTERM_ENGINE_JS, { ecmaVersion: 2019 })).not.toThrow()
})
it('answers the mode query OpenCode sends during startup', async () => {
vi.useFakeTimers()
const reply = vi.fn()
const window = {}
try {
new Script(
`${XTERM_ENGINE_JS}; const terminal = new window.Terminal();
terminal.onData(reply); terminal.write('\\x1b[?1004$p');`
).runInNewContext({
window,
self: window,
document: {},
navigator: { platform: 'Linux', userAgent: 'Chrome/74' },
structuredClone,
performance,
setTimeout,
clearTimeout,
queueMicrotask,
console,
URL,
reply
})
await vi.runAllTimersAsync()
expect(reply).toHaveBeenCalledWith('\x1b[?1004;2$y')
} finally {
vi.useRealTimers()
}
})
// Omit newer WebView APIs to verify runtime shims; esbuild lowers syntax without polyfilling WeakRef/structuredClone/replaceChildren.
it('exposes the xterm globals and installs the old-WebView runtime shims', () => {
const window: Record<string, unknown> = {}
class ElementStub {}
const context = {
window,
self: window,
document: {},
Element: ElementStub,
navigator: {
platform: 'Linux armv8l',
userAgent: 'Mozilla/5.0 Chrome/74.0.3729.157'
},
console,
setTimeout,
clearTimeout,
queueMicrotask,
URL
}
new Script(XTERM_ENGINE_JS).runInNewContext(context)
expect(window).toMatchObject({
Terminal: expect.any(Function),
Unicode11Addon: { Unicode11Addon: expect.any(Function) },
WebglAddon: { WebglAddon: expect.any(Function) }
})
const weakRef = window.WeakRef as (new (target: unknown) => { deref(): unknown }) | undefined
expect(typeof weakRef).toBe('function')
const token = {}
expect(new weakRef!(token).deref()).toBe(token)
expect(typeof window.structuredClone).toBe('function')
expect(typeof (ElementStub.prototype as { replaceChildren?: unknown }).replaceChildren).toBe(
'function'
)
})
it('keeps the bundled engine from breaking out of its inline script/style tags', () => {
// Inline script/style output must neutralize closing tags and tokenizer openers that could consume the remaining HTML.
expect(XTERM_ENGINE_JS).not.toMatch(/<\/script/i)
expect(XTERM_ENGINE_JS).not.toMatch(/<script/i)
expect(XTERM_ENGINE_JS).not.toContain('<!--')
expect(XTERM_ENGINE_CSS).not.toMatch(/<\/style/i)
})
it('recreates WebGL once after context loss, then stays on the DOM renderer', () => {
const { addons, logged, term, timers } = createWebglRecoveryHarness()
expect(addons).toHaveLength(1)
addons[0]?.fireContextLoss()
expect(logged).toContainEqual({
type: 'log',
tag: '[fit]webgl-context-loss',
payload: expect.objectContaining({ retry: true })
})
expect(addons[0]?.dispose).toHaveBeenCalledTimes(1)
expect(term.refresh).toHaveBeenCalledTimes(1)
expect(timers).toHaveLength(1)
timers.shift()?.()
expect(addons).toHaveLength(2)
expect(addons[1]?.clearTextureAtlas).toHaveBeenCalledTimes(1)
expect(term.refresh).toHaveBeenCalledTimes(2)
addons[1]?.fireContextLoss()
expect(addons[1]?.dispose).toHaveBeenCalledTimes(1)
expect(term.refresh).toHaveBeenCalledTimes(3)
expect(timers).toHaveLength(0)
})
it('falls back to a refreshed DOM renderer when the delayed WebGL retry fails', () => {
const { addons, term, timers } = createWebglRecoveryHarness(true)
addons[0]?.fireContextLoss()
timers.shift()?.()
expect(addons).toHaveLength(2)
expect(addons[1]?.dispose).toHaveBeenCalledTimes(1)
expect(term.refresh).toHaveBeenCalledTimes(2)
})
it('reapplies theme, clears the active atlas, and refreshes when visible', () => {
const harness = createWebglRecoveryHarness()
applyTerminalTheme(harness.scope, harness.scope.terminalThemeInput)
const firstTheme = harness.term.options.theme
// Stub only hidden state; Happy DOM’s visible default exercises real recovery.
vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden')
harness.fireVisibilityChange()
expect(harness.term.options.theme).toBe(firstTheme)
vi.restoreAllMocks()
harness.fireVisibilityChange()
expect(harness.term.options.theme).not.toBe(firstTheme)
expect(harness.addons[0]?.clearTextureAtlas).toHaveBeenCalledTimes(1)
expect(harness.term.refresh).toHaveBeenCalledTimes(1)
})
})