Skip to content

Commit 3e9d370

Browse files
Remove the ttyd spawn itself (ttyd retirement stage 2/7)
Closes R-03: plain `studyloop study` spawned a writable, unauthenticated ttyd on 127.0.0.1:7681 whenever ttyd was installed, even with no --web or --lan (the auth guard requires both a non-empty username and password, and the flag-less path passes an empty one). The spawn had to go before any cleanup work (stage 5) — landed in the other order, `session/cleanup.py` would stop killing a ttyd that a caller could still create, an orphaned writable terminal dressed as progress (test_ttyd_retirement_ordering.py's own guard exists to catch exactly that). Deletes `start_ttyd_background()` and its sole helper `_get_ttyd_port()` (session/orchestrator.py), and removes the import + call on both callers: the CLI study path (session/start.py) and the web app's legacy tmux+ttyd path (web/routes/session/_start.py). The legacy path's `_ttyd_credentials()` call is removed with it (kept dead code out of the diff), since removing only the spawn call would leave two now-unused locals; the function definition itself, and the fate of app.state.lan_username/lan_password, are stage 3's job per DECISIONS.md §E1. Proves the closure behaviourally, not just by absence: a new test puts a real, working `ttyd` shim on PATH (a shell script that touches a marker file) and asserts starting a session via the CLI study path never invokes it. `TestStartTtydBackground` (test_orchestrator.py, whole file) is deleted per the retirement manifest — it only ever exercised the function just removed. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
1 parent 3aeab7d commit 3e9d370

5 files changed

Lines changed: 68 additions & 167 deletions

File tree

‎packages/studyloop/src/studyloop/session/orchestrator.py‎

Lines changed: 0 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -364,72 +364,3 @@ def _open_browser(url: str) -> None:
364364
pass
365365
finally:
366366
os._exit(0) # Child must exit, never return to caller
367-
368-
369-
def _get_ttyd_port() -> int:
370-
"""Read ttyd port from config, default 7681."""
371-
try:
372-
from studyloop.settings import load_settings
373-
374-
return getattr(load_settings(), "ttyd_port", 7681)
375-
except Exception:
376-
return 7681
377-
378-
379-
def start_ttyd_background(
380-
session_name: str,
381-
*,
382-
lan: bool = False,
383-
username: str = "",
384-
password: str = "",
385-
) -> None:
386-
"""Start ttyd to expose the tmux session over HTTP.
387-
388-
Attaches a writable ttyd client to the study tmux session.
389-
When credentials are provided, passes ``-c username:password``
390-
so ttyd enforces HTTP Basic Auth on direct connections.
391-
Skips silently if ttyd is not installed.
392-
"""
393-
from studyloop.session_state import write_session_state
394-
395-
ttyd_bin = shutil.which("ttyd")
396-
if not ttyd_bin:
397-
return
398-
399-
host = "0.0.0.0" if lan else "127.0.0.1"
400-
port = _get_ttyd_port()
401-
402-
# Kill any stale ttyd left over from a previous session
403-
_kill_port_occupant(port, expected_cmd="ttyd")
404-
405-
cmd = [
406-
ttyd_bin,
407-
"-W", # writable (user interacts with the agent)
408-
"-i",
409-
host,
410-
"-p",
411-
str(port),
412-
]
413-
414-
# Enforce auth on ttyd when credentials are available
415-
if username and password:
416-
cmd.extend(["-c", f"{username}:{password}"])
417-
418-
cmd.extend(
419-
[
420-
"tmux",
421-
"attach",
422-
"-t",
423-
session_name,
424-
]
425-
)
426-
427-
try:
428-
proc = subprocess.Popen(
429-
cmd,
430-
stdout=subprocess.DEVNULL,
431-
stderr=subprocess.DEVNULL,
432-
)
433-
write_session_state({"ttyd_pid": proc.pid, "ttyd_port": port})
434-
except Exception:
435-
pass # ttyd failed to start — non-fatal

‎packages/studyloop/src/studyloop/session/start.py‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,6 @@ def start_session(
266266
build_wrapped_agent_cmd,
267267
create_tmux_environment,
268268
setup_session_dir,
269-
start_ttyd_background,
270269
start_web_background,
271270
)
272271
from studyloop.session_state import (
@@ -487,9 +486,6 @@ def start_session(
487486
if web:
488487
start_web_background(session_name, lan=lan, password=lan_password)
489488

490-
# Start ttyd if installed (allows iPad/LAN terminal access)
491-
start_ttyd_background(session_name, lan=lan, username=lan_username, password=lan_password)
492-
493489
# Persist LAN info to session state so it's visible after os.execvp
494490
if lan:
495491
import socket

‎packages/studyloop/src/studyloop/web/routes/session/_start.py‎

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -599,14 +599,15 @@ async def _start_acp_session(
599599
def _start_ttyd_session(
600600
body: StartSessionRequest, origin: str = _DEFAULT_ORIGIN, request: Request | None = None
601601
) -> JSONResponse:
602-
"""Legacy tmux+ttyd start path (plan §1.9 emergency fallback).
602+
"""Legacy tmux start path (plan §1.9 emergency fallback), ttyd removed.
603603
604604
Kept as-is to guarantee a deprecation window. New development should
605605
target the PTY path above.
606606
607-
``request`` carries ``app.state`` so ttyd's Basic-Auth credentials come
608-
from the SAME resolved source as the app's middleware (see the fail-closed
609-
guard below). It is optional only so the legacy CLI caller keeps working.
607+
``request`` is unused since ttyd retirement stage 2 removed the spawn
608+
that read Basic-Auth credentials from ``app.state`` — kept only for the
609+
legacy CLI caller's signature until stage 3 deletes this function
610+
entirely.
610611
"""
611612
import os
612613
import shutil
@@ -740,7 +741,6 @@ def _start_ttyd_session(
740741
build_wrapped_agent_cmd,
741742
create_tmux_environment,
742743
setup_session_dir,
743-
start_ttyd_background,
744744
)
745745

746746
setup_session_dir(session_dir, body.topic)
@@ -793,13 +793,10 @@ def _start_ttyd_session(
793793
state_update["topic_config_name"] = topic_config.name
794794
write_session_state(state_update)
795795

796-
# Credentials come from app.state (the single source of truth the app's
797-
# BasicAuthMiddleware was built from), NOT a fresh config.yaml read — the
798-
# two used to diverge, leaving ttyd unauthenticated when --password was
799-
# passed on the CLI but not persisted. Fails closed if app.state is
800-
# unreadable (see _ttyd_credentials).
801-
ttyd_username, ttyd_password = _ttyd_credentials(request)
802-
start_ttyd_background(session_name, username=ttyd_username, password=ttyd_password)
796+
# ttyd is no longer spawned here (stage 2 of the ttyd retirement removed
797+
# the spawn entirely — see PLAN-retire-ttyd.md). _ttyd_credentials() and
798+
# app.state.lan_username/lan_password are now dead below this point;
799+
# stage 3 deletes them along with the rest of this legacy path.
803800

804801
return JSONResponse(
805802
{

‎packages/studyloop/tests/test_orchestrator.py‎

Lines changed: 0 additions & 82 deletions
This file was deleted.

‎packages/studyloop/tests/test_session_start.py‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55

66
from __future__ import annotations
77

8+
import os
9+
import time
810
from unittest.mock import MagicMock, patch
911

1012
import pytest
@@ -232,6 +234,63 @@ def mock_create_session(name, **kwargs):
232234
assert "study-old-session-abcd1234" in created_names
233235

234236

237+
class TestNoTtydSpawnOnStudyPath:
238+
"""R-03: plain ``studyloop study`` must never spawn ttyd, even when installed.
239+
240+
Puts a working ``ttyd`` shim on PATH and proves the CLI study path never
241+
invokes it. Before stage 2 of the ttyd retirement, ``start_session()``
242+
unconditionally called ``start_ttyd_background()``, which shelled out to
243+
whatever ``ttyd`` it found on PATH with an empty password whenever neither
244+
``--web`` nor ``--lan`` was passed (R-03: a writable, unauthenticated
245+
terminal on ``127.0.0.1:7681``).
246+
"""
247+
248+
def test_fake_ttyd_on_path_is_never_invoked(self, tmp_path, monkeypatch):
249+
marker = tmp_path / "ttyd-was-spawned"
250+
bin_dir = tmp_path / "fakebin"
251+
bin_dir.mkdir()
252+
fake_ttyd = bin_dir / "ttyd"
253+
fake_ttyd.write_text(f"#!/bin/sh\ntouch {marker}\n")
254+
fake_ttyd.chmod(0o755)
255+
monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}{os.environ.get('PATH', '')}")
256+
257+
with (
258+
patch("studyloop.tmux.shutil.which", return_value="/usr/bin/tmux"),
259+
patch("studyloop.tmux.subprocess.run", side_effect=_tmux_side_effect),
260+
patch("studyloop.tmux.LOCK_FILE", tmp_path / "lock"),
261+
patch("studyloop.tmux.os.execvp"),
262+
# NOTE: this patches the process-wide `shutil.which` (all modules
263+
# share the one `shutil` module object), so it must resolve "ttyd"
264+
# for real — not just stub "claude" — or this test cannot tell
265+
# apart "ttyd was never looked up" from "the patch masked it".
266+
patch(
267+
"studyloop.agent_launcher.shutil.which",
268+
side_effect=lambda name: str(fake_ttyd) if name == "ttyd" else "/usr/bin/claude",
269+
),
270+
patch("studyloop.session_state.read_session_state", return_value={}),
271+
patch("studyloop.session_state.STATE_FILE", tmp_path / "state.json"),
272+
patch("studyloop.session_state.SESSION_DIR", tmp_path),
273+
patch("studyloop.session_state.TOPICS_FILE", tmp_path / "topics.md"),
274+
patch("studyloop.session_state.PARKING_FILE", tmp_path / "parking.md"),
275+
patch("studyloop.history.start_study_session", return_value="abc12345"),
276+
patch("studyloop.session.cleanup.auto_clean_zombies"),
277+
patch.dict("os.environ", {"TMUX": "/tmp/tmux"}),
278+
):
279+
start_session("Python Decorators", "claude", "study", "elapsed", 7, False)
280+
281+
# Poll rather than check once: a real spawn is an async subprocess, so
282+
# a single immediate check could pass by luck even with the spawn
283+
# still present and merely slow to touch the marker.
284+
for _ in range(20):
285+
if marker.exists():
286+
break
287+
time.sleep(0.05)
288+
assert not marker.exists(), (
289+
"ttyd was spawned from the CLI study path even with no --web/--lan; "
290+
"this is exactly the unauthenticated-terminal regression R-03 describes."
291+
)
292+
293+
235294
class TestStartSessionRollback:
236295
def _mock_adapter(self, tmp_path):
237296
adapter = MagicMock()

0 commit comments

Comments
 (0)