ai-battery 0.1.20 → 0.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,766 +1,766 @@
1
- param(
2
- [int]$TimeoutSeconds = 12,
3
- [string]$ReportPath = "",
4
- [switch]$KeepTemp
5
- )
6
-
7
- Set-StrictMode -Version Latest
8
- $ErrorActionPreference = "Stop"
9
- $script:SmokeFailed = $false
10
- $script:SmokeReport = [ordered]@{
11
- ok = $false
12
- overallPassed = $false
13
- startedAt = (Get-Date).ToUniversalTime().ToString("o")
14
- completedAt = $null
15
- finishedAt = $null
16
- failure = $null
17
- root = $null
18
- node = $null
19
- tempDir = $null
20
- rowptyExe = $null
21
- debugLog = $null
22
- install = $null
23
- processExitCode = $null
24
- checks = [ordered]@{}
25
- cases = @()
26
- debugEvents = @()
27
- }
28
-
29
- function Set-Check($Name, $Passed, $Details = $null) {
30
- $script:SmokeReport.checks[$Name] = [ordered]@{
31
- passed = [bool]$Passed
32
- details = $Details
33
- }
34
- }
35
-
36
- function Read-DebugEvents($DebugLogPath) {
37
- if (-not $DebugLogPath -or -not (Test-Path $DebugLogPath)) {
38
- return @()
39
- }
40
- $events = @()
41
- foreach ($line in Get-Content -Path $DebugLogPath) {
42
- try {
43
- $events += ($line | ConvertFrom-Json)
44
- } catch {
45
- }
46
- }
47
- return $events
48
- }
49
-
50
- function Import-DebugEvents($DebugLogPath) {
51
- $script:SmokeReport.debugEvents += @(Read-DebugEvents $DebugLogPath)
52
- }
53
-
54
- function New-CaseResult($Name, $DebugLogPath) {
55
- return [ordered]@{
56
- name = $Name
57
- ok = $false
58
- debugLog = $DebugLogPath
59
- runnerArgs = @()
60
- argumentLine = $null
61
- processExitCode = $null
62
- checks = [ordered]@{}
63
- debugEvents = @()
64
- }
65
- }
66
-
67
- function Set-CaseCheck($CaseResult, $Name, $Passed, $Details = $null) {
68
- $CaseResult.checks[$Name] = [ordered]@{
69
- passed = [bool]$Passed
70
- details = $Details
71
- }
72
- }
73
-
74
- function Write-SmokeReport {
75
- if (-not $ReportPath) {
76
- return
77
- }
78
- $finishedAt = (Get-Date).ToUniversalTime().ToString("o")
79
- $script:SmokeReport.overallPassed = [bool]$script:SmokeReport.ok
80
- $script:SmokeReport.completedAt = $finishedAt
81
- $script:SmokeReport.finishedAt = $finishedAt
82
- if ($script:SmokeReport.debugLog) {
83
- Import-DebugEvents $script:SmokeReport.debugLog
84
- }
85
- $parent = Split-Path -Parent $ReportPath
86
- if ($parent) {
87
- New-Item -ItemType Directory -Force -Path $parent | Out-Null
88
- }
89
- $script:SmokeReport | ConvertTo-Json -Depth 8 | Set-Content -Path $ReportPath -Encoding UTF8
90
- }
91
-
92
- function Write-Step($Message) {
93
- Write-Host "[ai-battery smoke] $Message"
94
- }
95
-
96
- function Fail($Message) {
97
- $script:SmokeFailed = $true
98
- $script:SmokeReport.ok = $false
99
- $script:SmokeReport.failure = $Message
100
- Write-SmokeReport
101
- Write-Host "[ai-battery smoke] FAIL: $Message" -ForegroundColor Red
102
- if ($ReportPath) {
103
- Write-Host "[ai-battery smoke] Report: $ReportPath"
104
- }
105
- exit 1
106
- }
107
-
108
- function Quote-WindowsArg($Value) {
109
- $text = [string]$Value
110
- if ($text.Length -gt 0 -and $text -notmatch '[\s"]' -and -not $text.StartsWith("\\")) {
111
- return $text
112
- }
113
-
114
- $result = '"'
115
- $backslashes = 0
116
- foreach ($ch in $text.ToCharArray()) {
117
- if ($ch -eq [char]92) {
118
- $backslashes += 1
119
- } elseif ($ch -eq '"') {
120
- $result += ('\' * (($backslashes * 2) + 1)) + '"'
121
- $backslashes = 0
122
- } else {
123
- if ($backslashes -gt 0) {
124
- $result += ('\' * $backslashes)
125
- $backslashes = 0
126
- }
127
- $result += $ch
128
- }
129
- }
130
- if ($backslashes -gt 0) {
131
- $result += ('\' * ($backslashes * 2))
132
- }
133
- return $result + '"'
134
- }
135
-
136
- function Join-WindowsArgs {
137
- param([object[]]$Values)
138
- return (($Values | ForEach-Object { Quote-WindowsArg $_ }) -join " ")
139
- }
140
-
141
- function ConvertTo-FileUrl($Path) {
142
- $resolved = (Resolve-Path $Path).ProviderPath
143
- return ([System.Uri]$resolved).AbsoluteUri
144
- }
145
-
146
- function Add-ConsoleReaderType {
147
- if ("AiBatteryConsoleSmoke" -as [type]) {
148
- return
149
- }
150
-
151
- Add-Type -TypeDefinition @"
152
- using System;
153
- using System.Runtime.InteropServices;
154
- using System.Text;
155
-
156
- public static class AiBatteryConsoleSmoke
157
- {
158
- private const int STD_OUTPUT_HANDLE = -11;
159
-
160
- [StructLayout(LayoutKind.Sequential)]
161
- public struct COORD
162
- {
163
- public short X;
164
- public short Y;
165
- }
166
-
167
- [StructLayout(LayoutKind.Sequential)]
168
- public struct SMALL_RECT
169
- {
170
- public short Left;
171
- public short Top;
172
- public short Right;
173
- public short Bottom;
174
- }
175
-
176
- [StructLayout(LayoutKind.Sequential)]
177
- public struct CONSOLE_SCREEN_BUFFER_INFO
178
- {
179
- public COORD dwSize;
180
- public COORD dwCursorPosition;
181
- public short wAttributes;
182
- public SMALL_RECT srWindow;
183
- public COORD dwMaximumWindowSize;
184
- }
185
-
186
- [DllImport("kernel32.dll", SetLastError = true)]
187
- private static extern IntPtr GetStdHandle(int nStdHandle);
188
-
189
- [DllImport("kernel32.dll", SetLastError = true)]
190
- private static extern bool GetConsoleScreenBufferInfo(IntPtr hConsoleOutput, out CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo);
191
-
192
- [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
193
- private static extern bool ReadConsoleOutputCharacterW(IntPtr hConsoleOutput, StringBuilder lpCharacter, uint nLength, COORD dwReadCoord, out uint lpNumberOfCharsRead);
194
-
195
- public static string ReadAll()
196
- {
197
- IntPtr handle = GetStdHandle(STD_OUTPUT_HANDLE);
198
- CONSOLE_SCREEN_BUFFER_INFO info;
199
- if (!GetConsoleScreenBufferInfo(handle, out info))
200
- {
201
- return "";
202
- }
203
-
204
- int width = Math.Max(1, (int)info.dwSize.X);
205
- int height = Math.Max(1, (int)info.dwSize.Y);
206
- StringBuilder all = new StringBuilder(width * Math.Min(height, 2000));
207
- for (short y = 0; y < height; y++)
208
- {
209
- StringBuilder line = new StringBuilder(width);
210
- COORD origin = new COORD();
211
- origin.X = 0;
212
- origin.Y = y;
213
- uint read;
214
- if (ReadConsoleOutputCharacterW(handle, line, (uint)width, origin, out read))
215
- {
216
- all.Append(line.ToString());
217
- all.Append('\n');
218
- }
219
- }
220
- return all.ToString();
221
- }
222
- }
223
- "@
224
- }
225
-
226
- function Get-ConsoleText {
227
- return [AiBatteryConsoleSmoke]::ReadAll()
228
- }
229
-
230
- function Find-LastLineIndex($Text, $Marker) {
231
- $lines = ([string]$Text) -split "`n"
232
- for ($i = $lines.Length - 1; $i -ge 0; $i -= 1) {
233
- if ($lines[$i].Contains($Marker)) {
234
- return $i
235
- }
236
- }
237
- return -1
238
- }
239
-
240
- function Ensure-ConsoleScrollback {
241
- try {
242
- $targetHeight = [Math]::Max([Console]::BufferHeight, [Console]::WindowHeight + 200)
243
- if ([Console]::BufferHeight -lt $targetHeight) {
244
- [Console]::BufferHeight = $targetHeight
245
- }
246
- Set-Check "consoleScrollbackBuffer" $true "windowHeight=$([Console]::WindowHeight), bufferHeight=$([Console]::BufferHeight)"
247
- } catch {
248
- Set-Check "consoleScrollbackBuffer" $false $_.Exception.Message
249
- }
250
- }
251
-
252
- $root = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot ".."))
253
- if (-not $ReportPath) {
254
- $ReportPath = Join-Path $root "rowpty-smoke-report.json"
255
- }
256
- $script:SmokeReport.root = $root
257
-
258
- if ([System.Environment]::OSVersion.Platform -ne [System.PlatformID]::Win32NT) {
259
- Set-Check "nativeWindows" $false "platform=$([System.Environment]::OSVersion.Platform)"
260
- Fail "This smoke test must run in native Windows cmd/PowerShell/Windows Terminal."
261
- }
262
- Set-Check "nativeWindows" $true ([System.Environment]::OSVersion.VersionString)
263
-
264
- if ([Console]::IsInputRedirected -or [Console]::IsOutputRedirected) {
265
- Set-Check "interactiveConsole" $false "stdinRedirected=$([Console]::IsInputRedirected), stdoutRedirected=$([Console]::IsOutputRedirected)"
266
- Fail "Run this in an interactive terminal; stdin/stdout must not be redirected."
267
- }
268
- Set-Check "interactiveConsole" $true "stdin/stdout are real console handles"
269
-
270
- $nodeCommand = Get-Command node -ErrorAction SilentlyContinue
271
- if (-not $nodeCommand) {
272
- Set-Check "nodeOnPath" $false $null
273
- Fail "node was not found on PATH."
274
- }
275
- $node = $nodeCommand.Source
276
- Set-Check "nodeOnPath" $true $node
277
-
278
- $runner = (Resolve-Path (Join-Path $root "bin/ai-battery-run-win.js")).ProviderPath
279
- $aiBatteryModule = (Resolve-Path (Join-Path $root "bin/ai-battery.js")).ProviderPath
280
- $tempDir = Join-Path ([System.IO.Path]::GetTempPath()) ("ai-battery-rowpty-smoke-" + [System.Guid]::NewGuid().ToString("N"))
281
- New-Item -ItemType Directory -Path $tempDir | Out-Null
282
- $script:SmokeReport.node = $node
283
- $script:SmokeReport.tempDir = $tempDir
284
-
285
- try {
286
- Add-ConsoleReaderType
287
- Ensure-ConsoleScrollback
288
-
289
- $installScript = Join-Path $tempDir "install-rowpty.mjs"
290
- $moduleUrl = ConvertTo-FileUrl $aiBatteryModule
291
-
292
- Set-Content -Path $installScript -Encoding UTF8 -Value @"
293
- import { installRowPtyHost } from "$moduleUrl";
294
- const result = installRowPtyHost();
295
- console.log(JSON.stringify(result));
296
- process.exit(result.ok ? 0 : 1);
297
- "@
298
-
299
- function Write-StatusScript($Path, $Marker) {
300
- Set-Content -Path $Path -Encoding UTF8 -Value "console.log(`"$Marker 99%`");"
301
- }
302
-
303
- function Write-NodeChildScript($Path, $Prefix) {
304
- Set-Content -Path $Path -Encoding UTF8 -Value @"
305
- const prefix = "$Prefix";
306
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
307
- process.stdout.write(prefix + "_CHILD_START\n");
308
- for (let i = 0; i < 6; i += 1) {
309
- process.stdout.write(prefix + "_LINE_" + i + "\n");
310
- await sleep(80);
311
- }
312
- process.stdout.write("\x1b[?1049h" + prefix + "_ALT_SCREEN\n\x1b[?1049l");
313
- process.stdout.write("\x1b[3J" + prefix + "_AFTER_3J\n");
314
- await sleep(700);
315
- // Extra blank line: absolute rows pass through to the host viewport with the
316
- // bundled ConPTY (real-terminal semantics), so the bottom-row prompt jump
317
- // below would otherwise land on the delayed-output line and overwrite it.
318
- process.stdout.write(prefix + "_DELAYED_OUTPUT\n\n");
319
- process.stdout.write("\x1b[999;1H" + prefix + "_PROMPT_AREA> ");
320
- await sleep(4500);
321
- process.stdout.write(prefix + "_CHILD_END\n");
322
- "@
323
- }
324
-
325
- function Write-CmdChildWrapper($Path, $NodePath, $ScriptPath) {
326
- $content = @(
327
- "@echo off",
328
- (Join-WindowsArgs -Values @($NodePath, $ScriptPath)),
329
- "exit /b %ERRORLEVEL%"
330
- ) -join "`r`n"
331
- Set-Content -Path $Path -Encoding ASCII -Value $content
332
- }
333
-
334
- function Write-PowerShellChildScript($Path, $Prefix) {
335
- $content = @'
336
- $prefix = "__PREFIX__"
337
- $esc = [char]27
338
- [Console]::Out.Write($prefix + "_CHILD_START`n")
339
- for ($i = 0; $i -lt 6; $i += 1) {
340
- [Console]::Out.Write($prefix + "_LINE_" + $i + "`n")
341
- Start-Sleep -Milliseconds 80
342
- }
343
- [Console]::Out.Write("$esc[?1049h" + $prefix + "_ALT_SCREEN`n" + "$esc[?1049l")
344
- [Console]::Out.Write("$esc[3J" + $prefix + "_AFTER_3J`n")
345
- Start-Sleep -Milliseconds 700
346
- # Extra blank line: absolute rows pass through to the host viewport with the
347
- # bundled ConPTY (real-terminal semantics), so the bottom-row prompt jump
348
- # below would otherwise land on the delayed-output line and overwrite it.
349
- [Console]::Out.Write($prefix + "_DELAYED_OUTPUT`n`n")
350
- [Console]::Out.Write("$esc[999;1H" + $prefix + "_PROMPT_AREA> ")
351
- Start-Sleep -Milliseconds 4500
352
- [Console]::Out.Write($prefix + "_CHILD_END`n")
353
- '@
354
- Set-Content -Path $Path -Encoding UTF8 -Value $content.Replace("__PREFIX__", $Prefix)
355
- }
356
-
357
- function Write-CodexHistoryChildScript($Path) {
358
- # Mirrors the VT pattern captured from the real Codex TUI (0.142.x):
359
- # synchronized updates plus top-anchored DECSTBM scroll regions that push
360
- # history lines into scrollback above a bottom-pinned viewport. The OS
361
- # in-box ConPTY re-renders this pattern as full viewport repaints, losing
362
- # or duplicating history lines; the bundled WT conpty.dll passes it through.
363
- Set-Content -Path $Path -Encoding UTF8 -Value @'
364
- const esc = "\x1b";
365
- const out = process.stdout;
366
- const rows = out.rows || 24;
367
- const VIEWPORT_H = 5;
368
- const historyBottom = Math.max(2, rows - VIEWPORT_H);
369
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
370
- const write = (text) => out.write(text);
371
- const HIST_TOTAL = 30;
372
-
373
- function insertHistoryLine(text) {
374
- write(`${esc}[?2026h`);
375
- write(`${esc}[1;${historyBottom}r`);
376
- write(`${esc}[${historyBottom};1H`);
377
- write(`\r\n${text}${esc}[K`);
378
- write(`${esc}[r`);
379
- write(`${esc}[?2026l`);
380
- }
381
-
382
- function redrawViewport(label) {
383
- write(`${esc}[?2026h`);
384
- const top = rows - VIEWPORT_H + 1;
385
- write(`${esc}[${top};1H${esc}[K`);
386
- write(`${esc}[${top + 1};1H> composer${esc}[K`);
387
- write(`${esc}[${top + 2};1H${label}${esc}[K`);
388
- write(`${esc}[${top + 3};1H${esc}[K`);
389
- write(`${esc}[?2026l`);
390
- }
391
-
392
- write(`${esc}[?25l${esc}[?2026h${esc}[1;1H${esc}[J${esc}[1;${rows}r${esc}[1;1H`);
393
- write(`${esc}M`.repeat(4));
394
- write(`${esc}[r${esc}[1;5r${esc}[1;1H`);
395
- write(`\r\nAI_BATTERY_CODEX_BANNER OpenAI Codex (smoke renderer)${esc}[K`);
396
- write(`\r\nmodel: smoke${esc}[K`);
397
- write(`${esc}[r`);
398
- redrawViewport("AI_BATTERY_TRANSIENT_FRAME_0_MUST_NOT_REMAIN");
399
- write(`${esc}[?2026l`);
400
- await sleep(200);
401
-
402
- for (let i = 0; i < HIST_TOTAL; i += 1) {
403
- insertHistoryLine(`AI_BATTERY_HIST_LINE_${String(i).padStart(3, "0")}`);
404
- if (i % 5 === 0) redrawViewport(`AI_BATTERY_TRANSIENT_FRAME_${i + 1}_MUST_NOT_REMAIN`);
405
- await sleep(60);
406
- }
407
-
408
- redrawViewport("AI_BATTERY_FINAL_RESPONSE_DONE");
409
- write(`${esc}[?25h`);
410
- await sleep(1800);
411
- '@
412
- }
413
-
414
- function Count-TextOccurrences($Text, $Pattern) {
415
- return ([regex]::Matches([string]$Text, [regex]::Escape($Pattern))).Count
416
- }
417
-
418
- Write-Step "Compiling/installing rowpty host if needed..."
419
- $installOutput = & $node $installScript 2>&1
420
- if ($LASTEXITCODE -ne 0) {
421
- Set-Check "rowptyInstall" $false (($installOutput | Out-String).Trim())
422
- Fail ("rowpty install failed: " + (($installOutput | Out-String).Trim()))
423
- }
424
-
425
- $installJson = ($installOutput | Select-Object -Last 1 | ConvertFrom-Json)
426
- $script:SmokeReport.install = $installJson
427
- $rowptyExe = [string]$installJson.exePath
428
- if (-not (Test-Path $rowptyExe)) {
429
- Set-Check "rowptyInstall" $false "missing exePath=$rowptyExe"
430
- Fail "rowpty.exe was not installed at $rowptyExe"
431
- }
432
- $script:SmokeReport.rowptyExe = $rowptyExe
433
- Set-Check "rowptyInstall" $true "compiled=$($installJson.compiled), conpty=$($installJson.conpty)"
434
- Write-Step "Using rowpty: $rowptyExe"
435
-
436
- function Invoke-RowPtySmokeCase($Name, [string[]]$ChildArgs) {
437
- $upperName = $Name.ToUpperInvariant()
438
- $prefix = "AI_BATTERY_SMOKE_$upperName"
439
- $statusMarker = "${prefix}_STATUS"
440
- $delayedMarker = "${prefix}_DELAYED_OUTPUT"
441
- $promptMarker = "${prefix}_PROMPT_AREA"
442
- $endMarker = "${prefix}_CHILD_END"
443
- $scrollbackSentinel = "${prefix}_SCROLLBACK_" + [System.Guid]::NewGuid().ToString("N")
444
- $statusScript = Join-Path $tempDir "status-$Name.mjs"
445
- $debugLog = Join-Path $tempDir "debug-$Name.log"
446
- $caseResult = New-CaseResult $Name $debugLog
447
- $script:SmokeReport.cases += $caseResult
448
-
449
- Write-StatusScript $statusScript $statusMarker
450
-
451
- Write-Host $scrollbackSentinel
452
- for ($i = 0; $i -lt ([Console]::WindowHeight + 20); $i += 1) {
453
- Write-Host ("{0}_PREFILL_{1:D3}" -f $prefix, $i)
454
- }
455
-
456
- $beforeText = Get-ConsoleText
457
- if (-not $beforeText.Contains($scrollbackSentinel)) {
458
- Set-CaseCheck $caseResult "prefillScrollbackSentinel" $false $scrollbackSentinel
459
- Fail ("${Name}: console buffer did not retain the prefill sentinel, so scrollback cannot be validated.")
460
- }
461
- Set-CaseCheck $caseResult "prefillScrollbackSentinel" $true $scrollbackSentinel
462
-
463
- Write-Step "Launching ai-battery-run-win through $Name. Do not type until this case finishes..."
464
- $runnerArgs = @(
465
- $runner,
466
- "--interval", "0.5",
467
- "--bar-width", "4",
468
- "--provider", "all",
469
- "--"
470
- ) + $ChildArgs
471
- $argumentLine = Join-WindowsArgs -Values $runnerArgs
472
- $caseResult.runnerArgs = $runnerArgs
473
- $caseResult.argumentLine = $argumentLine
474
-
475
- $psi = New-Object System.Diagnostics.ProcessStartInfo
476
- $psi.FileName = $node
477
- $psi.Arguments = $argumentLine
478
- $psi.WorkingDirectory = $root
479
- $psi.UseShellExecute = $false
480
- $psi.CreateNoWindow = $false
481
- $psi.RedirectStandardInput = $false
482
- $psi.RedirectStandardOutput = $false
483
- $psi.RedirectStandardError = $false
484
- $psi.EnvironmentVariables["AI_BATTERY_BIN"] = $statusScript
485
- $psi.EnvironmentVariables["AI_BATTERY_ROWPTY"] = $rowptyExe
486
- $psi.EnvironmentVariables["AI_BATTERY_ROWPTY_PRESERVE_SCROLLBACK"] = "1"
487
- $psi.EnvironmentVariables["AI_BATTERY_WIN_LAYOUT"] = "tui"
488
- $psi.EnvironmentVariables["AI_BATTERY_DEBUG_LOG"] = $debugLog
489
-
490
- $process = [System.Diagnostics.Process]::Start($psi)
491
- if (-not $process) {
492
- Fail ("${Name}: failed to start ai-battery-run-win.")
493
- }
494
-
495
- $deadline = [DateTime]::UtcNow.AddSeconds($TimeoutSeconds)
496
- $delayedSeenBeforeExit = $false
497
- $statusSeenBeforeExit = $false
498
- $promptSeenBeforeExit = $false
499
- $statusBelowPromptSeen = $false
500
- $promptLineIndex = -1
501
- $statusLineIndex = -1
502
- while ([DateTime]::UtcNow -lt $deadline) {
503
- Start-Sleep -Milliseconds 100
504
- $text = Get-ConsoleText
505
- if (-not $process.HasExited -and $text.Contains($delayedMarker)) {
506
- $delayedSeenBeforeExit = $true
507
- }
508
- if (-not $process.HasExited -and $text.Contains($statusMarker)) {
509
- $statusSeenBeforeExit = $true
510
- }
511
- if (-not $process.HasExited -and $text.Contains($promptMarker)) {
512
- $promptSeenBeforeExit = $true
513
- $candidatePromptLine = Find-LastLineIndex $text $promptMarker
514
- $candidateStatusLine = Find-LastLineIndex $text $statusMarker
515
- if ($candidatePromptLine -ge 0 -and $candidateStatusLine -gt $candidatePromptLine) {
516
- $promptLineIndex = $candidatePromptLine
517
- $statusLineIndex = $candidateStatusLine
518
- $statusBelowPromptSeen = $true
519
- }
520
- }
521
- if ($delayedSeenBeforeExit -and $statusSeenBeforeExit -and $promptSeenBeforeExit -and $statusBelowPromptSeen) {
522
- break
523
- }
524
- if ($process.HasExited -and -not $delayedSeenBeforeExit) {
525
- break
526
- }
527
- }
528
-
529
- if (-not $process.WaitForExit([Math]::Max(1000, $TimeoutSeconds * 1000))) {
530
- try { $process.Kill() } catch {}
531
- Set-CaseCheck $caseResult "processExited" $false "timeoutSeconds=$TimeoutSeconds"
532
- Fail ("${Name}: ai-battery-run-win did not exit within $TimeoutSeconds seconds.")
533
- }
534
- Set-CaseCheck $caseResult "processExited" $true "exitCode=$($process.ExitCode)"
535
-
536
- $afterText = Get-ConsoleText
537
- $debugText = if (Test-Path $debugLog) { Get-Content -Path $debugLog -Raw } else { "" }
538
- $caseResult.processExitCode = $process.ExitCode
539
- $caseResult.debugEvents = @(Read-DebugEvents $debugLog)
540
- Import-DebugEvents $debugLog
541
-
542
- if ($process.ExitCode -ne 0) {
543
- Set-CaseCheck $caseResult "processExitCode" $false $process.ExitCode
544
- Fail ("${Name}: ai-battery-run-win exited with code $($process.ExitCode).")
545
- }
546
- Set-CaseCheck $caseResult "processExitCode" $true $process.ExitCode
547
- if (-not $debugText.Contains('"event":"rowpty:start"')) {
548
- Set-CaseCheck $caseResult "rowptyStarted" $false $debugLog
549
- Fail ("${Name}: debug log does not show rowpty:start; rowpty path was not exercised.")
550
- }
551
- Set-CaseCheck $caseResult "rowptyStarted" $true $debugLog
552
- if ($debugText.Contains('"event":"overlay:start"') -or $debugText.Contains('"event":"conpty:start"')) {
553
- Set-CaseCheck $caseResult "noFallback" $false $debugLog
554
- Fail ("${Name}: runner fell back to overlay/node-pty instead of rowpty.")
555
- }
556
- Set-CaseCheck $caseResult "noFallback" $true $debugLog
557
- if (-not $delayedSeenBeforeExit) {
558
- Set-CaseCheck $caseResult "delayedOutputVisibleBeforeExit" $false $delayedMarker
559
- Fail ("${Name}: delayed child output was not visible while the child was still running.")
560
- }
561
- Set-CaseCheck $caseResult "delayedOutputVisibleBeforeExit" $true $delayedMarker
562
- if (-not $statusSeenBeforeExit) {
563
- Set-CaseCheck $caseResult "statusVisibleBeforeExit" $false $statusMarker
564
- Fail ("${Name}: status row output was not visible while rowpty was running.")
565
- }
566
- Set-CaseCheck $caseResult "statusVisibleBeforeExit" $true $statusMarker
567
- if (-not $promptSeenBeforeExit) {
568
- Set-CaseCheck $caseResult "promptVisibleBeforeExit" $false $promptMarker
569
- Fail ("${Name}: prompt marker was not visible while rowpty was running.")
570
- }
571
- Set-CaseCheck $caseResult "promptVisibleBeforeExit" $true $promptMarker
572
- if (-not $statusBelowPromptSeen) {
573
- Set-CaseCheck $caseResult "statusBelowPrompt" $false "promptLine=$promptLineIndex, statusLine=$statusLineIndex"
574
- Fail ("${Name}: status row did not remain below the prompt marker.")
575
- }
576
- Set-CaseCheck $caseResult "statusBelowPrompt" $true "promptLine=$promptLineIndex, statusLine=$statusLineIndex"
577
- if (-not $afterText.Contains($endMarker)) {
578
- Set-CaseCheck $caseResult "childEndMarker" $false $endMarker
579
- Fail ("${Name}: child end marker is missing from the console buffer.")
580
- }
581
- Set-CaseCheck $caseResult "childEndMarker" $true $endMarker
582
- if (-not $afterText.Contains($scrollbackSentinel)) {
583
- Set-CaseCheck $caseResult "scrollbackPreservedAfter3J" $false $scrollbackSentinel
584
- Fail ("${Name}: scrollback sentinel disappeared after the child emitted CSI 3J.")
585
- }
586
- Set-CaseCheck $caseResult "scrollbackPreservedAfter3J" $true $scrollbackSentinel
587
- $caseResult.ok = $true
588
- }
589
-
590
- function Invoke-CodexHistorySmokeCase([string[]]$ChildArgs) {
591
- $name = "codex-history"
592
- $statusMarker = "AI_BATTERY_CODEX_HISTORY_STATUS"
593
- $finalMarker = "AI_BATTERY_FINAL_RESPONSE_DONE"
594
- $debugLog = Join-Path $tempDir "debug-$name.log"
595
- $statusScript = Join-Path $tempDir "status-$name.mjs"
596
- $caseResult = New-CaseResult $name $debugLog
597
- $script:SmokeReport.cases += $caseResult
598
-
599
- Write-StatusScript $statusScript $statusMarker
600
-
601
- Write-Step "Launching Codex-like history renderer. Do not type until this case finishes..."
602
- $runnerArgs = @(
603
- $runner,
604
- "--interval", "0.5",
605
- "--bar-width", "4",
606
- "--provider", "all",
607
- "--"
608
- ) + $ChildArgs
609
- $argumentLine = Join-WindowsArgs -Values $runnerArgs
610
- $caseResult.runnerArgs = $runnerArgs
611
- $caseResult.argumentLine = $argumentLine
612
-
613
- $psi = New-Object System.Diagnostics.ProcessStartInfo
614
- $psi.FileName = $node
615
- $psi.Arguments = $argumentLine
616
- $psi.WorkingDirectory = $root
617
- $psi.UseShellExecute = $false
618
- $psi.CreateNoWindow = $false
619
- $psi.RedirectStandardInput = $false
620
- $psi.RedirectStandardOutput = $false
621
- $psi.RedirectStandardError = $false
622
- $psi.EnvironmentVariables["AI_BATTERY_BIN"] = $statusScript
623
- $psi.EnvironmentVariables["AI_BATTERY_ROWPTY"] = $rowptyExe
624
- $psi.EnvironmentVariables["AI_BATTERY_ROWPTY_PRESERVE_SCROLLBACK"] = "1"
625
- $psi.EnvironmentVariables["AI_BATTERY_WIN_LAYOUT"] = "tui"
626
- $psi.EnvironmentVariables["AI_BATTERY_DEBUG_LOG"] = $debugLog
627
-
628
- $process = [System.Diagnostics.Process]::Start($psi)
629
- if (-not $process) {
630
- Fail "${name}: failed to start ai-battery-run-win."
631
- }
632
-
633
- $deadline = [DateTime]::UtcNow.AddSeconds($TimeoutSeconds)
634
- $finalSeenBeforeExit = $false
635
- $statusSeenBeforeExit = $false
636
- while ([DateTime]::UtcNow -lt $deadline) {
637
- Start-Sleep -Milliseconds 100
638
- $text = Get-ConsoleText
639
- if (-not $process.HasExited -and $text.Contains($finalMarker)) {
640
- $finalSeenBeforeExit = $true
641
- }
642
- if (-not $process.HasExited -and $text.Contains($statusMarker)) {
643
- $statusSeenBeforeExit = $true
644
- }
645
- if ($finalSeenBeforeExit -and $statusSeenBeforeExit) {
646
- break
647
- }
648
- if ($process.HasExited -and -not $finalSeenBeforeExit) {
649
- break
650
- }
651
- }
652
-
653
- if (-not $process.WaitForExit([Math]::Max(1000, $TimeoutSeconds * 1000))) {
654
- try { $process.Kill() } catch {}
655
- Set-CaseCheck $caseResult "processExited" $false "timeoutSeconds=$TimeoutSeconds"
656
- Fail "${name}: ai-battery-run-win did not exit within $TimeoutSeconds seconds."
657
- }
658
- Set-CaseCheck $caseResult "processExited" $true "exitCode=$($process.ExitCode)"
659
-
660
- $afterText = Get-ConsoleText
661
- $debugText = if (Test-Path $debugLog) { Get-Content -Path $debugLog -Raw } else { "" }
662
- $caseResult.processExitCode = $process.ExitCode
663
- $caseResult.debugEvents = @(Read-DebugEvents $debugLog)
664
- Import-DebugEvents $debugLog
665
-
666
- if ($process.ExitCode -ne 0) {
667
- Set-CaseCheck $caseResult "processExitCode" $false $process.ExitCode
668
- Fail "${name}: ai-battery-run-win exited with code $($process.ExitCode)."
669
- }
670
- Set-CaseCheck $caseResult "processExitCode" $true $process.ExitCode
671
- if (-not $debugText.Contains('"event":"rowpty:start"')) {
672
- Set-CaseCheck $caseResult "rowptyStarted" $false $debugLog
673
- Fail "${name}: debug log does not show rowpty:start; rowpty path was not exercised."
674
- }
675
- Set-CaseCheck $caseResult "rowptyStarted" $true $debugLog
676
- if ($debugText.Contains('"event":"overlay:start"') -or $debugText.Contains('"event":"conpty:start"')) {
677
- Set-CaseCheck $caseResult "noFallback" $false $debugLog
678
- Fail "${name}: runner fell back to overlay/node-pty instead of rowpty."
679
- }
680
- Set-CaseCheck $caseResult "noFallback" $true $debugLog
681
- if (-not $finalSeenBeforeExit -and -not $afterText.Contains($finalMarker)) {
682
- Set-CaseCheck $caseResult "finalHistoryVisible" $false $finalMarker
683
- Fail "${name}: final response marker was not visible in the console buffer."
684
- }
685
- Set-CaseCheck $caseResult "finalHistoryVisible" $true $finalMarker
686
- if (-not $statusSeenBeforeExit) {
687
- Set-CaseCheck $caseResult "statusVisibleBeforeExit" $false $statusMarker
688
- Fail "${name}: status row was not visible while the Codex-like renderer was running."
689
- }
690
- Set-CaseCheck $caseResult "statusVisibleBeforeExit" $true $statusMarker
691
-
692
- $transientCount = ([regex]::Matches($afterText, "AI_BATTERY_TRANSIENT_FRAME_\d+_MUST_NOT_REMAIN")).Count
693
- $bannerCount = Count-TextOccurrences $afterText "AI_BATTERY_CODEX_BANNER"
694
- $statusCount = Count-TextOccurrences $afterText $statusMarker
695
- Set-CaseCheck $caseResult "noTransientFramesInConsoleBuffer" ($transientCount -eq 0) "count=$transientCount"
696
- if ($transientCount -ne 0) {
697
- Fail "${name}: transient Codex frame text remained in the console buffer (count=$transientCount)."
698
- }
699
- Set-CaseCheck $caseResult "bannerRenderedExactlyOnce" ($bannerCount -eq 1) "count=$bannerCount"
700
- if ($bannerCount -ne 1) {
701
- Fail "${name}: the Codex banner appeared $bannerCount times in the console buffer (ghost frames)."
702
- }
703
-
704
- $histMatches = [regex]::Matches($afterText, "AI_BATTERY_HIST_LINE_(\d{3})")
705
- $histNumbers = @($histMatches | ForEach-Object { [int]$_.Groups[1].Value })
706
- $histUnique = @($histNumbers | Sort-Object -Unique)
707
- $histInOrder = $true
708
- for ($i = 1; $i -lt $histNumbers.Count; $i += 1) {
709
- if ($histNumbers[$i] -lt $histNumbers[$i - 1]) { $histInOrder = $false; break }
710
- }
711
- Set-CaseCheck $caseResult "historyLinesPreserved" ($histUnique.Count -eq 30) "unique=$($histUnique.Count)/30"
712
- if ($histUnique.Count -ne 30) {
713
- Fail "${name}: only $($histUnique.Count)/30 scroll-region history lines survived in the console buffer."
714
- }
715
- Set-CaseCheck $caseResult "historyLinesNotDuplicated" ($histNumbers.Count -eq $histUnique.Count) "total=$($histNumbers.Count), unique=$($histUnique.Count)"
716
- if ($histNumbers.Count -ne $histUnique.Count) {
717
- Fail "${name}: history lines were duplicated in the console buffer (ghost frames)."
718
- }
719
- Set-CaseCheck $caseResult "historyLinesInOrder" $histInOrder "inOrder=$histInOrder"
720
- if (-not $histInOrder) {
721
- Fail "${name}: history lines appeared out of order in the console buffer."
722
- }
723
- Set-CaseCheck $caseResult "statusDoesNotLeakAfterExit" ($statusCount -eq 0) "count=$statusCount"
724
- if ($statusCount -ne 0) {
725
- Fail "${name}: status row text leaked into the console buffer after exit (count=$statusCount)."
726
- }
727
-
728
- $caseResult.ok = $true
729
- }
730
-
731
- $cmdChildScript = Join-Path $tempDir "child-cmd.mjs"
732
- $cmdChildWrapper = Join-Path $tempDir "child-cmd.cmd"
733
- $powershellChildScript = Join-Path $tempDir "child-powershell.ps1"
734
- $codexHistoryChildScript = Join-Path $tempDir "child-codex-history.mjs"
735
- Write-NodeChildScript $cmdChildScript "AI_BATTERY_SMOKE_CMD"
736
- Write-CmdChildWrapper $cmdChildWrapper $node $cmdChildScript
737
- Write-PowerShellChildScript $powershellChildScript "AI_BATTERY_SMOKE_POWERSHELL"
738
- Write-CodexHistoryChildScript $codexHistoryChildScript
739
-
740
- Invoke-RowPtySmokeCase "cmd" @($cmdChildWrapper)
741
- Invoke-RowPtySmokeCase "powershell" @("powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", $powershellChildScript)
742
- Invoke-CodexHistorySmokeCase @($node, $codexHistoryChildScript)
743
-
744
- $script:SmokeReport.ok = $true
745
- Write-SmokeReport
746
- Write-Host "[ai-battery smoke] PASS: rowpty output, status paint, scrollback preservation, and Codex-like history rendering look healthy." -ForegroundColor Green
747
- if ($ReportPath) {
748
- Write-Host "[ai-battery smoke] Report: $ReportPath"
749
- }
750
- } catch {
751
- $script:SmokeFailed = $true
752
- $script:SmokeReport.ok = $false
753
- $script:SmokeReport.failure = $_.Exception.Message
754
- Write-SmokeReport
755
- Write-Host "[ai-battery smoke] FAIL: $($_.Exception.Message)" -ForegroundColor Red
756
- if ($ReportPath) {
757
- Write-Host "[ai-battery smoke] Report: $ReportPath"
758
- }
759
- exit 1
760
- } finally {
761
- if (-not $KeepTemp -and -not $script:SmokeFailed -and (Test-Path $tempDir)) {
762
- Remove-Item -Recurse -Force $tempDir -ErrorAction SilentlyContinue
763
- } elseif ($KeepTemp -or $script:SmokeFailed) {
764
- Write-Step "Kept temp directory: $tempDir"
765
- }
766
- }
1
+ param(
2
+ [int]$TimeoutSeconds = 12,
3
+ [string]$ReportPath = "",
4
+ [switch]$KeepTemp
5
+ )
6
+
7
+ Set-StrictMode -Version Latest
8
+ $ErrorActionPreference = "Stop"
9
+ $script:SmokeFailed = $false
10
+ $script:SmokeReport = [ordered]@{
11
+ ok = $false
12
+ overallPassed = $false
13
+ startedAt = (Get-Date).ToUniversalTime().ToString("o")
14
+ completedAt = $null
15
+ finishedAt = $null
16
+ failure = $null
17
+ root = $null
18
+ node = $null
19
+ tempDir = $null
20
+ rowptyExe = $null
21
+ debugLog = $null
22
+ install = $null
23
+ processExitCode = $null
24
+ checks = [ordered]@{}
25
+ cases = @()
26
+ debugEvents = @()
27
+ }
28
+
29
+ function Set-Check($Name, $Passed, $Details = $null) {
30
+ $script:SmokeReport.checks[$Name] = [ordered]@{
31
+ passed = [bool]$Passed
32
+ details = $Details
33
+ }
34
+ }
35
+
36
+ function Read-DebugEvents($DebugLogPath) {
37
+ if (-not $DebugLogPath -or -not (Test-Path $DebugLogPath)) {
38
+ return @()
39
+ }
40
+ $events = @()
41
+ foreach ($line in Get-Content -Path $DebugLogPath) {
42
+ try {
43
+ $events += ($line | ConvertFrom-Json)
44
+ } catch {
45
+ }
46
+ }
47
+ return $events
48
+ }
49
+
50
+ function Import-DebugEvents($DebugLogPath) {
51
+ $script:SmokeReport.debugEvents += @(Read-DebugEvents $DebugLogPath)
52
+ }
53
+
54
+ function New-CaseResult($Name, $DebugLogPath) {
55
+ return [ordered]@{
56
+ name = $Name
57
+ ok = $false
58
+ debugLog = $DebugLogPath
59
+ runnerArgs = @()
60
+ argumentLine = $null
61
+ processExitCode = $null
62
+ checks = [ordered]@{}
63
+ debugEvents = @()
64
+ }
65
+ }
66
+
67
+ function Set-CaseCheck($CaseResult, $Name, $Passed, $Details = $null) {
68
+ $CaseResult.checks[$Name] = [ordered]@{
69
+ passed = [bool]$Passed
70
+ details = $Details
71
+ }
72
+ }
73
+
74
+ function Write-SmokeReport {
75
+ if (-not $ReportPath) {
76
+ return
77
+ }
78
+ $finishedAt = (Get-Date).ToUniversalTime().ToString("o")
79
+ $script:SmokeReport.overallPassed = [bool]$script:SmokeReport.ok
80
+ $script:SmokeReport.completedAt = $finishedAt
81
+ $script:SmokeReport.finishedAt = $finishedAt
82
+ if ($script:SmokeReport.debugLog) {
83
+ Import-DebugEvents $script:SmokeReport.debugLog
84
+ }
85
+ $parent = Split-Path -Parent $ReportPath
86
+ if ($parent) {
87
+ New-Item -ItemType Directory -Force -Path $parent | Out-Null
88
+ }
89
+ $script:SmokeReport | ConvertTo-Json -Depth 8 | Set-Content -Path $ReportPath -Encoding UTF8
90
+ }
91
+
92
+ function Write-Step($Message) {
93
+ Write-Host "[ai-battery smoke] $Message"
94
+ }
95
+
96
+ function Fail($Message) {
97
+ $script:SmokeFailed = $true
98
+ $script:SmokeReport.ok = $false
99
+ $script:SmokeReport.failure = $Message
100
+ Write-SmokeReport
101
+ Write-Host "[ai-battery smoke] FAIL: $Message" -ForegroundColor Red
102
+ if ($ReportPath) {
103
+ Write-Host "[ai-battery smoke] Report: $ReportPath"
104
+ }
105
+ exit 1
106
+ }
107
+
108
+ function Quote-WindowsArg($Value) {
109
+ $text = [string]$Value
110
+ if ($text.Length -gt 0 -and $text -notmatch '[\s"]' -and -not $text.StartsWith("\\")) {
111
+ return $text
112
+ }
113
+
114
+ $result = '"'
115
+ $backslashes = 0
116
+ foreach ($ch in $text.ToCharArray()) {
117
+ if ($ch -eq [char]92) {
118
+ $backslashes += 1
119
+ } elseif ($ch -eq '"') {
120
+ $result += ('\' * (($backslashes * 2) + 1)) + '"'
121
+ $backslashes = 0
122
+ } else {
123
+ if ($backslashes -gt 0) {
124
+ $result += ('\' * $backslashes)
125
+ $backslashes = 0
126
+ }
127
+ $result += $ch
128
+ }
129
+ }
130
+ if ($backslashes -gt 0) {
131
+ $result += ('\' * ($backslashes * 2))
132
+ }
133
+ return $result + '"'
134
+ }
135
+
136
+ function Join-WindowsArgs {
137
+ param([object[]]$Values)
138
+ return (($Values | ForEach-Object { Quote-WindowsArg $_ }) -join " ")
139
+ }
140
+
141
+ function ConvertTo-FileUrl($Path) {
142
+ $resolved = (Resolve-Path $Path).ProviderPath
143
+ return ([System.Uri]$resolved).AbsoluteUri
144
+ }
145
+
146
+ function Add-ConsoleReaderType {
147
+ if ("AiBatteryConsoleSmoke" -as [type]) {
148
+ return
149
+ }
150
+
151
+ Add-Type -TypeDefinition @"
152
+ using System;
153
+ using System.Runtime.InteropServices;
154
+ using System.Text;
155
+
156
+ public static class AiBatteryConsoleSmoke
157
+ {
158
+ private const int STD_OUTPUT_HANDLE = -11;
159
+
160
+ [StructLayout(LayoutKind.Sequential)]
161
+ public struct COORD
162
+ {
163
+ public short X;
164
+ public short Y;
165
+ }
166
+
167
+ [StructLayout(LayoutKind.Sequential)]
168
+ public struct SMALL_RECT
169
+ {
170
+ public short Left;
171
+ public short Top;
172
+ public short Right;
173
+ public short Bottom;
174
+ }
175
+
176
+ [StructLayout(LayoutKind.Sequential)]
177
+ public struct CONSOLE_SCREEN_BUFFER_INFO
178
+ {
179
+ public COORD dwSize;
180
+ public COORD dwCursorPosition;
181
+ public short wAttributes;
182
+ public SMALL_RECT srWindow;
183
+ public COORD dwMaximumWindowSize;
184
+ }
185
+
186
+ [DllImport("kernel32.dll", SetLastError = true)]
187
+ private static extern IntPtr GetStdHandle(int nStdHandle);
188
+
189
+ [DllImport("kernel32.dll", SetLastError = true)]
190
+ private static extern bool GetConsoleScreenBufferInfo(IntPtr hConsoleOutput, out CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo);
191
+
192
+ [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
193
+ private static extern bool ReadConsoleOutputCharacterW(IntPtr hConsoleOutput, StringBuilder lpCharacter, uint nLength, COORD dwReadCoord, out uint lpNumberOfCharsRead);
194
+
195
+ public static string ReadAll()
196
+ {
197
+ IntPtr handle = GetStdHandle(STD_OUTPUT_HANDLE);
198
+ CONSOLE_SCREEN_BUFFER_INFO info;
199
+ if (!GetConsoleScreenBufferInfo(handle, out info))
200
+ {
201
+ return "";
202
+ }
203
+
204
+ int width = Math.Max(1, (int)info.dwSize.X);
205
+ int height = Math.Max(1, (int)info.dwSize.Y);
206
+ StringBuilder all = new StringBuilder(width * Math.Min(height, 2000));
207
+ for (short y = 0; y < height; y++)
208
+ {
209
+ StringBuilder line = new StringBuilder(width);
210
+ COORD origin = new COORD();
211
+ origin.X = 0;
212
+ origin.Y = y;
213
+ uint read;
214
+ if (ReadConsoleOutputCharacterW(handle, line, (uint)width, origin, out read))
215
+ {
216
+ all.Append(line.ToString());
217
+ all.Append('\n');
218
+ }
219
+ }
220
+ return all.ToString();
221
+ }
222
+ }
223
+ "@
224
+ }
225
+
226
+ function Get-ConsoleText {
227
+ return [AiBatteryConsoleSmoke]::ReadAll()
228
+ }
229
+
230
+ function Find-LastLineIndex($Text, $Marker) {
231
+ $lines = ([string]$Text) -split "`n"
232
+ for ($i = $lines.Length - 1; $i -ge 0; $i -= 1) {
233
+ if ($lines[$i].Contains($Marker)) {
234
+ return $i
235
+ }
236
+ }
237
+ return -1
238
+ }
239
+
240
+ function Ensure-ConsoleScrollback {
241
+ try {
242
+ $targetHeight = [Math]::Max([Console]::BufferHeight, [Console]::WindowHeight + 200)
243
+ if ([Console]::BufferHeight -lt $targetHeight) {
244
+ [Console]::BufferHeight = $targetHeight
245
+ }
246
+ Set-Check "consoleScrollbackBuffer" $true "windowHeight=$([Console]::WindowHeight), bufferHeight=$([Console]::BufferHeight)"
247
+ } catch {
248
+ Set-Check "consoleScrollbackBuffer" $false $_.Exception.Message
249
+ }
250
+ }
251
+
252
+ $root = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot ".."))
253
+ if (-not $ReportPath) {
254
+ $ReportPath = Join-Path $root "rowpty-smoke-report.json"
255
+ }
256
+ $script:SmokeReport.root = $root
257
+
258
+ if ([System.Environment]::OSVersion.Platform -ne [System.PlatformID]::Win32NT) {
259
+ Set-Check "nativeWindows" $false "platform=$([System.Environment]::OSVersion.Platform)"
260
+ Fail "This smoke test must run in native Windows cmd/PowerShell/Windows Terminal."
261
+ }
262
+ Set-Check "nativeWindows" $true ([System.Environment]::OSVersion.VersionString)
263
+
264
+ if ([Console]::IsInputRedirected -or [Console]::IsOutputRedirected) {
265
+ Set-Check "interactiveConsole" $false "stdinRedirected=$([Console]::IsInputRedirected), stdoutRedirected=$([Console]::IsOutputRedirected)"
266
+ Fail "Run this in an interactive terminal; stdin/stdout must not be redirected."
267
+ }
268
+ Set-Check "interactiveConsole" $true "stdin/stdout are real console handles"
269
+
270
+ $nodeCommand = Get-Command node -ErrorAction SilentlyContinue
271
+ if (-not $nodeCommand) {
272
+ Set-Check "nodeOnPath" $false $null
273
+ Fail "node was not found on PATH."
274
+ }
275
+ $node = $nodeCommand.Source
276
+ Set-Check "nodeOnPath" $true $node
277
+
278
+ $runner = (Resolve-Path (Join-Path $root "bin/ai-battery-run-win.js")).ProviderPath
279
+ $aiBatteryModule = (Resolve-Path (Join-Path $root "bin/ai-battery.js")).ProviderPath
280
+ $tempDir = Join-Path ([System.IO.Path]::GetTempPath()) ("ai-battery-rowpty-smoke-" + [System.Guid]::NewGuid().ToString("N"))
281
+ New-Item -ItemType Directory -Path $tempDir | Out-Null
282
+ $script:SmokeReport.node = $node
283
+ $script:SmokeReport.tempDir = $tempDir
284
+
285
+ try {
286
+ Add-ConsoleReaderType
287
+ Ensure-ConsoleScrollback
288
+
289
+ $installScript = Join-Path $tempDir "install-rowpty.mjs"
290
+ $moduleUrl = ConvertTo-FileUrl $aiBatteryModule
291
+
292
+ Set-Content -Path $installScript -Encoding UTF8 -Value @"
293
+ import { installRowPtyHost } from "$moduleUrl";
294
+ const result = installRowPtyHost();
295
+ console.log(JSON.stringify(result));
296
+ process.exit(result.ok ? 0 : 1);
297
+ "@
298
+
299
+ function Write-StatusScript($Path, $Marker) {
300
+ Set-Content -Path $Path -Encoding UTF8 -Value "console.log(`"$Marker 99%`");"
301
+ }
302
+
303
+ function Write-NodeChildScript($Path, $Prefix) {
304
+ Set-Content -Path $Path -Encoding UTF8 -Value @"
305
+ const prefix = "$Prefix";
306
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
307
+ process.stdout.write(prefix + "_CHILD_START\n");
308
+ for (let i = 0; i < 6; i += 1) {
309
+ process.stdout.write(prefix + "_LINE_" + i + "\n");
310
+ await sleep(80);
311
+ }
312
+ process.stdout.write("\x1b[?1049h" + prefix + "_ALT_SCREEN\n\x1b[?1049l");
313
+ process.stdout.write("\x1b[3J" + prefix + "_AFTER_3J\n");
314
+ await sleep(700);
315
+ // Extra blank line: absolute rows pass through to the host viewport with the
316
+ // bundled ConPTY (real-terminal semantics), so the bottom-row prompt jump
317
+ // below would otherwise land on the delayed-output line and overwrite it.
318
+ process.stdout.write(prefix + "_DELAYED_OUTPUT\n\n");
319
+ process.stdout.write("\x1b[999;1H" + prefix + "_PROMPT_AREA> ");
320
+ await sleep(4500);
321
+ process.stdout.write(prefix + "_CHILD_END\n");
322
+ "@
323
+ }
324
+
325
+ function Write-CmdChildWrapper($Path, $NodePath, $ScriptPath) {
326
+ $content = @(
327
+ "@echo off",
328
+ (Join-WindowsArgs -Values @($NodePath, $ScriptPath)),
329
+ "exit /b %ERRORLEVEL%"
330
+ ) -join "`r`n"
331
+ Set-Content -Path $Path -Encoding ASCII -Value $content
332
+ }
333
+
334
+ function Write-PowerShellChildScript($Path, $Prefix) {
335
+ $content = @'
336
+ $prefix = "__PREFIX__"
337
+ $esc = [char]27
338
+ [Console]::Out.Write($prefix + "_CHILD_START`n")
339
+ for ($i = 0; $i -lt 6; $i += 1) {
340
+ [Console]::Out.Write($prefix + "_LINE_" + $i + "`n")
341
+ Start-Sleep -Milliseconds 80
342
+ }
343
+ [Console]::Out.Write("$esc[?1049h" + $prefix + "_ALT_SCREEN`n" + "$esc[?1049l")
344
+ [Console]::Out.Write("$esc[3J" + $prefix + "_AFTER_3J`n")
345
+ Start-Sleep -Milliseconds 700
346
+ # Extra blank line: absolute rows pass through to the host viewport with the
347
+ # bundled ConPTY (real-terminal semantics), so the bottom-row prompt jump
348
+ # below would otherwise land on the delayed-output line and overwrite it.
349
+ [Console]::Out.Write($prefix + "_DELAYED_OUTPUT`n`n")
350
+ [Console]::Out.Write("$esc[999;1H" + $prefix + "_PROMPT_AREA> ")
351
+ Start-Sleep -Milliseconds 4500
352
+ [Console]::Out.Write($prefix + "_CHILD_END`n")
353
+ '@
354
+ Set-Content -Path $Path -Encoding UTF8 -Value $content.Replace("__PREFIX__", $Prefix)
355
+ }
356
+
357
+ function Write-CodexHistoryChildScript($Path) {
358
+ # Mirrors the VT pattern captured from the real Codex TUI (0.142.x):
359
+ # synchronized updates plus top-anchored DECSTBM scroll regions that push
360
+ # history lines into scrollback above a bottom-pinned viewport. The OS
361
+ # in-box ConPTY re-renders this pattern as full viewport repaints, losing
362
+ # or duplicating history lines; the bundled WT conpty.dll passes it through.
363
+ Set-Content -Path $Path -Encoding UTF8 -Value @'
364
+ const esc = "\x1b";
365
+ const out = process.stdout;
366
+ const rows = out.rows || 24;
367
+ const VIEWPORT_H = 5;
368
+ const historyBottom = Math.max(2, rows - VIEWPORT_H);
369
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
370
+ const write = (text) => out.write(text);
371
+ const HIST_TOTAL = 30;
372
+
373
+ function insertHistoryLine(text) {
374
+ write(`${esc}[?2026h`);
375
+ write(`${esc}[1;${historyBottom}r`);
376
+ write(`${esc}[${historyBottom};1H`);
377
+ write(`\r\n${text}${esc}[K`);
378
+ write(`${esc}[r`);
379
+ write(`${esc}[?2026l`);
380
+ }
381
+
382
+ function redrawViewport(label) {
383
+ write(`${esc}[?2026h`);
384
+ const top = rows - VIEWPORT_H + 1;
385
+ write(`${esc}[${top};1H${esc}[K`);
386
+ write(`${esc}[${top + 1};1H> composer${esc}[K`);
387
+ write(`${esc}[${top + 2};1H${label}${esc}[K`);
388
+ write(`${esc}[${top + 3};1H${esc}[K`);
389
+ write(`${esc}[?2026l`);
390
+ }
391
+
392
+ write(`${esc}[?25l${esc}[?2026h${esc}[1;1H${esc}[J${esc}[1;${rows}r${esc}[1;1H`);
393
+ write(`${esc}M`.repeat(4));
394
+ write(`${esc}[r${esc}[1;5r${esc}[1;1H`);
395
+ write(`\r\nAI_BATTERY_CODEX_BANNER OpenAI Codex (smoke renderer)${esc}[K`);
396
+ write(`\r\nmodel: smoke${esc}[K`);
397
+ write(`${esc}[r`);
398
+ redrawViewport("AI_BATTERY_TRANSIENT_FRAME_0_MUST_NOT_REMAIN");
399
+ write(`${esc}[?2026l`);
400
+ await sleep(200);
401
+
402
+ for (let i = 0; i < HIST_TOTAL; i += 1) {
403
+ insertHistoryLine(`AI_BATTERY_HIST_LINE_${String(i).padStart(3, "0")}`);
404
+ if (i % 5 === 0) redrawViewport(`AI_BATTERY_TRANSIENT_FRAME_${i + 1}_MUST_NOT_REMAIN`);
405
+ await sleep(60);
406
+ }
407
+
408
+ redrawViewport("AI_BATTERY_FINAL_RESPONSE_DONE");
409
+ write(`${esc}[?25h`);
410
+ await sleep(1800);
411
+ '@
412
+ }
413
+
414
+ function Count-TextOccurrences($Text, $Pattern) {
415
+ return ([regex]::Matches([string]$Text, [regex]::Escape($Pattern))).Count
416
+ }
417
+
418
+ Write-Step "Compiling/installing rowpty host if needed..."
419
+ $installOutput = & $node $installScript 2>&1
420
+ if ($LASTEXITCODE -ne 0) {
421
+ Set-Check "rowptyInstall" $false (($installOutput | Out-String).Trim())
422
+ Fail ("rowpty install failed: " + (($installOutput | Out-String).Trim()))
423
+ }
424
+
425
+ $installJson = ($installOutput | Select-Object -Last 1 | ConvertFrom-Json)
426
+ $script:SmokeReport.install = $installJson
427
+ $rowptyExe = [string]$installJson.exePath
428
+ if (-not (Test-Path $rowptyExe)) {
429
+ Set-Check "rowptyInstall" $false "missing exePath=$rowptyExe"
430
+ Fail "rowpty.exe was not installed at $rowptyExe"
431
+ }
432
+ $script:SmokeReport.rowptyExe = $rowptyExe
433
+ Set-Check "rowptyInstall" $true "compiled=$($installJson.compiled), conpty=$($installJson.conpty)"
434
+ Write-Step "Using rowpty: $rowptyExe"
435
+
436
+ function Invoke-RowPtySmokeCase($Name, [string[]]$ChildArgs) {
437
+ $upperName = $Name.ToUpperInvariant()
438
+ $prefix = "AI_BATTERY_SMOKE_$upperName"
439
+ $statusMarker = "${prefix}_STATUS"
440
+ $delayedMarker = "${prefix}_DELAYED_OUTPUT"
441
+ $promptMarker = "${prefix}_PROMPT_AREA"
442
+ $endMarker = "${prefix}_CHILD_END"
443
+ $scrollbackSentinel = "${prefix}_SCROLLBACK_" + [System.Guid]::NewGuid().ToString("N")
444
+ $statusScript = Join-Path $tempDir "status-$Name.mjs"
445
+ $debugLog = Join-Path $tempDir "debug-$Name.log"
446
+ $caseResult = New-CaseResult $Name $debugLog
447
+ $script:SmokeReport.cases += $caseResult
448
+
449
+ Write-StatusScript $statusScript $statusMarker
450
+
451
+ Write-Host $scrollbackSentinel
452
+ for ($i = 0; $i -lt ([Console]::WindowHeight + 20); $i += 1) {
453
+ Write-Host ("{0}_PREFILL_{1:D3}" -f $prefix, $i)
454
+ }
455
+
456
+ $beforeText = Get-ConsoleText
457
+ if (-not $beforeText.Contains($scrollbackSentinel)) {
458
+ Set-CaseCheck $caseResult "prefillScrollbackSentinel" $false $scrollbackSentinel
459
+ Fail ("${Name}: console buffer did not retain the prefill sentinel, so scrollback cannot be validated.")
460
+ }
461
+ Set-CaseCheck $caseResult "prefillScrollbackSentinel" $true $scrollbackSentinel
462
+
463
+ Write-Step "Launching ai-battery-run-win through $Name. Do not type until this case finishes..."
464
+ $runnerArgs = @(
465
+ $runner,
466
+ "--interval", "0.5",
467
+ "--bar-width", "4",
468
+ "--provider", "all",
469
+ "--"
470
+ ) + $ChildArgs
471
+ $argumentLine = Join-WindowsArgs -Values $runnerArgs
472
+ $caseResult.runnerArgs = $runnerArgs
473
+ $caseResult.argumentLine = $argumentLine
474
+
475
+ $psi = New-Object System.Diagnostics.ProcessStartInfo
476
+ $psi.FileName = $node
477
+ $psi.Arguments = $argumentLine
478
+ $psi.WorkingDirectory = $root
479
+ $psi.UseShellExecute = $false
480
+ $psi.CreateNoWindow = $false
481
+ $psi.RedirectStandardInput = $false
482
+ $psi.RedirectStandardOutput = $false
483
+ $psi.RedirectStandardError = $false
484
+ $psi.EnvironmentVariables["AI_BATTERY_BIN"] = $statusScript
485
+ $psi.EnvironmentVariables["AI_BATTERY_ROWPTY"] = $rowptyExe
486
+ $psi.EnvironmentVariables["AI_BATTERY_ROWPTY_PRESERVE_SCROLLBACK"] = "1"
487
+ $psi.EnvironmentVariables["AI_BATTERY_WIN_LAYOUT"] = "tui"
488
+ $psi.EnvironmentVariables["AI_BATTERY_DEBUG_LOG"] = $debugLog
489
+
490
+ $process = [System.Diagnostics.Process]::Start($psi)
491
+ if (-not $process) {
492
+ Fail ("${Name}: failed to start ai-battery-run-win.")
493
+ }
494
+
495
+ $deadline = [DateTime]::UtcNow.AddSeconds($TimeoutSeconds)
496
+ $delayedSeenBeforeExit = $false
497
+ $statusSeenBeforeExit = $false
498
+ $promptSeenBeforeExit = $false
499
+ $statusBelowPromptSeen = $false
500
+ $promptLineIndex = -1
501
+ $statusLineIndex = -1
502
+ while ([DateTime]::UtcNow -lt $deadline) {
503
+ Start-Sleep -Milliseconds 100
504
+ $text = Get-ConsoleText
505
+ if (-not $process.HasExited -and $text.Contains($delayedMarker)) {
506
+ $delayedSeenBeforeExit = $true
507
+ }
508
+ if (-not $process.HasExited -and $text.Contains($statusMarker)) {
509
+ $statusSeenBeforeExit = $true
510
+ }
511
+ if (-not $process.HasExited -and $text.Contains($promptMarker)) {
512
+ $promptSeenBeforeExit = $true
513
+ $candidatePromptLine = Find-LastLineIndex $text $promptMarker
514
+ $candidateStatusLine = Find-LastLineIndex $text $statusMarker
515
+ if ($candidatePromptLine -ge 0 -and $candidateStatusLine -gt $candidatePromptLine) {
516
+ $promptLineIndex = $candidatePromptLine
517
+ $statusLineIndex = $candidateStatusLine
518
+ $statusBelowPromptSeen = $true
519
+ }
520
+ }
521
+ if ($delayedSeenBeforeExit -and $statusSeenBeforeExit -and $promptSeenBeforeExit -and $statusBelowPromptSeen) {
522
+ break
523
+ }
524
+ if ($process.HasExited -and -not $delayedSeenBeforeExit) {
525
+ break
526
+ }
527
+ }
528
+
529
+ if (-not $process.WaitForExit([Math]::Max(1000, $TimeoutSeconds * 1000))) {
530
+ try { $process.Kill() } catch {}
531
+ Set-CaseCheck $caseResult "processExited" $false "timeoutSeconds=$TimeoutSeconds"
532
+ Fail ("${Name}: ai-battery-run-win did not exit within $TimeoutSeconds seconds.")
533
+ }
534
+ Set-CaseCheck $caseResult "processExited" $true "exitCode=$($process.ExitCode)"
535
+
536
+ $afterText = Get-ConsoleText
537
+ $debugText = if (Test-Path $debugLog) { Get-Content -Path $debugLog -Raw } else { "" }
538
+ $caseResult.processExitCode = $process.ExitCode
539
+ $caseResult.debugEvents = @(Read-DebugEvents $debugLog)
540
+ Import-DebugEvents $debugLog
541
+
542
+ if ($process.ExitCode -ne 0) {
543
+ Set-CaseCheck $caseResult "processExitCode" $false $process.ExitCode
544
+ Fail ("${Name}: ai-battery-run-win exited with code $($process.ExitCode).")
545
+ }
546
+ Set-CaseCheck $caseResult "processExitCode" $true $process.ExitCode
547
+ if (-not $debugText.Contains('"event":"rowpty:start"')) {
548
+ Set-CaseCheck $caseResult "rowptyStarted" $false $debugLog
549
+ Fail ("${Name}: debug log does not show rowpty:start; rowpty path was not exercised.")
550
+ }
551
+ Set-CaseCheck $caseResult "rowptyStarted" $true $debugLog
552
+ if ($debugText.Contains('"event":"overlay:start"') -or $debugText.Contains('"event":"conpty:start"')) {
553
+ Set-CaseCheck $caseResult "noFallback" $false $debugLog
554
+ Fail ("${Name}: runner fell back to overlay/node-pty instead of rowpty.")
555
+ }
556
+ Set-CaseCheck $caseResult "noFallback" $true $debugLog
557
+ if (-not $delayedSeenBeforeExit) {
558
+ Set-CaseCheck $caseResult "delayedOutputVisibleBeforeExit" $false $delayedMarker
559
+ Fail ("${Name}: delayed child output was not visible while the child was still running.")
560
+ }
561
+ Set-CaseCheck $caseResult "delayedOutputVisibleBeforeExit" $true $delayedMarker
562
+ if (-not $statusSeenBeforeExit) {
563
+ Set-CaseCheck $caseResult "statusVisibleBeforeExit" $false $statusMarker
564
+ Fail ("${Name}: status row output was not visible while rowpty was running.")
565
+ }
566
+ Set-CaseCheck $caseResult "statusVisibleBeforeExit" $true $statusMarker
567
+ if (-not $promptSeenBeforeExit) {
568
+ Set-CaseCheck $caseResult "promptVisibleBeforeExit" $false $promptMarker
569
+ Fail ("${Name}: prompt marker was not visible while rowpty was running.")
570
+ }
571
+ Set-CaseCheck $caseResult "promptVisibleBeforeExit" $true $promptMarker
572
+ if (-not $statusBelowPromptSeen) {
573
+ Set-CaseCheck $caseResult "statusBelowPrompt" $false "promptLine=$promptLineIndex, statusLine=$statusLineIndex"
574
+ Fail ("${Name}: status row did not remain below the prompt marker.")
575
+ }
576
+ Set-CaseCheck $caseResult "statusBelowPrompt" $true "promptLine=$promptLineIndex, statusLine=$statusLineIndex"
577
+ if (-not $afterText.Contains($endMarker)) {
578
+ Set-CaseCheck $caseResult "childEndMarker" $false $endMarker
579
+ Fail ("${Name}: child end marker is missing from the console buffer.")
580
+ }
581
+ Set-CaseCheck $caseResult "childEndMarker" $true $endMarker
582
+ if (-not $afterText.Contains($scrollbackSentinel)) {
583
+ Set-CaseCheck $caseResult "scrollbackPreservedAfter3J" $false $scrollbackSentinel
584
+ Fail ("${Name}: scrollback sentinel disappeared after the child emitted CSI 3J.")
585
+ }
586
+ Set-CaseCheck $caseResult "scrollbackPreservedAfter3J" $true $scrollbackSentinel
587
+ $caseResult.ok = $true
588
+ }
589
+
590
+ function Invoke-CodexHistorySmokeCase([string[]]$ChildArgs) {
591
+ $name = "codex-history"
592
+ $statusMarker = "AI_BATTERY_CODEX_HISTORY_STATUS"
593
+ $finalMarker = "AI_BATTERY_FINAL_RESPONSE_DONE"
594
+ $debugLog = Join-Path $tempDir "debug-$name.log"
595
+ $statusScript = Join-Path $tempDir "status-$name.mjs"
596
+ $caseResult = New-CaseResult $name $debugLog
597
+ $script:SmokeReport.cases += $caseResult
598
+
599
+ Write-StatusScript $statusScript $statusMarker
600
+
601
+ Write-Step "Launching Codex-like history renderer. Do not type until this case finishes..."
602
+ $runnerArgs = @(
603
+ $runner,
604
+ "--interval", "0.5",
605
+ "--bar-width", "4",
606
+ "--provider", "all",
607
+ "--"
608
+ ) + $ChildArgs
609
+ $argumentLine = Join-WindowsArgs -Values $runnerArgs
610
+ $caseResult.runnerArgs = $runnerArgs
611
+ $caseResult.argumentLine = $argumentLine
612
+
613
+ $psi = New-Object System.Diagnostics.ProcessStartInfo
614
+ $psi.FileName = $node
615
+ $psi.Arguments = $argumentLine
616
+ $psi.WorkingDirectory = $root
617
+ $psi.UseShellExecute = $false
618
+ $psi.CreateNoWindow = $false
619
+ $psi.RedirectStandardInput = $false
620
+ $psi.RedirectStandardOutput = $false
621
+ $psi.RedirectStandardError = $false
622
+ $psi.EnvironmentVariables["AI_BATTERY_BIN"] = $statusScript
623
+ $psi.EnvironmentVariables["AI_BATTERY_ROWPTY"] = $rowptyExe
624
+ $psi.EnvironmentVariables["AI_BATTERY_ROWPTY_PRESERVE_SCROLLBACK"] = "1"
625
+ $psi.EnvironmentVariables["AI_BATTERY_WIN_LAYOUT"] = "tui"
626
+ $psi.EnvironmentVariables["AI_BATTERY_DEBUG_LOG"] = $debugLog
627
+
628
+ $process = [System.Diagnostics.Process]::Start($psi)
629
+ if (-not $process) {
630
+ Fail "${name}: failed to start ai-battery-run-win."
631
+ }
632
+
633
+ $deadline = [DateTime]::UtcNow.AddSeconds($TimeoutSeconds)
634
+ $finalSeenBeforeExit = $false
635
+ $statusSeenBeforeExit = $false
636
+ while ([DateTime]::UtcNow -lt $deadline) {
637
+ Start-Sleep -Milliseconds 100
638
+ $text = Get-ConsoleText
639
+ if (-not $process.HasExited -and $text.Contains($finalMarker)) {
640
+ $finalSeenBeforeExit = $true
641
+ }
642
+ if (-not $process.HasExited -and $text.Contains($statusMarker)) {
643
+ $statusSeenBeforeExit = $true
644
+ }
645
+ if ($finalSeenBeforeExit -and $statusSeenBeforeExit) {
646
+ break
647
+ }
648
+ if ($process.HasExited -and -not $finalSeenBeforeExit) {
649
+ break
650
+ }
651
+ }
652
+
653
+ if (-not $process.WaitForExit([Math]::Max(1000, $TimeoutSeconds * 1000))) {
654
+ try { $process.Kill() } catch {}
655
+ Set-CaseCheck $caseResult "processExited" $false "timeoutSeconds=$TimeoutSeconds"
656
+ Fail "${name}: ai-battery-run-win did not exit within $TimeoutSeconds seconds."
657
+ }
658
+ Set-CaseCheck $caseResult "processExited" $true "exitCode=$($process.ExitCode)"
659
+
660
+ $afterText = Get-ConsoleText
661
+ $debugText = if (Test-Path $debugLog) { Get-Content -Path $debugLog -Raw } else { "" }
662
+ $caseResult.processExitCode = $process.ExitCode
663
+ $caseResult.debugEvents = @(Read-DebugEvents $debugLog)
664
+ Import-DebugEvents $debugLog
665
+
666
+ if ($process.ExitCode -ne 0) {
667
+ Set-CaseCheck $caseResult "processExitCode" $false $process.ExitCode
668
+ Fail "${name}: ai-battery-run-win exited with code $($process.ExitCode)."
669
+ }
670
+ Set-CaseCheck $caseResult "processExitCode" $true $process.ExitCode
671
+ if (-not $debugText.Contains('"event":"rowpty:start"')) {
672
+ Set-CaseCheck $caseResult "rowptyStarted" $false $debugLog
673
+ Fail "${name}: debug log does not show rowpty:start; rowpty path was not exercised."
674
+ }
675
+ Set-CaseCheck $caseResult "rowptyStarted" $true $debugLog
676
+ if ($debugText.Contains('"event":"overlay:start"') -or $debugText.Contains('"event":"conpty:start"')) {
677
+ Set-CaseCheck $caseResult "noFallback" $false $debugLog
678
+ Fail "${name}: runner fell back to overlay/node-pty instead of rowpty."
679
+ }
680
+ Set-CaseCheck $caseResult "noFallback" $true $debugLog
681
+ if (-not $finalSeenBeforeExit -and -not $afterText.Contains($finalMarker)) {
682
+ Set-CaseCheck $caseResult "finalHistoryVisible" $false $finalMarker
683
+ Fail "${name}: final response marker was not visible in the console buffer."
684
+ }
685
+ Set-CaseCheck $caseResult "finalHistoryVisible" $true $finalMarker
686
+ if (-not $statusSeenBeforeExit) {
687
+ Set-CaseCheck $caseResult "statusVisibleBeforeExit" $false $statusMarker
688
+ Fail "${name}: status row was not visible while the Codex-like renderer was running."
689
+ }
690
+ Set-CaseCheck $caseResult "statusVisibleBeforeExit" $true $statusMarker
691
+
692
+ $transientCount = ([regex]::Matches($afterText, "AI_BATTERY_TRANSIENT_FRAME_\d+_MUST_NOT_REMAIN")).Count
693
+ $bannerCount = Count-TextOccurrences $afterText "AI_BATTERY_CODEX_BANNER"
694
+ $statusCount = Count-TextOccurrences $afterText $statusMarker
695
+ Set-CaseCheck $caseResult "noTransientFramesInConsoleBuffer" ($transientCount -eq 0) "count=$transientCount"
696
+ if ($transientCount -ne 0) {
697
+ Fail "${name}: transient Codex frame text remained in the console buffer (count=$transientCount)."
698
+ }
699
+ Set-CaseCheck $caseResult "bannerRenderedExactlyOnce" ($bannerCount -eq 1) "count=$bannerCount"
700
+ if ($bannerCount -ne 1) {
701
+ Fail "${name}: the Codex banner appeared $bannerCount times in the console buffer (ghost frames)."
702
+ }
703
+
704
+ $histMatches = [regex]::Matches($afterText, "AI_BATTERY_HIST_LINE_(\d{3})")
705
+ $histNumbers = @($histMatches | ForEach-Object { [int]$_.Groups[1].Value })
706
+ $histUnique = @($histNumbers | Sort-Object -Unique)
707
+ $histInOrder = $true
708
+ for ($i = 1; $i -lt $histNumbers.Count; $i += 1) {
709
+ if ($histNumbers[$i] -lt $histNumbers[$i - 1]) { $histInOrder = $false; break }
710
+ }
711
+ Set-CaseCheck $caseResult "historyLinesPreserved" ($histUnique.Count -eq 30) "unique=$($histUnique.Count)/30"
712
+ if ($histUnique.Count -ne 30) {
713
+ Fail "${name}: only $($histUnique.Count)/30 scroll-region history lines survived in the console buffer."
714
+ }
715
+ Set-CaseCheck $caseResult "historyLinesNotDuplicated" ($histNumbers.Count -eq $histUnique.Count) "total=$($histNumbers.Count), unique=$($histUnique.Count)"
716
+ if ($histNumbers.Count -ne $histUnique.Count) {
717
+ Fail "${name}: history lines were duplicated in the console buffer (ghost frames)."
718
+ }
719
+ Set-CaseCheck $caseResult "historyLinesInOrder" $histInOrder "inOrder=$histInOrder"
720
+ if (-not $histInOrder) {
721
+ Fail "${name}: history lines appeared out of order in the console buffer."
722
+ }
723
+ Set-CaseCheck $caseResult "statusDoesNotLeakAfterExit" ($statusCount -eq 0) "count=$statusCount"
724
+ if ($statusCount -ne 0) {
725
+ Fail "${name}: status row text leaked into the console buffer after exit (count=$statusCount)."
726
+ }
727
+
728
+ $caseResult.ok = $true
729
+ }
730
+
731
+ $cmdChildScript = Join-Path $tempDir "child-cmd.mjs"
732
+ $cmdChildWrapper = Join-Path $tempDir "child-cmd.cmd"
733
+ $powershellChildScript = Join-Path $tempDir "child-powershell.ps1"
734
+ $codexHistoryChildScript = Join-Path $tempDir "child-codex-history.mjs"
735
+ Write-NodeChildScript $cmdChildScript "AI_BATTERY_SMOKE_CMD"
736
+ Write-CmdChildWrapper $cmdChildWrapper $node $cmdChildScript
737
+ Write-PowerShellChildScript $powershellChildScript "AI_BATTERY_SMOKE_POWERSHELL"
738
+ Write-CodexHistoryChildScript $codexHistoryChildScript
739
+
740
+ Invoke-RowPtySmokeCase "cmd" @($cmdChildWrapper)
741
+ Invoke-RowPtySmokeCase "powershell" @("powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", $powershellChildScript)
742
+ Invoke-CodexHistorySmokeCase @($node, $codexHistoryChildScript)
743
+
744
+ $script:SmokeReport.ok = $true
745
+ Write-SmokeReport
746
+ Write-Host "[ai-battery smoke] PASS: rowpty output, status paint, scrollback preservation, and Codex-like history rendering look healthy." -ForegroundColor Green
747
+ if ($ReportPath) {
748
+ Write-Host "[ai-battery smoke] Report: $ReportPath"
749
+ }
750
+ } catch {
751
+ $script:SmokeFailed = $true
752
+ $script:SmokeReport.ok = $false
753
+ $script:SmokeReport.failure = $_.Exception.Message
754
+ Write-SmokeReport
755
+ Write-Host "[ai-battery smoke] FAIL: $($_.Exception.Message)" -ForegroundColor Red
756
+ if ($ReportPath) {
757
+ Write-Host "[ai-battery smoke] Report: $ReportPath"
758
+ }
759
+ exit 1
760
+ } finally {
761
+ if (-not $KeepTemp -and -not $script:SmokeFailed -and (Test-Path $tempDir)) {
762
+ Remove-Item -Recurse -Force $tempDir -ErrorAction SilentlyContinue
763
+ } elseif ($KeepTemp -or $script:SmokeFailed) {
764
+ Write-Step "Kept temp directory: $tempDir"
765
+ }
766
+ }