diff --git a/.changeset/tui-attach-by-name.md b/.changeset/tui-attach-by-name.md new file mode 100644 index 00000000..e2f22e3b --- /dev/null +++ b/.changeset/tui-attach-by-name.md @@ -0,0 +1,5 @@ +--- +'aicodeman': patch +--- + +`codeman tui ` attaches straight to the live session with that exact name, next to `codeman tui `. Digits only still mean a list number. Two live sessions sharing the name are refused with their numbers, a name only a finished session carries says so, and both refusals print without a terminal. diff --git a/CLAUDE.md b/CLAUDE.md index 9472b727..e396ff86 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -64,7 +64,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph **Requirements**: Node.js 22+, Claude CLI, tmux -**Git**: Main branch is `master`. Terminal session dashboard: `codeman tui` (`--list` to list, `codeman tui ` to attach). +**Git**: Main branch is `master`. Terminal session dashboard: `codeman tui` (`--list` to list, `codeman tui ` or `codeman tui ` to attach). ## Additional Commands diff --git a/docs/tui.md b/docs/tui.md index 92244f11..4a1f7581 100644 --- a/docs/tui.md +++ b/docs/tui.md @@ -7,7 +7,7 @@ tmux pane with one keystroke. It is **additional, not a replacement**: the web UI stays the primary surface and gets every feature first. The TUI exists for the terminal workflow (SSH, Termius, -a tmux window you keep open all day), and it is a *client* of the running server, +a tmux window you keep open all day), and it is a _client_ of the running server, so the two surfaces can never disagree about what a session is doing. It is also not a multiplexer: tmux still owns every pane, and attaching hands the terminal to tmux rather than proxying bytes. @@ -18,19 +18,20 @@ tmux rather than proxying bytes. codeman tui # the dashboard codeman tui --list # print the numbered session list and exit codeman tui 2 # attach straight to session 2 of that list +codeman tui api-docs # attach straight to the live session named api-docs ``` -The two fast paths are the scriptable ones. +The fast paths are the scriptable ones. Neither sets up a screen, so both are as quick as the one API call they make, and `--list` prints plain text when piped, so it composes with `grep`/`awk`. What it needs: -| Needs | What you get | -| --- | --- | +| Needs | What you get | +| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Full features** | A running Codeman server (states, approvals, preview, prompts, search, digest). The TUI finds it the way `codeman attach` does: `CODEMAN_API_URL`, else loopback on `CODEMAN_PORT` for this `CODEMAN_INSTANCE`. The self-signed certificate an `--https` install generates is accepted, as it is everywhere else in the CLI. | -| **Server down** | It still starts, in **degraded mode**: sessions are enumerated straight from `tmux -L codeman` plus a read-only peek at `state.json`, and attach is the only verb. See [Troubleshooting](#troubleshooting). | -| **A terminal** | `codeman tui` refuses to run when stdin/stdout are not a TTY, and says to use `--list` instead. A cron job or a pipe therefore fails loudly rather than emitting escape codes into a log. | +| **Server down** | It still starts, in **degraded mode**: sessions are enumerated straight from `tmux -L codeman` plus a read-only peek at `state.json`, and attach is the only verb. See [Troubleshooting](#troubleshooting). | +| **A terminal** | `codeman tui` refuses to run when stdin/stdout are not a TTY, and says to use `--list` instead. A cron job or a pipe therefore fails loudly rather than emitting escape codes into a log. | ## What it looks like @@ -84,17 +85,25 @@ The same world through `--list`: The numbers are the same on both surfaces, so `codeman tui --list` then `codeman tui 4` is one thought. +A number moves as sessions change state; a name does not. `codeman tui ` attaches to the +live session whose name is exactly `` (case-sensitive, never a prefix, never the folder), so +the same line gets you back into the same session from any folder or a fresh SSH login. Digits +only always mean a list number. Session names are not unique in Codeman, so when two live +sessions share the name it refuses and prints their numbers instead of guessing; a name only a +RECENT row carries says the session has finished. Both refusals are printed before the terminal +check, so a script can tell them apart without a TTY. + ## The four groups Groups are always in this order, and a session is in exactly one of them: -| Group | Glyph | Means | Comes from | -| --- | --- | --- | --- | -| **NEEDS YOU** | `⚠` | A permission or question dialog is blocking the agent | The approvals inbox (`permission_prompt` hooks, with the on-screen options parsed; for Codex, a dialog read off its screen) | -| | `✋` | Waiting for your next instruction, or errored | `idle_prompt`, or an errored session (equally something only a human clears) | -| **WORKING** | `✻` animating | A turn is running | The same working classification the web dashboard uses | -| **IDLE** | `○` | Live, but sitting there | | -| **RECENT** | `✔` | A past session from the unified list | History rows, no live pane | +| Group | Glyph | Means | Comes from | +| ------------- | ------------- | ----------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | +| **NEEDS YOU** | `⚠` | A permission or question dialog is blocking the agent | The approvals inbox (`permission_prompt` hooks, with the on-screen options parsed; for Codex, a dialog read off its screen) | +| | `✋` | Waiting for your next instruction, or errored | `idle_prompt`, or an errored session (equally something only a human clears) | +| **WORKING** | `✻` animating | A turn is running | The same working classification the web dashboard uses | +| **IDLE** | `○` | Live, but sitting there | | +| **RECENT** | `✔` | A past session from the unified list | History rows, no live pane | Ordering inside a group is "the one that has waited longest, first": blocked sessions sort by how long the dialog has been up, working sessions by when their @@ -111,20 +120,20 @@ same item announced twice does not ring twice. ## Keymap -| Key | Does | -| --- | --- | -| `↑` `↓` or `j` `k` | Move the cursor. PageUp/PageDown jump five rows. | -| `Enter` | Attach to the selected session (see [Attaching](#attaching)) | -| `1`-`9` | Jump to that row and attach. When a dialog is on screen, a digit answers it instead (see below). | -| `y` | Approve the selected session's dialog | -| `n` | Deny it, or **start a new session** when there is no dialog | -| `p` | Send one line to the selected session without attaching | -| `x` | Kill the selected session; `y` confirms, any other key cancels | -| `/` | Search sessions, events and files | -| `g` | Away digest: what happened while you were gone | -| `?` | Help overlay | -| `Esc` | Close whatever overlay is open | -| `q` or `Ctrl+C` | Quit, restoring the screen you started with | +| Key | Does | +| ------------------ | ------------------------------------------------------------------------------------------------ | +| `↑` `↓` or `j` `k` | Move the cursor. PageUp/PageDown jump five rows. | +| `Enter` | Attach to the selected session (see [Attaching](#attaching)) | +| `1`-`9` | Jump to that row and attach. When a dialog is on screen, a digit answers it instead (see below). | +| `y` | Approve the selected session's dialog | +| `n` | Deny it, or **start a new session** when there is no dialog | +| `p` | Send one line to the selected session without attaching | +| `x` | Kill the selected session; `y` confirms, any other key cancels | +| `/` | Search sessions, events and files | +| `g` | Away digest: what happened while you were gone | +| `?` | Help overlay | +| `Esc` | Close whatever overlay is open | +| `q` or `Ctrl+C` | Quit, restoring the screen you started with | Inside the `p` composer and the `/` query: `←` `→` `Home` `End` `Delete` `Backspace` plus `Ctrl+A` / `Ctrl+E` / `Ctrl+U` / `Ctrl+W`, `Enter` to send or open, @@ -213,11 +222,11 @@ resume the conversation in a fresh one instead. Three cases: -| Where you are | What happens | -| --- | --- | -| Not in tmux | `tmux -L codeman attach-session` | -| Already in tmux on Codeman's socket | `switch-client`, so you do not nest | -| In tmux on a **different** socket | Refused, with an explanation: detach from that tmux first, then run `codeman tui` again | +| Where you are | What happens | +| ----------------------------------- | --------------------------------------------------------------------------------------- | +| Not in tmux | `tmux -L codeman attach-session` | +| Already in tmux on Codeman's socket | `switch-client`, so you do not nest | +| In tmux on a **different** socket | Refused, with an explanation: detach from that tmux first, then run `codeman tui` again | A direct-PTY session has no pane to attach to, and says so. @@ -257,7 +266,7 @@ server. Start the server (`codeman web -d`, or `systemctl --user start codeman-w and the banner clears on its own: the TUI keeps re-probing. **It found the wrong server, or none.** Discovery is instance-scoped. A beta -instance (`CODEMAN_INSTANCE=beta`) has its own data dir *and* its own tmux socket, +instance (`CODEMAN_INSTANCE=beta`) has its own data dir _and_ its own tmux socket, so its TUI sees only its own sessions. Set `CODEMAN_PORT` or `CODEMAN_API_URL` explicitly when you run more than one. diff --git a/src/cli.ts b/src/cli.ts index f3a659a9..44c7c2f2 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -927,7 +927,7 @@ program program .command('tui') - .argument('[n]', 'attach straight to the nth session of `codeman tui --list`') + .argument('[session]', 'attach straight to a session: its number in `codeman tui --list`, or its exact session name') .description('Terminal dashboard for your sessions (the web UI remains the primary surface)') .option('-l, --list', 'Print the numbered session list and exit, instead of opening the dashboard') .action(async (position: string | undefined, options: { list?: boolean }) => { @@ -940,6 +940,16 @@ program return; } if (position !== undefined) { + // Digits only is a list number, as it always was; anything else is a session name. + if (!/^\d+$/.test(position)) { + if (position.trim() === '') { + console.error(palette.err('An empty session name matches nothing.')); + process.exitCode = 1; + return; + } + process.exitCode = await runTuiAttach(position); + return; + } const n = Number.parseInt(position, 10); if (!Number.isSafeInteger(n) || n < 1) { console.error(palette.err(`"${position}" is not a session number.`)); diff --git a/src/tui/tui-app.ts b/src/tui/tui-app.ts index 6161e83e..f32f513f 100644 --- a/src/tui/tui-app.ts +++ b/src/tui/tui-app.ts @@ -2643,7 +2643,7 @@ export async function runTui(options: TuiRunOptions = {}): Promise { if (!stdout.isTTY || !stdin.isTTY) { process.stderr.write( `${palette.err('codeman tui needs an interactive terminal.')}\n` + - `Use ${palette.info('codeman tui --list')} for a plain list, or ${palette.info('codeman tui ')} to attach.\n` + `Use ${palette.info('codeman tui --list')} for a plain list, or ${palette.info('codeman tui ')} to attach.\n` ); return 1; } @@ -2689,17 +2689,72 @@ export async function runTuiList(options: TuiRunOptions = {}): Promise { } } +/** What `codeman tui ` points at, resolved against one snapshot of the list. */ +export type TuiAttachTarget = + | { kind: 'row'; row: TuiRow } + /** A number with no row, or a name nothing in the list carries. */ + | { kind: 'none' } + /** Several LIVE sessions carry the name; `positions` are their `--list` numbers. */ + | { kind: 'ambiguous'; positions: number[] } + /** Only a finished (RECENT) row carries the name: nothing to attach to. */ + | { kind: 'finished' }; + /** - * `codeman tui `: attach straight to the nth row of `--list`. No screen setup - * at all, so it is as fast as the API call it makes. + * Resolve `codeman tui ` against the rows `--list` prints. + * + * Digits only is a position, exactly as before names were accepted. Anything else + * is a session name, matched exactly (case-sensitive) and only against the + * session's name, never its folder or a prompt. Session names are not unique in + * Codeman, so more than one LIVE match refuses rather than guessing; a RECENT row + * is history with no pane, so it never counts as a live match. */ -export async function runTuiAttach(position: number, options: TuiRunOptions = {}): Promise { +export function resolveAttachTarget(rows: readonly TuiRow[], target: number | string): TuiAttachTarget { + if (typeof target === 'number' || /^\d+$/.test(target)) { + const row = rows[Math.trunc(Number(target)) - 1]; + return row ? { kind: 'row', row } : { kind: 'none' }; + } + const positions: number[] = []; + let finished = false; + rows.forEach((row, index) => { + if (row.session.name !== target) return; + if (row.group === 'recent') finished = true; + else positions.push(index + 1); + }); + if (positions.length === 1) return { kind: 'row', row: rows[positions[0] - 1] }; + if (positions.length > 1) return { kind: 'ambiguous', positions }; + return finished ? { kind: 'finished' } : { kind: 'none' }; +} + +/** The stderr text for a target that resolved to no row, ending in a newline. */ +export function attachTargetError( + resolved: Exclude, + target: number | string +): string { + const list = palette.info('codeman tui --list'); + switch (resolved.kind) { + case 'ambiguous': + return ( + `${palette.err(`${resolved.positions.length} live sessions are named ${target} (${resolved.positions.join(', ')} in the list)`)}\n` + + `Attach by number instead: ${palette.info(`codeman tui ${resolved.positions[0]}`)}, or run ${list}.\n` + ); + case 'finished': + return `${palette.err(`there is no live session named ${target}, only a finished one`)}\nRun ${list} to see the live ones.\n`; + case 'none': + return typeof target === 'number' || /^\d+$/.test(target) + ? `${palette.err(`there is no session ${target}`)}\nRun ${list} to see the numbers.\n` + : `${palette.err(`there is no session named ${target}`)}\nRun ${list} to see the names.\n`; + } +} + +/** + * `codeman tui `: attach straight to a row of `--list`, by its number or + * by its session name. No screen setup at all, so it is as fast as the API call + * it makes. The target is resolved before the terminal check, so a script learns + * that a name does not exist (or is ambiguous) without needing a TTY. + */ +export async function runTuiAttach(target: number | string, options: TuiRunOptions = {}): Promise { const stdin = options.stdin ?? process.stdin; const stdout = options.stdout ?? process.stdout; - if (!stdout.isTTY || !stdin.isTTY) { - process.stderr.write(`${palette.err('attaching needs an interactive terminal.')}\n`); - return 1; - } const env = options.env ?? process.env; const client = options.client ?? new TuiClient(); try { @@ -2712,11 +2767,14 @@ export async function runTuiAttach(position: number, options: TuiRunOptions = {} process.stderr.write(authHint()); return 1; } - const row = state.rows[Math.trunc(position) - 1]; - if (!row) { - process.stderr.write( - `${palette.err(`there is no session ${position}`)}\nRun ${palette.info('codeman tui --list')} to see the numbers.\n` - ); + const resolved = resolveAttachTarget(state.rows, target); + if (resolved.kind !== 'row') { + process.stderr.write(attachTargetError(resolved, target)); + return 1; + } + const row = resolved.row; + if (!stdout.isTTY || !stdin.isTTY) { + process.stderr.write(`${palette.err('attaching needs an interactive terminal.')}\n`); return 1; } const plan = planAttach(row.session.muxName, { diff --git a/test/tui/tui-app.test.ts b/test/tui/tui-app.test.ts index a9451818..c3e0e03a 100644 --- a/test/tui/tui-app.test.ts +++ b/test/tui/tui-app.test.ts @@ -13,6 +13,7 @@ import { describe, it, expect } from 'vitest'; import { applyLiveMetrics, applyMuxNames, + attachTargetError, beginAttachHandoff, buildAttachBanner, buildListLines, @@ -30,6 +31,7 @@ import { planResume, previewIntervalMs, previewNoteFor, + resolveAttachTarget, resyncDelayMs, sameFrame, samePreview, @@ -915,3 +917,58 @@ describe('planResume', () => { }); }); }); + +describe('resolveAttachTarget (codeman tui )', () => { + function named(name: string, group: TuiRow['group'], sessionId: string): TuiRow { + return { + session: { sessionId, sources: ['live'], name }, + state: group === 'recent' ? 'recent' : 'idle', + group, + since: 0, + }; + } + const rows: TuiRow[] = [ + named('api', 'working', 'aaaaaaaa01'), + named('docs', 'idle', 'bbbbbbbb02'), + named('twin', 'idle', 'cccccccc03'), + named('twin', 'needs-you', 'dddddddd04'), + named('old', 'recent', 'eeeeeeee05'), + named('docs', 'recent', 'ffffffff06'), + ]; + + it('keeps digits-only as a list position, as a number or as a string', () => { + expect(resolveAttachTarget(rows, 2)).toEqual({ kind: 'row', row: rows[1] }); + expect(resolveAttachTarget(rows, '2')).toEqual({ kind: 'row', row: rows[1] }); + expect(resolveAttachTarget(rows, '7')).toEqual({ kind: 'none' }); + }); + + it('attaches the one live session with that exact name, ignoring a finished namesake', () => { + expect(resolveAttachTarget(rows, 'api')).toEqual({ kind: 'row', row: rows[0] }); + expect(resolveAttachTarget(rows, 'docs')).toEqual({ kind: 'row', row: rows[1] }); + }); + + it('matches case-sensitively and never by prefix', () => { + expect(resolveAttachTarget(rows, 'API')).toEqual({ kind: 'none' }); + expect(resolveAttachTarget(rows, 'ap')).toEqual({ kind: 'none' }); + }); + + it('refuses a name two live sessions share, naming their positions', () => { + expect(resolveAttachTarget(rows, 'twin')).toEqual({ kind: 'ambiguous', positions: [3, 4] }); + }); + + it('says a name only history carries is finished, not missing', () => { + expect(resolveAttachTarget(rows, 'old')).toEqual({ kind: 'finished' }); + expect(resolveAttachTarget(rows, 'nope')).toEqual({ kind: 'none' }); + }); + + it('words each refusal for a human and points at --list', () => { + expect(attachTargetError({ kind: 'ambiguous', positions: [3, 4] }, 'twin')).toMatch( + /2 live sessions are named twin \(3, 4 in the list\)[\s\S]*codeman tui 3/ + ); + expect(attachTargetError({ kind: 'finished' }, 'old')).toContain('no live session named old'); + expect(attachTargetError({ kind: 'none' }, 'nope')).toContain('there is no session named nope'); + expect(attachTargetError({ kind: 'none' }, 9)).toContain('there is no session 9'); + for (const kind of ['finished', 'none'] as const) + expect(attachTargetError({ kind }, 'x')).toContain('codeman tui --list'); + }); +}); diff --git a/test/tui/tui-e2e.test.ts b/test/tui/tui-e2e.test.ts index 15c001a5..6e7b6cbe 100644 --- a/test/tui/tui-e2e.test.ts +++ b/test/tui/tui-e2e.test.ts @@ -778,6 +778,47 @@ describe('codeman tui --list', () => { }, 30_000); }); +describe('codeman tui ', () => { + it('resolves an exact live name before asking for a terminal', async () => { + const result = await runPiped(['tui', 'w1-alpha']); + expect(result.code).toBe(1); + // Got past resolution: the only refusal left is the missing TTY. + expect(result.stderr).toContain('attaching needs an interactive terminal'); + expect(result.stderr).not.toContain('no session'); + }, 30_000); + + it('says a name nothing carries is missing, and points at --list', async () => { + const result = await runPiped(['tui', 'w9-nope']); + expect(result.code).toBe(1); + expect(result.stderr).toContain('there is no session named w9-nope'); + expect(result.stderr).toContain('codeman tui --list'); + }, 30_000); + + it('says a name only history carries is finished', async () => { + const result = await runPiped(['tui', 'w3-gamma']); + expect(result.code).toBe(1); + expect(result.stderr).toContain('no live session named w3-gamma, only a finished one'); + }, 30_000); + + it('refuses a name two live sessions share and names their numbers', async () => { + sessions.push({ ...sessions[1], sessionId: 'eeee5555-0000-0000-0000-000000000000' }); + try { + const result = await runPiped(['tui', 'w1-alpha']); + expect(result.code).toBe(1); + expect(result.stderr).toMatch(/2 live sessions are named w1-alpha \(\d+, \d+ in the list\)/); + expect(result.stderr).toContain('Attach by number instead'); + } finally { + resetSessions(); + } + }, 30_000); + + it('still reads digits as a list number', async () => { + const result = await runPiped(['tui', '42']); + expect(result.code).toBe(1); + expect(result.stderr).toContain('there is no session 42'); + }, 30_000); +}); + describe('codeman tui without a terminal', () => { it('refuses to open the dashboard and points at the fast paths', async () => { const result = await runPiped(['tui']);