Files
Gabriel VidalandClaude Opus 5.5 dc3252ba84 feat(computers): pick which Claude a guest's terminal runs, and sync its sessions to the app
On a guest's own computer, `claude` in a terminal now asks (arrow-key box,
remembered per folder tree): ai-agent Claude — the hub's proxy pair, synced —
or the machine's own login, synced later on demand.

- worker/claude_launcher.py + the installer's shell hook (bash/zsh/fish):
  the picker, --ai-agent/--local/--choose, no question for -p / pipes /
  known --resume, --session-id up front so the start line links the app;
  ai-agent-worker sync|unsync|claude.
- worker/claude-mod: a Claude Code mod — status line (synced · budget left),
  a toast with the link, /ai-agent [sync|unsync], and Continue on ai-agent
  Claude when the guest's own plan runs out (the launcher resumes it there).
- hub: workers/terminal.py claims a session on its first proxied call
  (X-Claude-Code-Session-Id) or when /feed lists it as synced; refused for an
  id known elsewhere; Stop syncing keeps the copy, takes no more. The probe
  pushes the picker's figures (budget left, paused) to the computer.
- portal: My computers → Terminal sessions (Sync / Stop syncing, Ask at
  start); the Terminal badge; continuing a local one confirms the move to the
  host's Claude and sends on a fresh context.

Form choose-claude-at-terminal-start-sync-to-the-app_n789ku.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 18:47:08 +01:00

136 lines
5.4 KiB
Python

"""terminal.py: the synced sessions, the launcher's remembered choice, and the
portal's /terminal routes."""
import json
import os
import pytest
from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
import terminal
H = {"Authorization": "Bearer t"}
SID = "0b7c8f6e-1d2a-4c3b-9e8f-0123456789ab"
SID2 = "1b7c8f6e-1d2a-4c3b-9e8f-0123456789ab"
def _auth(h):
if h != "Bearer t":
raise HTTPException(401, "unauthorized")
@pytest.fixture(autouse=True)
def state(monkeypatch, tmp_path):
monkeypatch.setenv("WORKER_STATE_DIR", str(tmp_path / "state"))
return tmp_path / "state"
def _transcript(root, sid, rows, proj="-home-akira-code"):
p = root / proj / f"{sid}.jsonl"
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text("".join(json.dumps(r) + "\n" for r in rows))
return p
def test_sync_and_unsync(state):
assert terminal.sync(SID.upper(), cwd="/home/akira")
assert terminal.sync("../etc/passwd") is False
assert list(terminal.synced()) == [SID]
assert terminal.synced()[SID]["cwd"] == "/home/akira"
assert oct((state / "terminal-synced.json").stat().st_mode & 0o777) == "0o600"
assert terminal.unsync(SID) and not terminal.unsync(SID)
assert terminal.synced() == {}
def test_preselect_this_folder_then_anywhere_then_ai_agent(tmp_path):
a, b = str(tmp_path / "a"), str(tmp_path / "b")
assert terminal.preselect(a) == "ai-agent"
terminal.note(a, "local")
assert terminal.preselect(a) == "local" and terminal.preselect(b) == "local"
terminal.note(b, "ai-agent")
assert terminal.preselect(a) == "local" and terminal.preselect(b) == "ai-agent"
assert terminal.remembered(a) is None # a pick isn't a remembered choice
def test_session_modes():
terminal.note_session(SID, "local")
terminal.note_session("nope", "local")
assert terminal.session_mode(SID) == "local"
assert terminal.session_mode(SID2) is None
def test_a_choice_covers_its_subfolders(tmp_path):
a = tmp_path / "code"
(a / "app" / "src").mkdir(parents=True)
terminal.remember(str(a), "ai-agent")
assert terminal.remembered(str(a / "app" / "src")) == ("ai-agent", str(a))
terminal.remember(str(a / "app"), "local")
assert terminal.remembered(str(a / "app" / "src"))[0] == "local"
assert terminal.remembered(str(tmp_path)) is None
assert terminal.forget(str(a)) == [str(a), str(a / "app")]
assert terminal.choices() == {}
with pytest.raises(ValueError):
terminal.remember(str(a), "cloud")
def test_launcher_switch():
assert terminal.launcher_on()
terminal.set_launcher(False)
assert not terminal.launcher_on()
assert terminal.public() == {"launcher": False, "synced": 0, "statusHash": None}
terminal.set_launcher(True)
assert terminal.launcher_on()
def test_sessions_lists_asked_ones_newest_first(tmp_path):
root = tmp_path / "projects"
old = _transcript(root, SID, [
{"type": "user", "cwd": "/home/akira/code",
"message": {"content": "<command-name>/clear</command-name>"}},
{"type": "user", "cwd": "/home/akira/code",
"message": {"content": [{"type": "text", "text": "fix the\nlogin page"}]}},
{"type": "ai-title", "aiTitle": "Login page fix"}])
os.utime(old, (1e9, 1e9))
_transcript(root, SID2, [{"type": "user", "cwd": "/x",
"message": {"content": "hello"}}])
# opened and closed: nothing asked, not listed
_transcript(root, "2b7c8f6e-1d2a-4c3b-9e8f-0123456789ab", [{"type": "mode"}])
# a subagent transcript isn't a session of its own
sub = root / "-home-akira-code" / SID / "subagents"
sub.mkdir(parents=True)
(sub / "agent-a.jsonl").write_text('{"type":"user","message":{"content":"x"}}\n')
terminal.sync(SID2)
got = terminal.sessions(root, days=1e9)
assert [s["id"] for s in got] == [SID2, SID]
assert got[0]["synced"] and not got[1]["synced"]
assert got[1]["title"] == "Login page fix"
assert got[1]["prompt"] == "fix the login page"
assert got[1]["cwd"] == "/home/akira/code"
def test_routes(monkeypatch, tmp_path):
monkeypatch.setattr("config.IS_WORKER", True)
root = tmp_path / "projects"
_transcript(root, SID, [{"type": "user", "cwd": "/a", "message": {"content": "hi"}}])
app = FastAPI()
app.include_router(terminal.make_router(_auth, lambda: root))
c = TestClient(app)
assert c.get("/terminal/sessions").status_code == 401
r = c.get("/terminal/sessions", headers=H).json()
assert r["launcher"] and [s["id"] for s in r["sessions"]] == [SID]
assert c.post("/terminal/sync", json={"sid": "nope"}, headers=H).status_code == 400
assert c.post("/terminal/sync", json={"sid": SID}, headers=H).json()["synced"] == 1
assert c.delete(f"/terminal/sync/{SID}", headers=H).json() == {"ok": True}
assert c.put("/terminal/launcher", json={"on": False}, headers=H).json() == {"launcher": False}
st = {"leftUsd": 4.2, "paused": False}
h = c.put("/terminal/status", json={"status": {**st, "evil": 1}}, headers=H).json()
assert terminal.hub_status() == st and h["statusHash"] == terminal.public()["statusHash"]
def test_routes_refused_on_the_host_sidecar(monkeypatch, tmp_path):
monkeypatch.setattr("config.IS_WORKER", False)
app = FastAPI()
app.include_router(terminal.make_router(_auth, lambda: tmp_path))
assert TestClient(app).get("/terminal/sessions", headers=H).status_code == 409