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 @@...@@ -594,7 +594,7 @@
594 },594 },
595 {595 {
596 "name": "computer_vm",596 "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.",
598 "inputSchema": {598 "inputSchema": {
599 "type": "object",599 "type": "object",
600 "properties": {600 "properties": {
...@@ -607,6 +607,8 @@...@@ -607,6 +607,8 @@
607 "start",607 "start",
608 "shutdown",608 "shutdown",
609 "reboot",609 "reboot",
610 "force_off",
611 "reset",
610 "extend",612 "extend",
611 "delete"613 "delete"
612 ]614 ]
dashboard/src/computer.rs+4-3
...@@ -173,11 +173,12 @@ impl ServerHandler for Computer {...@@ -173,11 +173,12 @@ impl ServerHandler for Computer {
173 return match arguments.get("operation").and_then(Value::as_str) {173 return match arguments.get("operation").and_then(Value::as_str) {
174 Some(operation @ ("extend" | "delete")) => host::call(json!({"operation":"vm.ai","payload":{174 Some(operation @ ("extend" | "delete")) => host::call(json!({"operation":"vm.ai","payload":{
175 "action":operation,"name":vm,"owner":grant["user"],"seconds":arguments.get("seconds").unwrap_or(&json!(3600))}})).await,175 "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") => {176 Some(operation @ ("start" | "shutdown" | "reboot" | "force_off" | "reset")) if !arguments.contains_key("seconds") => {
177 host::call(json!({"operation":"vm.act","payload":{"name":vm,"action":operation}})).await?;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?;
178 Ok(json!({"id":vm,"requested":operation}))179 Ok(json!({"id":vm,"requested":operation}))
179 },180 },
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.")),
181 };182 };
182 }183 }
183 if matches!(action,"upload"|"download") {184 if matches!(action,"upload"|"download") {
tools/computer-client-test.py+8
...@@ -29,6 +29,7 @@ HOST = "snowglobe.paperclover.net"...@@ -29,6 +29,7 @@ HOST = "snowglobe.paperclover.net"
29class Host(socketserver.StreamRequestHandler):29class Host(socketserver.StreamRequestHandler):
30 owner = None30 owner = None
31 files = {}31 files = {}
32 power_actions = []
3233
33 def handle(self):34 def handle(self):
34 request = json.loads(self.rfile.readline())35 request = json.loads(self.rfile.readline())
...@@ -48,6 +49,9 @@ class Host(socketserver.StreamRequestHandler):...@@ -48,6 +49,9 @@ class Host(socketserver.StreamRequestHandler):
48 "os": "Fedora", "arch": "x86_64", "state": "running", "aiOwned": False}]49 "os": "Fedora", "arch": "x86_64", "state": "running", "aiOwned": False}]
49 if operation == "vm.owner":50 if operation == "vm.owner":
50 return {"owner": self.owner}51 return {"owner": self.owner}
52 if operation == "vm.act":
53 self.power_actions.append(payload["action"])
54 return None
51 if operation != "vm.computer":55 if operation != "vm.computer":
52 raise KeyError(operation)56 raise KeyError(operation)
53 request, files = payload["request"], self.files57 request, files = payload["request"], self.files
...@@ -164,6 +168,10 @@ class Client(unittest.TestCase):...@@ -164,6 +168,10 @@ class Client(unittest.TestCase):
164 self.assertEqual([c["id"] for c in vm.call("computer_list")["computers"]], ["test-vm"])168 self.assertEqual([c["id"] for c in vm.call("computer_list")["computers"]], ["test-vm"])
165 ran = vm.call("computer_exec", vm="test-vm", script="uname")169 ran = vm.call("computer_exec", vm="test-vm", script="uname")
166 self.assertEqual((ran["stdout"], ran["png"]), ("ran uname", base64.b64decode(PNG)))170 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"])
167 with self.assertRaisesRegex(computer.ComputerError, "granted"):175 with self.assertRaisesRegex(computer.ComputerError, "granted"):
168 vm.call("computer_shot", vm="other-vm")176 vm.call("computer_shot", vm="other-vm")
169177
tools/dashboard-vms-test.py+37
...@@ -427,6 +427,43 @@ class VMTests(unittest.TestCase):...@@ -427,6 +427,43 @@ class VMTests(unittest.TestCase):
427 vms.validate('upload', {'volume': filename, 'size': 32768})427 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
430class DisposableStorage(unittest.TestCase):467class DisposableStorage(unittest.TestCase):
431 def setUp(self):468 def setUp(self):
432 temporary = tempfile.TemporaryDirectory()469 temporary = tempfile.TemporaryDirectory()
tools/vm-computer.py+1-4
...@@ -530,10 +530,7 @@ def handle(name, request):...@@ -530,10 +530,7 @@ def handle(name, request):
530 if active.get('id') != identity:530 if active.get('id') != identity:
531 return {'running': False}531 return {'running': False}
532 if request['operation'] == 'stop':532 if request['operation'] == 'stop':
533 control.seek(0)533 vms.computer_cancel(control, identity)
534 control.truncate()
535 control.write(identity)
536 control.flush()
537 else:534 else:
538 active['stopping'] = control.read() == identity535 active['stopping'] = control.read() == identity
539 return {'running': True, **active, 'stopping': request['operation'] == 'stop' or active.get('stopping', False)}536 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):...@@ -176,7 +176,7 @@ def validate(action, payload):
176 for field in ("autostart", "start", "disks"):176 for field in ("autostart", "start", "disks"):
177 if field in payload and not isinstance(payload[field], bool):177 if field in payload and not isinstance(payload[field], bool):
178 raise ValueError(f"Choose whether to enable {field}.")178 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"}):
180 raise ValueError("Choose a supported VM action.")180 raise ValueError("Choose a supported VM action.")
181 if action == "clipboard" and (not isinstance(payload["text"], str) or len(payload["text"].encode()) > 262144):181 if action == "clipboard" and (not isinstance(payload["text"], str) or len(payload["text"].encode()) > 262144):
182 raise ValueError("Shorten the clipboard text, then send it again.")182 raise ValueError("Shorten the clipboard text, then send it again.")
...@@ -238,6 +238,13 @@ def computer_control(name):...@@ -238,6 +238,13 @@ def computer_control(name):
238 yield control238 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
241def computer_activity(name):248def computer_activity(name):
242 try:249 try:
243 with os.fdopen(open_regular(DISKS / name / "computer.lock")) as incoming:250 with os.fdopen(open_regular(DISKS / name / "computer.lock")) as incoming:
...@@ -309,7 +316,7 @@ def domains(*, computers=False):...@@ -309,7 +316,7 @@ def domains(*, computers=False):
309 "arch": root.find("./os/type").get("arch"), "state": state,316 "arch": root.find("./os/type").get("arch"), "state": state,
310 "aiOwned": ai is not None, "ownerOnly": ai is not None,317 "aiOwned": ai is not None, "ownerOnly": ai is not None,
311 "expiresAt": ai["expiresAt"] if ai else None,318 "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"],
313 }320 }
314 if computers:321 if computers:
315 result.append(entry)322 result.append(entry)
...@@ -1138,14 +1145,19 @@ def main():...@@ -1138,14 +1145,19 @@ def main():
1138 elif action == "act":1145 elif action == "act":
1139 name = payload["name"]1146 name = payload["name"]
1140 ensure_name(name)1147 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"])
1142 if payload["action"] == "start":1154 if payload["action"] == "start":
1143 root = ET.fromstring(virsh("dumpxml", name, "--inactive"))1155 root = ET.fromstring(virsh("dumpxml", name, "--inactive"))
1144 if root.find("./devices/interface/source[@network='default']") is not None:1156 if root.find("./devices/interface/source[@network='default']") is not None:
1145 ensure_network()1157 ensure_network()
1146 ai = import_module("vm-ai")1158 ai = import_module("vm-ai")
1147 ai.lease(name, ai.LIMITS["idle_seconds"])1159 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)
1149 elif action == "update":1161 elif action == "update":
1150 name = payload["name"]1162 name = payload["name"]
1151 ensure_name(name)1163 ensure_name(name)