authoravatarclover caruso<git@paperclover.net>2026-10-22 13:14:53-07:00
committeravatarclover caruso<git@paperclover.net>2026-10-24 19:01:23-07:00
logd7a4e059a91fedc10fe5726256c78d46f20499b5
treeebb4ce29af08c23a8c50c48c18b956d14a210068
parent92dda739cbc51cce5bb840529388707c70648e64
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Preserve Windows computer output across guest versions

Read PowerShell setup output through QGA files because native ARM64 console handles bypass capture. Set the console code page before PowerShell starts so PowerShell 3 preserves Unicode pipeline output. Combine installation probes and allow emulated startup and cleanup within the host connection budget. Assisted-by: gpt-6.1-sol

4 files changed, 35 insertions(+), 28 deletions(-)

dashboard/src/host.rs+3-1
......@@ -34,7 +34,9 @@ pub async fn open(request: Value) -> Result<(Value, tokio::net::UnixStream)> {
3434 Some("vm.create" | "vm.media" | "vm.preset" | "vm.ai")
3535 ) {
3636 910
37 } else if matches!(request["operation"].as_str(), Some("vm.act" | "vm.computer")) {
37 } else if request["operation"] == "vm.computer" {
38 300
39 } else if request["operation"] == "vm.act" {
3840 240
3941 } else if request["operation"] == "copyparty.manage" {
4042 310
guest/computer-windows.cs+2-1
......@@ -210,7 +210,8 @@ public static class ComputerWorker {
210210 string runtime=Text(request,"runtime","default"),directory=System.IO.Path.GetDirectoryName(requestPath),file,exe,arguments,script=Text(request,"script");
211211 if(runtime=="default")runtime="powershell";
212212 switch(runtime) {
213 case "powershell": file=System.IO.Path.Combine(directory,"script.ps1");exe="powershell.exe";arguments="-NoProfile -NonInteractive -ExecutionPolicy Bypass -File \""+file+"\"";script="[Console]::OutputEncoding=New-Object Text.UTF8Encoding($false)\n"+script;break;
213 // PowerShell 3 caches pipeline encoding before the script runs.
214 case "powershell": file=System.IO.Path.Combine(directory,"script.ps1");exe="cmd.exe";arguments="/d /s /c \"chcp 65001 >nul & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File \""+file+"\"\"";break;
214215 case "cmd": file=System.IO.Path.Combine(directory,"script.cmd");exe="cmd.exe";arguments="/d /s /c \"\""+file+"\"\"";script="@chcp 65001 >nul\r\n"+script;break;
215216 case "ahk": file=System.IO.Path.Combine(directory,"script.ahk");exe=System.IO.Path.Combine(root,"AutoHotkey.exe");arguments="/ErrorStdOut \""+file+"\"";script="#Requires AutoHotkey v2.0\n#SingleInstance Off\n#NoTrayIcon\nFileEncoding 'UTF-8-RAW'\nSendMode 'Input'\nCoordMode 'Mouse', 'Screen'\nCoordMode 'Pixel', 'Screen'\nCoordMode 'ToolTip', 'Screen'\nSetTitleMatchMode 2\nDetectHiddenWindows true\n"+script;break;
216217 default:throw new Exception("Choose a runtime reported by computer_status.");
tools/computer-test.py+13-3
......@@ -75,6 +75,16 @@ class GuestCancellation(unittest.TestCase):
7575 patcher.start()
7676 self.addCleanup(patcher.stop)
7777
78 def test_windows_powershell_reads_redirected_output_without_console_capture(self):
79 with patch.object(computer, 'write_file'), patch.object(computer, 'guest_exec', return_value=b''), patch.object(computer, 'read_file', return_value=b'file output'):
80 self.assertEqual(computer.powershell('fixture', "Write-Output 'file output'"), b'file output')
81
82 def test_windows_powershell_rejects_failed_execution_before_reading_output(self):
83 with patch.object(computer, 'write_file'), patch.object(computer, 'guest_exec', side_effect=ValueError('Failed')), patch.object(computer, 'read_file') as read:
84 with self.assertRaises(ValueError):
85 computer.powershell('fixture', 'exit 7')
86 read.assert_not_called()
87
7888 def test_reused_guest_pid_waits_for_current_process(self):
7989 replies = [{'pid': 2596}, {'exited': True, 'exitcode': 1}, {'exited': False},
8090 {'exited': True, 'exitcode': 0, 'out-data': base64.b64encode(b'current').decode()},
......@@ -113,7 +123,7 @@ class GuestCancellation(unittest.TestCase):
113123 self.assertGreater(computer.remaining(20), 0)
114124 running.clear()
115125 return b''
116 return b'True'
126 return b'[true,true]'
117127 token = computer.DEADLINE.set(time.monotonic() + 30)
118128 try:
119129 with patch.object(computer, 'powershell', execute), patch.object(computer, 'write_file'):
......@@ -160,7 +170,7 @@ class GuestCancellation(unittest.TestCase):
160170 def execute(name, script, **kwargs):
161171 if 'DeleteTask' in script:
162172 raise TimeoutError()
163 return b'True'
173 return b'[true,true]'
164174 with patch.object(computer, 'powershell', execute), patch.object(computer, 'write_file'), patch.object(computer, 'read_file', return_value=json.dumps(result).encode()):
165175 self.assertEqual(computer.worker('fixture', 'windows', {'action': 'spawn'}), result)
166176 pending = computer.vms.DISKS / 'fixture' / 'computer-operation.json'
......@@ -177,7 +187,7 @@ class GuestCancellation(unittest.TestCase):
177187 if operation.get('keep_spawn'):
178188 raise OSError('Disk full')
179189 record(name, operation)
180 with patch.object(computer, 'record_operation', persist), patch.object(computer, 'powershell', return_value=b'True') as execute, patch.object(computer, 'write_file'), patch.object(computer, 'read_file', return_value=b'{"id":"123:456"}'):
190 with patch.object(computer, 'record_operation', persist), patch.object(computer, 'powershell', return_value=b'[true,true]') as execute, patch.object(computer, 'write_file'), patch.object(computer, 'read_file', return_value=b'{"id":"123:456"}'):
181191 with self.assertRaises(OSError):
182192 computer.worker('fixture', 'windows', {'action': 'spawn'})
183193 self.assertIn('$t.Stop(0)', execute.call_args.args[1])
tools/vm-computer.py+17-23
......@@ -101,25 +101,15 @@ def write_file(name, path, data, offset=0):
101101 qga(name, 'guest-file-close', handle=handle)
102102
103103
104def powershell(name, script, timeout=20):
105 """Windows 7 PowerShell needs a hidden console when launched by QGA."""
104def powershell(name, script, timeout=60):
105 """Win7 needs a hidden console; ARM64 QGA cannot capture WSH's console output."""
106106 stem = 'C:\\Windows\\Temp\\snowglobe-computer-' + uuid.uuid4().hex
107107 command = 'cmd.exe /d /c powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File ' + stem + '.ps1'
108108 command += ' > ' + stem + '.out 2> ' + stem + '.err'
109109 launcher = '''Set shell = CreateObject("WScript.Shell")
110110code = shell.Run("COMMAND", 0, True)
111Set stream = CreateObject("ADODB.Stream")
112stream.Type = 1
113stream.Open
114stream.LoadFromFile "STEM.out"
115Set xml = CreateObject("Msxml2.DOMDocument.6.0")
116Set node = xml.createElement("output")
117node.DataType = "bin.base64"
118node.nodeTypedValue = stream.Read
119WScript.StdOut.Write Replace(Replace(node.Text, vbCr, ""), vbLf, "")
120stream.Close
121111Set files = CreateObject("Scripting.FileSystemObject")
122files.DeleteFile "STEM.out"
112If code <> 0 Then files.DeleteFile "STEM.out"
123113files.DeleteFile "STEM.err"
124114files.DeleteFile "STEM.ps1"
125115files.DeleteFile WScript.ScriptFullName
......@@ -127,7 +117,11 @@ WScript.Quit code
127117'''.replace('COMMAND', command).replace('STEM', stem)
128118 write_file(name, stem + '.ps1', b'\xff\xfe' + script.encode('utf-16le'))
129119 write_file(name, stem + '.vbs', launcher.encode('ascii'))
130 return base64.b64decode(guest_exec(name, 'cscript.exe', ['//nologo', stem + '.vbs'], timeout=timeout), validate=True)
120 guest_exec(name, 'cscript.exe', ['//nologo', stem + '.vbs'], timeout=timeout)
121 try:
122 return read_file(name, stem + '.out', length=2*1024*1024)
123 finally:
124 guest_exec(name, 'cmd.exe', ['/d', '/c', 'del ' + stem + '.out'])
131125
132126
133127async def desktop(name, actions=None, platform=None, screenshot=True, native_text=True):
......@@ -351,7 +345,7 @@ def record_operation(name, operation):
351345
352346
353347def finish_operation(name, operation):
354 token = DEADLINE.set(time.monotonic() + 20)
348 token = DEADLINE.set(time.monotonic() + 60)
355349 try:
356350 if operation['platform'] == 'linux':
357351 guest_exec(name, '/etc/qemu-ga/fsfreeze-hook.d/snowglobe-computer', [],
......@@ -372,7 +366,7 @@ def finish_operation(name, operation):
372366 cleanup += "$f.DeleteTask('SnowglobeComputer-"+run+"',0)};"
373367 if not operation.get('keep_spawn'):
374368 cleanup += "if(Test-Path -LiteralPath $d){Remove-Item -LiteralPath $d -Recurse -Force}"
375 powershell(name, cleanup, timeout=18)
369 powershell(name, cleanup, timeout=58)
376370 (vms.DISKS / name / 'computer-operation.json').unlink()
377371 except Exception as error:
378372 raise BlockingIOError('The previous operation has not stopped. Check its screenshot, then retry when the guest agent reconnects.') from error
......@@ -417,18 +411,18 @@ def worker(name, platform, request):
417411 if platform == 'windows':
418412 run = uuid.uuid4().hex
419413 directory = 'C:\\ProgramData\\SnowglobeComputer\\' + run
420 setup = "$d='" + directory + "'; New-Item -ItemType Directory -Force -Path $d | Out-Null; Test-Path C:\\ProgramData\\SnowglobeComputer\\AutoHotkey.exe"
421 installed=powershell(name,setup).strip()==b'True'
414 source = Path(__file__).resolve().parent.parent / 'guest/computer-windows.cs'
415 content = source.read_bytes()
416 digest = hashlib.sha256(content).hexdigest()[:16]
417 installed_worker = 'C:\\ProgramData\\SnowglobeComputer\\worker-' + digest + '.exe'
418 setup = "$d='" + directory + "'; New-Item -ItemType Directory -Force -Path $d | Out-Null; "
419 setup += "@((Test-Path C:\\ProgramData\\SnowglobeComputer\\AutoHotkey.exe),(Test-Path -LiteralPath '" + installed_worker + "')) | ConvertTo-Json -Compress"
420 installed, exists = json.loads(powershell(name,setup))
422421 ahk=os.environ.get('SNOWGLOBE_COMPUTER_AHK')
423422 if not installed and ahk:
424423 write_file(name,'C:\\ProgramData\\SnowglobeComputer\\AutoHotkey.exe',(Path(ahk)/'AutoHotkey32.exe').read_bytes())
425424 write_file(name,'C:\\ProgramData\\SnowglobeComputer\\AutoHotkey-license.txt',(Path(ahk)/'license.txt').read_bytes())
426425 write_file(name,directory+'\\request.json',json.dumps(request).encode())
427 source = Path(__file__).resolve().parent.parent / 'guest/computer-windows.cs'
428 content = source.read_bytes()
429 digest = hashlib.sha256(content).hexdigest()[:16]
430 installed_worker = 'C:\\ProgramData\\SnowglobeComputer\\worker-' + digest + '.exe'
431 exists = powershell(name, "Test-Path -LiteralPath '" + installed_worker + "'").strip() == b'True'
432426 if not exists:
433427 source_path = directory + '\\worker.cs'
434428 write_file(name, source_path, content)