The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
os: route shortcuts to the supervised foreground terminal (#934)
Deef595178d7529
diff --git a/os/root/usr/lib/harness-os/open-wifi b/os/root/usr/lib/harness-os/open-wifiindex 84cb8e27f..2cf0631f7 100644--- a/os/root/usr/lib/harness-os/open-wifi+++ b/os/root/usr/lib/harness-os/open-wifi@@ -1,3 +1,3 @@#!/bin/shset -eu-exec hn os-action wifi+exec /usr/lib/harness-os/screen-action wifidiff --git a/os/root/usr/lib/harness-os/screen-action b/os/root/usr/lib/harness-os/screen-actionnew file mode 100755index 000000000..99e23f952--- /dev/null+++ b/os/root/usr/lib/harness-os/screen-action@@ -0,0 +1,97 @@+#!/usr/bin/python3+"""Send an OS shortcut to the hn client inside the supervised screen."""+import argparse+import os+from pathlib import Path+import re+import socket+import struct+import subprocess++PROC = Path('/proc')+ACTIONS = ('terminal', 'new', 'connect', 'wifi', 'updates')+++def process(pid):+ try:+ path = PROC / str(pid)+ fields = (path / 'stat').read_text().rsplit(')', 1)[1].split()+ if path.stat().st_uid != os.getuid() or fields[0] in ('Z', 'X'):+ return None+ return dict(parent=int(fields[1]), group=int(fields[2]), tty=int(fields[4]),+ foreground=int(fields[5]), start=fields[19])+ except (OSError, IndexError, ValueError):+ return None+++def peer_pid(path):+ # A stale pathname or the retained headless server must not own an action+ # meant for the visible screen. Linux reports who actually listens here.+ try:+ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection:+ connection.settimeout(.2)+ connection.connect(str(path))+ pid, uid, _ = struct.unpack('3i', connection.getsockopt(+ socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize('3i')))+ return pid if uid == os.getuid() else None+ except OSError:+ return None+++def screen_socket():+ main = int(subprocess.check_output([+ 'systemctl', '--user', 'show', 'hn-screen.service', '--property=MainPID', '--value',+ ], text=True, timeout=3).strip())+ owner = process(main) if main > 0 else None+ if not owner:+ raise RuntimeError('Harness has no active screen.')+ children = (PROC / str(main) / 'task' / str(main) / 'children').read_text().split()+ matches = []+ for value in children:+ pid = int(value)+ client = process(pid)+ if not client or client['parent'] != main or not client['tty'] or client['group'] != client['foreground']:+ continue+ try:+ env = dict(part.split('=', 1) for part in (PROC / value / 'environ').read_text().split('\0') if '=' in part)+ except OSError:+ continue+ if env.get('HARNESS_OS') != '1':+ continue+ name = env.get('HN_SOCKET_NAME') or 'default'+ base = Path(env.get('HN_TMPDIR') or env.get('TMUX_TMPDIR') or '/tmp')+ if not base.is_absolute() or not re.fullmatch(r'[A-Za-z0-9_.-]+', name):+ continue+ directory = base / ('hn-' + str(os.getuid()))+ for path in (directory / f'{name}@{pid}.sock', directory / f'{name}.sock'):+ if peer_pid(path) == pid and process(pid) == client:+ matches.append(str(path))+ break+ if len(matches) != 1 or process(main) != owner:+ raise RuntimeError('The Harness screen is reconnecting. Try the shortcut again.')+ return matches[0]+++def dispatch(action):+ if action not in ACTIONS:+ raise ValueError('Unknown screen action.')+ target = screen_socket()+ env = dict(os.environ, HN_SOCKET=target)+ if action == 'updates':+ command = ['/usr/lib/harness-os/open-updates']+ else:+ command = ['/usr/bin/hn', '-S', target, 'os-action', action]+ os.execve(command[0], command, env)+++if __name__ == '__main__':+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('action', choices=(*ACTIONS, 'socket'))+ args = parser.parse_args()+ try:+ if args.action == 'socket':+ print(screen_socket())+ else:+ dispatch(args.action)+ except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as error:+ raise SystemExit('Harness: ' + str(error))diff --git a/os/root/usr/share/harness-os/labwc/rc.xml b/os/root/usr/share/harness-os/labwc/rc.xmlindex 72b444015..4f99620ed 100644--- a/os/root/usr/share/harness-os/labwc/rc.xml+++ b/os/root/usr/share/harness-os/labwc/rc.xml@@ -24,7 +24,7 @@<keybind key="A-Tab"><action name="NextWindowImmediate" /></keybind><keybind key="W-l"><action name="Execute" command="/usr/lib/harness-os/lock" /></keybind><keybind key="W-u">- <action name="Execute" command="/usr/lib/harness-os/open-updates" />+ <action name="Execute" command="/usr/lib/harness-os/screen-action updates" /><action name="ForEach"><query identifier="hn" /><then><action name="Raise" /><action name="Focus" /></then></action></keybind><keybind key="W-i">@@ -36,11 +36,11 @@<action name="ForEach"><query identifier="hn" /><then><action name="Raise" /><action name="Focus" /></then></action></keybind><keybind key="W-n">- <action name="Execute" command="hn os-action new" />+ <action name="Execute" command="/usr/lib/harness-os/screen-action new" /><action name="ForEach"><query identifier="hn" /><then><action name="Raise" /><action name="Focus" /></then></action></keybind><keybind key="W-t">- <action name="Execute" command="hn os-action terminal" />+ <action name="Execute" command="/usr/lib/harness-os/screen-action terminal" /><action name="ForEach"><query identifier="hn" /><then><action name="Raise" /><action name="Focus" /></then></action></keybind><!-- Super+e is run-or-raise for the file manager window, then back to hn, as Super+b is. -->@@ -56,7 +56,7 @@<!-- Super+o asks for a folder or a file in a new file manager window. --><keybind key="W-o"><action name="Execute" command="/usr/lib/harness-os/files --open" /></keybind><keybind key="W-m">- <action name="Execute" command="hn os-action connect" />+ <action name="Execute" command="/usr/lib/harness-os/screen-action connect" /><action name="ForEach"><query identifier="hn" /><then><action name="Raise" /><action name="Focus" /></then></action></keybind><!-- Screenshots go to ~/Pictures/Screenshots and the clipboard. Super+p/r stand in for Printdiff --git a/os/tests/arm_update_vm.py b/os/tests/arm_update_vm.pyindex 794d31d9b..1e09e3b59 100644--- a/os/tests/arm_update_vm.py+++ b/os/tests/arm_update_vm.py@@ -104,6 +104,7 @@ def prepare_updates(machine):files = {'os/live_update.py': '/usr/lib/harness-os/live_update.py','os/root/usr/lib/harness-os/open-updates': '/usr/lib/harness-os/open-updates',+ 'os/root/usr/lib/harness-os/screen-action': '/usr/lib/harness-os/screen-action','os/root/usr/lib/systemd/user/harness-update.service': '/usr/lib/systemd/user/harness-update.service','os/root/usr/lib/systemd/user/harness-update.timer': '/usr/lib/systemd/user/harness-update.timer',}diff --git a/os/tests/test_fedora_package.py b/os/tests/test_fedora_package.pyindex 7ae2582d8..e6e338db2 100644--- a/os/tests/test_fedora_package.py+++ b/os/tests/test_fedora_package.py@@ -67,6 +67,8 @@ class FedoraPayload(unittest.TestCase):self.assertNotIn('usr/lib/harness-os/' + name, result['files'])self.assertNotIn('usr/share/harness-os/lock.json', result['files'])self.assertIn('usr/lib/harness-os/live_update.py', result['files'])+ self.assertIn('usr/lib/harness-os/screen-action', result['files'])+ self.assertEqual((destination / 'usr/lib/harness-os/screen-action').stat().st_mode & 0o777, 0o755)self.assertIn('usr/lib/systemd/user/harness-update.timer', result['files'])self.assertEqual(result['symlinks']['usr/bin/harness-session'], '../lib/harness-os/session')self.assertEqual(result['symlinks']['usr/bin/harness-session-setup'], '../lib/harness-os/fedora_session.py')diff --git a/os/tests/test_screen_action.py b/os/tests/test_screen_action.pynew file mode 100644index 000000000..58cab8b69--- /dev/null+++ b/os/tests/test_screen_action.py@@ -0,0 +1,152 @@+import importlib.machinery+import importlib.util+import os+from pathlib import Path+import socket+import tempfile+import unittest+from unittest.mock import patch+import xml.etree.ElementTree as ET++ROOT = Path(__file__).resolve().parents[1] / 'root'+SOURCE = ROOT / 'usr/lib/harness-os/screen-action'+loader = importlib.machinery.SourceFileLoader('screen_action', str(SOURCE))+spec = importlib.util.spec_from_loader(loader.name, loader)+screen = importlib.util.module_from_spec(spec)+loader.exec_module(screen)+++class ScreenRouting(unittest.TestCase):+ def setUp(self):+ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ self.root = Path(temporary.name)+ self.proc = self.root / 'proc'+ self.base = self.root / 'sockets'+ self.peers = {}+ for value in (patch.object(screen, 'PROC', self.proc),+ patch.object(screen.subprocess, 'check_output', return_value='10\n'),+ patch.object(screen, 'peer_pid', side_effect=lambda path: self.peers.get(str(path))),+ patch.dict(os.environ, {}, clear=True), patch.object(screen.os, 'execve')):+ value.start()+ self.addCleanup(value.stop)+ self.make_process(10, 1, tty=0)+ self.make_process(20, 10)+ self.children(20)+ self.primary = self.endpoint('default.sock')+ self.attached = self.endpoint('[email protected]')++ def endpoint(self, name):+ return str(self.base / ('hn-' + str(os.getuid())) / name)++ def make_process(self, pid, parent, *, tty=34816, foreground=None, start=100, state='S', env=None):+ path = self.proc / str(pid)+ path.mkdir(parents=True, exist_ok=True)+ fields = [state, str(parent), str(pid), '10', str(tty), str(pid if foreground is None else foreground)]+ (path / 'stat').write_text(f'{pid} (test (process)) ' + ' '.join(fields + ['0'] * 13 + [str(start)]))+ environment = {'HARNESS_OS': '1', 'HN_TMPDIR': str(self.base)} if env is None else env+ (path / 'environ').write_text('\0'.join(k+'='+v for k,v in environment.items())+'\0')++ def children(self, *pids):+ task = self.proc / '10/task/10'+ task.mkdir(parents=True, exist_ok=True)+ (task / 'children').write_text(' '.join(str(pid) for pid in pids))++ def test_first_screen_uses_its_primary_socket(self):+ self.peers[self.primary] = 20+ self.assertEqual(screen.screen_socket(), self.primary)++ def test_retained_headless_primary_cannot_take_the_visible_shortcut(self):+ self.peers[self.primary] = 30+ self.peers[self.attached] = 20+ self.make_process(30, 1, tty=0)+ self.assertEqual(screen.screen_socket(), self.attached)++ def test_inherited_shell_socket_does_not_redirect_a_compositor_action(self):+ self.peers[self.primary] = 30+ self.peers[self.attached] = 20+ with patch.dict(os.environ, HN_SOCKET=self.primary, TMUX=self.primary+',30,0'):+ screen.dispatch('terminal')+ command, arguments, environment = screen.os.execve.call_args.args+ self.assertEqual(arguments, ['/usr/bin/hn', '-S', self.attached, 'os-action', 'terminal'])+ self.assertEqual(command, arguments[0])+ self.assertEqual(environment['HN_SOCKET'], self.attached)++ def test_update_opener_inherits_the_exact_visible_socket(self):+ self.peers[self.attached] = 20+ screen.dispatch('updates')+ command, arguments, environment = screen.os.execve.call_args.args+ self.assertEqual(arguments, ['/usr/lib/harness-os/open-updates'])+ self.assertEqual(command, arguments[0])+ self.assertEqual(environment['HN_SOCKET'], self.attached)++ def test_no_fallback_to_a_headless_or_unrelated_client(self):+ self.peers[self.primary] = 30+ self.peers[self.attached] = 30 # stale path now owned by a different process+ with self.assertRaisesRegex(RuntimeError, 'reconnecting'):+ screen.dispatch('terminal')+ screen.os.execve.assert_not_called()++ def test_background_dead_or_non_os_children_are_not_screens(self):+ self.peers[self.attached] = 20+ for options in ({'tty':0}, {'foreground':30}, {'state':'Z'}, {'env':{}}, {'parent':30}):+ with self.subTest(options=options):+ arguments = dict(parent=10)+ arguments.update(options)+ self.make_process(20, **arguments)+ with self.assertRaises(RuntimeError):+ screen.screen_socket()++ def test_multiple_eligible_children_are_ambiguous(self):+ self.make_process(21, 10)+ self.children(20,21)+ self.peers[self.attached] = 20+ self.peers[self.endpoint('[email protected]')] = 21+ with self.assertRaises(RuntimeError):+ screen.screen_socket()++ def test_screen_restart_during_lookup_does_not_dispatch(self):+ self.peers[self.attached] = 20+ original = screen.peer_pid+ def restart(path):+ self.make_process(10, 1, tty=0, start=200)+ return original(path)+ with patch.object(screen, 'peer_pid', side_effect=restart):+ with self.assertRaises(RuntimeError):+ screen.dispatch('wifi')+ screen.os.execve.assert_not_called()++ def test_stopped_service_and_unknown_action_do_not_run_commands(self):+ with patch.object(screen.subprocess,'check_output',return_value='0\n'):+ with self.assertRaises(RuntimeError):+ screen.dispatch('new')+ with self.assertRaises(ValueError):+ screen.dispatch('arbitrary-command')+ screen.os.execve.assert_not_called()++ def test_named_socket_uses_the_screen_process_environment(self):+ self.make_process(20, 10, env={'HARNESS_OS':'1', 'HN_SOCKET_NAME':'my-screen',+ 'TMUX_TMPDIR':str(self.base)})+ named = self.endpoint('[email protected]')+ self.peers[named] = 20+ self.assertEqual(screen.screen_socket(), named)+++class ShortcutBindings(unittest.TestCase):+ def test_compositor_actions_share_the_foreground_router(self):+ tree = ET.parse(ROOT / 'usr/share/harness-os/labwc/rc.xml')+ commands = {key.get('key'): [a.get('command') for a in key.findall('.//action') if a.get('name')=='Execute']+ for key in tree.findall('.//keybind')}+ for key, action in [('W-n','new'),('W-t','terminal'),('W-m','connect'),('W-u','updates')]:+ self.assertEqual(commands[key], ['/usr/lib/harness-os/screen-action '+action])+ self.assertEqual(commands['W-w'], ['/usr/lib/harness-os/open-wifi'])+ self.assertIn('exec /usr/lib/harness-os/screen-action wifi', (ROOT / 'usr/lib/harness-os/open-wifi').read_text())++ @unittest.skipUnless(hasattr(socket, 'SO_PEERCRED'), 'Linux peer credentials')+ def test_linux_peer_identity_and_missing_socket(self):+ with tempfile.TemporaryDirectory(prefix='hn-socket-', dir='/tmp') as folder:+ path=Path(folder)/'owned.sock'+ with socket.socket(socket.AF_UNIX,socket.SOCK_STREAM) as listener:+ listener.bind(str(path));listener.listen()+ self.assertEqual(screen.peer_pid(path), os.getpid())+ self.assertIsNone(screen.peer_pid(path))diff --git a/os/tests/update_intent_vm.py b/os/tests/update_intent_vm.pyindex 7530dc78b..38b57cbdd 100644--- a/os/tests/update_intent_vm.py+++ b/os/tests/update_intent_vm.py@@ -37,6 +37,7 @@ BUSY = '{"harness_update_worker":1,"status":"busy"}\n'OWNERSHIP_SOURCE = '0de712afa23cb10bf9ab096dec933a9828767fe3'INPUTS = ['os/live_update.py', 'os/root/usr/bin/harness', 'os/root/usr/lib/harness-os/open-updates',+ 'os/root/usr/lib/harness-os/screen-action','os/root/usr/lib/systemd/user/harness-update.service','os/root/usr/lib/systemd/user/harness-update.timer', 'os/root/usr/share/harness-os/labwc/rc.xml','os/tests/update_intent_vm.py', 'os/tests/update_intent_guest.py', 'os/tests/update_intent_observer.py',diff --git a/os/tools/fedora_payload.py b/os/tools/fedora_payload.pyindex 9b83a3804..8e388a2e3 100644--- a/os/tools/fedora_payload.py+++ b/os/tools/fedora_payload.py@@ -53,7 +53,7 @@ def stage(source, runtime, destination, commit, runtime_commit, agent=None):'usr/share/harness-os/lock/layout.ui', 'usr/share/harness-os/lock/style.css',*['usr/share/harness-os/labwc/' + name for name in ['autostart', 'shutdown', 'rc.xml']],*['usr/lib/harness-os/' + name for name in- ['session', 'session-settings.py', 'runtime-path', 'wait-runtime', 'virtio-2d', 'open-wifi', 'open-updates', 'screenshot', 'lock', 'files']],+ ['session', 'session-settings.py', 'runtime-path', 'wait-runtime', 'virtio-2d', 'open-wifi', 'open-updates', 'screen-action', 'screenshot', 'lock', 'files']],*['usr/lib/systemd/user/' + name for name in['hn-screen.service', 'harness-daemon.service', 'harness-idle.service','harness-update.service', 'harness-update.timer']],