Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ Install the release locally: `brew update && brew upgrade ccs`.
- `internal/mcp/hold.go` - the hold: `Holder` (`NewHolder`, `HoldConfig`: Who, Wait, KeyRelease, MayHold, Yields, OnYield) owns serve-hook.sock and serve-control.sock while it holds the flock on `serve-hook.lock` (`tryLock`; a crashed owner's lock goes with its process, and its sockets are removed on the next bind). `Listen(takeOver)`: ccs serve passes true and asks a TUI owner to `yield` over the control socket (a serve owner refuses: "another ccs serve"); a TUI passes false and is otherwise a client. `holdPrompt` (the nonce acknowledgement, MayHold false lets it go at once, `ReleaseAll`'s channel, the wait, the key release), `serveControl` (list, answer, yield), `control` and `List`/`Answer` for an owner's own use. `ccs serve` holds through one (`s.hold`, `s.prompts` its book; `listenHooks`/`listenControl` are `ownHold`)
- `internal/mcp/serve.go`, `access.go`, `serve_pages.go`, `serve_view.go` (the phone layout: `buckets`, `messageViews` and `segments` turn `Conversation.Messages` into bubbles, `pageOf` pages them, `refreshes` decides the meta refresh (the sessions page, a waiting session's page, whose composer is then hidden), the manifest and icons, `/manifest.webmanifest`, `/icon.svg`, `/icon/{180,192,512}`, behind the same checks; a preview's redirects keep its path, `statusWriter.base`) - `ccs serve` (`RunServe`): the sessions as a web page for a phone, behind a Cloudflare Tunnel with Cloudflare Access. It listens on loopback only (`loopbackOnly`) and, on every request, checks the Host (`--host`), then Access's signed `Cf-Access-Jwt-Assertion` itself (`accessVerifier`: RS256 against the team's certs, used for `accessKeysFresh` then fetched again (at most every `accessRefetch`, outside the cache lock; a failed fetch keeps keys under `accessKeysStale`, then refuses), aud, iss, exp/nbf within `accessSkew`, an allowed email), then a POST's `Origin`/`Sec-Fetch-Site`, then the rate limit (`rateLimits`: only a confirmed write spends the write allowance). Pages: `/` the triage (`TriageRows`), `/session` `read_session` with the pending question and, with `--allow-write`, the forms; `/prs` `list_prs`; JSON under `/api/`. Writes are POSTs to `/act` with the CSRF token (`csrf`, HMAC of the email, a key per process), shown as a confirm page (`describe`) until `confirm=yes`. Send goes over the session's socket as `the user, via ccs` with `CcsNote` (Codex: its queue), never typed; nothing is ever typed into a terminal; prompts are answered through `ccs hook permission` (`hook.go`: a PermissionRequest hook that sends its input with a nonce (`hookHello`) to `hookSockPath` once `trustedSocket` passes (a real 0600 socket of this user's in a folder of theirs no one else can write; other users are what it keeps out, same-user processes are out of scope), needs serve's acknowledgement echoing the nonce within `hookAckWait`, and prints `hookDecision`, built from its own input (serve sends only allow or deny and a question's labels, `hookReply`, checked against the question's options), or nothing when no serve listens or it's let go, so the terminal asks as usual. Its hello carries `WaitAt`, its own wait (`ownWait`: the statusUpdatedAt its session file, `hookSessionFile` for its parent pid, shows waiting within `ownWaitWindow` of its start), and a holder with that known holds it on exactly that wait, letting it go at once, unlisted, when its scan shows the wait over. A holder going away (`Holder.Handoff`: the TUI's `releaseHold` on quit or update restart, a yield to ccs serve, ccs serve stopping) replies `Retry` instead of a final no-decision (logged "handed back for a restart"), and the hook (`hookOnce` in a loop) dials again every `hookRedial` with every check repeated (trustedSocket, `hookPeerUID`, a new nonce, the acknowledgement), as it does when the connection closes with no reply (a crash). It stops, printing nothing, when `ownWait.over` (its file shows another session, not waiting, or another wait; an unreadable file says nothing) or `hookMaxWait` after its start (`hookNow`, `hookSleep` stubbed in tests). A reply for another nonce, or a final no-decision, ends it. `Close` stays final; tests' `TestMain` stubs the session file as another session's, so a hook a test leaves behind stops at its first redial; `ccs hook install|uninstall [--print]`, `editHookSettings`, keeps the old settings as `.before-ccs-hook`, timeout `hookTimeout` above `maxHookWait`). With `--allow-write`, `listenHooks` (one ccs serve at a time) holds each prompt (`serve_prompts.go`, `holdPrompt`, `promptBook`) until the page answers it (`actPrompt`, `promptDecision`: allow, an AskUserQuestion's answers in `updatedInput`, each one of its options, deny, or `mac` to let it go), the hook goes away, `--hook-wait` passes, or (not in `--preview`) `keyIdle` (`sessions.KeyIdle`, shared with ^X A) shows a key pressed since it arrived; letting go never decides; a session's own question with no held prompt is shown only (`askView`); `serve_control.go`: `serve-control.sock` (`ControlSockPath`, opened by `listenControl` with the hook socket) lets the TUI list held prompts and answer one (`{"op":"list"}`, `{"op":"answer",prompt,choice,answers}`: a choice and labels only, unknown fields dropped, through `promptDecision` and `prompts.take`, first wins, logged as `tui (this Mac)`), both ends checked with `trustedSocket` and `peerUID`; clients `HeldPrompts`, `AnswerHeld`; launch, close and restart go through `Call`, close and restart passing `session_id` (both tools take it). Every stop goes through `sessions.CloseSession(name, pid, id)`, which checks `IdentityOf(pid)` (the session file's id, read up to three times, else a fresh, uncached `LiveCodexSessions` look for a Codex thread) against id immediately before the SIGTERM and refuses on a mismatch, an unreadable file or no id; `ccs close` by name takes the id at discovery after `sameSession` checks the name is still exactly that session's. Requests share one scan while it runs (`load(ctx)`, `inflight`; the scan runs in its own goroutine and each waiter leaves when its request's context ends) and at most `serveSlots` are served at once. A graceful close whose session id changes in the same pid (`replaced`) leaves that pid running; `SameSession` checks a Codex session (no session file) against `LiveCodexSessions`. Every request goes to the activity log. `--preview` (`serveConfig.preview`) has no verifier: everything lives under `/p/<token>` (`base`, `pageData.Base`, `$.Base` in every template link and form; `previewPath` checks it in constant time and strips it before routing, anything else is a 404 that never logs the path, since loopback is shared by every user and a 127.0.0.1 cookie would reach every port), a loopback Host only, the Access flags refused, logged as `previewUser`; `ccs serve install` refuses it, and `privateServeLog` keeps the agent's log 0600; read-only unless `--allow-write`, and then a POST needs `Origin` `http://<its Host>`, a same-origin `Sec-Fetch-Site` and the CSRF token, as remotely. Tests stub `sendEnvelope`, `readSessionFile`, `peerToken`, `serveCall`, `sessions.TypeKeys` and the verifier's `fetch`
- Remote Control names (`internal/state/remote.go`): Claude Code ignores a session's `--name`/`/rename` title for Remote Control while it suppresses the conversation's history (a conversation started under another organisation, as after a cswap switch: `history-suppression` records in its transcript), showing `<hostname>-<words>` and later a title made from a message; only an explicit `--remote-control <name>` always names it. `state.RemoteControlArgs` adds that when ^X V (`remote_control` in settings.json, `state.RemoteControl`, kept by `foreignSettings`) is on or the caller asks: `launchScript` (Claude only, `LaunchOpts.RemoteControl`), `OpenResumeTab` and the exec-in-place resume through `ResumeRemoteControlArgs` (a user-set name only, never a fork), and `RestartSession` asks whenever the old session file had a `bridgeSessionId` (`SessionFile.BridgeSessionID`, `restartTarget.remote`). ^X V opens a popup (`internal/tui/remote.go`: `rcPopup`, `rcKey`, `m.rcOpen`): v toggles that setting (`toggleRemoteControl`); t (the selection) and a (`rcCandidates`: every live Claude Code row) type `/remote-control <name>` into running sessions (`rcStart`, `rcType`), the name from `rcName` (the session file's name, else a user-set title, matching `state.SessionName`). `rcCheck` refuses on the key: not live, `SessionStat.Remote` (a `bridgeSessionId`; with it on the command opens a menu that waits for a key), no name, anything `slashRefusal` (shared with `typeSlash`: Codex, agy, subagent, background, app-hosted, a held prompt, busy, waiting, unverified) says, or not idle; `typeSlashNow` (also `typeSlash`'s) checks again just before the keys, with a recheck of the fresh session file's `bridgeSessionId`. Then `rcType` polls each typed session's file for `bridgeSessionId` (`rcConfirmWait`, `rcConfirmEvery`) and says when it didn't appear; `applyRC` gives each session a note in its box (grey when skipped), logs each to the activity log and sums it up
- Queued messages (`internal/transcript/queue.go`): Claude Code's queue-operation lines (enqueue with content; remove with content and a reason, `absorbed_mid_turn` then that message's `queued_command`; popAll / popOne per message pulled back to edit; dequeue with no content, then the user line holding it) kept as `Conversation.Queue` (`QueuedMessage`, text cleaned in `noteEnqueued`, `key` the raw `queueKey`: a cross-session message's body, whitespace collapsed, matched exactly, never drawn). A remove or pop drops by content (`noteRemoved`; an absorbed one's key waits in `queueTaken` for its `queued_command`, so the same text queued twice keeps the second), a user line or `queued_command` drops the one it is (`noteUnqueued`); harness text and channel events are never queued. `QueuedNow` is those enqueued after the last turn end, since a turn that ends with messages queued takes them in at once: an older one is one never seen taken in (a slash command). The preview draws them last (`queuedLines`: `❯` text or `From <name>`, then a dim `⎿ Queued`; not in a search), only while the session is busy or waiting (`queuedShown`), and `ccs sessions` rows carry `queued` (`QueuedMessage.Plain`); not `read_session`. Not messages: counts, unread, done, WHEN and the search ignore them. Codex rollouts record no queue
- Launch briefs: `briefText` puts a newline before a brief that starts with `-`, so the brief, a positional argument after claude's or codex's options, is never read as an option
- `internal/tui` (all `package tui`, same directory) - the terminal UI and the command line (`Main`): everything else, split by area into the files below

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,7 @@ export CCS_CLAUDE_ARGS="--permission-mode auto"
- The rule for which is which: single keys act now and leave nothing behind (move, open, message, fork, refresh); `Ctrl+X` then a letter changes something that stays (a mark, a setting, a file, whether a session runs), and the ones that can't be undone (`Ctrl+X D` delete, `Ctrl+X K` stop, `Ctrl+X X` shrink) ask first
- `↑/↓` or `Ctrl+P/N` - Move through the list
- Background sessions (`claude --bg`) show `bg <state>` on the grey row: Enter opens one with `claude attach` in a new tmux window or iTerm tab, and `Ctrl+X K` stops it once you say `y` (on a session in a terminal tab, it stops it and closes the tab). One started from another session's `claude --bg` sits under it
- Queued messages: while a session is mid-turn, the messages it has queued and not taken in yet (typed in its tab, sent from ccs or from another session) show at the end of its preview as Claude Code draws them, each followed by a dim `⎿ Queued`, until Claude takes it in and it becomes an ordinary message. `ccs sessions` lists them too, as `queued:` lines (`queued` in `--json`). Codex records no queue, so its sessions show none
- Messages between sessions show at both ends: the sender's preview shows each `SendMessage` as `To <session>` (`✓ arrived` once it's in that session's transcript), the recipient's `From <session>`
- A live session run by an app without a terminal shows `in <app>`. One in T3 Code opens in T3 Code with Enter, at its thread; any other app gets a hollow `○`, since ccs can't switch to it, and Enter on its empty message box says to open it there. Messaging it from that box and forking it (`Ctrl+F`) work either way
- Each session's name is coloured by its state: magenta waiting on you, light magenta asked you something, amber busy, cyan done since you last looked; plain when it's running and idle, and dim when it isn't running. A session in an app ccs can't open has a `○` before it
Expand Down
9 changes: 9 additions & 0 deletions internal/mcp/sessions.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ type SessionRow struct {
WaitingFor string `json:"waiting_for,omitempty"` // with waiting: "permission prompt", "input needed"
Question string `json:"question,omitempty"` // with waiting: the menu or the tool call it asks about
Asked bool `json:"asked,omitempty"` // idle, and its last message ends in a question
Queued []string `json:"queued,omitempty"` // busy or waiting: messages it has queued and not taken in yet
LastError string `json:"last_error,omitempty"` // the latest API error, until a later reply succeeds
LastErrorAt string `json:"last_error_at,omitempty"`
PRs []string `json:"prs,omitempty"` // every PR it or its subagents opened, merged or touched
Expand Down Expand Up @@ -144,6 +145,11 @@ func sessionRow(conv transcript.Conversation, l sessions.LiveSession, ok bool, n
case "idle":
r.Asked = conv.AskedLast()
}
if st.Status == "busy" || st.Status == "waiting" { // an idle session takes a message in as it arrives
for _, q := range conv.QueuedNow() {
r.Queued = append(r.Queued, q.Plain())
}
}
since, _ := time.Parse(time.ANSIC, strings.Join(strings.Fields(l.Start), " "))
r.Tasks = len(transcript.RunningTasks(conv, since, now))
for _, s := range transcript.SubagentsOf(conv) {
Expand Down Expand Up @@ -235,6 +241,9 @@ func (r SessionRow) details(now time.Time) []string {
if r.Asked {
out = append(out, "its last message asks something")
}
for _, q := range r.Queued {
out = append(out, "queued: "+strings.ReplaceAll(q, "\n", "\n "))
}
if r.LastError != "" {
at := ""
if r.LastErrorAt != "" {
Expand Down
21 changes: 21 additions & 0 deletions internal/mcp/sessions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -240,3 +240,24 @@ func TestSessionRowStaleBusyIsIdle(t *testing.T) {
t.Errorf("got %s since %s, want idle since the turn's end", r.Status, r.Since)
}
}

// A busy session lists the messages it has queued and not taken in; an idle
// one has none, whatever an old enqueue says.
func TestSessionRowQueued(t *testing.T) {
now := time.Date(2026, 11, 20, 12, 40, 0, 0, time.UTC)
conv := transcript.Conversation{SessionID: "a"}
transcript.ParseLine(&conv, []byte(`{"type":"user","timestamp":"`+now.Add(-2*time.Minute).Format(time.RFC3339Nano)+`","message":{"role":"user","content":"go"}}`))
transcript.ParseLine(&conv, []byte(`{"type":"queue-operation","operation":"enqueue","timestamp":"`+now.Add(-time.Minute).Format(time.RFC3339Nano)+`","content":"and the tests"}`))
busy := sessions.LiveSession{PID: 1, Stat: sessions.SessionStat{Status: "busy", Since: now.Add(-2 * time.Minute)}}
r := sessionRow(conv, busy, true, now)
if len(r.Queued) != 1 || r.Queued[0] != "and the tests" {
t.Fatalf("queued: %q", r.Queued)
}
if d := strings.Join(r.details(now), "\n"); !strings.Contains(d, "queued: and the tests") {
t.Errorf("details: %q", d)
}
idle := sessions.LiveSession{PID: 1, Stat: sessions.SessionStat{Status: "idle", Since: now}}
if r := sessionRow(conv, idle, true, now); r.Queued != nil {
t.Errorf("idle: %q", r.Queued)
}
}
6 changes: 4 additions & 2 deletions internal/transcript/ingest.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ package transcript
// Left raw on purpose, because code matches them rather than draws them:
// SessionID, FilePath, PeerRef.Key and .Addr (the other end's copy and
// socket path are compared byte for byte), Pending's raw tool input (decoded
// where it is drawn, and cleaned after decoding: DecodeClean), and PRs
// (validated as github.com addresses before use).
// where it is drawn, and cleaned after decoding: DecodeClean), PRs
// (validated as github.com addresses before use), and a queued message's key
// and queueTaken (matched against the copy taken in; its Text is cleaned by
// noteEnqueued, not cleanSince, since the capped queue can keep its length).

// ingestMark is how far each record list had got before a line was applied:
// everything at or past it is new and still raw.
Expand Down
Loading
Loading