Add repos from the page, answer actions in place, Expo-style redesign
Add repository: - New remote verb `add-repo KEY OWNER/NAME`. Off unless config.toml has [repo_add] (base_url + owners). Only listed owners; the dev box builds the URL itself, checks it with `git ls-remote` (bot access), then appends to [repos] under the lock. No URL crosses the SSH link. - `repos` also reports where adding is allowed, so the page shows the form only when it's on and rejects other hosts before calling SSH. - set_toml_string inserts after the section's last key, not after trailing blank lines / the next section's comments. Responsiveness: - web/static/app.js (progressive enhancement; every form still works without JS): forms go via fetch and get a JSON answer instead of POST-redirect-GET; buttons/cards show the change immediately; the list refreshes itself (15 s, 3 s while something is starting). - `repos` is cached for 5 min (refreshed on add-repo), so a page view is one SSH call instead of two. - `list` reads all unit states with one `systemctl show` instead of one per session: 676 -> 374 ms on the dev box with 21 sessions. - Static assets are content-hashed and cached immutably. Design: slate greys, hairline borders, black primary action, tinted status badges, monospace repo/branch, two columns on desktop, stacked on phones, light and dark. Docs: README security model, AGENTS.md (JS convention, add-repo invariant), config.example.toml. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MCUMXh8zZConC75Mptbeou
This commit is contained in:
parent
39997de1e8
commit
1b3172bd50
10 changed files with 1084 additions and 92 deletions
|
|
@ -17,6 +17,14 @@ remote_control_prefix = "dev-box"
|
|||
[repos]
|
||||
sessions = "ssh://git@git.reudy.net:14922/reudy-net/sessions.git"
|
||||
|
||||
# Optional: let the web page add repos to [repos] ("Add repository").
|
||||
# Off while this section is absent. Only repos of the owners listed here can
|
||||
# be added, the URL is always <base_url><owner>/<name>.git, and the bot
|
||||
# account must already be able to read the repo. Removing one is a manual edit.
|
||||
# [repo_add]
|
||||
# base_url = "ssh://git@git.reudy.net:14922/"
|
||||
# owners = ["reudy-net"]
|
||||
|
||||
[ssh_access]
|
||||
# prod's key may only connect from the address(es) this name resolves to.
|
||||
# Re-resolved hourly by sessions-access-refresh.timer.
|
||||
|
|
|
|||
|
|
@ -66,13 +66,18 @@ TRUST_PROMPT = "Yes, I trust this folder"
|
|||
# has "skipDangerousModePermissionPrompt": true.
|
||||
BYPASS_PROMPT = "running in Bypass Permissions mode"
|
||||
|
||||
REMOTE_VERBS = {"list", "repos", "status", "create", "start", "stop", "archive", "unarchive", "health"}
|
||||
# Forgejo owner (user/org) and repository names, for `add-repo`.
|
||||
OWNER_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,39}$")
|
||||
REPO_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$")
|
||||
|
||||
REMOTE_VERBS = {"list", "repos", "add-repo", "status", "create", "start", "stop", "archive", "unarchive", "health"}
|
||||
|
||||
DEFAULTS = {
|
||||
"workspace_root": "~/sessions",
|
||||
"max_running": 2,
|
||||
"remote_control_prefix": socket.gethostname(),
|
||||
"repos": {},
|
||||
"repo_add": {},
|
||||
"ssh_access": {},
|
||||
}
|
||||
|
||||
|
|
@ -178,9 +183,28 @@ def systemctl(*args: str, check: bool = True) -> subprocess.CompletedProcess:
|
|||
return r
|
||||
|
||||
|
||||
def unit_state(name: str) -> dict:
|
||||
r = systemctl("show", UNIT.format(name), "-p", "ActiveState", "-p", "SubState", "-p", "UnitFileState", "-p", "NRestarts", check=False)
|
||||
props = dict(line.split("=", 1) for line in r.stdout.splitlines() if "=" in line)
|
||||
def unit_states(names: list[str]) -> dict[str, dict]:
|
||||
"""State of several session units from one `systemctl show` call.
|
||||
|
||||
One call per unit costs ~25 ms each, which made `list` slow with a few
|
||||
dozen sessions. systemctl prints one blank-line-separated block per unit;
|
||||
blocks are matched back by their Id, not by position.
|
||||
"""
|
||||
out = {n: _unit_props({}) for n in names}
|
||||
if not names:
|
||||
return out
|
||||
r = systemctl("show", *(UNIT.format(n) for n in names),
|
||||
"-p", "Id", "-p", "ActiveState", "-p", "SubState", "-p", "UnitFileState", "-p", "NRestarts",
|
||||
check=False)
|
||||
by_unit = {UNIT.format(n): n for n in names}
|
||||
for block in r.stdout.split("\n\n"):
|
||||
props = dict(line.split("=", 1) for line in block.splitlines() if "=" in line)
|
||||
if props.get("Id") in by_unit:
|
||||
out[by_unit[props["Id"]]] = _unit_props(props)
|
||||
return out
|
||||
|
||||
|
||||
def _unit_props(props: dict) -> dict:
|
||||
return {
|
||||
"active": props.get("ActiveState", "unknown"),
|
||||
"sub": props.get("SubState", "unknown"),
|
||||
|
|
@ -189,6 +213,10 @@ def unit_state(name: str) -> dict:
|
|||
}
|
||||
|
||||
|
||||
def unit_state(name: str) -> dict:
|
||||
return unit_states([name])[name]
|
||||
|
||||
|
||||
def tmux_socket(name: str) -> str:
|
||||
return f"claude-{name}"
|
||||
|
||||
|
|
@ -251,8 +279,8 @@ def claude_args(state: dict, prefix: str, projects_dir: Path = CLAUDE_PROJECTS)
|
|||
# ---------------------------------------------------------------- verbs
|
||||
|
||||
|
||||
def session_view(state: dict, with_pane: bool = True) -> dict:
|
||||
u = unit_state(state["name"])
|
||||
def session_view(state: dict, with_pane: bool = True, u: dict | None = None) -> dict:
|
||||
u = u or unit_state(state["name"])
|
||||
view = {
|
||||
"name": state["name"],
|
||||
"title": state.get("title") or state["name"],
|
||||
|
|
@ -284,12 +312,79 @@ def session_view(state: dict, with_pane: bool = True) -> dict:
|
|||
|
||||
def cmd_list(cfg: dict, args: list[str]) -> dict:
|
||||
_arity(args, 0, 0)
|
||||
return {"sessions": [session_view(s) for s in all_states()], "max_running": cfg["max_running"]}
|
||||
states = all_states()
|
||||
units = unit_states([s["name"] for s in states])
|
||||
return {"sessions": [session_view(s, u=units[s["name"]]) for s in states], "max_running": cfg["max_running"]}
|
||||
|
||||
|
||||
def cmd_repos(cfg: dict, args: list[str]) -> dict:
|
||||
"""The allowlist keys, plus where `add-repo` may add from (absent when it's off)."""
|
||||
_arity(args, 0, 0)
|
||||
return {"repos": sorted(cfg["repos"])}
|
||||
out = {"repos": sorted(cfg["repos"])}
|
||||
add = repo_add_settings(cfg)
|
||||
if add:
|
||||
out["add"] = add
|
||||
return out
|
||||
|
||||
|
||||
def repo_add_settings(cfg: dict) -> dict | None:
|
||||
"""[repo_add] from the config, or None if adding repos remotely is off.
|
||||
|
||||
Off unless both base_url and at least one owner are set: the default is
|
||||
that only the admin, editing config.toml, extends the allowlist.
|
||||
"""
|
||||
ra = cfg.get("repo_add") or {}
|
||||
base, owners = ra.get("base_url"), ra.get("owners")
|
||||
if not base or not owners:
|
||||
return None
|
||||
if not isinstance(base, str) or not re.fullmatch(r"(ssh|https)://[A-Za-z0-9@.:-]+/", base):
|
||||
raise UserError('config: repo_add.base_url must look like "ssh://git@host:port/"')
|
||||
if not isinstance(owners, list) or not all(isinstance(o, str) and OWNER_RE.fullmatch(o) for o in owners):
|
||||
raise UserError("config: repo_add.owners must be a list of Forgejo user/org names")
|
||||
return {"base_url": base, "owners": sorted(owners)}
|
||||
|
||||
|
||||
def cmd_add_repo(cfg: dict, args: list[str]) -> dict:
|
||||
"""add-repo KEY OWNER/REPO — add <base_url>OWNER/REPO.git to the allowlist.
|
||||
|
||||
The URL is built here from config; only the owner/repo path crosses the
|
||||
SSH link, and only owners listed in [repo_add] are accepted. The repo must
|
||||
be reachable with this box's git credentials (the bot account), which is
|
||||
checked before anything is written.
|
||||
"""
|
||||
key, path = _arity(args, 2, 2)
|
||||
add = repo_add_settings(cfg)
|
||||
if not add:
|
||||
raise UserError("adding repos from the web is turned off ([repo_add] in config.toml)")
|
||||
validate_name(key)
|
||||
owner, _, repo = path.partition("/")
|
||||
repo = repo.removesuffix(".git")
|
||||
if not OWNER_RE.fullmatch(owner) or not REPO_RE.fullmatch(repo) or ".." in repo:
|
||||
raise UserError("repository must be OWNER/NAME")
|
||||
if owner not in add["owners"]:
|
||||
raise UserError(f"owner {owner!r} is not allowed; allowed: {', '.join(add['owners'])}")
|
||||
url = f"{add['base_url']}{owner}/{repo}.git"
|
||||
|
||||
if key in cfg["repos"]:
|
||||
raise UserError(f"a repo named {key!r} already exists")
|
||||
dupe = [k for k, u in cfg["repos"].items() if u.lower() == url.lower()]
|
||||
if dupe:
|
||||
raise UserError(f"already in the allowlist as {dupe[0]!r}")
|
||||
env = {**os.environ, "GIT_TERMINAL_PROMPT": "0"}
|
||||
try:
|
||||
r = subprocess.run(["git", "ls-remote", "--", url, "HEAD"], capture_output=True, text=True,
|
||||
timeout=30, env=env)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise UserError("the git host did not answer in time")
|
||||
if r.returncode != 0:
|
||||
raise UserError(f"can't reach {owner}/{repo}: check the name, and that the bot account has access")
|
||||
|
||||
with lock(): # re-read: another add may have landed since load_config
|
||||
text = CONFIG_PATH.read_text() if CONFIG_PATH.exists() else ""
|
||||
if key in load_config()["repos"]:
|
||||
raise UserError(f"a repo named {key!r} already exists")
|
||||
atomic_write(CONFIG_PATH, set_toml_string(text, "repos", key, url), 0o600)
|
||||
return {"repo": key, "repos": sorted(load_config()["repos"])}
|
||||
|
||||
|
||||
def cmd_status(cfg: dict, args: list[str]) -> dict:
|
||||
|
|
@ -498,27 +593,32 @@ def cmd_keygen(cfg: dict, args: list[str]) -> dict:
|
|||
|
||||
|
||||
def set_toml_string(text: str, section: str, key: str, value: str) -> str:
|
||||
"""Set `key = "value"` inside [section] of a simple TOML file, keeping the rest."""
|
||||
"""Set `key = "value"` inside [section] of a simple TOML file, keeping the rest.
|
||||
|
||||
An existing key is replaced in place. A new key goes right after the
|
||||
section's last key line, so blank lines and the next section's leading
|
||||
comments stay where they were.
|
||||
"""
|
||||
if '"' in value or "\\" in value or "\n" in value:
|
||||
raise UserError("refusing to write an unusual value into config.toml")
|
||||
lines, out, in_section, done = text.splitlines(), [], False, False
|
||||
for line in lines:
|
||||
new = f'{key} = "{value}"'
|
||||
out, in_section, insert_at = [], False, None
|
||||
for line in text.splitlines():
|
||||
stripped = line.strip()
|
||||
if stripped.startswith("["):
|
||||
if in_section and not done:
|
||||
out.append(f'{key} = "{value}"')
|
||||
done = True
|
||||
in_section = stripped == f"[{section}]"
|
||||
if in_section:
|
||||
insert_at = len(out) + 1
|
||||
elif in_section and re.match(rf"^{re.escape(key)}\s*=", stripped):
|
||||
if not done:
|
||||
out.append(f'{key} = "{value}"')
|
||||
done = True
|
||||
continue
|
||||
out.append(new)
|
||||
return "\n".join(out + text.splitlines()[len(out):]) + "\n"
|
||||
elif in_section and stripped and not stripped.startswith("#"):
|
||||
insert_at = len(out) + 1
|
||||
out.append(line)
|
||||
if not done:
|
||||
if not in_section:
|
||||
out += ["", f"[{section}]"]
|
||||
out.append(f'{key} = "{value}"')
|
||||
if insert_at is None:
|
||||
out += ["", f"[{section}]", new] if out else [f"[{section}]", new]
|
||||
else:
|
||||
out.insert(insert_at, new)
|
||||
return "\n".join(out) + "\n"
|
||||
|
||||
|
||||
|
|
@ -572,6 +672,7 @@ def _run(cmd: list[str], timeout: int = 60) -> subprocess.CompletedProcess:
|
|||
VERBS = {
|
||||
"list": cmd_list,
|
||||
"repos": cmd_repos,
|
||||
"add-repo": cmd_add_repo,
|
||||
"status": cmd_status,
|
||||
"create": cmd_create,
|
||||
"start": cmd_start,
|
||||
|
|
|
|||
|
|
@ -243,6 +243,120 @@ class TomlEdit(unittest.TestCase):
|
|||
sc.set_toml_string("", "s", "k", 'a" \nx = "y')
|
||||
|
||||
|
||||
def test_new_key_goes_after_last_key_not_into_next_sections_comments(self):
|
||||
text = '[repos]\na = "x"\n\n# about ssh\n[ssh_access]\nk = "v"\n'
|
||||
out = sc.set_toml_string(text, "repos", "b", "y")
|
||||
self.assertEqual(out, '[repos]\na = "x"\nb = "y"\n\n# about ssh\n[ssh_access]\nk = "v"\n')
|
||||
self.assertEqual(sc.set_toml_string("[repos]\n# none yet\n", "repos", "b", "y"), '[repos]\nb = "y"\n# none yet\n')
|
||||
|
||||
|
||||
class UnitStates(unittest.TestCase):
|
||||
def test_one_call_matched_by_id(self):
|
||||
from unittest import mock
|
||||
out = ("Id=claude-session@b.service\nActiveState=active\nSubState=running\nUnitFileState=enabled\nNRestarts=2\n\n"
|
||||
"Id=claude-session@a.service\nActiveState=inactive\nSubState=dead\nUnitFileState=disabled\nNRestarts=0\n")
|
||||
calls = []
|
||||
|
||||
def systemctl(*args, check=True):
|
||||
calls.append(args)
|
||||
return mock.Mock(stdout=out)
|
||||
|
||||
with mock.patch.object(sc, "systemctl", systemctl):
|
||||
states = sc.unit_states(["a", "b", "c"])
|
||||
self.assertEqual(len(calls), 1)
|
||||
self.assertEqual(states["a"]["active"], "inactive")
|
||||
self.assertEqual(states["b"], {"active": "active", "sub": "running", "enabled": True, "restarts": 2})
|
||||
self.assertEqual(states["c"]["active"], "unknown") # missing block: unknown, not someone else's state
|
||||
with mock.patch.object(sc, "systemctl", systemctl):
|
||||
self.assertEqual(sc.unit_states([]), {})
|
||||
self.assertEqual(len(calls), 1)
|
||||
|
||||
|
||||
class AddRepo(unittest.TestCase):
|
||||
"""add-repo with git and the config file in a temp dir."""
|
||||
|
||||
BASE = "ssh://git@git.example:14922/"
|
||||
|
||||
def setUp(self):
|
||||
from unittest import mock
|
||||
d = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(d.cleanup)
|
||||
self.cfg_path = Path(d.name) / "config.toml"
|
||||
self.cfg_path.write_text(
|
||||
'max_running = 2\n\n[repos]\nold = "ssh://git@git.example:14922/team/Old.git"\n\n'
|
||||
f'[repo_add]\nbase_url = "{self.BASE}"\nowners = ["team"]\n\n[ssh_access]\nallow_from_host = "x"\n')
|
||||
self.cfg_path.chmod(0o600)
|
||||
self.git = []
|
||||
self.git_rc = 0
|
||||
|
||||
def run(cmd, **kw):
|
||||
self.git.append(cmd)
|
||||
return mock.Mock(returncode=self.git_rc, stdout="", stderr="")
|
||||
|
||||
for target, value in (("CONFIG_PATH", self.cfg_path), ("STATE_DIR", Path(d.name) / "state")):
|
||||
p = mock.patch.object(sc, target, value)
|
||||
p.start()
|
||||
self.addCleanup(p.stop)
|
||||
p = mock.patch.object(sc.subprocess, "run", run)
|
||||
p.start()
|
||||
self.addCleanup(p.stop)
|
||||
|
||||
def add(self, *args):
|
||||
return sc.cmd_add_repo(sc.load_config(self.cfg_path), list(args))
|
||||
|
||||
def test_adds_and_keeps_the_rest(self):
|
||||
import os, stat
|
||||
before = self.cfg_path.read_text()
|
||||
out = self.add("elorasmus", "team/elorasmus")
|
||||
self.assertEqual(out["repos"], ["elorasmus", "old"])
|
||||
self.assertEqual(self.git, [["git", "ls-remote", "--", f"{self.BASE}team/elorasmus.git", "HEAD"]])
|
||||
after = self.cfg_path.read_text()
|
||||
self.assertEqual(after, before.replace('Old.git"\n', f'Old.git"\nelorasmus = "{self.BASE}team/elorasmus.git"\n'))
|
||||
self.assertEqual(stat.S_IMODE(os.stat(self.cfg_path).st_mode), 0o600)
|
||||
self.assertEqual(sc.cmd_repos(sc.load_config(self.cfg_path), [])["add"],
|
||||
{"base_url": self.BASE, "owners": ["team"]})
|
||||
|
||||
def test_strips_dot_git(self):
|
||||
self.add("x", "team/x.git")
|
||||
self.assertIn(f'x = "{self.BASE}team/x.git"', self.cfg_path.read_text())
|
||||
|
||||
def test_rejects_before_touching_git_or_config(self):
|
||||
before = self.cfg_path.read_text()
|
||||
bad = [
|
||||
("Bad", "team/x"), ("x", "other/x"), ("x", "team"), ("x", "team/"), ("x", "team/a/b"),
|
||||
("x", "team/../x"), ("x", "team/-x"), ("x", "team/x y"), ("x", "team/x\n"), ("x", "../team/x"),
|
||||
("old", "team/new"), # key taken
|
||||
("again", "team/old"), # URL already listed (case-insensitive)
|
||||
]
|
||||
for args in bad:
|
||||
with self.assertRaises(sc.UserError, msg=args):
|
||||
self.add(*args)
|
||||
with self.assertRaises(sc.UserError):
|
||||
self.add("x")
|
||||
self.assertEqual(self.git, [])
|
||||
self.assertEqual(self.cfg_path.read_text(), before)
|
||||
|
||||
def test_unreachable_repo_is_not_added(self):
|
||||
before = self.cfg_path.read_text()
|
||||
self.git_rc = 128
|
||||
with self.assertRaises(sc.UserError):
|
||||
self.add("x", "team/x")
|
||||
self.assertEqual(self.cfg_path.read_text(), before)
|
||||
|
||||
def test_off_without_repo_add_section(self):
|
||||
cfg = sc.load_config(self.cfg_path)
|
||||
cfg["repo_add"] = {}
|
||||
with self.assertRaises(sc.UserError):
|
||||
sc.cmd_add_repo(cfg, ["x", "team/x"])
|
||||
self.assertNotIn("add", sc.cmd_repos(cfg, []))
|
||||
cfg["repo_add"] = {"base_url": "file:///tmp/", "owners": ["team"]}
|
||||
with self.assertRaises(sc.UserError):
|
||||
sc.cmd_add_repo(cfg, ["x", "team/x"])
|
||||
|
||||
def test_is_a_remote_verb(self):
|
||||
self.assertEqual(sc.parse_remote("add-repo x team/x"), ["add-repo", "x", "team/x"])
|
||||
|
||||
|
||||
class Keygen(unittest.TestCase):
|
||||
def test_keygen_end_to_end_in_temp_dirs(self):
|
||||
import base64, os
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue