authoravatarclover caruso<git@paperclover.net>2026-11-16 22:26:45-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-22 00:44:02-08:00
logffeeff93bd50abd5d2198b8d2890329265d550a1
tree49ccfbd5a463d8f090771a0623b279b6136aa13f
parent62fb5e2102b3da5f14e1c90a004b32f1f69089a6
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Keep force-off and reset available during active VM commands

Cancel the active operation through the control file before bounded libvirt force-off or reset. Preserve the execution guard for graceful power actions. Expose explicit recovery actions through computer_vm. Verified real Linux and Windows commands interrupted by both actions, old-operation cleanup, no late writes, and subsequent commands; 28 VM boundary, 42 protocol, 61 Rust tests and the OAuth client integration pass. Assisted-by: gpt-6.1-sol

6 files changed, 69 insertions(+), 12 deletions(-)

dashboard/src/computer-tools.json+3-1
......@@ -594,7 +594,7 @@
594594 },
595595 {
596596 "name": "computer_vm",
597 "description": "Start, shut down, or reboot a granted VM. For AI-owned test VMs only: extend idle expiry by up to 24 hours from now, or delete the VM and its disposable disk. Listing VMs does not extend expiry.",
597 "description": "Start, shut down, reboot, force off, or reset a granted VM. Force off and reset lose unsaved work and are unavailable on managed Macs. For AI-owned test VMs, extend idle expiry by up to 24 hours or delete the VM and disk. Listing does not extend expiry.",
598598 "inputSchema": {
599599 "type": "object",
600600 "properties": {
......@@ -607,6 +607,8 @@
607607 "start",
608608 "shutdown",
609609 "reboot",
610 "force_off",
611 "reset",
610612 "extend",
611613 "delete"
612614 ]
dashboard/src/computer.rs+4-3
......@@ -173,11 +173,12 @@ impl ServerHandler for Computer {
173173 return match arguments.get("operation").and_then(Value::as_str) {
174174 Some(operation @ ("extend" | "delete")) => host::call(json!({"operation":"vm.ai","payload":{
175175 "action":operation,"name":vm,"owner":grant["user"],"seconds":arguments.get("seconds").unwrap_or(&json!(3600))}})).await,
176 Some(operation @ ("start" | "shutdown" | "reboot")) if !arguments.contains_key("seconds") => {
177 host::call(json!({"operation":"vm.act","payload":{"name":vm,"action":operation}})).await?;
176 Some(operation @ ("start" | "shutdown" | "reboot" | "force_off" | "reset")) if !arguments.contains_key("seconds") => {
177 let host_action = if operation == "force_off" { "destroy" } else { operation };
178 host::call(json!({"operation":"vm.act","payload":{"name":vm,"action":host_action}})).await?;
178179 Ok(json!({"id":vm,"requested":operation}))
179180 },
180 _ => Err(Error::new(400,"Choose start, shutdown, reboot, extend, or delete.")),
181 _ => Err(Error::new(400,"Choose start, shutdown, reboot, force_off, reset, extend, or delete.")),
181182 };
182183 }
183184 if matches!(action,"upload"|"download") {
tools/computer-client-test.py+8
......@@ -29,6 +29,7 @@ HOST = "snowglobe.paperclover.net"
2929class Host(socketserver.StreamRequestHandler):
3030 owner = None
3131 files = {}
32 power_actions = []
3233
3334 def handle(self):
3435 request = json.loads(self.rfile.readline())
......@@ -48,6 +49,9 @@ class Host(socketserver.StreamRequestHandler):
4849 "os": "Fedora", "arch": "x86_64", "state": "running", "aiOwned": False}]
4950 if operation == "vm.owner":
5051 return {"owner": self.owner}
52 if operation == "vm.act":
53 self.power_actions.append(payload["action"])
54 return None
5155 if operation != "vm.computer":
5256 raise KeyError(operation)
5357 request, files = payload["request"], self.files
......@@ -164,6 +168,10 @@ class Client(unittest.TestCase):
164168 self.assertEqual([c["id"] for c in vm.call("computer_list")["computers"]], ["test-vm"])
165169 ran = vm.call("computer_exec", vm="test-vm", script="uname")
166170 self.assertEqual((ran["stdout"], ran["png"]), ("ran uname", base64.b64decode(PNG)))
171 for operation in ["force_off", "reset"]:
172 self.assertEqual(vm.call("computer_vm", vm="test-vm", operation=operation),
173 {"id":"test-vm", "requested":operation})
174 self.assertEqual(Host.power_actions, ["destroy", "reset"])
167175 with self.assertRaisesRegex(computer.ComputerError, "granted"):
168176 vm.call("computer_shot", vm="other-vm")
169177
tools/dashboard-vms-test.py+37
......@@ -427,6 +427,43 @@ class VMTests(unittest.TestCase):
427427 vms.validate('upload', {'volume': filename, 'size': 32768})
428428
429429
430class PowerControls(unittest.TestCase):
431 def setUp(self):
432 temporary = tempfile.TemporaryDirectory()
433 self.addCleanup(temporary.cleanup)
434 self.root = Path(temporary.name)
435 (self.root / 'fixture').mkdir()
436 patcher = patch.object(vms, 'DISKS', self.root)
437 patcher.start()
438 self.addCleanup(patcher.stop)
439
440 def test_force_controls_cancel_the_active_call_without_waiting_for_it(self):
441 for action in ['reset', 'destroy']:
442 with self.subTest(action=action), vms.computer_lock('fixture', 'exec') as active:
443 with patch.object(vms.sys, 'argv', ['vms.py','act',json.dumps({'name':'fixture','action':action})]), patch.object(vms, 'virsh', return_value='') as virsh:
444 self.assertIsNone(vms.main())
445 virsh.assert_called_once_with(action, 'fixture', timeout=15)
446 with vms.computer_control('fixture') as control:
447 self.assertEqual(control.read(), active['id'])
448 self.assertEqual(vms.computer_activity('fixture')['id'], active['id'])
449
450 def test_failed_force_request_keeps_the_cancellation_intent(self):
451 with vms.computer_lock('fixture', 'exec') as active:
452 with patch.object(vms.sys, 'argv', ['vms.py','act',json.dumps({'name':'fixture','action':'reset'})]), \
453 patch.object(vms, 'virsh', side_effect=vms.subprocess.CalledProcessError(1, 'virsh', stderr='Connection lost')):
454 with self.assertRaises(vms.subprocess.CalledProcessError):
455 vms.main()
456 with vms.computer_control('fixture') as control:
457 self.assertEqual(control.read(), active['id'])
458
459 def test_graceful_actions_preserve_the_active_command_guard(self):
460 with vms.computer_lock('fixture', 'exec'), patch.object(vms, 'virsh') as virsh:
461 for action in ['start', 'shutdown', 'reboot', 'suspend', 'resume']:
462 with patch.object(vms.sys, 'argv', ['vms.py','act',json.dumps({'name':'fixture','action':action})]):
463 with self.assertRaises(BlockingIOError):
464 vms.main()
465 virsh.assert_not_called()
466
430467class DisposableStorage(unittest.TestCase):
431468 def setUp(self):
432469 temporary = tempfile.TemporaryDirectory()
tools/vm-computer.py+1-4
......@@ -530,10 +530,7 @@ def handle(name, request):
530530 if active.get('id') != identity:
531531 return {'running': False}
532532 if request['operation'] == 'stop':
533 control.seek(0)
534 control.truncate()
535 control.write(identity)
536 control.flush()
533 vms.computer_cancel(control, identity)
537534 else:
538535 active['stopping'] = control.read() == identity
539536 return {'running': True, **active, 'stopping': request['operation'] == 'stop' or active.get('stopping', False)}
tools/vms.py+16-4
......@@ -176,7 +176,7 @@ def validate(action, payload):
176176 for field in ("autostart", "start", "disks"):
177177 if field in payload and not isinstance(payload[field], bool):
178178 raise ValueError(f"Choose whether to enable {field}.")
179 if action == "act" and (not isinstance(payload["action"], str) or payload["action"] not in {"start", "shutdown", "reboot", "destroy", "resume", "suspend"}):
179 if action == "act" and (not isinstance(payload["action"], str) or payload["action"] not in {"start", "shutdown", "reboot", "reset", "destroy", "resume", "suspend"}):
180180 raise ValueError("Choose a supported VM action.")
181181 if action == "clipboard" and (not isinstance(payload["text"], str) or len(payload["text"].encode()) > 262144):
182182 raise ValueError("Shorten the clipboard text, then send it again.")
......@@ -238,6 +238,13 @@ def computer_control(name):
238238 yield control
239239
240240
241def computer_cancel(control, identity):
242 control.seek(0)
243 control.truncate()
244 control.write(identity)
245 control.flush()
246
247
241248def computer_activity(name):
242249 try:
243250 with os.fdopen(open_regular(DISKS / name / "computer.lock")) as incoming:
......@@ -309,7 +316,7 @@ def domains(*, computers=False):
309316 "arch": root.find("./os/type").get("arch"), "state": state,
310317 "aiOwned": ai is not None, "ownerOnly": ai is not None,
311318 "expiresAt": ai["expiresAt"] if ai else None,
312 "capabilities": ["start", "shutdown", "reboot", "destroy", "resume", "suspend", "edit", "delete", "media", "preset", "computer"],
319 "capabilities": ["start", "shutdown", "reboot", "reset", "destroy", "resume", "suspend", "edit", "delete", "media", "preset", "computer"],
313320 }
314321 if computers:
315322 result.append(entry)
......@@ -1138,14 +1145,19 @@ def main():
11381145 elif action == "act":
11391146 name = payload["name"]
11401147 ensure_name(name)
1141 with computer_lock(name):
1148 forced = payload["action"] in {"reset", "destroy"}
1149 with computer_control(name) if forced else computer_lock(name) as control:
1150 if forced:
1151 active = computer_activity(name)
1152 if active is not None and active.get("id"):
1153 computer_cancel(control, active["id"])
11421154 if payload["action"] == "start":
11431155 root = ET.fromstring(virsh("dumpxml", name, "--inactive"))
11441156 if root.find("./devices/interface/source[@network='default']") is not None:
11451157 ensure_network()
11461158 ai = import_module("vm-ai")
11471159 ai.lease(name, ai.LIMITS["idle_seconds"])
1148 virsh({"start": "start", "shutdown": "shutdown", "reboot": "reboot", "destroy": "destroy", "resume": "resume", "suspend": "suspend"}[payload["action"]], name)
1160 virsh(payload["action"], name, timeout=15 if forced else None)
11491161 elif action == "update":
11501162 name = payload["name"]
11511163 ensure_name(name)