| 1 | // Actual Windows Terminal clipboard acceptance on disposable GitHub runners. |
| 2 | // Uses a disposable home and the existing draft stash; no inference or credentials. |
| 3 | // This qualifies clipboard-to-draft delivery in the runner's interactive session, not |
| 4 | // every Windows desktop, IME, remote-desktop client or terminal distribution. |
| 5 | import assert from 'node:assert/strict'; |
| 6 | import { createHash, randomUUID } from 'node:crypto'; |
| 7 | import fs from 'node:fs/promises'; |
| 8 | import { appendFileSync } from 'node:fs'; |
| 9 | import path from 'node:path'; |
| 10 | import { spawn, execFileSync } from 'node:child_process'; |
| 11 | import { fileURLToPath } from 'node:url'; |
| 12 | import { setTimeout as delay } from 'node:timers/promises'; |
| 13 | |
| 14 | assert.equal(process.platform, 'win32', 'requires a real Windows desktop'); |
| 15 | assert.equal(process.env.GITHUB_ACTIONS, 'true', 'disposable GitHub runner only'); |
| 16 | const [binaryArg, evidenceArg] = process.argv.slice(2); |
| 17 | assert.ok(binaryArg && evidenceArg, 'usage: node windows-terminal-clipboard.mjs BINARY EVIDENCE_DIR'); |
| 18 | const binary = path.resolve(binaryArg); |
| 19 | const evidence = path.resolve(evidenceArg); |
| 20 | await fs.mkdir(evidence, { recursive: true }); |
| 21 | const root = await fs.mkdtemp(path.join(process.env.RUNNER_TEMP, 'cw-terminal-fixture-')); |
| 22 | const qaHome = path.join(root, 'home'); |
| 23 | const workspace = path.join(root, 'workspace'); |
| 24 | const terminalRoot = path.join(root, 'terminal'); |
| 25 | const title = `Codewhale clipboard ${randomUUID()}`; |
| 26 | const expected = Array.from({ length: 24 }, (_, n) => `cw-clipboard-${String(n + 1).padStart(2, '0')} 漢字 🐳 line ${n + 1}`).join('\n'); |
| 27 | const stashFile = path.join(qaHome, '.codewhale', 'composer_stash.jsonl'); |
| 28 | const receipt = { source: process.env.GITHUB_SHA, binary, result: 'failed', scope: 'Windows Terminal clipboard-to-stashed-draft', lineCount: 24, harnessSubmitKeys: 0, title }; |
| 29 | let desktop; |
| 30 | let desktopClosed; |
| 31 | let desktopEnv; |
| 32 | let terminal; |
| 33 | let desktopError = ''; |
| 34 | |
| 35 | async function until(check, label, milliseconds = 60_000) { |
| 36 | const deadline = Date.now() + milliseconds; |
| 37 | while (Date.now() < deadline) { |
| 38 | const result = await check(); |
| 39 | if (result) return result; |
| 40 | assert.ok(!receipt.desktop?.error && desktop?.exitCode === null && desktop?.signalCode === null, `desktop stopped while waiting for ${label}: ${desktopError}`); |
| 41 | await delay(100); |
| 42 | } |
| 43 | throw new Error(`deadline waiting for ${label}: ${desktopError}`); |
| 44 | } |
| 45 | const exists = async name => fs.access(path.join(evidence, name)).then(() => true, () => false); |
| 46 | try { |
| 47 | receipt.binarySha256 = createHash('sha256').update(await fs.readFile(binary)).digest('hex'); |
| 48 | receipt.version = execFileSync(binary, ['--version'], { encoding: 'utf8' }).trim(); |
| 49 | for (const dir of [workspace, path.join(qaHome, '.codewhale'), path.join(qaHome, '.deepseek'), path.join(qaHome, 'AppData', 'Roaming'), path.join(qaHome, 'AppData', 'Local')]) await fs.mkdir(dir, { recursive: true }); |
| 50 | const config = 'telemetry = false\n[notifications]\nmethod = "off"\ncompletion_sound = "off"\n'; |
| 51 | for (const folder of ['.codewhale', '.deepseek']) await fs.writeFile(path.join(qaHome, folder, 'config.toml'), config); |
| 52 | assert.equal(await fs.lstat(stashFile).then(() => true, error => { if (error.code === 'ENOENT') return false; throw error; }), false, 'fresh profile has no preexisting draft stash'); |
| 53 | await fs.writeFile(path.join(evidence, 'expected.txt'), expected.replaceAll('\n', '\r\n')); |
| 54 | // Official Microsoft ZIP, pinned by release and GitHub's asset SHA-256. |
| 55 | const terminalUrl = 'https://github.com/microsoft/terminal/releases/download/v1.25.2733.0/Microsoft.WindowsTerminal_1.25.2733.0_x64.zip'; |
| 56 | const terminalHash = 'bf3ef2012f6c44d8340a4c58125acc9498d19b580f9890dc043cdf831852e796'; |
| 57 | let bytes; |
| 58 | for (let attempt = 1; attempt <= 5; attempt += 1) { |
| 59 | try { |
| 60 | const download = await fetch(terminalUrl, { signal: AbortSignal.timeout(180_000) }); |
| 61 | assert.equal(download.status, 200, 'official Terminal download'); |
| 62 | const candidate = Buffer.from(await download.arrayBuffer()); |
| 63 | assert.equal(createHash('sha256').update(candidate).digest('hex'), terminalHash, 'Terminal asset digest'); |
| 64 | bytes = candidate; |
| 65 | break; |
| 66 | } catch (error) { |
| 67 | if (attempt === 5) throw error; |
| 68 | await new Promise(resolve => setTimeout(resolve, attempt * 15_000)); |
| 69 | } |
| 70 | } |
| 71 | const zip = path.join(root, 'terminal.zip'); await fs.writeFile(zip, bytes); |
| 72 | await fs.mkdir(terminalRoot); |
| 73 | execFileSync('tar.exe', ['-xf', zip, '-C', terminalRoot], { timeout: 60_000 }); |
| 74 | const files = await fs.readdir(terminalRoot, { recursive: true }); |
| 75 | const executables = files.filter(f => path.basename(f).toLowerCase() === 'windowsterminal.exe'); |
| 76 | assert.equal(executables.length, 1, 'unique portable Terminal executable'); |
| 77 | terminal = path.join(terminalRoot, executables[0]); |
| 78 | const terminalDir = path.dirname(terminal); |
| 79 | await fs.writeFile(path.join(terminalDir, '.portable'), ''); |
| 80 | await fs.mkdir(path.join(terminalDir, 'settings'), { recursive: true }); |
| 81 | const profile = '{9e4b713f-d69c-4206-85fb-98663b729f17}'; |
| 82 | await fs.writeFile(path.join(terminalDir, 'settings', 'settings.json'), JSON.stringify({ |
| 83 | defaultProfile: profile, initialCols: 110, initialRows: 38, confirmCloseAllTabs: false, |
| 84 | // The payload is trusted fixture text; this tests Codewhale's paste path, |
| 85 | // excluding Terminal's own optional multiline confirmation dialog. |
| 86 | multiLinePasteWarning: false, largePasteWarning: false, |
| 87 | profiles: { defaults: { font: { size: 12 } }, list: [{ guid: profile, name: 'Codewhale fixture', commandline: 'cmd.exe' }] }, |
| 88 | actions: [{ command: 'paste', keys: 'shift+insert' }], |
| 89 | }, null, 2)); |
| 90 | const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => /^(PATH|SYSTEMROOT|WINDIR|COMSPEC|TEMP|TMP|PATHEXT|SYSTEMDRIVE|PROGRAMFILES|PROGRAMFILES\(X86\)|PROGRAMW6432|PROCESSOR_ARCHITECTURE|NUMBER_OF_PROCESSORS)$/i.test(k))); |
| 91 | Object.assign(env, { |
| 92 | HOME: qaHome, USERPROFILE: qaHome, APPDATA: path.join(qaHome, 'AppData', 'Roaming'), LOCALAPPDATA: path.join(qaHome, 'AppData', 'Local'), |
| 93 | XDG_CONFIG_HOME: path.join(qaHome, '.config'), XDG_DATA_HOME: path.join(qaHome, '.local', 'share'), XDG_CACHE_HOME: path.join(qaHome, '.cache'), |
| 94 | CODEWHALE_CONFIG_PATH: path.join(qaHome, '.codewhale', 'config.toml'), DEEPSEEK_CONFIG_PATH: path.join(qaHome, '.deepseek', 'config.toml'), |
| 95 | CODEWHALE_TELEMETRY: '0', CODEWHALE_NO_UPDATE_CHECK: '1', CODEWHALE_DISABLE_MODELS_DEV_FETCH: '1', CODEWHALE_DISABLE_LOCAL_OLLAMA_PROBE: '1', NO_ANIMATIONS: '1', |
| 96 | }); |
| 97 | desktopEnv = env; |
| 98 | receipt.terminal = { version: '1.25.2733.0', sha256: terminalHash, distribution: 'official portable x64' }; |
| 99 | const script = fileURLToPath(new URL('./windows-terminal-clipboard.ps1', import.meta.url)); |
| 100 | receipt.desktop = { requestedAt: new Date().toISOString() }; |
| 101 | desktop = spawn('powershell.exe', ['-NoProfile', '-STA', '-File', script, terminal, binary, workspace, title, evidence], { env, windowsHide: false, stdio: ['ignore', 'pipe', 'pipe'] }); |
| 102 | desktop.stdout.on('data', data => { try { appendFileSync(path.join(evidence, 'desktop.log'), data); } catch (error) { receipt.desktop.logError = String(error); desktopError += String(error); } }); |
| 103 | desktop.stderr.on('data', data => { desktopError += data; try { appendFileSync(path.join(evidence, 'desktop-error.log'), data); } catch (error) { receipt.desktop.logError = String(error); desktopError += String(error); } }); |
| 104 | desktop.once('spawn', () => { receipt.desktop.pid = desktop.pid; receipt.desktop.spawnedAt = new Date().toISOString(); }); |
| 105 | desktopClosed = new Promise(resolve => { |
| 106 | desktop.once('error', error => { receipt.desktop.error = String(error); desktopError += String(error); }); |
| 107 | desktop.once('exit', (code, signal) => { receipt.desktop.exit = { code, signal, at: new Date().toISOString() }; }); |
| 108 | desktop.once('close', code => { receipt.desktop.closedAt = new Date().toISOString(); resolve(code); }); |
| 109 | }); |
| 110 | await until(() => exists('ready.json'), 'Windows Terminal composer readiness', 120_000); |
| 111 | receipt.readyAt = new Date().toISOString(); |
| 112 | await until(() => exists('pasted.json'), 'actual clipboard paste'); |
| 113 | receipt.pastedAt = new Date().toISOString(); |
| 114 | await fs.writeFile(path.join(evidence, 'stash'), 'stash once'); |
| 115 | await until(() => exists('completed.json'), 'actual composer stash'); |
| 116 | const metadata = await fs.lstat(stashFile); |
| 117 | assert.ok(metadata.isFile() && !metadata.isSymbolicLink(), 'draft stash is a regular file'); |
| 118 | assert.ok(metadata.size <= 64 * 1024, 'draft stash stays bounded'); |
| 119 | const stashBytes = await fs.readFile(stashFile); |
| 120 | const lines = stashBytes.toString('utf8').split(/\r?\n/); |
| 121 | if (lines.at(-1) === '') lines.pop(); |
| 122 | assert.equal(lines.length, 1, 'exactly one draft stash record'); |
| 123 | const draft = JSON.parse(lines[0]); |
| 124 | assert.ok(draft && typeof draft === 'object' && !Array.isArray(draft) && typeof draft.text === 'string' && typeof draft.ts === 'string', 'draft stash record has text and timestamp'); |
| 125 | assert.ok(Number.isFinite(Date.parse(draft.ts)), 'draft stash timestamp is valid'); |
| 126 | const normalized = draft.text.replaceAll('\r\n', '\n'); |
| 127 | assert.equal(normalized, expected, 'all24 Unicode lines are stashed exactly'); |
| 128 | for (let line = 1; line <= 24; line++) assert.equal(normalized.split(`cw-clipboard-${String(line).padStart(2, '0')}`).length - 1, 1, `line${line} occurs once`); |
| 129 | await fs.writeFile(path.join(evidence, 'composer_stash.jsonl'), stashBytes); |
| 130 | receipt.stash = { path: stashFile, sha256: createHash('sha256').update(stashBytes).digest('hex'), records: 1, exactDraftMatch: true, normalization: 'CRLF to LF only' }; |
| 131 | assert.equal(await desktopClosed, 0, desktopError); |
| 132 | assert.equal(desktopError, '', 'no desktop errors'); |
| 133 | receipt.cleanup = JSON.parse((await fs.readFile(path.join(evidence, 'cleanup.json'), 'utf8')).replace(/^\uFEFF/, '')); |
| 134 | assert.equal(receipt.cleanup.terminal, terminal, 'cleanup used the owned Terminal path'); |
| 135 | assert.equal(receipt.cleanup.remaining, 0, 'owned Terminal processes are gone'); |
| 136 | receipt.result = 'passed'; |
| 137 | } catch (error) { |
| 138 | receipt.error = String(error); process.exitCode = 1; |
| 139 | } finally { |
| 140 | if (desktop) { |
| 141 | receipt.desktop.beforeCleanup = { exitCode: desktop.exitCode, signalCode: desktop.signalCode, at: new Date().toISOString() }; |
| 142 | if (desktop.exitCode === null && desktop.signalCode === null) { |
| 143 | receipt.desktop.cancelRequestedAt = new Date().toISOString(); |
| 144 | try { |
| 145 | await fs.writeFile(path.join(evidence, 'cancel'), 'retire owned Terminal'); |
| 146 | await Promise.race([desktopClosed, delay(5000)]); |
| 147 | } catch (error) { receipt.desktop.cancelError = String(error); } |
| 148 | } |
| 149 | if (receipt.result !== 'passed') { |
| 150 | try { |
| 151 | const cleanup = execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', |
| 152 | '$ErrorActionPreference = "Stop"; $terminal = $env:CODEWHALE_CLIPBOARD_TERMINAL; $stopped = @(); foreach ($process in @(Get-Process | Where-Object { $_.Path -eq $terminal })) { Stop-Process -InputObject $process -Force; if (!$process.WaitForExit(5000)) { throw "Owned Terminal did not exit" }; $stopped += $process.Id }; $remaining = @(Get-Process | Where-Object { $_.Path -eq $terminal }).Count; if ($remaining) { throw "Owned Terminal is still running" }; @{ terminal = $terminal; stopped = $stopped; remaining = $remaining } | ConvertTo-Json -Compress'], |
| 153 | { env: { ...desktopEnv, CODEWHALE_CLIPBOARD_TERMINAL: terminal }, encoding: 'utf8', timeout: 10_000 }); |
| 154 | receipt.desktop.fallbackCleanup = JSON.parse(cleanup.replace(/^\uFEFF/, '')); |
| 155 | assert.equal(receipt.desktop.fallbackCleanup.terminal, terminal, 'fallback cleanup used the owned Terminal path'); |
| 156 | assert.equal(receipt.desktop.fallbackCleanup.remaining, 0, 'fallback cleanup retired the owned Terminal'); |
| 157 | } catch (error) { |
| 158 | receipt.desktop.cleanupError = String(error); receipt.result = 'failed'; process.exitCode = 1; |
| 159 | } |
| 160 | } |
| 161 | if (desktop.exitCode === null && desktop.signalCode === null) { |
| 162 | receipt.desktop.killRequestedAt = new Date().toISOString(); desktop.kill(); |
| 163 | } |
| 164 | await desktopClosed; |
| 165 | } |
| 166 | await fs.writeFile(path.join(evidence, 'receipt.json'), JSON.stringify(receipt, null, 2)); |
| 167 | console.log(JSON.stringify(receipt)); |
| 168 | } |
| 169 |