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:
agent 2026-10-06 09:42:40 +00:00
parent 2569937fa7
commit 0738171f1e
7 changed files with 244 additions and 32 deletions

View file

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