From 6454f2d6e324f07d99f62548dd0da58639859c96 Mon Sep 17 00:00:00 2001 From: Bharat Kunwar Date: Fri, 20 Nov 2026 19:44:57 +0545 Subject: [PATCH] feat: list Claude subagents as rows nested under their session MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex subagents and codex exec runs already appear as their own rows nested under the session that ran them; Claude Code subagents and teammates only showed as the pink ◆N count. Now each live Claude session's subagents get rows of their own, nested └ under it, with a pink ◆ glyph and "subagent" on the grey row. A row is listed while the subagent is alive (not finished, started by the session's current claude process) and for closedCooldown (30m) after it finishes, marked closed, then dropped. Only live sessions' subagents are looked at. The rows are read in the live tick, off the UI goroutine, through the shared SubagentsOf cache: each transcript is read whole once, then only appended lines, and nothing is read while drawing. Rows are read-only: they preview, have no message box, Enter opens the parent session, and fork, delete, rename, prune, pin and snooze are refused with a grey note. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 5 +- README.md | 2 +- internal/transcript/subagentrows.go | 72 ++++++++ internal/transcript/transcript.go | 13 +- internal/tui/live.go | 41 +++++ internal/tui/parse.go | 5 + internal/tui/preview.go | 8 +- internal/tui/subagents.go | 186 +++++++++++++++++++++ internal/tui/subagents_test.go | 244 ++++++++++++++++++++++++++++ internal/tui/tree.go | 3 + internal/tui/ui.go | 26 ++- 11 files changed, 594 insertions(+), 11 deletions(-) create mode 100644 internal/transcript/subagentrows.go create mode 100644 internal/tui/subagents.go create mode 100644 internal/tui/subagents_test.go diff --git a/AGENTS.md b/AGENTS.md index 2eb7e40..94e6d36 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -78,6 +78,7 @@ Install the release locally: `brew update && brew upgrade ccs`. - `update.go` - the update checks and offer, installing and restarting, the changelog popups and restore-after-restart state; the update machinery itself is `internal/selfupdate` - `usage.go` - usage screen, allowance, keychain, cswap account switcher - `tasks.go` - which of a session's background tasks and subagents are running (`runningTasks`, `runningSubagents`), the list's ⧗ count and the preview's Tasks and Subagents lines; reading them from the transcript is `internal/transcript` +- `subagents.go` - Claude Code subagents as list rows of their own, nested under their session (see `transcript.SubagentsOf` below) - `organise.go` - what ccs remembers per session across runs (`sessionMarks` in `state.MarksPath`, `sessions.json` beside the settings): when you last looked at each (`Seen`), for done. `Since` is ccs's first run, so nothing that finished before it is done. Looking = selected with its preview drawn while ccs has the terminal's focus, marked seen only once the selection moves off it, so it keeps its place while you read; its circle stops showing it unread as soon as it is being looked at (`noteSeen`, from `Update`, keeps it in `viewing` meanwhile; `tea.WithReportFocus`, `blurred`; a terminal that doesn't report focus counts as focused), or opened with Enter (`markSeen` in `focusCmd`/`resumeCmd`); a session read in its own tab without ccs stays done until selected. Seen times over a year old are dropped on load. Pinned sessions (`Pinned`, in order; ^X P `togglePin`, Alt+↑/↓ `movePin`) sit in a `pinnedSection` above every state: a pinned family's `familyState` is negative, its place among the pins (`familyPin`, `sectionOf` folds them into one section, never grouped by folder). ^X S puts the selected session away (`snoozePopup`, `snoozeChoices`: settle, an hour, 4 hours, tomorrow 9:00) into the settled or snoozed section at the bottom (`putAway`, liveGroup 5/6): `Settled` keeps its last message's timestamp and wakes when that changes, `Snoozed` its wake time (expired ones dropped on load); waiting on a menu or prompt always wakes it; ^X S on a put-away session wakes it (`wake`) - Codex sessions in the list (no file of their own: parsing is `internal/transcript`, which are live, their status and delivery `internal/sessions`): `transcript.ParseCodexFile` reads a rollout (`$CODEX_HOME/sessions/YYYY/MM/DD/rollout-*.jsonl`) into a `transcript.Conversation` with `Kind` "codex" (session_meta: id, cwd, source; turn_context's model; user and assistant messages, Codex's own AGENTS.md and environment blocks left out by `transcript.codexHarness`; token_count's context and the window it states, `Conversation.Window`, read through `window()`; `CommandExecution` items that are a `transcript.GHPRCall` add the PRs they printed; task_started/task_complete for busy), cached in `transcript.ParseCache` and parsed again whole when it changes (`transcript.ParseAppended` hands Codex ones over). The title is the `ccs launch` name (its launch folder among the workspace roots), else Codex's from `session_index.jsonl` (`transcript.codexThreadNames`). `transcript.GetConversations` adds `transcript.CodexRollouts()` to the same worker pool. Live: `sessions.CodexLiveSessions` (as `sessions.LiveCodexSessions`, stubbed in tests; one look shared for `transcript.CodexLiveTTL`) is merged into `sessions.ScanSessions` and never kept from an earlier scan (`liveSession.codex`): each `codex` TUI (a tty, no subcommand) and its thread, from `resume `, else its `ccs launch` folder, else the latest rollout in its folder (`transcript.CodexProcCwd`, lsof) written since it started, since Codex doesn't hold the rollout open; status from the rollout's last turn event (`sessions.CodexStat`, also the fast tick's). Enter focuses its tab by pid as for Claude; otherwise `sessions.OpenResumeTab` and the exec-in-place path run `transcript.CodexResumeArgs` (`codex resume|fork ` with `transcript.CodexSandboxArgs`, shared with `ccs launch --codex`); the message box sends with `sessions.DeliverCodex` (`codex queue`); rename, delete and prune are refused with a grey note. A Codex row's grey line starts `codex`, the preview header has `Agent: ⬡ codex`, and `transcript.SearchTextOf` adds the kind so `codex` matches. Nesting: a `codex exec` seen running is linked to the live Claude session its process descends from (`sessions.NoteCodexExecs`, from each live tick: one `proc.PsTree` listing (pid, ppid, command; `sessions.codexExecArgs` finds the subcommand past option values), the parent chain walked to a live claude pid, the thread being the newest exec rollout in the run's folder begun since it started; kept in `codex-exec-parents.json` beside the marks via `sessions.ExecParentOf`, so it holds after the run exits and across restarts), and `spawnParent` uses that link first; a run ccs never saw alive falls back to `transcript.IsSpawn` counting `codex exec`, so one whose prompt is on the command line nests under the Claude session that ran it; one whose prompt is in a file (codex-delegate's `codex-run.sh -f`, which `transcript.StartsCodex` counts too) goes to the session whose Bash, its own or a subagent's (`transcript.SubagentSpawns`, read incrementally), started codex closest before the run began, within `codexStartWindow` (`codexStarter`, only sessions active then). Codex liveness for a claim (`sessions.CodexLive`) is a running process for a session ccs launched, else its transcript written within `sessions.CodexIdle` (12 hours): Codex sessions in VS Code or the desktop app have no TUI process to tie the thread to, so a process-based check would drop their claims; a subagent's `ParentID` (session_meta source.subagent.thread_spawn.parent_thread_id) is its parent in `spawnParent`. `ccs mcp` lists them with `kind codex` and how to resume them. Both glyphs are one cell in tmux (`narrowSymbols`) - `prs.go` - the PR lookup rounds (`prCmd`, `applyPRs`), the PRS column and the preview's PR lines; finding and looking up the PRs is `internal/github` @@ -144,7 +145,7 @@ Install the release locally: `brew update && brew upgrade ccs`. - `sortList()` / `startedAt()` / `liveGroup()` / `sortItems()` - list order: newest started first, so rows move only when a new session appears. Each sort works out once per item its `putAway` (`listItem.state`: awake, settled, snoozed) and `startedAt` (`listItem.started`: its `FirstTimestamp`, else its transcript's file birth, `fileBirth`, cached in `births`, else its `LastTimestamp`), and `sortItems` sorts through an index so comparisons never copy a `listItem`: put-away last, then search rank (`listItem.rank`), then started, newest first, then session id. A session's state, unread replies and PRs never reorder anything: the title's colour shows the state, and Tab (`nextWaiting`, by attention tier, whatever the list order) finds what needs you. `liveGroup` is only a session's state (waiting on a menu or prompt, asked something, idle with done included, busy, closed, put away), never a sort key. `Update` re-sorts after every message except those that only move the selection or scroll (`movesOnly`: the mouse, arrows, page keys; anything that reorders, such as pinning, sorts itself), keeping the cursor on its session: the selection never changes without the user, with one exception the user asks for by turning ^X A on: `autoSelect` (held.go) selects a session that starts waiting once they've stopped typing in ccs. Folders compare as a `group` value, never a built string, and `sortItems` reorders in place (`permute`), as does `nestFamilies` - `prCmd()` / `github.QueryPRs()` / `prInfo.status()` / `prLines()` / `prCell()` - a session's PRs are the `pr-link` records Claude Code writes whenever a gh command in it touches a PR, plus those a `gh pr create` or `gh pr merge` call printed (`transcript.GHPRCall`, `transcript.GHOutputPRs`: the address, or `Merged pull request owner/repo#N`), since Claude Code links none named only through shell variables, as in a loop (`Conversation.PRs`, github.com addresses only, validated by `transcript.PRURL` since they go into a GraphQL query). Its subagents' gh output counts too (`github.subagentPRs`, from `/subagents/` and its `workflows/*/`, read incrementally at most every `github.subagentPRsTTL`, and once none of them was written within `SubagentIdle` only again when the session's transcript grows or its subagents or workflows folder changes; the header's Tab hint asks for every session on every frame, so `nextWaiting` works out each session's attention once); everything goes through `github.PRsOf`, never `conv.PRs` alone. A PR only mentioned in other output never counts. `prCmd` runs from `Update`. The selected session's open PRs are refreshed once each time it's landed on (`prSelected`), and any not looked up yet are asked about too, in a request of their own (`prSelBusy`, `prSelAsked` stops retries until the next round) that never waits behind a round. Once a minute (`prNext`, after the previous round has drained) a round queues every PR not merged or closed of sessions live, active within `prScope` (7 days) or selected, `github.PRBatch` per request (`prQueue`), `prParallel` in flight (`prRound`), each applied as it lands; merged/closed PRs are asked once. A PR GitHub returns null for is `GONE` ("not found"), never left "checking…"; without gh it says it needs gh. `github.QueryPRs` asks about `github.PRBatch` PRs per `gh api graphql` call (aliased fields) and reads the data even when gh exits non-zero over a missing PR. "Ready to merge" is GitHub's `mergeStateStatus` CLEAN/HAS_HOOKS/UNSTABLE on an open non-draft PR with no failed check (UNSTABLE says "optional checks running" while the rollup is pending); `status()` groups the rest: needs you (conflicts, checks failing, named: the rollup's contexts, check runs whose conclusion `github.failedCheck` counts and commit statuses in FAILURE/ERROR, at most three then +N; "optional checks failing" for an UNSTABLE PR with a failed check: mergeable, but a failed optional check often skipped the build or deploy after it; unresolved review threads, after conflicts and failing checks but before any ready case, so a PR with one open is never ✓ (`Unresolved`, from `reviewThreads(first:100)` in the same batch query; with more threads than that and none of those unresolved, `ThreadsUnread` keeps it waiting, never ready); changes requested, behind), waiting (checks running, review required, draft, unknown), then merged, closed. The PRS column counts them by group (`prMark`, `prGroup`: `✓` ready, `✗` needs you, `◷` waiting, `○` draft, counted apart from waiting (`prDraft`), `+` merged (never a circle, which would read as a session's state); closed and not found left out; every count has its glyph, and `legendLines` explains them at the bottom of ? help), in GitHub's colours: green ready, amber waiting, grey draft or not looked up yet, red to fix or closed, purple merged; the preview header lists open PRs in that order (at most `github.MaxPRLines`) and one line counting merged/closed; ^O lists all of them first (`linksWithPRs`), then the session's artifacts (`artifactLinks`). No gh on PATH: `fetchPRs` is nil and nothing is looked up - `transcript.noteCall()` / `transcript.noteResult()` / `transcript.noteEnds()` / `runningTasks()` / `taskLines()` - background tasks: Bash run in the background and Monitors (subagents are counted apart, below, so never twice). A Bash or Monitor call (`conv.calls`) becomes a task (`conv.tasks`, `transcript.BgTask`) when its result starts with Claude Code's own words for it ("Command running in background", "Monitor started" with its expiry); anywhere else in a result it's only output mentioning them. A `` line marks one completed, failed or stopped by its tool-use id. Running = no end yet, the session open in claude, started after its current claude process (`lastScan`'s procStart: a resume or exit takes tasks with it unreported), and a monitor not past its expiry. A task killed without a notification still counts as running (its output file ends "[killed]"; not read). The list shows `⧗N` in its own light blue (`transcript.TaskColour`; on the sidebar's title row, before HITS while searching (which stay lined up at the edge), so the grey row below keeps the PRs to itself; the table after the title); the preview lists up to `transcript.MaxTaskLines` with kind and age, then one line counting the ended -- `transcript.SubagentsOf()` / `runningSubagents()` / `subagentLines()` - a session's subagents (Agent tool, async or teammates), from the `meta.json` Claude Code writes beside each transcript in `/subagents/` (name or description, `finished`), started at the transcript's first line; read at most every `transcript.subagentsTTL` (2s; a meta.json parsed again only when its time changes, a start time kept once a line gave it) per session. They never appear in the list, only as a pink `◆N` running count beside the ⧗ (`transcript.SubagentColour`) and a Subagents block in the preview header: one line per running one (at most `transcript.MaxTaskLines`, with age), then a count of idle, finished and ended with the session. Running = not finished (older Claude Code wrote no flag; a finished one whose transcript was written over `transcript.subagentResumed`, 5s, after its meta.json was resumed by a SendMessage, since Claude Code leaves the flag set), the session open in claude, started by its current claude process (`procStart`: a resume or exit takes them with it), and its transcript written within `transcript.SubagentIdle` (10 min); alive but quiet longer is idle (a teammate waiting for work or shutdown). A start time comes from the first of a transcript's first lines with a timestamp, else its file date +- `transcript.SubagentsOf()` / `runningSubagents()` / `subagentLines()` - a session's subagents (Agent tool, async or teammates), from the `meta.json` Claude Code writes beside each transcript in `/subagents/` (name or description, `finished`), started at the transcript's first line; read at most every `transcript.subagentsTTL` (2s; a meta.json parsed again only when its time changes, a start time kept once a line gave it) per session. Each also has a row of its own (`subagents.go`): every live tick, off the UI goroutine, `liveCmd` hands the live Claude sessions (`subagentParents`; headless ones only with --all) to `subagentRowsFor`, which keeps those `listedSubagent` says (started by the current claude process; not finished, or finished within `closedCooldown`) and reads each through `transcript.SubagentConv` (`Kind` `transcript.KindSubagent`, `SessionID` its `agent-`, `ParentID` its session, titled by its meta.json; read whole once, `transcript.SubagentReads` counts that, then only appended lines via `ParseAppended`), under `sessions.LiveReads` (`subagentRowsKey`) and the tick's deadline; `applySubagents` rebuilds the rows when the set changes and hands grown ones to `applyLive`, `applyRefresh` keeps them (the scan never lists them) and `m.subagents` keeps their meta for `subagentAliveRow` and `subagentTitleColour` (amber writing, plain idle, grey finished). Nothing is read while drawing. A row is read-only: no message box (not live), Enter opens its session (`resumeCmd`/`focusCmd` swap in `subagentParentOf`), ^F and ^X D/E/X/P/S are refused with `subagentNote` (`refuseSubagent`); `AgentGlyph` gives it a pink ◆ and the grey row and preview say `subagent`. The session keeps its pink `◆N` running count beside the ⧗ (`transcript.SubagentColour`) and a Subagents block in the preview header: one line per running one (at most `transcript.MaxTaskLines`, with age), then a count of idle, finished and ended with the session. Running = not finished (older Claude Code wrote no flag; a finished one whose transcript was written over `transcript.subagentResumed`, 5s, after its meta.json was resumed by a SendMessage, since Claude Code leaves the flag set), the session open in claude, started by its current claude process (`procStart`: a resume or exit takes them with it), and its transcript written within `transcript.SubagentIdle` (10 min); alive but quiet longer is idle (a teammate waiting for work or shutdown). A start time comes from the first of a transcript's first lines with a timestamp, else its file date - `transcript.FormatAgo()` - WHEN column: time since the last message (`now`, `5m ago` ... `1y ago`), recomputed each frame; replaces the absolute date in the list (full timestamps stay searchable) - `transcript.FormatTokens()` / `Conversation.ContextTokens` - CTX column: context size as of the last reply (input + cache reads + cache writes from its `usage`; zero-usage placeholder replies skipped) - `transcript.ContextWindow()` / `transcript.CtxColour()` - CTX column traffic light (green/yellow/amber/red/flashing, thresholds scaled to a 200k or 1M window inferred from the model, or proven 1M by a context over 200k) @@ -197,7 +198,7 @@ Install the release locally: `brew update && brew upgrade ccs`. - `renameConversation()` / `appendLine()` - Ctrl+X E (edit its name) rename: appends a `custom-title` line like `/rename`; refused on live sessions since a running claude re-appends its own title - `Conversation.Spawned` - first user line has `entrypoint: sdk-cli` or a `teamName`: a candidate for nesting under the session that started it. A teammate keeps its team as `Conversation.Team`, and `spawnParent` puts it under the team's lead (`teamLeadOf`: `transcript.TeamLead`, the `leadSessionId` in the Claude folder's `teams//config.json`, kept once found; with the config gone, the listed session whose id starts as a `session-` team name says, `transcript.TeamSessionPrefix`), never by prompt matching, which can't find one. Apps you type in start sessions as `cli`, `claude-desktop` or `sdk-ts` (T3 Code); `sdk-cli` is `claude -p` and the Agent SDK's CLI - `Conversation.headless()` / `hideHeadless()` / `showHeadless` - a one-shot run nobody talks to is headless: `sdk-cli` with a single `promptId` (a second prompt, anything that talked to it, flips it back) and no user-set name, or a `codex exec`. `hideHeadless` (from `updateFilter`, after the search, so the search can't find them either) leaves them out unless `--all` (`showHeadless`), pinned, or opened through `selectSession` (`revealed`); nesting under a shown session doesn't keep one (a script's `claude -p` loop would hang dozens under it), and running doesn't count, since a backtest runs dozens at once. ^X H flips `showHeadless` live (`lastFilterQuery` reset so a search doesn't narrow from the list that hid them; cursor kept; not saved, but an update restart carries it in `uiState.Headless`, nil from an older ccs keeps the flag's). Nothing on screen says they are hidden; ^X H is listed only in ? help, `--help` and the README. `ccs mcp`'s list and search skip them unless `include_headless`; `read_session` reads any -- `nestFamilies()` / `spawnParent()` / `findSpawnParent()` / `transcript.SpawnCmd` - a spawned session sits under the session that started it, marked `└` (`listItem.depth`). Claude Code records no parent, so `transcript.trackTools` keeps each `claude -p` / `cswap run` Bash command a session runs (`Conversation.spawns`, text normalised by `transcript.SpawnText`), and the parent is the session whose command holds the child's first prompt within 10 minutes before it began (2 for a prompt under 20 characters), the closest in time; found once and cached in `m.parents`, a miss retried when the list grows. `sortList` nests after sorting: a family sits where its first member landed, its newest-started session's place, so only a new session in it moves it; ^X G groups a family by its top session's folder (`familyCwd`). A child nests under its parent when that is shown, else under the nearest shown session above it (`shownAncestor`: launch parent or spawn parent, up to five levels), so a headless codex exec's subagents sit under the Claude session that ran the exec. Esc on a nested row selects its parent row (`parentRow`: the nearest shallower row above, which is always listed, since a fold or closed line hides a parent's tree with it), one level a press with the search kept; at a top-level row Esc clears the search and goes to the top as before +- `nestFamilies()` / `spawnParent()` / `findSpawnParent()` / `transcript.SpawnCmd` - a spawned session sits under the session that started it, marked `└` (`listItem.depth`). Claude Code records no parent, so `transcript.trackTools` keeps each `claude -p` / `cswap run` Bash command a session runs (`Conversation.spawns`, text normalised by `transcript.SpawnText`), and the parent is the session whose command holds the child's first prompt within 10 minutes before it began (2 for a prompt under 20 characters), the closest in time; found once and cached in `m.parents`, a miss retried when the list grows. `sortList` nests after sorting: a family sits where its first member landed, its newest-started session's place, so only a new session in it moves it; ^X G groups a family by its top session's folder (`familyCwd`). A child nests under its parent when that is shown, else under the nearest shown session above it (`shownAncestor`: launch parent or spawn parent, up to five levels), so a headless codex exec's subagents sit under the Claude session that ran the exec. A Claude subagent's row (`transcript.KindSubagent`) is `Spawned` with its session as `ParentID`, so it nests the same way, and counts as running while not finished (`subagentAliveRow`), so it never waits behind a closed line. Esc on a nested row selects its parent row (`parentRow`: the nearest shallower row above, which is always listed, since a fold or closed line hides a parent's tree with it), one level a press with the search kept; at a top-level row Esc clears the search and goes to the top as before - `transcript.PruneFile()` / `transcript.pruneStream()` - Shrink a conversation by dropping duplicate/redundant data (never touches user/assistant lines) - `transcript.RunPrune()` - `ccs prune` subcommand driver diff --git a/README.md b/README.md index ce6f12d..5e00d77 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ Launch, watch, search and resume your coding CLI sessions: [Claude Code](https:/ - Preview conversation context with search term highlighting - See context size (tokens as of the last reply), message counts, hit counts, and file size per conversation - Resume conversations directly from the search interface -- Background tasks and subagents: a session open in `claude` shows `⧗N` for its running background commands and monitors and a pink `◆N` for its running subagents, and the preview lists both with how long each has run +- Background tasks and subagents: a session open in `claude` shows `⧗N` for its running background commands and monitors and a pink `◆N` for its running subagents, and the preview lists both with how long each has run. Its subagents and teammates (Agent tool) also get rows of their own, nested `└` under it with a pink `◆` and `subagent` on the grey row, while they run and for 30 minutes after one finishes (marked `closed`), then they leave the list; only a running session's are shown. Selecting one previews its transcript; it has no message box, Enter opens its session, and delete, rename, prune, fork, pin and snooze are refused - Every count in the list has its own glyph, explained at the bottom of `?` help: `⌕N` search hits, and each session's PRs as `✓` ready, `✗` needs you, `◷` waiting (checks running, review required, blocked), `○` draft, `+` merged - Auto-refreshes every minute; a green `●` marks conversations open in a running `claude`, and ones started by another session's `claude -p` sit `└` under it - Artifacts: the claude.ai pages a session (or its subagents) published, opened or read with Claude Code's Artifact tool show on the preview's `Artifacts:` line (the latest, and how many more), and `Ctrl+O` lists them all by title, after its PRs, to open with Enter diff --git a/internal/transcript/subagentrows.go b/internal/transcript/subagentrows.go new file mode 100644 index 0000000..46e457c --- /dev/null +++ b/internal/transcript/subagentrows.go @@ -0,0 +1,72 @@ +package transcript + +import ( + "os" + "strings" + "sync/atomic" +) + +// KindSubagent is a Claude Code subagent (Agent tool, async or a teammate) +// listed as a row of its own under the session running it: its transcript +// is /subagents/agent-.jsonl, which GetConversations never +// reads. Rows are read-only: a subagent has no session file or socket. +const KindSubagent = "subagent" + +// SubagentConv is s, one of parent's subagents, as a Conversation: SessionID +// s.ID, Kind KindSubagent, ParentID the parent's session, titled by its +// meta.json. With prev (the last read of it) only the lines appended since +// are parsed (ParseAppended); without, a copy cached at the file's size and +// time is reused, else it's read whole once. +func SubagentConv(prev *Conversation, parent Conversation, s Subagent) (*Conversation, error) { + if prev != nil && prev.FilePath == s.Path { + return ParseAppended(prev) + } + info, err := os.Stat(s.Path) + if err != nil { + return nil, err + } + ParseCacheMu.Lock() + cached, ok := ParseCache[s.Path] + ParseCacheMu.Unlock() + if ok && cached.size == info.Size() && cached.modTime.Equal(info.ModTime()) { + if cached.conv == nil { + return nil, nil + } + c := *cached.conv + return &c, nil + } + return parseSubagentWhole(s.Path, parent.SessionID, s.Name, parent.Cwd) +} + +// SubagentReads counts whole reads of subagent transcripts; tests use it to +// see a row isn't read again until its file changes. +var SubagentReads atomic.Int64 + +// parseSubagentWhole reads a subagent's transcript whole and caches it in +// ParseCache by its size and time, like any transcript. +func parseSubagentWhole(path, parentID, name, cwd string) (*Conversation, error) { + info, err := os.Stat(path) + if err != nil { + return nil, err + } + SubagentReads.Add(1) + conv, err := ParseConversationUncached(path, info) + if err != nil { + return nil, err + } + if conv != nil { + conv.Kind, conv.ParentID, conv.Spawned = KindSubagent, parentID, true + if name != "" { + conv.Title = name // meta.json's, cleaned as it was read + } + if conv.Cwd == "unknown" && cwd != "" { + conv.Cwd = cwd + } + conv.SearchText = SearchTextOf(*conv) // with its kind and title + conv.SearchLower = strings.ToLower(conv.SearchText) + } + ParseCacheMu.Lock() + ParseCache[path] = parsedFile{info.Size(), info.ModTime(), conv} + ParseCacheMu.Unlock() + return conv, nil +} diff --git a/internal/transcript/transcript.go b/internal/transcript/transcript.go index b5388a9..782e10c 100644 --- a/internal/transcript/transcript.go +++ b/internal/transcript/transcript.go @@ -443,6 +443,9 @@ func ParseAppended(prev *Conversation) (*Conversation, error) { return &c, nil } if info.Size() < prev.Size || prev.TailApplied || prev.ParsedBytes > info.Size() { + if prev.Kind == KindSubagent { // ParseConversationFile skips agent-*.jsonl + return parseSubagentWhole(prev.FilePath, prev.ParentID, prev.Title, prev.Cwd) + } return ParseConversationFile(prev.FilePath, time.Time{}, 0) } file, err := os.Open(prev.FilePath) @@ -1103,6 +1106,9 @@ func (c Conversation) Questions() []askQuestion { // --all (showHeadless). Apps you type in start sessions as cli, // claude-desktop or sdk-ts, never sdk-cli. func (c Conversation) Headless() bool { + if c.Kind == KindSubagent { // listed only while its session runs it (SubagentConv) + return false + } if c.Kind == KindCodex { return c.CodexExec && !c.IsCustomTitle } @@ -1654,6 +1660,9 @@ func AgentGlyph(conv Conversation) (glyph, colour string) { if conv.Kind == KindCodex { return "⬡", "37" } + if conv.Kind == KindSubagent { // the ◆ its session's count uses + return "◆", SubagentColour + } return "✻", "38;5;173" } @@ -2111,6 +2120,8 @@ const MaxTaskLines = 5 // included), from the meta.json Claude Code writes beside its transcript in // /subagents/. type Subagent struct { + ID string // its transcript's name without .jsonl (agent-): its row's SessionID (SubagentConv) + Path string // its transcript Name string Started time.Time LastWrite time.Time // its transcript's: a working subagent writes every few seconds @@ -2197,8 +2208,8 @@ func SubagentsOf(conv Conversation) []Subagent { c.name = CleanText(meta.Description) } } - s := Subagent{Name: c.name, Finished: c.finished} transcript := strings.TrimSuffix(path, ".meta.json") + ".jsonl" + s := Subagent{ID: strings.TrimSuffix(filepath.Base(transcript), ".jsonl"), Path: transcript, Name: c.name, Finished: c.finished} s.Started = c.subagentStarted(transcript) subagentCache.metas[path] = c if info, err := os.Stat(transcript); err == nil { diff --git a/internal/tui/live.go b/internal/tui/live.go index 9a18090..9ecc4f2 100644 --- a/internal/tui/live.go +++ b/internal/tui/live.go @@ -65,6 +65,11 @@ type liveMsg struct { hosts map[string]string // live sessions run by an app, not in a terminal: the app's name bg map[string]sessions.BgSession // background sessions (claude --bg); nil when not asked this tick gen int + // The live sessions' subagent rows (subagents.go) and their meta, when + // subsKnown: read in time this tick, so a missing row was dropped. + subRows []transcript.Conversation + subStats map[string]transcript.Subagent + subsKnown bool } func liveTick() tea.Cmd { @@ -111,6 +116,26 @@ func (m model) liveCmd(askAgents bool) tea.Cmd { } var mu sync.Mutex var wg sync.WaitGroup + // The live sessions' subagent rows, beside the transcript reads + // and under the same deadline; one still stuck from an earlier + // tick isn't started again, and its rows stand meanwhile. + if _, busy := sessions.LiveReads.LoadOrStore(subagentRowsKey, true); !busy { + starts := make(map[string]string, len(scanned)) + for id, s := range scanned { + starts[id] = s.Start + } + parents, since, prevSubs := subagentParents(byID, live, starts) + wg.Add(1) + go func() { + defer wg.Done() + defer sessions.LiveReads.Delete(subagentRowsKey) + defer transcript.RecoverWorker() + rows, subs := subagentRowsFor(parents, since, prevSubs, time.Now()) + mu.Lock() + msg.subRows, msg.subStats, msg.subsKnown = rows, subs, true + mu.Unlock() + }() + } for id := range check { conv, ok := byID[id] if !ok { @@ -259,6 +284,14 @@ func (m *model) opening(id string, fork bool) bool { // exited, or whose file can't be read right now, is reported instead of // resumed a second time. func (m *model) focusCmd(conv transcript.Conversation) tea.Cmd { + if conv.Kind == transcript.KindSubagent { // it runs inside its session: that's what opens + p, ok := m.subagentParentOf(conv) + if !ok { + m.note(subagentNote) + return nil + } + conv = p + } if m.inT3(conv.SessionID) { return m.openT3Cmd(conv) } @@ -284,6 +317,14 @@ func (m *model) focusCmd(conv transcript.Conversation) tea.Cmd { // a session resumed elsewhere since the last live tick is focused, not // resumed a second time. Forks always open a new session. func (m *model) resumeCmd(conv transcript.Conversation, fork bool) tea.Cmd { + if conv.Kind == transcript.KindSubagent { // Enter opens its session; there's nothing of its own to fork + p, ok := m.subagentParentOf(conv) + if fork || !ok { + m.note(subagentNote) + return nil + } + conv = p + } if !fork && m.inT3(conv.SessionID) { return m.openT3Cmd(conv) } diff --git a/internal/tui/parse.go b/internal/tui/parse.go index dd5439c..70925d4 100644 --- a/internal/tui/parse.go +++ b/internal/tui/parse.go @@ -117,6 +117,11 @@ func (m *model) applyRefresh(msg refreshMsg) { selectedID = m.filtered[m.cursor].conv.SessionID } prevScroll := m.previewScroll + for _, it := range m.items { // subagent rows come from the live tick, not the scan + if it.conv.Kind == transcript.KindSubagent { + msg.items = append(msg.items, it) + } + } m.items = msg.items m.lastFilterQuery = "" // force a full rescan, not incremental narrowing m.hits = &hitCounter{byID: make(map[string]int)} diff --git a/internal/tui/preview.go b/internal/tui/preview.go index c9ae48f..f070859 100644 --- a/internal/tui/preview.go +++ b/internal/tui/preview.go @@ -928,9 +928,9 @@ const ( // (under 40 columns the time goes too), never the glyph. func (m model) headerSummary(conv transcript.Conversation, query, when string) string { parts := []string{highlight(transcript.Truncate(filepath.Base(conv.Cwd), 24), query)} - if conv.Kind == transcript.KindCodex { + if conv.Kind != "" { // codex, or a Claude subagent glyph, colour := transcript.AgentGlyph(conv) - parts = append(parts, "\033["+colour+"m"+glyph+"\033[0m codex") + parts = append(parts, "\033["+colour+"m"+glyph+"\033[0m "+conv.Kind) } if conv.LastError != "" { parts = append(parts, "\033[1;31m! "+conv.LastError+"\033[0m") @@ -1049,9 +1049,9 @@ func (m model) renderPreview(item listItem, height int) string { // sessionStats is the preview header's model, token and error lines. func sessionStats(conv transcript.Conversation) []string { var lines []string - if conv.Kind == transcript.KindCodex { + if conv.Kind != "" { glyph, colour := transcript.AgentGlyph(conv) - lines = append(lines, "\033[1;33mAgent:\033[0m \033["+colour+"m"+glyph+"\033[0m codex") + lines = append(lines, "\033[1;33mAgent:\033[0m \033["+colour+"m"+glyph+"\033[0m "+conv.Kind) } if conv.ActiveModel != "" || conv.ContextTokens > 0 { window := conv.WindowSize() diff --git a/internal/tui/subagents.go b/internal/tui/subagents.go new file mode 100644 index 0000000..023dade --- /dev/null +++ b/internal/tui/subagents.go @@ -0,0 +1,186 @@ +package tui + +import ( + "strings" + "time" + + "github.com/agentic-utils/ccs/internal/transcript" +) + +// Claude Code subagents as rows of their own, nested └ under the session +// running them, as Codex subagents and codex exec runs are. Listed while +// alive (not finished, started by the session's current claude process: +// transcript.SubagentAlive) and for closedCooldown after one finishes, +// marked closed, then dropped: a busy session runs dozens a day, and its +// ◆N count and Subagents lines still cover every one. Only a live session's +// are looked at, so nothing is read for the thousands of finished ones. + +// subagentRowsKey holds sessions.LiveReads while a tick reads subagent rows, +// so one stuck on a hung mount isn't started again. +const subagentRowsKey = "\x00subagent-rows" + +// procStartOf parses a session file's procStart (time.ANSIC, spaces evened). +func procStartOf(start string) time.Time { + t, _ := time.Parse(time.ANSIC, strings.Join(strings.Fields(start), " ")) + return t +} + +// listedSubagent: s is shown as a row under a session whose claude process +// started at since. +func listedSubagent(s transcript.Subagent, since, now time.Time) bool { + if s.Started.Before(since) { // an earlier process's: it ended with it + return false + } + return !s.Finished || now.Sub(s.LastWrite) < closedCooldown +} + +// subagentRowsFor is the subagent rows of parents (live Claude sessions), +// each read through transcript.SubagentConv from prev, its last read, so an +// unchanged transcript isn't read again and a growing one only from where +// it was. transcript.SubagentsOf's cache (subagentsTTL) is shared with the +// ◆ count, so the listing costs no extra globbing. Off the UI goroutine +// (liveCmd). subs is each listed one's meta, by row id. +func subagentRowsFor(parents []transcript.Conversation, starts map[string]time.Time, prev map[string]transcript.Conversation, now time.Time) (rows []transcript.Conversation, subs map[string]transcript.Subagent) { + subs = map[string]transcript.Subagent{} + for _, p := range parents { + for _, s := range transcript.SubagentsOf(p) { + if !listedSubagent(s, starts[p.SessionID], now) { + continue + } + var last *transcript.Conversation + if c, ok := prev[s.ID]; ok { + last = &c + } + c, err := transcript.SubagentConv(last, p, s) + if err != nil || c == nil { + continue + } + rows = append(rows, *c) + subs[s.ID] = s + } + } + return rows, subs +} + +// subagentParents is what liveCmd hands subagentRowsFor, from byID (its +// copy of the list): the live Claude sessions (headless ones only with +// --all), their claude process's start, and the subagent rows as last read. +func subagentParents(byID map[string]transcript.Conversation, live map[string]bool, starts map[string]string) ([]transcript.Conversation, map[string]time.Time, map[string]transcript.Conversation) { + var parents []transcript.Conversation + since := map[string]time.Time{} + prev := map[string]transcript.Conversation{} + for _, c := range byID { + switch { + case c.Kind == transcript.KindSubagent: + prev[c.SessionID] = c + case c.Kind == "" && live[c.SessionID] && (showHeadless || !c.Headless()): + parents = append(parents, c) + since[c.SessionID] = procStartOf(starts[c.SessionID]) + } + } + return parents, since, prev +} + +// applySubagents brings the subagent rows in m.items up to rows: a set that +// changed (one started, or dropped) is rebuilt and the list filtered and +// sorted again, keeping the selection and its scroll; otherwise the rows +// whose transcript grew are returned for applyLive, as a live session's are. +func (m *model) applySubagents(rows []transcript.Conversation, subs map[string]transcript.Subagent) []transcript.Conversation { + m.subagents = subs + have := map[string]int64{} + for _, it := range m.items { + if it.conv.Kind == transcript.KindSubagent { + have[it.conv.SessionID] = it.conv.Size + } + } + same := len(have) == len(rows) + var grew []transcript.Conversation + for _, c := range rows { + size, ok := have[c.SessionID] + if !ok { + same = false + break + } + if size != c.Size { + grew = append(grew, c) + } + } + if same { + return grew + } + var selectedID string + if len(m.filtered) > 0 { + selectedID = m.filtered[m.cursor].conv.SessionID + } + scroll := m.previewScroll + items := make([]listItem, 0, len(m.items)+len(rows)) + for _, it := range m.items { + if it.conv.Kind != transcript.KindSubagent { + items = append(items, it) + } + } + m.items = append(items, buildItems(rows)...) + m.lastFilterQuery = "" // a full pass: the new rows were never matched + m.updateFilter() + if i := m.cursorOf(selectedID); i >= 0 { + m.cursor = i + m.previewScroll = min(scroll, m.maxPreviewScroll()) + } + return nil +} + +// cursorOf is id's place in m.filtered, -1 if it isn't shown. +func (m model) cursorOf(id string) int { + for i, it := range m.filtered { + if it.conv.SessionID == id { + return i + } + } + return -1 +} + +// subagentAliveRow: c is a subagent row whose subagent hasn't finished, so +// its family counts as running (nestFamilies) and it isn't marked closed. +func (m model) subagentAliveRow(c transcript.Conversation) bool { + if c.Kind != transcript.KindSubagent { + return false + } + s, ok := m.subagents[c.SessionID] + return ok && !s.Finished +} + +// subagentTitleColour is a subagent row's title colour: amber while it +// writes (transcript.SubagentIdle), plain when an idle teammate, grey once +// finished. +func (m model) subagentTitleColour(c transcript.Conversation) string { + s, ok := m.subagents[c.SessionID] + switch { + case !ok || s.Finished: + return "90" + case time.Since(s.LastWrite) < transcript.SubagentIdle: + return amber + } + return "" +} + +// subagentParentOf is the listed session running subagent row c. +func (m *model) subagentParentOf(c transcript.Conversation) (transcript.Conversation, bool) { + if i, ok := m.itemAt(c.ParentID); ok { + return m.items[i].conv, true + } + return transcript.Conversation{}, false +} + +// refuseSubagent: the selected row is a subagent, which has no session of +// its own to fork, rename, prune, delete, pin or put away; says so with a +// grey note. +func (m *model) refuseSubagent() bool { + if len(m.filtered) == 0 || m.filtered[m.cursor].conv.Kind != transcript.KindSubagent { + return false + } + m.note(subagentNote) + return true +} + +// subagentNote is the grey note for anything a subagent row can't do. +const subagentNote = "A subagent: it runs inside its session, which Enter opens; select that for anything else" diff --git a/internal/tui/subagents_test.go b/internal/tui/subagents_test.go new file mode 100644 index 0000000..d489144 --- /dev/null +++ b/internal/tui/subagents_test.go @@ -0,0 +1,244 @@ +package tui + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" + + "github.com/agentic-utils/ccs/internal/sessions" + "github.com/agentic-utils/ccs/internal/transcript" +) + +// subagentFixture writes a parent session's transcript and, under its +// subagents/ folder, made-up subagents: worker (running), helper (an idle +// teammate, quiet for an hour), recent (finished a minute ago), old +// (finished two hours ago) and before (from a claude process before the +// current one). It returns the parent and when its process started. +func subagentFixture(t *testing.T) (transcript.Conversation, time.Time, string) { + t.Helper() + dir := t.TempDir() + path := filepath.Join(dir, "s1.jsonl") + os.WriteFile(path, []byte(`{"type":"user","message":{"content":"fix the flaky test"},"timestamp":"2026-11-20T09:00:00Z","cwd":"`+dir+`"}`+"\n"), 0o600) + subs := filepath.Join(dir, "s1", "subagents") + os.MkdirAll(subs, 0o755) + since := time.Now().Add(-time.Hour) + write := func(name, meta string, started, last time.Time) { + os.WriteFile(filepath.Join(subs, "agent-"+name+".meta.json"), []byte(meta), 0o600) + tr := filepath.Join(subs, "agent-"+name+".jsonl") + ts := started.UTC().Format(time.RFC3339) + os.WriteFile(tr, []byte(fmt.Sprintf(`{"type":"user","isSidechain":true,"message":{"content":"look into %s"},"timestamp":%q}`+"\n"+ + `{"type":"assistant","isSidechain":true,"message":{"content":[{"type":"text","text":"on it"}]},"timestamp":%q}`+"\n", name, ts, ts)), 0o600) + os.Chtimes(tr, last, last) + os.Chtimes(filepath.Join(subs, "agent-"+name+".meta.json"), last, last) // written with its last line: not resumed + } + now := time.Now() + write("worker", `{"name":"worker"}`, now.Add(-5*time.Minute), now) + write("helper", `{"name":"helper"}`, now.Add(-50*time.Minute), now.Add(-45*time.Minute)) + write("recent", `{"name":"recent","finished":true}`, now.Add(-3*time.Minute), now.Add(-time.Minute)) + write("old", `{"name":"old","finished":true}`, now.Add(-55*time.Minute), now.Add(-50*time.Minute)) + write("before", `{"name":"before"}`, now.Add(-2*time.Hour), now.Add(-2*time.Hour)) + parent := transcript.Conversation{SessionID: "s1", Title: "parent", FilePath: path, Cwd: dir, + FirstTimestamp: "2026-11-20T09:00:00Z", LastTimestamp: "2026-11-20T09:00:00Z", + Messages: []transcript.Message{{Role: "user", Text: "fix the flaky test", Ts: "2026-11-20T09:00:00Z"}}} + return parent, since, subs +} + +func subagentModel(t *testing.T) (model, transcript.Conversation, string) { + t.Helper() + parent, since, subs := subagentFixture(t) + other := transcript.Conversation{SessionID: "s2", Title: "other", FirstTimestamp: "2026-11-20T08:00:00Z", LastTimestamp: "2026-11-20T08:00:00Z", + Messages: []transcript.Message{{Role: "user", Text: "hi", Ts: "2026-11-20T08:00:00Z"}}} + m := initialModel(buildItems([]transcript.Conversation{parent, other}), "", nil) + m.live = map[string]bool{"s1": true} + m.lastScan = map[string]sessions.LiveSession{"s1": {Start: since.UTC().Format(time.ANSIC)}} + m.width, m.height = 120, 40 + rows, st := subagentRowsFor([]transcript.Conversation{parent}, map[string]time.Time{"s1": since}, nil, time.Now()) + m.applySubagents(rows, st) + return m, parent, subs +} + +func listedIDs(m model) []string { + var ids []string + for _, it := range m.filtered { + ids = append(ids, fmt.Sprintf("%s@%d", it.conv.SessionID, it.depth)) + } + return ids +} + +// A live session's subagents are rows of their own, nested under it as a +// Codex subagent is: running and idle ones, and one finished within +// closedCooldown (marked closed); one finished long ago, or from an earlier +// claude process, isn't listed. +func TestSubagentRowsNestUnderTheirSession(t *testing.T) { + m, _, _ := subagentModel(t) + got := strings.Join(listedIDs(m), " ") + for _, want := range []string{"s1@0", "agent-worker@1", "agent-helper@1", "agent-recent@1", "s2@0"} { + if !strings.Contains(got, want) { + t.Errorf("want %s listed: %s", want, got) + } + } + if strings.Contains(got, "agent-old") || strings.Contains(got, "agent-before") { + t.Errorf("a long-finished subagent, or an earlier process's, isn't listed: %s", got) + } + if !strings.HasPrefix(got, "s1@0 agent-") { + t.Errorf("the subagents sit right under their session: %s", got) + } + var worker, recent listItem + for _, it := range m.filtered { + switch it.conv.SessionID { + case "agent-worker": + worker = it + case "agent-recent": + recent = it + } + } + if worker.conv.Title != "worker" || worker.conv.Kind != transcript.KindSubagent || worker.conv.ParentID != "s1" { + t.Errorf("a row titled by its meta.json, of kind subagent, under s1: %+v", worker.conv.Title) + } + row := m.sidebarRow(worker, false, 48) + if !strings.Contains(row[0], "\033["+transcript.SubagentColour+"m◆") || !strings.Contains(row[0], "\033["+amber+"mworker") { + t.Errorf("a running subagent: the pink ◆ and an amber title: %q", row[0]) + } + if !strings.Contains(strip2(row[1]), "subagent · ") { + t.Errorf("its grey row says it's a subagent: %q", strip2(row[1])) + } + if worker.cooling || !recent.cooling || !strings.Contains(strip2(m.sidebarRow(recent, false, 48)[1]), "closed") { + t.Errorf("only the finished one is marked closed: worker %v, recent %v", worker.cooling, recent.cooling) + } + if got := m.taskCell(m.filtered[0].conv, false); got != "◆1" { + t.Errorf("the session keeps its ◆ count of running subagents: %q", got) + } +} + +// A subagent's row is read-only: it previews, has no message box, Enter +// opens its session, and the actions on a session of its own are refused. +func TestSubagentRowIsReadOnly(t *testing.T) { + m, _, _ := subagentModel(t) + m.cursor = m.cursorOf("agent-worker") + m.marks = &sessionMarks{Seen: map[string]time.Time{}} + if m.selectedLive() { + t.Fatal("a subagent has no socket: no message box") + } + if p := strip2(m.renderPreview(m.filtered[m.cursor], 30)); !strings.Contains(p, "look into worker") || !strings.Contains(p, "◆ subagent") { + t.Errorf("its transcript previews, marked a subagent:\n%s", p) + } + for _, k := range []string{"e", "d", "x", "p", "s"} { + m2, _ := key(m, tea.KeyMsg{Type: tea.KeyCtrlX}) + m2, _ = key(m2, tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{rune(k[0])}}) + if m2.renaming || m2.confirmDelete || m2.confirmPrune || m2.snoozeOpen || m2.pinIndex("agent-worker") >= 0 || m2.errorMsg != subagentNote { + t.Errorf("^X %s on a subagent is refused with a note, got %q", strings.ToUpper(k), m2.errorMsg) + } + } + if up, _ := key(m, tea.KeyMsg{Type: tea.KeyEsc}); up.filtered[up.cursor].conv.SessionID != "s1" { + t.Errorf("Esc walks from a subagent to its session, got %s", up.filtered[up.cursor].conv.SessionID) + } + if _, cmd := key(m, tea.KeyMsg{Type: tea.KeyCtrlF}); cmd != nil { + t.Error("^F has nothing of its own to fork") + } + + old := liveSessionPIDs + t.Cleanup(func() { liveSessionPIDs = old }) + liveSessionPIDs = func() map[string]int { return map[string]int{"s1": 42} } + _, cmd := key(m, tea.KeyMsg{Type: tea.KeyEnter}) + if cmd == nil { + t.Fatal("Enter opens its session") + } + if msg, ok := cmd().(focusDoneMsg); !ok || msg.pid != 42 { + t.Errorf("Enter focuses the session running it (pid 42): %#v", msg) + } +} + +// Reads are the live tick's, never a frame's: drawing the list doesn't read +// a subagent's transcript, an unchanged one isn't read again on a tick, and +// a growing one is read only from where it was. +func TestSubagentRowsAreNotReadPerFrame(t *testing.T) { + m, parent, subs := subagentModel(t) + reads := transcript.SubagentReads.Load() + for range 50 { + m.View() + } + if transcript.SubagentReads.Load() != reads { + t.Errorf("drawing read subagent transcripts: %d reads", transcript.SubagentReads.Load()-reads) + } + since := time.Now().Add(-time.Hour) + prev := func() map[string]transcript.Conversation { + p := map[string]transcript.Conversation{} + for _, it := range m.items { + if it.conv.Kind == transcript.KindSubagent { + p[it.conv.SessionID] = it.conv + } + } + return p + } + for range 5 { + rows, st := subagentRowsFor([]transcript.Conversation{parent}, map[string]time.Time{"s1": since}, prev(), time.Now()) + if grew := m.applySubagents(rows, st); grew != nil { + t.Errorf("nothing grew: %d rows", len(grew)) + } + } + if transcript.SubagentReads.Load() != reads { + t.Errorf("unchanged transcripts were read again: %d reads", transcript.SubagentReads.Load()-reads) + } + f, _ := os.OpenFile(filepath.Join(subs, "agent-worker.jsonl"), os.O_APPEND|os.O_WRONLY, 0) + fmt.Fprintf(f, `{"type":"assistant","isSidechain":true,"message":{"content":[{"type":"text","text":"found it"}]},"timestamp":%q}`+"\n", time.Now().UTC().Format(time.RFC3339)) + f.Close() + rows, st := subagentRowsFor([]transcript.Conversation{parent}, map[string]time.Time{"s1": since}, prev(), time.Now()) + grew := m.applySubagents(rows, st) + if transcript.SubagentReads.Load() != reads { + t.Errorf("a growing transcript is read from where it was, not whole: %d reads", transcript.SubagentReads.Load()-reads) + } + if len(grew) != 1 || grew[0].SessionID != "agent-worker" || grew[0].Messages[len(grew[0].Messages)-1].Text != "found it" || grew[0].Kind != transcript.KindSubagent { + t.Fatalf("the grown row goes to applyLive, still a subagent: %+v", grew) + } + m.applyLive(grew) + m.sortList() // as Update does after every tick + if i := m.cursorOf("agent-worker"); i < 0 || m.filtered[i].depth != 1 { + t.Errorf("still nested after it grew: %v", listedIDs(m)) + } +} + +// The minute's full scan doesn't list subagents, so it keeps the rows the +// live tick read, selection included. +func TestRefreshKeepsSubagentRows(t *testing.T) { + m, _, _ := subagentModel(t) + m.cursor = m.cursorOf("agent-helper") + var scanned []transcript.Conversation + for _, it := range m.items { + if it.conv.Kind == "" { + scanned = append(scanned, it.conv) + } + } + m.applyRefresh(refreshMsg{items: buildItems(scanned)}) + if m.filtered[m.cursor].conv.SessionID != "agent-helper" { + t.Errorf("the selected subagent stays selected: %v", listedIDs(m)) + } + // Its session closed: the next tick lists none, and they go. + m.live = map[string]bool{} + rows, st := subagentRowsFor(nil, nil, nil, time.Now()) + m.applySubagents(rows, st) + if got := strings.Join(listedIDs(m), " "); strings.Contains(got, "agent-") { + t.Errorf("a closed session's subagents go with it: %s", got) + } +} + +// The live tick reads them: a live session's subagents appear after one. +func TestLiveTickListsSubagents(t *testing.T) { + parent, _, _ := subagentFixture(t) + m := initialModel(buildItems([]transcript.Conversation{parent}), "", nil) + dir := t.TempDir() + old := sessions.GetSessionsDir + sessions.GetSessionsDir = func() string { return dir } + t.Cleanup(func() { sessions.GetSessionsDir = old }) + fakeStart(t) + sessionFileFor(t, fmt.Sprintf(`{"pid":%d,"sessionId":"s1","status":"busy","procStart":%q}`, os.Getpid(), "Fri Sep 25 10:00:00 2026")) + m = liveTickOnce(m) + got := strings.Join(listedIDs(m), " ") + if !m.live["s1"] || !strings.Contains(got, "agent-worker@1") { + t.Errorf("after a live tick the session's subagents are listed under it: %s", got) + } +} diff --git a/internal/tui/tree.go b/internal/tui/tree.go index 6d5ea36..3d52d28 100644 --- a/internal/tui/tree.go +++ b/internal/tui/tree.go @@ -211,6 +211,9 @@ func (m model) treePrefix(it listItem) string { // running. func (m model) titleColour(it listItem) string { conv := it.conv + if conv.Kind == transcript.KindSubagent { + return m.subagentTitleColour(conv) + } if !m.live[conv.SessionID] { return "90" } diff --git a/internal/tui/ui.go b/internal/tui/ui.go index 632683b..32628fa 100644 --- a/internal/tui/ui.go +++ b/internal/tui/ui.go @@ -71,6 +71,8 @@ var selectedStyle = lipgloss.NewStyle(). // model is the bubbletea application state type model struct { + subagents map[string]transcript.Subagent // the subagent rows' meta, by row id, as of the last live tick (subagents.go) + items []listItem filtered []listItem textInput textinput.Model @@ -765,7 +767,7 @@ func (m *model) nestFamilies() { isAlive = func(i, d int) bool { if alive[i] == 0 { alive[i] = 2 - if c := m.filtered[i].conv; m.live[c.SessionID] || codexSubagentBusy(c) || justClosed(c) { + if c := m.filtered[i].conv; m.live[c.SessionID] || codexSubagentBusy(c) || m.subagentAliveRow(c) || justClosed(c) { alive[i] = 1 } for _, k := range kids[i] { @@ -786,7 +788,7 @@ func (m *model) nestFamilies() { } for i := range m.filtered { // a nested session that just closed: shown a while, marked c := m.filtered[i].conv - m.filtered[i].cooling = parent[i] >= 0 && !m.live[c.SessionID] && !codexSubagentBusy(c) && justClosed(c) + m.filtered[i].cooling = parent[i] >= 0 && !m.live[c.SessionID] && !codexSubagentBusy(c) && !m.subagentAliveRow(c) && justClosed(c) } order := make([]int, 0, n) // the new list, as indexes into m.filtered seen := make([]bool, n) @@ -988,7 +990,7 @@ var putAwaySections = [...]struct{ name, colour string }{ // spawnParent is the session whose claude -p started c, "" if none is known. // Found once and kept; a miss is retried when the list grows. func (m *model) spawnParent(c transcript.Conversation) string { - if c.ParentID != "" { // a Codex subagent names its parent thread + if c.ParentID != "" { // a Codex subagent names its parent thread, a Claude one's row its session return c.ParentID } if c.Team != "" { // an agent-team teammate: its team's lead @@ -1544,6 +1546,9 @@ func (m model) update(msg tea.Msg) (tea.Model, tea.Cmd) { m.live[id] = true } } + if msg.subsKnown && msg.gen == m.gen && !m.prompting() { + msg.updated = append(msg.updated, m.applySubagents(msg.subRows, msg.subStats)...) + } if len(msg.updated) > 0 && msg.gen == m.gen && !m.prompting() { m.applyLive(msg.updated) } @@ -1910,6 +1915,9 @@ func (m model) update(msg tea.Msg) (tea.Model, tea.Cmd) { } if k == "^x s" && len(m.filtered) > 0 && m.marks != nil && !m.prompting() && !m.acctOpen && !m.showUsage { m.helpOpen = false + if m.refuseSubagent() { + return m, nil + } if c := m.filtered[m.cursor].conv; m.putAway(c) != awake { stats.Record("tui.wake", stats.Key) m.wake(c.SessionID) @@ -2206,6 +2214,9 @@ func (m model) update(msg tea.Msg) (tea.Model, tea.Cmd) { if k == "^x p" && !m.prompting() && !m.acctOpen && !m.showUsage { stats.Record("tui.pin", stats.Key) m.helpOpen = false + if m.refuseSubagent() { + return m, nil + } m.togglePin() return m, nil } @@ -2640,6 +2651,9 @@ func (m model) update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, m.resumeCmd(m.filtered[m.cursor].conv, true) case "^x d": + if m.refuseSubagent() { + return m, nil + } if len(m.filtered) > 0 && m.filtered[m.cursor].conv.Kind == transcript.KindCodex { m.note("A Codex session: ccs leaves Codex's files alone (codex delete removes one)") return m, nil @@ -2656,6 +2670,9 @@ func (m model) update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, m.refreshNow() case "^x e": + if m.refuseSubagent() { + return m, nil + } if len(m.filtered) > 0 { conv := m.filtered[m.cursor].conv if conv.Kind == transcript.KindCodex { @@ -2681,6 +2698,9 @@ func (m model) update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, nil case "^x x": + if m.refuseSubagent() { + return m, nil + } if len(m.filtered) > 0 && m.filtered[m.cursor].conv.Kind == transcript.KindCodex { m.note("A Codex session: ccs only prunes Claude's transcripts") return m, nil