Archive sessions, allow spaces in names, stop tripping the SSH rate limit
Connection refused: the dev box's UFW `limit` rule refuses the 6th new SSH connection from one address within 30 s. Every page view made two calls (list, repos) and every button one more, so stopping two sessions and refreshing hit it (kernel log: "UFW LIMIT BLOCK" from prod's IP). The web app now multiplexes all calls over one connection (ControlMaster=auto, ControlPersist=120), with the socket in its private temp dir. compose.yaml gets `init: true` so the backgrounded master is reaped; the app warns if it runs as PID 1. Spaces in names: `create` now takes a title (letters, digits, '-', single spaces, <= 48 chars). The slug used for the directory, branch, unit and tmux socket is derived from it; the title is shown on the page and passed to claude as --name. A plain slug still maps to itself. Archive: new remote verbs `archive` (stop + flag, keeps checkout and conversation) and `unarchive` (back to the list, still stopped). An archived session refuses `start`. The page lists archived sessions in a collapsible section. `list` re-reads state under the lock before saving a Remote Control URL so it can't undo a concurrent archive. Also: name/branch validation used re.match with `$`, which accepts a trailing newline; it now uses fullmatch. Tested end to end with a throwaway 127.0.0.1 key and the real container: 24 remote calls went over 1 TCP connection. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Rog8S9b5qKaw6nUicxXLkM
This commit is contained in:
parent
2569937fa7
commit
0738171f1e
7 changed files with 244 additions and 32 deletions
|
|
@ -56,6 +56,9 @@ UNIT = "claude-session@{}.service"
|
|||
KEY_MARKER = "sessions-manager" # comment that tags the one line we own in authorized_keys
|
||||
|
||||
NAME_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,31}$")
|
||||
# What the user typed as the name: letters, digits, single spaces and '-'. The
|
||||
# session's NAME (directory, branch, unit, tmux socket) is derived from it.
|
||||
TITLE_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9-]| (?! )){0,47}(?<! )$")
|
||||
BRANCH_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._/-]{0,99}$")
|
||||
RC_URL_RE = re.compile(r"https://claude\.ai/code/session_[A-Za-z0-9]+")
|
||||
TRUST_PROMPT = "Yes, I trust this folder"
|
||||
|
|
@ -63,7 +66,7 @@ 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", "health"}
|
||||
REMOTE_VERBS = {"list", "repos", "status", "create", "start", "stop", "archive", "unarchive", "health"}
|
||||
|
||||
DEFAULTS = {
|
||||
"workspace_root": "~/sessions",
|
||||
|
|
@ -90,19 +93,27 @@ def load_config(path: Path | None = None) -> dict:
|
|||
cfg["workspace_root"] = Path(os.path.expanduser(cfg["workspace_root"]))
|
||||
cfg["max_running"] = int(cfg["max_running"])
|
||||
for key, url in cfg["repos"].items():
|
||||
if not NAME_RE.match(key) or not isinstance(url, str):
|
||||
if not NAME_RE.fullmatch(key) or not isinstance(url, str):
|
||||
raise UserError(f"config: bad repo entry {key!r}")
|
||||
return cfg
|
||||
|
||||
|
||||
def validate_name(name: str) -> str:
|
||||
if not NAME_RE.match(name):
|
||||
if not NAME_RE.fullmatch(name):
|
||||
raise UserError("name must be 1-32 chars of a-z, 0-9 and '-', starting with a letter or digit")
|
||||
return name
|
||||
|
||||
|
||||
def name_from_title(title: str) -> tuple[str, str]:
|
||||
"""'Fix login bug' -> ('fix-login-bug', 'Fix login bug'). A plain NAME maps to itself."""
|
||||
if not TITLE_RE.fullmatch(title):
|
||||
raise UserError("name must be 1-48 chars of letters, digits, '-' and single spaces")
|
||||
name = re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-")[:32].rstrip("-")
|
||||
return validate_name(name), title
|
||||
|
||||
|
||||
def validate_branch(branch: str) -> str:
|
||||
if not BRANCH_RE.match(branch) or ".." in branch or branch.endswith((".lock", "/", ".")):
|
||||
if not BRANCH_RE.fullmatch(branch) or ".." in branch or branch.endswith((".lock", "/", ".")):
|
||||
raise UserError("invalid branch name")
|
||||
return branch
|
||||
|
||||
|
|
@ -230,7 +241,8 @@ def claude_args(state: dict, prefix: str, projects_dir: Path = CLAUDE_PROJECTS)
|
|||
approval. See README "Security model" for why that is acceptable here.
|
||||
"""
|
||||
rc_name = f"{prefix}-{state['name']}"
|
||||
args = ["claude", "--dangerously-skip-permissions", "--remote-control", rc_name, "--name", state["name"]]
|
||||
title = state.get("title") or state["name"]
|
||||
args = ["claude", "--dangerously-skip-permissions", "--remote-control", rc_name, "--name", title]
|
||||
if any(projects_dir.glob(f"*/{state['uuid']}.jsonl")):
|
||||
return args + ["--resume", state["uuid"]]
|
||||
return args + ["--session-id", state["uuid"]]
|
||||
|
|
@ -243,6 +255,8 @@ def session_view(state: dict, with_pane: bool = True) -> dict:
|
|||
u = unit_state(state["name"])
|
||||
view = {
|
||||
"name": state["name"],
|
||||
"title": state.get("title") or state["name"],
|
||||
"archived": bool(state.get("archived")),
|
||||
"repo": state["repo"],
|
||||
"branch": state["branch"],
|
||||
"created_at": state["created_at"],
|
||||
|
|
@ -256,8 +270,11 @@ def session_view(state: dict, with_pane: bool = True) -> dict:
|
|||
pane = capture_pane(state["name"])
|
||||
m = RC_URL_RE.search(pane)
|
||||
if m and m.group(0) != state.get("remote_control_url"):
|
||||
state["remote_control_url"] = view["remote_control_url"] = m.group(0)
|
||||
write_state(state)
|
||||
view["remote_control_url"] = m.group(0)
|
||||
with lock(): # re-read so this can't undo a concurrent archive/unarchive
|
||||
fresh = read_state(state["name"])
|
||||
fresh["remote_control_url"] = m.group(0)
|
||||
write_state(fresh)
|
||||
if TRUST_PROMPT in pane:
|
||||
view["needs_attention"] = "stuck on the folder-trust prompt; attach with tmux to accept"
|
||||
elif BYPASS_PROMPT in pane:
|
||||
|
|
@ -281,8 +298,8 @@ def cmd_status(cfg: dict, args: list[str]) -> dict:
|
|||
|
||||
|
||||
def cmd_create(cfg: dict, args: list[str]) -> dict:
|
||||
name, repo, *rest = _arity(args, 2, 3)
|
||||
validate_name(name)
|
||||
title, repo, *rest = _arity(args, 2, 3)
|
||||
name, title = name_from_title(title)
|
||||
if repo not in cfg["repos"]:
|
||||
raise UserError(f"repo {repo!r} is not in the allowlist")
|
||||
base = validate_branch(rest[0]) if rest else None
|
||||
|
|
@ -306,6 +323,7 @@ def cmd_create(cfg: dict, args: list[str]) -> dict:
|
|||
trust_workspace(workspace)
|
||||
state = {
|
||||
"name": name,
|
||||
"title": title,
|
||||
"repo": repo,
|
||||
"base": base,
|
||||
"branch": f"session/{name}",
|
||||
|
|
@ -320,8 +338,11 @@ def cmd_create(cfg: dict, args: list[str]) -> dict:
|
|||
|
||||
def cmd_start(cfg: dict, args: list[str]) -> dict:
|
||||
(name,) = _arity(args, 1, 1)
|
||||
state = read_state(validate_name(name))
|
||||
validate_name(name)
|
||||
with lock():
|
||||
state = read_state(name)
|
||||
if state.get("archived"):
|
||||
raise UserError(f"{name} is archived; unarchive it first")
|
||||
if unit_state(name)["active"] != "active" and running_count() >= cfg["max_running"]:
|
||||
raise UserError(f"limit reached: {cfg['max_running']} sessions already running")
|
||||
systemctl("enable", "--now", UNIT.format(name))
|
||||
|
|
@ -335,6 +356,27 @@ def cmd_stop(cfg: dict, args: list[str]) -> dict:
|
|||
return {"session": session_view(state, with_pane=False)}
|
||||
|
||||
|
||||
def cmd_archive(cfg: dict, args: list[str]) -> dict:
|
||||
"""Stop the session and move it to the archive. Keeps its checkout and conversation."""
|
||||
(name,) = _arity(args, 1, 1)
|
||||
with lock(): # so a concurrent `start` can't slip in between the stop and the flag
|
||||
state = read_state(validate_name(name))
|
||||
systemctl("disable", "--now", UNIT.format(name))
|
||||
state["archived"] = True
|
||||
write_state(state)
|
||||
return {"session": session_view(state, with_pane=False)}
|
||||
|
||||
|
||||
def cmd_unarchive(cfg: dict, args: list[str]) -> dict:
|
||||
"""Back to the normal list, still stopped."""
|
||||
(name,) = _arity(args, 1, 1)
|
||||
with lock():
|
||||
state = read_state(validate_name(name))
|
||||
state.pop("archived", None)
|
||||
write_state(state)
|
||||
return {"session": session_view(state, with_pane=False)}
|
||||
|
||||
|
||||
def cmd_health(cfg: dict, args: list[str]) -> dict:
|
||||
_arity(args, 0, 0)
|
||||
mem = {}
|
||||
|
|
@ -534,6 +576,8 @@ VERBS = {
|
|||
"create": cmd_create,
|
||||
"start": cmd_start,
|
||||
"stop": cmd_stop,
|
||||
"archive": cmd_archive,
|
||||
"unarchive": cmd_unarchive,
|
||||
"health": cmd_health,
|
||||
"delete": cmd_delete,
|
||||
"refresh-access": cmd_refresh_access,
|
||||
|
|
|
|||
|
|
@ -63,6 +63,88 @@ class Validation(unittest.TestCase):
|
|||
sc.cmd_repos({"repos": {}}, ["extra"])
|
||||
|
||||
|
||||
def test_trailing_newline_rejected(self):
|
||||
# re.match + "$" would accept "a\n"; sessions-ctl must use fullmatch.
|
||||
for f, v in ((sc.validate_name, "a\n"), (sc.validate_branch, "main\n"), (sc.name_from_title, "Fix\n")):
|
||||
with self.assertRaises(sc.UserError, msg=repr(v)):
|
||||
f(v)
|
||||
|
||||
def test_titles(self):
|
||||
self.assertEqual(sc.name_from_title("Fix login bug"), ("fix-login-bug", "Fix login bug"))
|
||||
self.assertEqual(sc.name_from_title("fix-login"), ("fix-login", "fix-login"))
|
||||
self.assertEqual(sc.name_from_title("a - b"), ("a-b", "a - b"))
|
||||
self.assertEqual(sc.name_from_title("X" * 48)[0], "x" * 32)
|
||||
for bad in ("", " a", "a ", "a b", "X" * 49, "a_b", "-a", "a\tb", "a;b", "$(id)", "---", "'a'"):
|
||||
with self.assertRaises(sc.UserError, msg=bad):
|
||||
sc.name_from_title(bad)
|
||||
|
||||
def test_title_survives_the_ssh_round_trip(self):
|
||||
import shlex
|
||||
self.assertEqual(sc.parse_remote(shlex.join(["create", "Fix login bug", "papure"])),
|
||||
["create", "Fix login bug", "papure"])
|
||||
|
||||
|
||||
class Archive(unittest.TestCase):
|
||||
"""archive/unarchive with systemd stubbed out and state in a temp dir."""
|
||||
|
||||
def setUp(self):
|
||||
from unittest import mock
|
||||
d = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(d.cleanup)
|
||||
self.calls = []
|
||||
self.active = set()
|
||||
|
||||
def systemctl(*args, check=True):
|
||||
self.calls.append(args)
|
||||
if args[:2] == ("disable", "--now"):
|
||||
self.active.discard(args[2])
|
||||
elif args[:2] == ("enable", "--now"):
|
||||
self.active.add(args[2])
|
||||
|
||||
def unit_state(name):
|
||||
on = sc.UNIT.format(name) in self.active
|
||||
return {"active": "active" if on else "inactive", "sub": "", "enabled": on, "restarts": 0}
|
||||
|
||||
for target, value in (("STATE_DIR", Path(d.name)), ("systemctl", systemctl), ("unit_state", unit_state)):
|
||||
p = mock.patch.object(sc, target, value)
|
||||
p.start()
|
||||
self.addCleanup(p.stop)
|
||||
sc.write_state({"name": "s1", "title": "S 1", "repo": "r", "branch": "session/s1",
|
||||
"workspace": "/nonexistent", "uuid": "u", "created_at": "2026-10-06T00:00:00+00:00"})
|
||||
self.active.add(sc.UNIT.format("s1"))
|
||||
self.cfg = {"max_running": 2}
|
||||
|
||||
def test_archive_stops_and_flags(self):
|
||||
view = sc.cmd_archive(self.cfg, ["s1"])["session"]
|
||||
self.assertIn(("disable", "--now", "claude-session@s1.service"), self.calls)
|
||||
self.assertTrue(view["archived"])
|
||||
self.assertEqual(view["state"], "inactive")
|
||||
self.assertEqual(view["title"], "S 1")
|
||||
self.assertTrue(sc.read_state("s1")["archived"])
|
||||
|
||||
def test_archived_cannot_start_until_unarchived(self):
|
||||
sc.cmd_archive(self.cfg, ["s1"])
|
||||
with self.assertRaises(sc.UserError):
|
||||
sc.cmd_start(self.cfg, ["s1"])
|
||||
view = sc.cmd_unarchive(self.cfg, ["s1"])["session"]
|
||||
self.assertFalse(view["archived"])
|
||||
self.assertEqual(view["state"], "inactive") # unarchive doesn't start it
|
||||
sc.cmd_start(self.cfg, ["s1"])
|
||||
self.assertEqual(sc.unit_state("s1")["active"], "active")
|
||||
|
||||
def test_validates_name(self):
|
||||
for verb in (sc.cmd_archive, sc.cmd_unarchive):
|
||||
for bad in ("../x", "$(id)", "nope"):
|
||||
with self.assertRaises(sc.UserError, msg=bad):
|
||||
verb(self.cfg, [bad])
|
||||
with self.assertRaises(sc.UserError):
|
||||
verb(self.cfg, ["s1", "extra"])
|
||||
|
||||
def test_remote_verbs(self):
|
||||
self.assertEqual(sc.parse_remote("archive s1"), ["archive", "s1"])
|
||||
self.assertEqual(sc.parse_remote("unarchive s1"), ["unarchive", "s1"])
|
||||
|
||||
|
||||
class AuthorizedKeys(unittest.TestCase):
|
||||
def test_line_shape(self):
|
||||
line = sc.authorized_line(KEY, ["37.205.10.63"], "/home/agent/.local/bin/sessions-ctl")
|
||||
|
|
@ -117,6 +199,11 @@ class ClaudeArgs(unittest.TestCase):
|
|||
self.assertEqual(resumed[-2:], ["--resume", state["uuid"]])
|
||||
self.assertIn("--dangerously-skip-permissions", resumed)
|
||||
|
||||
def test_title_is_the_claude_name(self):
|
||||
args = sc.claude_args({"name": "s1", "title": "Fix login bug", "uuid": "u"}, "dev-box", Path("/nonexistent"))
|
||||
self.assertEqual(args[args.index("--name") + 1], "Fix login bug")
|
||||
self.assertEqual(args[args.index("--remote-control") + 1], "dev-box-s1")
|
||||
|
||||
|
||||
class MainContract(unittest.TestCase):
|
||||
def test_remote_without_command_prints_json_error(self):
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue