Let sessions outlive the backend, and never resume one twice

Three `claude` processes ended up running against this checkout on
2026-08-29, and the account hit its session limit. One cause, several
ways in.

An agent imported the Claude Code session it was *itself* running in.
That is an ordinary import, and importing runs `--resume` -- so a second
CLI attached to a file the first was still writing. The whole 65 MB
conversation, 154 embedded screenshots included, was re-appended to the
transcript under a new prompt id; both copies then read each other's
writes as work done elsewhere, and the adopted one was billed for
re-reading all of it. Meanwhile `shutdown_all` asked each session to stop
and the process exited immediately, so the SIGKILL timer died with the
runtime, the stop was unreliable, and whatever survived was orphaned with
nothing written down to find it by.

The processes leaked either way. So leak them on purpose, and be able to
pick them back up.

A session's process now outlives the backend and is adopted again on the
way up, which is worth having for its own sake: restarting the server no
longer ends a turn somebody is waiting on. Its stdio lives in the session
directory -- a fifo opened read-write so the process is its own last
writer and never reads EOF, plus stdout/stderr logs read from a byte
offset. `session::process` records the pid *and* the kernel's start time
for it, because a pid alone is reused and adopting a stranger's would mean
never resuming the real conversation.

That makes the fix structural rather than a check: everything goes through
`ClaudeDriver::launch`, which adopts if it can and starts if it cannot,
and `--resume` is reachable only on the second path. `Driver` gains two
ways out where it had one -- `detach` (coming back) and `stop` (the
session is being deleted, so the process must not survive).

Importing a session that is open is now refused outright. Claude Code
keeps `~/.claude/sessions/<pid>.json` for every live session, so this is a
measurement rather than a guess; it reports no/yes/unknown, because a
machine that keeps no such record cannot answer and "could not check" is
not "nobody is using it". `SessionStatus` gains `Unknown` for the same
reason.

Also here, found on the way:

- A reconnecting phone was sent the entire backlog. Opening a session was
  bounded to a page but reconnecting was not, so a long disconnect
  delivered thousands of events one frame at a time. Past `CATCH_UP_LIMIT`
  the stream sends a `reset` frame and the newest window, and the client
  rebuilds from it as it does on open -- without the reset the window is
  spliced onto rows no longer adjacent to it.
- A session's status was assumed idle at launch. Read from the transcript
  instead, so a restart stops claiming an exited session is waiting for
  you.
- `llama-server`'s stdout was piped and never drained, so a chatty one
  blocked on a full pipe buffer mid-load. It goes to a log now.
- A turn that exited or errored never emitted `Idle`, so the queue stayed
  "running" for good: every later message was held forever and, since a
  message is only recorded when taken, vanished with nothing on screen.
- Two doc comments had drifted onto the wrong functions.

Verified by killing the server mid-turn: the process survived, finished
its turn unattended (12.8 KB of output nothing was reading), and the
restarted server adopted it -- one process, all 700 lines in the
transcript, no hole, and it still took a new message afterwards. Deleting
a session stops its process; a 266-event backlog resets while a 16-event
one streams. 46 tests, clippy and rustfmt clean, app compiles and lints.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VETa8afmpWaYezLCqJhDB8
This commit is contained in:
irisandClaude Opus 5 committed 2026-08-29 04:47:43 -04:00
1 parent 9791afcfd6
commit 362d436d4f
23 files changed
+1934 -345

No files matched your search

@@ -13,6 +13,12 @@ import java.net.URL
* of throwing, so a deliberate close doesn't surface as a connection error. The caller owns
* reconnecting (with the last seq it saw as the new cursor) -- see SessionScreen.
*/
/**
* The frame name the server uses to say a cursor was too far behind to continue from. Must match
* `send_backlog` in the backend's routes.rs.
*/
private const val RESET_EVENT = "reset"
class EventStream(private val settings: ServerSettings, private val sessionId: String) {
@Volatile private var connection: HttpURLConnection? = null
@Volatile private var closed = false
@@ -22,8 +28,15 @@ class EventStream(private val settings: ServerSettings, private val sessionId: S
connection?.disconnect()
}
/** Streams events after [after] into [onEvent] until the stream drops. */
fun run(after: Long, onEvent: (SeqEvent) -> Unit) {
/**
* Streams events after [after] into [onEvent] until the stream drops.
*
* [onReset] fires when the server answers that the cursor is too far behind to continue from:
* everything already displayed is stale and the events that follow are a fresh window, so the
* caller drops what it holds and rebuilds -- the same thing it does when the screen opens. It
* arrives before those events, so a caller that clears on it stays in order.
*/
fun run(after: Long, onReset: () -> Unit, onEvent: (SeqEvent) -> Unit) {
val connection =
URL("${settings.baseUrl}/sessions/$sessionId/events?after=$after").openConnection()
as HttpURLConnection
@@ -43,22 +56,26 @@ class EventStream(private val settings: ServerSettings, private val sessionId: S
}
val reader = connection.inputStream.bufferedReader()
// SSE framing: `data:` lines accumulate until a blank line ends
// the event. `id:` (the seq) is also inside the JSON payload,
// so only data lines matter; comment lines (keep-alives) start
// with ':' and are skipped.
// SSE framing: `data:` and `event:` lines accumulate until a
// blank line ends the frame. `id:` (the seq) is also inside the
// JSON payload, so it needs no separate handling; comment lines
// (keep-alives) start with ':' and are skipped.
val data = StringBuilder()
var name: String? = null
while (true) {
val line = reader.readLine() ?: break
when {
line.isEmpty() -> {
if (data.isNotEmpty()) {
onEvent(parseSeqEvent(data.toString()))
data.clear()
}
// A named frame carries no payload and a data frame
// has no name, so this is one or the other.
if (name == RESET_EVENT) onReset()
else if (data.isNotEmpty()) onEvent(parseSeqEvent(data.toString()))
data.clear()
name = null
}
line.startsWith("data:") -> data.append(line.removePrefix("data:").trim())
else -> {} // id:, event:, comments -- nothing to do
line.startsWith("event:") -> name = line.removePrefix("event:").trim()
else -> {} // id:, comments -- nothing to do
}
}
} catch (e: ApiException) {