Skip to content

Commit 82829c1

Browse files
feat(web): redesign study session layout — sidebar feed + full terminal + status bar
Replace the Split.js split-pane layout with a simpler architecture: - Activity feed moves to sidebar (SSE-driven, scrollable) - Terminal iframe fills the entire content area (no resize) - Bottom status bar: timer + controls + topic + energy + counters This eliminates tmux SIGWINCH issues where resizing the terminal iframe corrupted the Claude Code agent session in the adjacent tmux pane. Also includes from prior sessions: - Pomodoro timer (web UI + TUI sidebar) - HTTP Basic Auth for LAN mode with credential passthrough to ttyd - Port-based ttyd cleanup (replaces fragile PID tracking) - Service worker self-destruct for cache busting - STUDYCTL_SESSION_DIR env var for test isolation - 18 data-driven Playwright E2E tests with results.json output - 20 tests for pomodoro/auth/terminal bug fixes Bumps version to 2.3.0. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent 2e9a95b commit 82829c1

24 files changed

Lines changed: 2804 additions & 311 deletions

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -500,6 +500,7 @@ eval-results.tsv
500500
.pytest-junit.xml
501501
docs/reports/
502502
docs/brainstorms/
503+
packages/studyctl/tests/results/
503504

504505
# Dev-only tooling (autoresearch eval harness — not shipped to users)
505506
dev/

‎docs/architecture-c4.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ C4Container
5959
6060
Container(cli, "studyctl CLI", "Python / Click + LazyGroup", "Entry point for all commands. 26 commands across 12 lazy-loaded modules. Delegates to services, session orchestrator, and specialist packages.")
6161
62-
Container(web, "Web UI", "Python / FastAPI + Alpine.js PWA", "Dashboard served on localhost:8567 (configurable). Shows session state, flashcard review, artefacts, and terminal embed. Optional HTTP Basic Auth for LAN mode.")
62+
Container(web, "Web UI", "Python / FastAPI + Alpine.js PWA", "Dashboard served on localhost:8567 (configurable). Study session view: full-screen terminal embed with sidebar activity feed and bottom status bar (timer, controls, counters). Also provides flashcard review and body-double timer. Optional HTTP Basic Auth for LAN mode.")
6363
6464
Container(mcp_server, "MCP Server (studyctl-mcp)", "Python / FastMCP via stdio", "Exposes study tools to AI agents: list_courses, get_study_context, record_study_progress, park_question, get_session_state. Launched automatically by each agent adapter.")
6565
@@ -113,13 +113,13 @@ C4Component
113113
114114
Component(content_pkg, "content/", "Python", "Content pipeline (absorbed from pdf-by-chapters). splitter.py: PDF chapter splitting. notebooklm_client.py: upload and trigger artefact generation. syllabus.py: course syllabus parsing. storage.py, models.py, markdown_converter.py.")
115115
116-
Component(web_pkg, "web/", "Python / FastAPI", "Web dashboard. app.py: FastAPI application factory with security headers and optional Basic Auth middleware. auth.py: HTTP Basic Auth. routes/: artefacts, cards, courses, history, session, terminal_proxy. static/: Alpine.js PWA assets.")
116+
Component(web_pkg, "web/", "Python / FastAPI", "Web dashboard. app.py: FastAPI application factory with security headers and optional Basic Auth middleware. auth.py: HTTP Basic Auth. routes/: artefacts, cards, courses, history, session, terminal_proxy. static/: Alpine.js PWA assets. Study session layout: sidebar activity feed (SSE-driven), full-screen terminal iframe (no Split.js resize — avoids tmux SIGWINCH), bottom status bar. Body-double view uses Split.js for timer+terminal split.")
117117
118118
Component(mcp_pkg, "mcp/", "Python / FastMCP", "MCP server entry point. server.py: FastMCP app with lifespan DB connection. tools.py: register_tools() wires list_courses, get_study_context, record_study_progress, park_question, get_session_state.")
119119
120120
Component(logic_pkg, "logic/", "Python", "Domain logic modules. break_logic.py: break detection and timing. streaks_logic.py: study streak calculation. briefing_logic.py: pre-session briefing generation. backlog_logic.py: topic backlog management. clean_logic.py: orphan cleanup. topic_resolver.py: topic name resolution.")
121121
122-
Component(settings_mod, "settings.py", "Python / dataclasses", "Single configuration source. Settings dataclass loaded from ~/.config/studyctl/config.yaml. Contains: TopicConfig, AgentsConfig, ContentConfig, NotebookLMConfig, KnowledgeDomainsConfig, EvalConfig.")
122+
Component(settings_mod, "settings.py", "Python / dataclasses", "Single configuration source. Settings dataclass loaded from ~/.config/studyctl/config.yaml. Contains: TopicConfig, AgentsConfig, ContentConfig, NotebookLMConfig, KnowledgeDomainsConfig, PomodoroConfig. session_state.py: IPC file paths overridable via STUDYCTL_SESSION_DIR env var for test isolation.")
123123
}
124124
125125
Rel(cli_entry, services, "Calls business logic", "import")
Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
---
2+
title: "studyctl Web UI: Four-Bug Fix (Pomodoro Config, ttyd Auth, Port Cleanup, Terminal Resilience)"
3+
date: 2026-04-07
4+
category: integration-issues
5+
tags:
6+
- web-ui
7+
- pomodoro
8+
- ttyd
9+
- security
10+
- process-management
11+
- terminal-health
12+
- fastapi
13+
- websocket
14+
- alpine-js
15+
affected_modules:
16+
- studyctl.settings
17+
- studyctl.session.orchestrator
18+
- studyctl.session.cleanup
19+
- studyctl.web.routes.session
20+
- studyctl.web.routes.terminal_proxy
21+
- studyctl.web.static (components.js, index.html, style.css)
22+
- studyctl.tui.sidebar
23+
- studyctl.cli._study
24+
severity: high
25+
resolution_time: "~2 hours (fixes only; split layout rewrite is separate)"
26+
---
27+
28+
# Web UI: Four-Bug Fix Session
29+
30+
## Problem Summary
31+
32+
Four user-reported issues with the studyctl web UI during v2.2.0 usage:
33+
34+
1. **Pomodoro timer hardcoded to 25 minutes** — no way to adjust focus/break durations
35+
2. **ttyd terminal accessible without auth** — `-c` flag not passed, WebSocket proxy didn't forward credentials
36+
3. **Stale ttyd/web server processes blocked new sessions** — orphaned processes on ports 7681/8567 prevented startup
37+
4. **Terminal panel showed raw tmux error** — "can't find session: study-harness-matrix-1d96f243" when ttyd attached to dead session
38+
39+
## Root Causes
40+
41+
### 1. Pomodoro Hardcoded
42+
Module-level constants in `sidebar.py` (`POMODORO_FOCUS = 25 * 60`) and `components.js` (`STUDY: 25 * 60`). No config path existed — `Settings` dataclass had no pomodoro fields.
43+
44+
### 2. ttyd No Auth
45+
`start_ttyd_background()` built the ttyd command without `-c` credentials. The WebSocket proxy in `terminal_proxy.py` connected to upstream ttyd without forwarding the browser's `Authorization` header — HTTP proxy forwarded it but WS didn't.
46+
47+
### 3. Stale Processes
48+
`end_session_common()` killed processes by PID only (from session state). When cleanup didn't run (abrupt exit, test harness crash), PIDs were lost. New session's `start_web_background()` / `start_ttyd_background()` silently failed to bind the occupied port.
49+
50+
### 4. Terminal Panel Error
51+
The `terminalPanel()` Alpine component checked `state.ttyd_port` to set `available=true` but never verified ttyd was actually reachable. ttyd stayed running after tmux session died (no `--once` flag), serving the raw tmux "can't find session" error to every new client.
52+
53+
## Solutions
54+
55+
### Fix 1: Configurable Pomodoro Timer
56+
57+
**Settings layer** (`settings.py`):
58+
```python
59+
@dataclass
60+
class PomodoroConfig:
61+
focus: int = 25 # minutes
62+
short_break: int = 5
63+
long_break: int = 15
64+
cycles: int = 4
65+
```
66+
Added to `Settings`, loaded from YAML `pomodoro:` section.
67+
68+
**API endpoint** (`web/routes/session.py`):
69+
```python
70+
@router.get("/settings/pomodoro")
71+
def get_pomodoro_settings() -> dict:
72+
pomo = load_settings().pomodoro
73+
return {"focus": pomo.focus, "short_break": pomo.short_break, ...}
74+
```
75+
76+
**Web UI** (`components.js`): Alpine store loads `localStorage > API > defaults`. `saveDurations()` persists to localStorage. Editable number inputs in header overlay and body-double panel.
77+
78+
**TUI sidebar** (`sidebar.py`): Reads from `load_settings().pomodoro`. Keybindings: `s` start/stop, `+/-` adjust focus, `p` pause, `r` reset.
79+
80+
### Fix 2: ttyd Authentication
81+
82+
**Credential passthrough** (`orchestrator.py`):
83+
```python
84+
def start_ttyd_background(session_name, *, lan=False, username="", password=""):
85+
if username and password:
86+
cmd.extend(["-c", f"{username}:{password}"])
87+
```
88+
89+
**WebSocket auth** (`terminal_proxy.py`):
90+
```python
91+
auth_header = ws.headers.get("authorization")
92+
if auth_header:
93+
upstream_kwargs["additional_headers"] = {"Authorization": auth_header}
94+
```
95+
96+
Both CLI (`_study.py`) and web route (`session.py`) read config credentials and pass them through.
97+
98+
### Fix 3: Stale Process Cleanup
99+
100+
**Port-based kill** (`orchestrator.py`):
101+
```python
102+
def _kill_port_occupant(port: int, expected_cmd: str = "") -> None:
103+
"""Kill any process listening on port. Safety guard: only kills if command matches."""
104+
# Uses lsof -ti :port, ps -p PID -o command=, os.kill(SIGTERM)
105+
# 0.5s grace period after kill for port release
106+
```
107+
108+
Called before `start_ttyd_background()` and `start_web_background()`. Port-based fallback also added to `end_session_common()` in `cleanup.py`. `web_port` now stored in session state.
109+
110+
### Fix 4: Terminal Panel Resilience
111+
112+
**Zombie ttyd killer** (`session.py`):
113+
```python
114+
def _kill_stale_ttyd(state: dict) -> None:
115+
"""Kill stale ttyd process if the tmux session it attaches to is gone."""
116+
```
117+
Called from `_get_full_state()` during zombie detection.
118+
119+
**Health check** (`index.html`): `terminalPanel()` component split into `available` (state has ttyd_port) vs `connected` (probe `/terminal/` succeeds). 10s periodic health check. `.terminal-unavailable` overlay shows "Terminal session ended" when connected=false.
120+
121+
## Investigation Steps That Failed
122+
123+
- **Split-pane resizable layout**: Attempted CSS Flexbox, CSS Grid, absolute positioning (Alpine), absolute positioning (vanilla JS). ALL produced correct DOM values in Playwright but didn't render correctly in real browsers (Chrome/Brave/Firefox on macOS). Deferred to next session — see handoff document.
124+
125+
## Prevention Strategies
126+
127+
1. **Always pass auth credentials through the full chain** — HTTP proxy, WebSocket proxy, and the underlying service. Test with `curl -u` against both the proxy and direct endpoints.
128+
2. **Kill by port, not just PID** — PIDs are fragile (recycling, lost state). Port-based cleanup is reliable. Always call `_kill_port_occupant()` before binding.
129+
3. **Health-check backing services** — don't assume a port number in state means the service is actually running. Probe the endpoint before showing UI.
130+
4. **Config should flow to ALL consumers** — if a value is configurable, wire it through to every place that uses it (API, web UI, TUI, CLI).
131+
132+
## Test Coverage
133+
134+
20 new tests in `tests/test_fixes_pomodoro_auth_terminal.py`:
135+
- `TestPomodoroConfig` (4 tests): defaults, custom values, YAML loading
136+
- `TestPomodoroAPI` (3 tests): endpoint returns config/defaults/fallback
137+
- `TestTtydAuth` (3 tests): `-c` flag present/absent based on credentials
138+
- `TestTtydLifecycle` (4 tests): kill stale ttyd, zombie detector integration
139+
- `TestPomodoroWebUI` (4 Playwright E2E): settings row visible/hidden, custom duration, API
140+
- `TestTerminalResilience` (2 Playwright E2E): unavailable message, hidden when no ttyd
141+
142+
## Related Documentation
143+
144+
- `docs/plans/2026-04-04-ttyd-integration.md` — original ttyd integration plan
145+
- `docs/plans/2026-04-05-web-ui-alpine-sidebar-plan.md` — Alpine sidebar plan
146+
- `docs/internal/solutions/tmux-session-management-and-ci-issues.md` — prior session cleanup patterns
147+
- `docs/internal/solutions/parallel-research-catches-pre-implementation-assumptions.md` — ttyd auth research (Note: `-c` flag IS supported despite this doc's finding about `TTYD_CREDENTIAL`)
148+
- `.claude/handoffs/2026-04-07-184001-web-ui-split-layout-rewrite.md` — handoff for the unfinished split layout rewrite

‎packages/studyctl/pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[project]
22
name = "studyctl"
3-
version = "2.2.0"
3+
version = "2.3.0"
44
description = "AuDHD-aware study tool with AI Socratic mentoring, spaced repetition, and content pipeline"
55
requires-python = ">=3.12"
66
readme = "README.md"

‎packages/studyctl/src/studyctl/cli/_study.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -616,7 +616,7 @@ def _handle_start(
616616
start_web_background(session_name, lan=lan, password=lan_password)
617617

618618
# Start ttyd if installed (allows iPad/LAN terminal access)
619-
start_ttyd_background(session_name, lan=lan)
619+
start_ttyd_background(session_name, lan=lan, username=lan_username, password=lan_password)
620620

621621
# Persist LAN info to session state so it's visible after os.execvp
622622
if lan:

‎packages/studyctl/src/studyctl/session/cleanup.py‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -140,11 +140,12 @@ def end_session_common(
140140
oneline.unlink()
141141

142142
# Kill background processes (web dashboard, ttyd).
143-
# Verify PID identity before killing to guard against PID recycling:
144-
# if the process exited and its PID was reused by an unrelated process,
145-
# we'd kill the wrong thing.
143+
# Strategy: kill by PID first (fast), then by port as fallback
144+
# to catch processes started by a different code path.
146145
import subprocess as _sp
147146

147+
# PID-based kill — check command matches to guard against PID recycling.
148+
# "studyctl" matches both the binary and "python -m studyctl.cli".
148149
pid_checks = {"web_pid": "studyctl", "ttyd_pid": "ttyd"}
149150
for pid_key, expected in pid_checks.items():
150151
pid = state.get(pid_key)
@@ -162,6 +163,16 @@ def end_session_common(
162163
except (OSError, _sp.TimeoutExpired):
163164
pass
164165

166+
# Port-based kill — fallback for orphaned processes whose PIDs we lost.
167+
from studyctl.session.orchestrator import _kill_port_occupant
168+
169+
ttyd_port = state.get("ttyd_port")
170+
if ttyd_port:
171+
_kill_port_occupant(int(ttyd_port), expected_cmd="ttyd")
172+
web_port = state.get("web_port")
173+
if web_port:
174+
_kill_port_occupant(int(web_port), expected_cmd="studyctl")
175+
165176
# Kill all study tmux sessions
166177
with contextlib.suppress(Exception):
167178
kill_all_study_sessions(current_session=session_name)

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

Lines changed: 70 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,9 @@ def start_web_background(session_name: str, *, lan: bool = False, password: str
237237

238238
port = _get_web_port()
239239

240+
# Kill any stale web server left over from a previous session
241+
_kill_port_occupant(port, expected_cmd="studyctl")
242+
240243
studyctl_bin = shutil.which("studyctl")
241244
cmd = (
242245
[studyctl_bin, "web", "--port", str(port)]
@@ -255,12 +258,53 @@ def start_web_background(session_name: str, *, lan: bool = False, password: str
255258
)
256259
from studyctl.session_state import write_session_state
257260

258-
write_session_state({"web_pid": proc.pid})
261+
write_session_state({"web_pid": proc.pid, "web_port": port})
259262
_open_browser(f"http://127.0.0.1:{port}/session")
260263
except Exception:
261264
console.print("[yellow]Could not start web dashboard.[/yellow]")
262265

263266

267+
def _kill_port_occupant(port: int, expected_cmd: str = "") -> None:
268+
"""Kill any process listening on *port*.
269+
270+
If *expected_cmd* is given, only kill when the process command contains
271+
that string (safety guard against killing unrelated processes).
272+
"""
273+
import signal
274+
import time as _time
275+
276+
killed = False
277+
try:
278+
result = subprocess.run(
279+
["lsof", "-ti", f":{port}"],
280+
capture_output=True,
281+
text=True,
282+
timeout=5,
283+
)
284+
if not result.stdout.strip():
285+
return
286+
for pid_str in result.stdout.strip().splitlines():
287+
pid = int(pid_str)
288+
if expected_cmd:
289+
ps_result = subprocess.run(
290+
["ps", "-p", str(pid), "-o", "command="],
291+
capture_output=True,
292+
text=True,
293+
timeout=5,
294+
)
295+
if expected_cmd not in ps_result.stdout:
296+
continue
297+
with __import__("contextlib").suppress(OSError):
298+
os.kill(pid, signal.SIGTERM)
299+
killed = True
300+
except (subprocess.TimeoutExpired, ValueError, OSError):
301+
pass
302+
303+
# Wait for the port to be released after killing
304+
if killed:
305+
_time.sleep(0.5)
306+
307+
264308
def _get_web_port() -> int:
265309
"""Read web port from config, default 8567."""
266310
try:
@@ -339,10 +383,18 @@ def _get_ttyd_port() -> int:
339383
return 7681
340384

341385

342-
def start_ttyd_background(session_name: str, *, lan: bool = False) -> None:
386+
def start_ttyd_background(
387+
session_name: str,
388+
*,
389+
lan: bool = False,
390+
username: str = "",
391+
password: str = "",
392+
) -> None:
343393
"""Start ttyd to expose the tmux session over HTTP.
344394
345395
Attaches a writable ttyd client to the study tmux session.
396+
When credentials are provided, passes ``-c username:password``
397+
so ttyd enforces HTTP Basic Auth on direct connections.
346398
Skips silently if ttyd is not installed.
347399
"""
348400
from studyctl.session_state import write_session_state
@@ -354,19 +406,31 @@ def start_ttyd_background(session_name: str, *, lan: bool = False) -> None:
354406
host = "0.0.0.0" if lan else "127.0.0.1"
355407
port = _get_ttyd_port()
356408

409+
# Kill any stale ttyd left over from a previous session
410+
_kill_port_occupant(port, expected_cmd="ttyd")
411+
357412
cmd = [
358413
ttyd_bin,
359414
"-W", # writable (user interacts with the agent)
360415
"-i",
361416
host,
362417
"-p",
363418
str(port),
364-
"tmux",
365-
"attach",
366-
"-t",
367-
session_name,
368419
]
369420

421+
# Enforce auth on ttyd when credentials are available
422+
if username and password:
423+
cmd.extend(["-c", f"{username}:{password}"])
424+
425+
cmd.extend(
426+
[
427+
"tmux",
428+
"attach",
429+
"-t",
430+
session_name,
431+
]
432+
)
433+
370434
try:
371435
proc = subprocess.Popen(
372436
cmd,

‎packages/studyctl/src/studyctl/session_state.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
from dataclasses import dataclass
1414
from pathlib import Path
1515

16-
SESSION_DIR = Path.home() / ".config" / "studyctl"
16+
SESSION_DIR = Path(os.environ.get("STUDYCTL_SESSION_DIR", Path.home() / ".config" / "studyctl"))
1717
STATE_FILE = SESSION_DIR / "session-state.json"
1818
TOPICS_FILE = SESSION_DIR / "session-topics.md"
1919
PARKING_FILE = SESSION_DIR / "session-parking.md"

0 commit comments

Comments
 (0)