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:
agent 2026-11-10 22:17:37 +00:00
parent 39997de1e8
commit 1b3172bd50
10 changed files with 1084 additions and 92 deletions

View file

@ -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,