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 97ecf3e4..ea49a70f 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/README.md b/README.md index 2f71aec8..f6e7ad97 100644 --- a/README.md +++ b/README.md @@ -744,6 +744,7 @@ A full-screen dashboard for your sessions, in the terminal. Same states as the w codeman tui # the dashboard codeman tui --list # numbered session list, then exit (scriptable) codeman tui 2 # attach straight to session 2 of that list +codeman tui api-docs # attach straight to the live session named api-docs ``` Sessions are grouped **NEEDS YOU → WORKING → IDLE → RECENT**, longest-waiting first. `↑↓`/`j`/`k` select, `1`-`9` and `[`/`]` switch between sessions, `Enter` attaches into the tmux pane (**`F1`** to come back). Inside a pane the bar across the top keeps the session strip visible and `Alt+1`-`Alt+9` switch without leaving. `y`/`n`/digit answer a pending permission dialog right from the list, `p` sends a one-line prompt, `n` starts a session and opens straight into it, `x` kills one (`y` confirms), `/` searches, `g` shows the away digest, `?` is help, `q` quits. Below 72 columns it drops the preview pane and becomes a single-column list, so it stays usable in Termius on a phone. With no server running it still starts in attach-only degraded mode. diff --git a/README.zh-CN.md b/README.zh-CN.md index d0900772..b7e5d2cd 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -741,6 +741,7 @@ Codeman 默认用 `--dangerously-skip-permissions` 启动会话,因此 Web UI codeman tui # 仪表盘 codeman tui --list # 带编号的会话列表,随即退出(可用于脚本) codeman tui 2 # 直接附着到列表里的第 2 个会话 +codeman tui api-docs # 直接附着到名为 api-docs 的活动会话 ``` 会话按 **NEEDS YOU → WORKING → IDLE → RECENT** 分组,等得最久的排最前。`↑↓`/`j`/`k` 选择,`1`-`9` 与 `[`/`]` 切换会话,`Enter` 附着进 tmux 面板(按 **`F1`** 回来)。在面板里,顶部的横条会一直显示会话条,`Alt+1`-`Alt+9` 不用离开就能切换。`y`/`n`/数字可以直接在列表里回答待处理的权限对话框,`p` 发送一行提示,`n` 新建会话并直接进入,`x` 杀掉一个(`y` 确认),`/` 搜索,`g` 显示离开摘要,`?` 是帮助,`q` 退出。窄于 72 列时它会去掉预览面板、变成单列列表,所以在手机上的 Termius 里依然好用。没有服务器在跑时,它仍会以仅附着的降级模式启动。 diff --git a/docs/tui.md b/docs/tui.md index 92244f11..571e0f15 100644 --- a/docs/tui.md +++ b/docs/tui.md @@ -18,6 +18,7 @@ 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. @@ -84,6 +85,15 @@ 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: diff --git a/docs/wiki/Remote-Access.md b/docs/wiki/Remote-Access.md index 49e577cb..8c42113a 100644 --- a/docs/wiki/Remote-Access.md +++ b/docs/wiki/Remote-Access.md @@ -255,6 +255,7 @@ works well in SSH clients like Termius or Blink: ```bash codeman tui # the dashboard codeman tui 2 # attach straight to session 2 +codeman tui api-docs # attach to the live session named api-docs codeman tui --list # numbered list, then exit ``` 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..bbe39a58 100644 --- a/src/tui/tui-app.ts +++ b/src/tui/tui-app.ts @@ -1,6 +1,6 @@ /** * @fileoverview `codeman tui`: the full-screen dashboard plus the two - * non-interactive fast paths (`--list`, ``). + * non-interactive fast paths (`--list`, ``). * * This is the IO half of `src/tui/`: it owns the terminal, the timers, stdin * and the tmux handoff. Every decision it makes that can be stated as a @@ -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}`)}\nNames match exactly. Run ${list} and attach by number instead.\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/cli-commands.test.ts b/test/cli-commands.test.ts index 68990785..802cfbaf 100644 --- a/test/cli-commands.test.ts +++ b/test/cli-commands.test.ts @@ -172,7 +172,7 @@ describe('registered arguments', () => { ['attach', ['path']], ['start', []], // Optional: bare `codeman tui` opens the dashboard. - ['tui', ['n']], + ['tui', ['session']], ])('declares the operands of `%s`', (name, expected) => { const args = find(program, name)!.registeredArguments.map((arg) => arg.name()); expect(args).toEqual(expected); 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']);