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)> {...@@ -34,7 +34,9 @@ pub async fn open(request: Value) -> Result<(Value, tokio::net::UnixStream)> {
34 Some("vm.create" | "vm.media" | "vm.preset" | "vm.ai")34 Some("vm.create" | "vm.media" | "vm.preset" | "vm.ai")
35 ) {35 ) {
36 91036 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" {
38 24040 240
39 } else if request["operation"] == "copyparty.manage" {41 } else if request["operation"] == "copyparty.manage" {
40 31042 310
guest/computer-windows.cs+2-1
...@@ -210,7 +210,8 @@ public static class ComputerWorker {...@@ -210,7 +210,8 @@ public static class ComputerWorker {
210 string runtime=Text(request,"runtime","default"),directory=System.IO.Path.GetDirectoryName(requestPath),file,exe,arguments,script=Text(request,"script");210 string runtime=Text(request,"runtime","default"),directory=System.IO.Path.GetDirectoryName(requestPath),file,exe,arguments,script=Text(request,"script");
211 if(runtime=="default")runtime="powershell";211 if(runtime=="default")runtime="powershell";
212 switch(runtime) {212 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;
214 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;215 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;
215 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;216 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;
216 default:throw new Exception("Choose a runtime reported by computer_status.");217 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):...@@ -75,6 +75,16 @@ class GuestCancellation(unittest.TestCase):
75 patcher.start()75 patcher.start()
76 self.addCleanup(patcher.stop)76 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
78 def test_reused_guest_pid_waits_for_current_process(self):88 def test_reused_guest_pid_waits_for_current_process(self):
79 replies = [{'pid': 2596}, {'exited': True, 'exitcode': 1}, {'exited': False},89 replies = [{'pid': 2596}, {'exited': True, 'exitcode': 1}, {'exited': False},
80 {'exited': True, 'exitcode': 0, 'out-data': base64.b64encode(b'current').decode()},90 {'exited': True, 'exitcode': 0, 'out-data': base64.b64encode(b'current').decode()},
...@@ -113,7 +123,7 @@ class GuestCancellation(unittest.TestCase):...@@ -113,7 +123,7 @@ class GuestCancellation(unittest.TestCase):
113 self.assertGreater(computer.remaining(20), 0)123 self.assertGreater(computer.remaining(20), 0)
114 running.clear()124 running.clear()
115 return b''125 return b''
116 return b'True'126 return b'[true,true]'
117 token = computer.DEADLINE.set(time.monotonic() + 30)127 token = computer.DEADLINE.set(time.monotonic() + 30)
118 try:128 try:
119 with patch.object(computer, 'powershell', execute), patch.object(computer, 'write_file'):129 with patch.object(computer, 'powershell', execute), patch.object(computer, 'write_file'):
...@@ -160,7 +170,7 @@ class GuestCancellation(unittest.TestCase):...@@ -160,7 +170,7 @@ class GuestCancellation(unittest.TestCase):
160 def execute(name, script, **kwargs):170 def execute(name, script, **kwargs):
161 if 'DeleteTask' in script:171 if 'DeleteTask' in script:
162 raise TimeoutError()172 raise TimeoutError()
163 return b'True'173 return b'[true,true]'
164 with patch.object(computer, 'powershell', execute), patch.object(computer, 'write_file'), patch.object(computer, 'read_file', return_value=json.dumps(result).encode()):174 with patch.object(computer, 'powershell', execute), patch.object(computer, 'write_file'), patch.object(computer, 'read_file', return_value=json.dumps(result).encode()):
165 self.assertEqual(computer.worker('fixture', 'windows', {'action': 'spawn'}), result)175 self.assertEqual(computer.worker('fixture', 'windows', {'action': 'spawn'}), result)
166 pending = computer.vms.DISKS / 'fixture' / 'computer-operation.json'176 pending = computer.vms.DISKS / 'fixture' / 'computer-operation.json'
...@@ -177,7 +187,7 @@ class GuestCancellation(unittest.TestCase):...@@ -177,7 +187,7 @@ class GuestCancellation(unittest.TestCase):
177 if operation.get('keep_spawn'):187 if operation.get('keep_spawn'):
178 raise OSError('Disk full')188 raise OSError('Disk full')
179 record(name, operation)189 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"}'):
181 with self.assertRaises(OSError):191 with self.assertRaises(OSError):
182 computer.worker('fixture', 'windows', {'action': 'spawn'})192 computer.worker('fixture', 'windows', {'action': 'spawn'})
183 self.assertIn('$t.Stop(0)', execute.call_args.args[1])193 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):...@@ -101,25 +101,15 @@ def write_file(name, path, data, offset=0):
101 qga(name, 'guest-file-close', handle=handle)101 qga(name, 'guest-file-close', handle=handle)
102102
103103
104def powershell(name, script, timeout=20):104def powershell(name, script, timeout=60):
105 """Windows 7 PowerShell needs a hidden console when launched by QGA."""105 """Win7 needs a hidden console; ARM64 QGA cannot capture WSH's console output."""
106 stem = 'C:\\Windows\\Temp\\snowglobe-computer-' + uuid.uuid4().hex106 stem = 'C:\\Windows\\Temp\\snowglobe-computer-' + uuid.uuid4().hex
107 command = 'cmd.exe /d /c powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File ' + stem + '.ps1'107 command = 'cmd.exe /d /c powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File ' + stem + '.ps1'
108 command += ' > ' + stem + '.out 2> ' + stem + '.err'108 command += ' > ' + stem + '.out 2> ' + stem + '.err'
109 launcher = '''Set shell = CreateObject("WScript.Shell")109 launcher = '''Set shell = CreateObject("WScript.Shell")
110code = shell.Run("COMMAND", 0, True)110code = 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
121Set files = CreateObject("Scripting.FileSystemObject")111Set files = CreateObject("Scripting.FileSystemObject")
122files.DeleteFile "STEM.out"112If code <> 0 Then files.DeleteFile "STEM.out"
123files.DeleteFile "STEM.err"113files.DeleteFile "STEM.err"
124files.DeleteFile "STEM.ps1"114files.DeleteFile "STEM.ps1"
125files.DeleteFile WScript.ScriptFullName115files.DeleteFile WScript.ScriptFullName
...@@ -127,7 +117,11 @@ WScript.Quit code...@@ -127,7 +117,11 @@ WScript.Quit code
127'''.replace('COMMAND', command).replace('STEM', stem)117'''.replace('COMMAND', command).replace('STEM', stem)
128 write_file(name, stem + '.ps1', b'\xff\xfe' + script.encode('utf-16le'))118 write_file(name, stem + '.ps1', b'\xff\xfe' + script.encode('utf-16le'))
129 write_file(name, stem + '.vbs', launcher.encode('ascii'))119 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
133async def desktop(name, actions=None, platform=None, screenshot=True, native_text=True):127async def desktop(name, actions=None, platform=None, screenshot=True, native_text=True):
...@@ -351,7 +345,7 @@ def record_operation(name, operation):...@@ -351,7 +345,7 @@ def record_operation(name, operation):
351345
352346
353def finish_operation(name, operation):347def finish_operation(name, operation):
354 token = DEADLINE.set(time.monotonic() + 20)348 token = DEADLINE.set(time.monotonic() + 60)
355 try:349 try:
356 if operation['platform'] == 'linux':350 if operation['platform'] == 'linux':
357 guest_exec(name, '/etc/qemu-ga/fsfreeze-hook.d/snowglobe-computer', [],351 guest_exec(name, '/etc/qemu-ga/fsfreeze-hook.d/snowglobe-computer', [],
...@@ -372,7 +366,7 @@ def finish_operation(name, operation):...@@ -372,7 +366,7 @@ def finish_operation(name, operation):
372 cleanup += "$f.DeleteTask('SnowglobeComputer-"+run+"',0)};"366 cleanup += "$f.DeleteTask('SnowglobeComputer-"+run+"',0)};"
373 if not operation.get('keep_spawn'):367 if not operation.get('keep_spawn'):
374 cleanup += "if(Test-Path -LiteralPath $d){Remove-Item -LiteralPath $d -Recurse -Force}"368 cleanup += "if(Test-Path -LiteralPath $d){Remove-Item -LiteralPath $d -Recurse -Force}"
375 powershell(name, cleanup, timeout=18)369 powershell(name, cleanup, timeout=58)
376 (vms.DISKS / name / 'computer-operation.json').unlink()370 (vms.DISKS / name / 'computer-operation.json').unlink()
377 except Exception as error:371 except Exception as error:
378 raise BlockingIOError('The previous operation has not stopped. Check its screenshot, then retry when the guest agent reconnects.') from error372 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):...@@ -417,18 +411,18 @@ def worker(name, platform, request):
417 if platform == 'windows':411 if platform == 'windows':
418 run = uuid.uuid4().hex412 run = uuid.uuid4().hex
419 directory = 'C:\\ProgramData\\SnowglobeComputer\\' + run413 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"414 source = Path(__file__).resolve().parent.parent / 'guest/computer-windows.cs'
421 installed=powershell(name,setup).strip()==b'True'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))
422 ahk=os.environ.get('SNOWGLOBE_COMPUTER_AHK')421 ahk=os.environ.get('SNOWGLOBE_COMPUTER_AHK')
423 if not installed and ahk:422 if not installed and ahk:
424 write_file(name,'C:\\ProgramData\\SnowglobeComputer\\AutoHotkey.exe',(Path(ahk)/'AutoHotkey32.exe').read_bytes())423 write_file(name,'C:\\ProgramData\\SnowglobeComputer\\AutoHotkey.exe',(Path(ahk)/'AutoHotkey32.exe').read_bytes())
425 write_file(name,'C:\\ProgramData\\SnowglobeComputer\\AutoHotkey-license.txt',(Path(ahk)/'license.txt').read_bytes())424 write_file(name,'C:\\ProgramData\\SnowglobeComputer\\AutoHotkey-license.txt',(Path(ahk)/'license.txt').read_bytes())
426 write_file(name,directory+'\\request.json',json.dumps(request).encode())425 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'
432 if not exists:426 if not exists:
433 source_path = directory + '\\worker.cs'427 source_path = directory + '\\worker.cs'
434 write_file(name, source_path, content)428 write_file(name, source_path, content)