import { createHash, randomUUID } from 'node:crypto' import { rmSync, writeFileSync } from 'node:fs' import path from 'node:path' import { test, expect } from './helpers/orca-app' import { attachRepoAndOpenTerminal } from './helpers/orca-restart' import { focusActiveTerminalInput, getTerminalContent, sendToTerminal, waitForActivePanePtyId, waitForActiveTerminalManager, waitForTerminalOutput } from './helpers/terminal' import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' const DRAFT = 'ORCA_CODEX_PASTE_DRAFT_SHOULD_STAY_UNSENT' const CODEX_TRUST_PROMPT_RE = /Do[\s\S]*you[\s\S]*trust[\s\S]*contents/i function pastePayload(repeats = 4): string { const lines = [ 'Repository: stablyai/orca', '', 'Required exact revision:', '', '0123456789abcdef0123456789abcdef01234567', '', 'This is validation only:', '', '- Do not modify files.', '', '- Do not commit or push.', '', '- If the worktree is dirty before starting, stop and report it.', '', '- Use native Windows PowerShell, Node 24, and pnpm 12.', '', '- Confirm the checked-out full SHA before testing.', '', 'Run:', '', '1. pnpm typecheck', '', '2. pnpm lint', '', '3. Run the focused Node 24 suite and report every result.', '', '4. Run the registered Electron gate exactly as written.', '', 'If anything fails, include the first useful stack trace and distinguish product failure from test-harness or environmental failure.' ] return Array.from({ length: repeats }, () => lines.join('\r\n')).join('\r\n\r\n') } async function activateTestRepository( page: Parameters[0], repoPath: string ): Promise { const worktreeId = await attachRepoAndOpenTerminal(page, repoPath) await page.evaluate((id) => window.__store!.getState().createTab(id), worktreeId) } function pasteCollectorScript( expectedLength: number, expectedHash: string, marker: string ): string { return ` import { createHash } from 'node:crypto' process.stdin.setEncoding('utf8') if (process.stdin.isTTY) process.stdin.setRawMode(true) process.stdin.resume() let received = '' const start = String.fromCharCode(27) + '[200~' const end = String.fromCharCode(27) + '[201~' process.stdout.write(${JSON.stringify(`${marker}_READY`)} + '\\n') process.stdin.on('data', (chunk) => { received += chunk const startIndex = received.indexOf(start) const endIndex = received.indexOf(end, Math.max(0, startIndex + start.length)) if (startIndex === -1 || endIndex === -1) return const body = received.slice(startIndex + start.length, endIndex) const hash = createHash('sha256').update(body).digest('hex') const matches = body.length === ${expectedLength} && hash === ${JSON.stringify(expectedHash)} process.stdout.write(${JSON.stringify(`${marker}_RESULT:`)} + (matches ? 'MATCH' : 'MISMATCH') + ':' + body.length + ':' + hash + '\\n') process.exit(matches ? 0 : 1) }) ` } async function enableTerminalAccessibilityDom( page: Parameters[0], ptyId: string ): Promise { await page.evaluate((targetPtyId) => { const managers = Array.from(window.__paneManagers?.values() ?? []) const pane = managers .flatMap((manager) => manager.getPanes?.() ?? []) .find((candidate) => candidate.container.dataset.ptyId === targetPtyId) if (!pane) { throw new Error(`Terminal pane ${targetPtyId} is unavailable`) } // Enable screen-reader DOM rows for user-facing prompt assertions despite canvas rendering. pane.terminal.options.screenReaderMode = true pane.terminal.refresh(0, pane.terminal.rows - 1) }, ptyId) await expect( page.locator(`[data-pty-id=${JSON.stringify(ptyId)}] .xterm-accessibility-tree`) ).toBeAttached({ timeout: 10_000 }) } async function waitForCodexComposerReady( page: Parameters[0] ): Promise { // Wait for delayed MCP startup to finish after the header, then paste into idle composer. await page.waitForTimeout(5_000) await expect .poll(async () => await getTerminalContent(page, 12_000), { timeout: 60_000 }) .not.toMatch(/Booting MCP server|tab to queue message/i) // Require the idle placeholder positively; absent boot states also match an empty screen. await expect .poll(async () => await getTerminalContent(page, 12_000), { timeout: 60_000 }) .toMatch(/Ask Codex/i) } test.describe('Windows Codex multiline paste', () => { test.use({ seedTestRepo: false }) test('multiline Ctrl+V keeps the existing Codex draft unsent @local-real-codex', async ({ orcaPage, testRepoPath }) => { test.skip(process.platform !== 'win32', 'Windows ConPTY coverage is Windows-only') test.skip( process.env.ORCA_E2E_REAL_CODEX !== '1', 'Set ORCA_E2E_REAL_CODEX=1 to exercise the locally installed Codex TUI' ) test.slow() await waitForSessionReady(orcaPage) await activateTestRepository(orcaPage, testRepoPath) await waitForActiveWorktree(orcaPage) await ensureTerminalVisible(orcaPage) await waitForActiveTerminalManager(orcaPage, 30_000) const ptyId = await waitForActivePanePtyId(orcaPage) await sendToTerminal(orcaPage, ptyId, 'codex -m orca-e2e-invalid-model\r') await expect .poll(() => getTerminalContent(orcaPage, 12_000), { timeout: 20_000 }) .toMatch(/Do[\s\S]*you[\s\S]*trust[\s\S]*contents|OpenAI Codex/i) if (CODEX_TRUST_PROMPT_RE.test(await getTerminalContent(orcaPage, 12_000))) { await sendToTerminal(orcaPage, ptyId, '\r') } await waitForTerminalOutput(orcaPage, 'OpenAI Codex', 20_000, 30_000) await waitForCodexComposerReady(orcaPage) await enableTerminalAccessibilityDom(orcaPage, ptyId) await focusActiveTerminalInput(orcaPage) await orcaPage.keyboard.type(DRAFT) const terminalDom = orcaPage.locator( `[data-pty-id=${JSON.stringify(ptyId)}] .xterm-accessibility-tree` ) await expect(terminalDom).toContainText(DRAFT, { timeout: 10_000 }) await orcaPage.evaluate((text) => window.api.ui.writeClipboardText(text), pastePayload()) await orcaPage.keyboard.press('Control+V') await expect(terminalDom).toContainText('[Pasted Content', { timeout: 10_000 }) await expect(terminalDom).toContainText(DRAFT) await orcaPage.waitForTimeout(2_000) await expect(terminalDom).not.toContainText('Working') await expect(terminalDom).not.toContainText('unexpected status 404') }) test('delivers a normalized large paste through native ConPTY', async ({ orcaPage, testRepoPath }) => { test.skip(process.platform !== 'win32', 'Windows ConPTY coverage is Windows-only') test.slow() await waitForSessionReady(orcaPage) await activateTestRepository(orcaPage, testRepoPath) await waitForActiveWorktree(orcaPage) await ensureTerminalVisible(orcaPage) await waitForActiveTerminalManager(orcaPage, 30_000) const ptyId = await waitForActivePanePtyId(orcaPage) const payload = pastePayload(110) const expectedText = payload.replace(/\r?\n/g, '\r') // Require normalized payload >64KiB so chunked-lane coverage survives changes to byte-planning order. expect(Buffer.byteLength(expectedText, 'utf8')).toBeGreaterThan(64 * 1024) const expectedHash = createHash('sha256').update(expectedText).digest('hex') const marker = `ORCA_LARGE_PASTE_${randomUUID().replaceAll('-', '')}` const scriptPath = path.join(testRepoPath, `.${marker}.mjs`) writeFileSync(scriptPath, pasteCollectorScript(expectedText.length, expectedHash, marker)) try { await sendToTerminal(orcaPage, ptyId, `node ${JSON.stringify(scriptPath)}\r`) await waitForTerminalOutput(orcaPage, `${marker}_READY`, 10_000, 12_000) await enableTerminalAccessibilityDom(orcaPage, ptyId) await focusActiveTerminalInput(orcaPage) await orcaPage.evaluate((text) => window.api.ui.writeClipboardText(text), payload) await orcaPage.keyboard.press('Control+V') const terminalDom = orcaPage.locator( `[data-pty-id=${JSON.stringify(ptyId)}] .xterm-accessibility-tree` ) await expect(terminalDom).toContainText(`${marker}_RESULT:MATCH`, { timeout: 30_000 }) } finally { rmSync(scriptPath, { force: true }) } }) })