@hype/clod 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2026 Nate Goldman
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,109 @@
1
+ # clod
2
+
3
+ Terminal UI for managing Claude Code sessions.
4
+
5
+ Browse, search, preview, resume, and delete any session from any directory.
6
+
7
+ ![clod session list](images/demo.png)
8
+
9
+ Like `claude -r` but better.
10
+
11
+ ## Install
12
+
13
+ ```
14
+ npm install -g @hype/clod
15
+ ```
16
+
17
+ This puts `clod` on your PATH, so you can run it from anywhere:
18
+
19
+ ```
20
+ clod
21
+ ```
22
+
23
+ ### Requirements
24
+
25
+ - Node 22+
26
+ - Claude Code CLI (`claude`) on PATH for resume
27
+
28
+ ## Usage
29
+
30
+ ### Keys
31
+
32
+ | Key | Action |
33
+ |-----|--------|
34
+ | `↑` / `↓` | Navigate list |
35
+ | `PgUp` / `PgDn` | Jump up/down a page |
36
+ | `/` | Search titles (fuzzy) and message contents |
37
+ | `space` | Preview conversation |
38
+ | `enter` | Resume selected session |
39
+ | `u` | Usage dashboard (token counts) |
40
+ | `s` | Cycle sort: recent → lexicographic → by directory |
41
+ | `D` | Delete (moves to Trash; includes tasks, file-history, session-env, debug/telemetry, and history.jsonl prompt lines) |
42
+ | `q` / `esc` | Quit |
43
+
44
+ ### What it shows
45
+
46
+ Each row: session title · branch · project path · tokens used · context window · time since last activity
47
+
48
+ `used` is real throughput: tokens processed and generated (input + output +
49
+ cache writes), excluding cache reads. Cache reads re-count the same context
50
+ every turn and would inflate the figure ~10x, so they're left out. `ctx` is the
51
+ input context size of the session's most recent turn.
52
+
53
+ Times within today are relative (`now`, `5m`, `3h`); older sessions show a date.
54
+
55
+ Bottom bar: last user message from the selected session.
56
+
57
+ ### Dashboard
58
+
59
+ Press `u` for an aggregate view across all sessions: total throughput, a token
60
+ breakdown by type (input / output / cache write / cache read), a 30-day
61
+ throughput-per-day sparkline, a per-model breakdown, and top projects by
62
+ throughput. The cache-inclusive grand total is shown alongside the headline so
63
+ you can see how much of the raw count is cache re-reads. All figures are real
64
+ recorded token counts, no estimation.
65
+
66
+ ![clod usage dashboard](images/demo-dashboard.png)
67
+
68
+ ### How it works
69
+
70
+ Claude Code stores all session files in `~/.claude/projects/`, regardless of which directory the session was started in. `clod` reads from there directly. No home directory scanning.
71
+
72
+ ### Maintenance
73
+
74
+ `scripts/cleanup.js` trashes orphaned session artifacts under `~/.claude`
75
+ (file-history, session-env, tasks, telemetry, and stale `history.jsonl` lines
76
+ for sessions with no transcript left). Dry-run by default; `--apply` to act.
77
+ Per-session delete already covers these, so this is only for backlog from
78
+ deletions made outside `clod`. Don't `--apply` mid-session — a just-started
79
+ session looks orphaned until its transcript flushes.
80
+
81
+ ```
82
+ node scripts/cleanup.js # preview
83
+ node scripts/cleanup.js --apply # trash them
84
+ ```
85
+
86
+ ## Development
87
+
88
+ TypeScript, ESM-only. Source in `src/` compiles to `dist/` with `tsc`.
89
+
90
+ ```
91
+ pnpm dev # run from source with reload
92
+ pnpm test # lint, typecheck, build, and run tests
93
+ pnpm coverage # tests with the 100% coverage gate
94
+ pnpm lint # biome check
95
+ pnpm format # biome check --write
96
+ ```
97
+
98
+ Tests use `node:test` and run through Node's type stripping, so no test-runner
99
+ dependency. The parsing, sorting, and stats logic lives in `src/{sessions,list,stats,config}.ts`
100
+ and is held at 100% coverage; the Ink render layer (`src/ui.ts`) is exercised by
101
+ `ink-testing-library` but kept out of the gate.
102
+
103
+ ## Contributing
104
+
105
+ Contributions are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
106
+
107
+ ## License
108
+
109
+ [ISC](LICENSE)
package/dist/config.js ADDED
@@ -0,0 +1,26 @@
1
+ import { readFile, writeFile } from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ // Persisted local to the clod install (gitignored). The linked bin runs from
5
+ // anywhere, so resolve relative to this module, not the cwd.
6
+ const CONFIG_FILE = join(dirname(fileURLToPath(import.meta.url)), '..', '.clod.json');
7
+ const SORT_MODES = new Set(['recent', 'lexic', 'directory']);
8
+ function isSortMode(value) {
9
+ return typeof value === 'string' && SORT_MODES.has(value);
10
+ }
11
+ export async function loadConfig(file = CONFIG_FILE) {
12
+ try {
13
+ const c = JSON.parse(await readFile(file, 'utf8'));
14
+ const sortMode = c?.sortMode;
15
+ return { sortMode: isSortMode(sortMode) ? sortMode : 'recent' };
16
+ }
17
+ catch {
18
+ return { sortMode: 'recent' };
19
+ }
20
+ }
21
+ export async function saveConfig(config, file = CONFIG_FILE) {
22
+ try {
23
+ await writeFile(file, `${JSON.stringify(config, null, 2)}\n`);
24
+ }
25
+ catch { }
26
+ }
package/dist/index.js ADDED
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env node
2
+ import { loadConfig } from "./config.js";
3
+ import { listSessionFiles, parseSessions } from "./sessions.js";
4
+ // Parse enough newest sessions to fill a viewport; stream the rest in later.
5
+ const FIRST_BATCH = 40;
6
+ const files = await listSessionFiles();
7
+ if (files.length === 0) {
8
+ console.log('No Claude sessions found in ~/.claude/projects');
9
+ process.exit(0);
10
+ }
11
+ // Start parsing before the react/ink import so the two overlap.
12
+ const firstBatch = parseSessions(files.slice(0, FIRST_BATCH));
13
+ const loadRest = files.length > FIRST_BATCH ? () => parseSessions(files.slice(FIRST_BATCH)) : null;
14
+ const [{ default: React }, { render }, { default: App }, config] = await Promise.all([
15
+ import('react'),
16
+ import('ink'),
17
+ import("./ui.js"),
18
+ loadConfig()
19
+ ]);
20
+ // Object holder: TS narrows a reassigned `let` back to null after the closure,
21
+ // but a property read stays widened.
22
+ const resume = { target: null };
23
+ process.stdout.write('\x1b[?1049h'); // enter alternate screen
24
+ process.on('exit', () => process.stdout.write('\x1b[?1049l')); // restore on any exit
25
+ const { waitUntilExit } = render(React.createElement(App, {
26
+ loadFirst: () => firstBatch,
27
+ loadRest,
28
+ initialSortMode: config.sortMode,
29
+ onResume: (session) => {
30
+ resume.target = session;
31
+ }
32
+ }));
33
+ await waitUntilExit();
34
+ process.stdout.write('\x1b[?1049l'); // restore normal screen
35
+ const target = resume.target;
36
+ if (target) {
37
+ const { spawnSync } = await import('node:child_process');
38
+ spawnSync('claude', ['--resume', target.sessionId], {
39
+ stdio: 'inherit',
40
+ cwd: target.cwd
41
+ });
42
+ }
package/dist/list.js ADDED
@@ -0,0 +1,196 @@
1
+ import { fmtTokens, relativeTime, shortPath } from "./sessions.js";
2
+ // items[i] is always a session here: callers skip headers before calling.
3
+ const sessionIdAt = (items, i) => items[i].session.sessionId;
4
+ // below these widths a column is hidden rather than truncated into noise
5
+ export const BRANCH_MIN = 8;
6
+ export const DIR_MIN = 10;
7
+ export function truncate(str, max) {
8
+ if (!str)
9
+ return '';
10
+ return str.length > max ? `${str.slice(0, max - 1)}…` : str;
11
+ }
12
+ export function pad(str, len) {
13
+ return str.length >= len ? str.slice(0, len) : str + ' '.repeat(len - str.length);
14
+ }
15
+ export function padLeft(str, len) {
16
+ return str.length >= len ? str.slice(0, len) : ' '.repeat(len - str.length) + str;
17
+ }
18
+ // subsequence fuzzy match: query chars must appear in order, case-insensitive
19
+ export function fuzzyMatch(query, target) {
20
+ if (!query)
21
+ return true;
22
+ const q = query.toLowerCase();
23
+ const t = target.toLowerCase();
24
+ let qi = 0;
25
+ for (let ti = 0; ti < t.length && qi < q.length; ti++) {
26
+ if (t[ti] === q[qi])
27
+ qi++;
28
+ }
29
+ return qi === q.length;
30
+ }
31
+ // Title matches fuzzy (it's short); content matches by substring (fuzzy over a
32
+ // long blob hits everything).
33
+ export function sessionMatches(query, session) {
34
+ if (fuzzyMatch(query, session.title || 'Untitled'))
35
+ return true;
36
+ return session.searchText ? session.searchText.includes(query.toLowerCase()) : false;
37
+ }
38
+ export const usedStr = (s) => s.throughput ? `${fmtTokens(s.throughput)} used` : '—';
39
+ export const ctxStr = (s) => s.contextTokens != null ? `${fmtTokens(s.contextTokens)} ctx` : '—';
40
+ // Title-first: title takes its natural width; dir then branch fill the remainder
41
+ // and drop out (not stubbed) when it's too tight.
42
+ export function computeRowLayout(opts) {
43
+ const { session, termWidth, sortMode, timeWidth, usedWidth, ctxWidth } = opts;
44
+ const timeStr = relativeTime(session.lastTimestamp);
45
+ const pathStr = shortPath(session.cwd);
46
+ const naturalBranch = session.gitBranch ?? null;
47
+ const showDir = sortMode !== 'directory';
48
+ // flex = space for title + branch + dir after the fixed right block
49
+ // (used/ctx/time + three 2-space gaps).
50
+ const fullTitle = session.title || 'Untitled';
51
+ const flex = termWidth - 2 - usedWidth - ctxWidth - timeWidth - 6;
52
+ let avail = flex - fullTitle.length;
53
+ let dirWidth = 0;
54
+ if (showDir && avail >= DIR_MIN + 2) {
55
+ dirWidth = Math.min(pathStr.length, avail - 2);
56
+ avail -= dirWidth + 2;
57
+ }
58
+ let branchWidth = 0;
59
+ if (naturalBranch && avail >= BRANCH_MIN + 2) {
60
+ branchWidth = Math.min(naturalBranch.length, avail - 2);
61
+ avail -= branchWidth + 2;
62
+ }
63
+ // title absorbs the leftover as padding so the right block stays aligned
64
+ const titleWidth = Math.max(1, flex - (dirWidth ? dirWidth + 2 : 0) - (branchWidth ? branchWidth + 2 : 0));
65
+ return {
66
+ title: pad(truncate(fullTitle, titleWidth), titleWidth),
67
+ branchCol: branchWidth > 0 ? truncate(naturalBranch, branchWidth) : null,
68
+ dirCol: dirWidth > 0 ? truncate(pathStr, dirWidth) : null,
69
+ usedCol: padLeft(usedStr(session), usedWidth),
70
+ ctxCol: padLeft(ctxStr(session), ctxWidth),
71
+ timeCol: pad(timeStr, timeWidth)
72
+ };
73
+ }
74
+ // Sorted (and grouped, for directory mode) flat list of display items.
75
+ export function buildDisplayItems(sessions, sortMode) {
76
+ let sorted;
77
+ if (sortMode === 'recent') {
78
+ sorted = [...sessions].sort((a, b) => b.lastTimestamp - a.lastTimestamp);
79
+ }
80
+ else if (sortMode === 'lexic') {
81
+ sorted = [...sessions].sort((a, b) => {
82
+ const ta = a.title || 'Untitled';
83
+ const tb = b.title || 'Untitled';
84
+ return ta < tb ? -1 : ta > tb ? 1 : b.lastTimestamp - a.lastTimestamp;
85
+ });
86
+ }
87
+ else {
88
+ const cwdLatest = new Map();
89
+ for (const s of sessions) {
90
+ if (s.lastTimestamp > (cwdLatest.get(s.cwd) ?? 0))
91
+ cwdLatest.set(s.cwd, s.lastTimestamp);
92
+ }
93
+ // every cwd is in cwdLatest, so the lookups are defined
94
+ sorted = [...sessions].sort((a, b) => {
95
+ const g = cwdLatest.get(b.cwd) - cwdLatest.get(a.cwd);
96
+ return g !== 0 ? g : b.lastTimestamp - a.lastTimestamp;
97
+ });
98
+ }
99
+ if (sortMode === 'recent' || sortMode === 'lexic')
100
+ return sorted.map((s) => ({ type: 'session', session: s }));
101
+ const items = [];
102
+ let lastCwd = null;
103
+ for (const s of sorted) {
104
+ if (s.cwd !== lastCwd) {
105
+ items.push({ type: 'header', cwd: s.cwd });
106
+ lastCwd = s.cwd;
107
+ }
108
+ items.push({ type: 'session', session: s });
109
+ }
110
+ return items;
111
+ }
112
+ // Keep matching sessions; keep a header only if a matching session follows it.
113
+ export function filterItems(items, query) {
114
+ if (!query)
115
+ return items;
116
+ const filtered = [];
117
+ let pendingHeader = null;
118
+ for (const item of items) {
119
+ if (item.type === 'header') {
120
+ pendingHeader = item;
121
+ }
122
+ else if (sessionMatches(query, item.session)) {
123
+ if (pendingHeader) {
124
+ filtered.push(pendingHeader);
125
+ pendingHeader = null;
126
+ }
127
+ filtered.push(item);
128
+ }
129
+ }
130
+ return filtered;
131
+ }
132
+ // Pull viewStart back to show a header just above it, unless that would push the
133
+ // selection off-screen.
134
+ function includeHeaderAbove(items, newVs, selected, listHeight) {
135
+ if (newVs > 0 && items[newVs - 1].type === 'header' && selected <= newVs - 1 + listHeight - 1)
136
+ return newVs - 1;
137
+ return newVs;
138
+ }
139
+ // Move selection by ±1, skipping headers, scrolling to keep it visible.
140
+ // null when there's nowhere to go.
141
+ export function computeNavigate(items, selectedIdx, viewStart, listHeight, dir) {
142
+ let next = selectedIdx + dir;
143
+ while (next >= 0 && next < items.length && items[next].type === 'header')
144
+ next += dir;
145
+ if (next < 0 || next >= items.length)
146
+ return null;
147
+ let newVs = viewStart;
148
+ if (next < viewStart)
149
+ newVs = next;
150
+ else if (next >= viewStart + listHeight)
151
+ newVs = next - listHeight + 1;
152
+ newVs = includeHeaderAbove(items, newVs, next, listHeight);
153
+ return { selectedId: sessionIdAt(items, next), viewStart: newVs };
154
+ }
155
+ // Page selection and viewport, landing on a session and clamping at the edges.
156
+ // null when there's nowhere to go.
157
+ export function computePage(items, selectedIdx, viewStart, listHeight, dir) {
158
+ if (items.length === 0 || selectedIdx < 0)
159
+ return null;
160
+ const last = items.length - 1;
161
+ const step = dir * listHeight;
162
+ const target = Math.max(0, Math.min(last, selectedIdx + step));
163
+ let t = target;
164
+ while (t >= 0 && t <= last && items[t].type === 'header')
165
+ t += dir;
166
+ if (t < 0 || t > last) {
167
+ t = target;
168
+ while (t >= 0 && t <= last && items[t].type === 'header')
169
+ t -= dir;
170
+ }
171
+ if (t < 0 || t > last)
172
+ return null;
173
+ const maxVs = Math.max(0, items.length - listHeight);
174
+ let newVs = Math.max(0, Math.min(maxVs, viewStart + step));
175
+ if (t < newVs)
176
+ newVs = t;
177
+ else if (t >= newVs + listHeight)
178
+ newVs = t - listHeight + 1;
179
+ newVs = includeHeaderAbove(items, newVs, t, listHeight);
180
+ return { selectedId: sessionIdAt(items, t), viewStart: Math.max(0, newVs) };
181
+ }
182
+ // recent -> lexic -> directory -> recent
183
+ export function nextSortMode(sortMode) {
184
+ return sortMode === 'recent' ? 'lexic' : sortMode === 'directory' ? 'recent' : 'directory';
185
+ }
186
+ // Nearest surviving session to the deleted one: prefer the next below, else above.
187
+ export function findAdjacentSessionId(items, selectedIdx, remaining) {
188
+ const match = (i) => i.type === 'session' && remaining.has(i.session.sessionId);
189
+ const below = items.slice(selectedIdx + 1).find(match);
190
+ if (below)
191
+ return below.session.sessionId;
192
+ const above = items.slice(0, selectedIdx).reverse().find(match);
193
+ if (above)
194
+ return above.session.sessionId;
195
+ return null;
196
+ }
@@ -0,0 +1,371 @@
1
+ import { readdir, readFile, stat, writeFile } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { basename, join } from 'node:path';
4
+ import { trashPaths } from "./trash.js";
5
+ // Resolved lazily so tests can point $HOME at a fixture tree; os.homedir()
6
+ // honors $HOME on posix, read afresh each call.
7
+ const claudeDir = () => join(homedir(), '.claude');
8
+ const projectsDir = () => join(claudeDir(), 'projects');
9
+ // Claude Code injects system content as XML-tagged blocks; any message starting
10
+ // with an opening tag is injected content, not a real user message
11
+ const INJECTED = /^<[a-z]/i;
12
+ function isRealUserMessage(record) {
13
+ if (record.type !== 'user' || record.isMeta)
14
+ return false;
15
+ const content = record.message?.content;
16
+ if (typeof content === 'string')
17
+ return !INJECTED.test(content);
18
+ if (Array.isArray(content))
19
+ return content.some((b) => b.type === 'text' && !INJECTED.test(b.text ?? ''));
20
+ return false;
21
+ }
22
+ export function extractText(content) {
23
+ if (typeof content === 'string')
24
+ return content;
25
+ if (Array.isArray(content)) {
26
+ return content.find((b) => b.type === 'text' && !INJECTED.test(b.text ?? ''))?.text ?? '';
27
+ }
28
+ return '';
29
+ }
30
+ // All text blocks of a message, joined; used to build the searchable content blob.
31
+ export function textBlocks(content) {
32
+ if (typeof content === 'string')
33
+ return content;
34
+ if (Array.isArray(content))
35
+ return content
36
+ .filter((b) => b.type === 'text')
37
+ .map((b) => b.text ?? '')
38
+ .join(' ');
39
+ return '';
40
+ }
41
+ function modelKey(modelId) {
42
+ if (!modelId)
43
+ return null;
44
+ if (modelId.includes('opus'))
45
+ return 'opus';
46
+ if (modelId.includes('sonnet'))
47
+ return 'sonnet';
48
+ if (modelId.includes('haiku'))
49
+ return 'haiku';
50
+ return null;
51
+ }
52
+ // Fold one assistant turn's usage into the per-model accumulator. cacheRead is
53
+ // tracked apart: it re-counts the cached context every turn and dwarfs the rest
54
+ // (~10x). Returns this turn's context size (input + cache), or null if no usage.
55
+ function accumulateUsage(message, acc) {
56
+ const u = message?.usage;
57
+ if (!u)
58
+ return null;
59
+ const input = u.input_tokens || 0;
60
+ const output = u.output_tokens || 0;
61
+ const cacheRead = u.cache_read_input_tokens || 0;
62
+ const cacheWrite = u.cache_creation_input_tokens || 0;
63
+ const key = modelKey(message?.model);
64
+ if (key) {
65
+ acc[key] ??= { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
66
+ const m = acc[key];
67
+ m.input += input;
68
+ m.output += output;
69
+ m.cacheRead += cacheRead;
70
+ m.cacheWrite += cacheWrite;
71
+ }
72
+ return input + cacheRead + cacheWrite;
73
+ }
74
+ // Real throughput: new tokens processed + generated, excluding cache re-reads.
75
+ // Matches the figure shown in the shell status line.
76
+ export function throughputOf(usage) {
77
+ return (usage.input || 0) + (usage.output || 0) + (usage.cacheWrite || 0);
78
+ }
79
+ // last capture of re in str; re must have the g flag
80
+ function matchLast(re, str) {
81
+ let last = null;
82
+ for (const m of str.matchAll(re))
83
+ last = m[1]; // single capture group, always present on a match
84
+ return last;
85
+ }
86
+ export async function parseSession(filePath, fileStats) {
87
+ const sessionId = basename(filePath, '.jsonl');
88
+ try {
89
+ // Read as a Buffer and decode per line only as far as the sniff needs; skipped
90
+ // lines (most of the bytes) are never decoded, which is the big startup cost.
91
+ const buf = await readFile(filePath);
92
+ let title = null;
93
+ let cwd = null;
94
+ let gitBranch = null;
95
+ let lastUserMessage = null;
96
+ let lastTimestamp = null;
97
+ let contextTokens = null; // input context of the most recent assistant turn
98
+ const models = {};
99
+ const searchParts = []; // prose for content search, lowercased at the end
100
+ const setEnvelope = (ts, branch, dir) => {
101
+ if (ts)
102
+ lastTimestamp = ts;
103
+ if (branch && branch !== 'HEAD')
104
+ gitBranch = branch; // last-write: captures branch switches
105
+ if (dir && !cwd)
106
+ cwd = dir; // first-write: cwd doesn't change mid-session
107
+ };
108
+ // Most bytes are tool results and attachments clod never shows. Sniff each line's
109
+ // head to decide whether to JSON.parse it; the sniff only gates parsing, so a
110
+ // false positive costs one wasted parse, never wrong data. Assistant records
111
+ // serialize "message" before "type", so their early marker is the message "role";
112
+ // skipped lines get their envelope (timestamp/branch/cwd) from a tail regex.
113
+ const NL = 10;
114
+ for (let pos = 0, lineEnd = 0; pos < buf.length; pos = lineEnd + 1) {
115
+ lineEnd = buf.indexOf(NL, pos);
116
+ if (lineEnd === -1)
117
+ lineEnd = buf.length;
118
+ if (lineEnd === pos)
119
+ continue;
120
+ const head = buf.toString('utf8', pos, Math.min(pos + 600, lineEnd));
121
+ const isAssistant = head.includes('"role":"assistant"') || head.includes('"type":"assistant"');
122
+ const isUser = !isAssistant && (head.includes('"type":"user"') || head.includes('"role":"user"'));
123
+ const isProse = isAssistant ||
124
+ (isUser &&
125
+ !head.includes('"isMeta":true') &&
126
+ !head.includes('"tool_use_id"') &&
127
+ !head.includes('"type":"tool_result"'));
128
+ if (isProse) {
129
+ try {
130
+ const r = JSON.parse(buf.toString('utf8', pos, lineEnd));
131
+ setEnvelope(r.timestamp, r.gitBranch, r.cwd);
132
+ if (r.type === 'assistant') {
133
+ const ctx = accumulateUsage(r.message, models); // usage on every turn, incl. tool-only
134
+ if (ctx != null)
135
+ contextTokens = ctx;
136
+ searchParts.push(textBlocks(r.message?.content));
137
+ }
138
+ else if (isRealUserMessage(r)) {
139
+ lastUserMessage = extractText(r.message?.content);
140
+ searchParts.push(lastUserMessage);
141
+ }
142
+ }
143
+ catch { }
144
+ }
145
+ else if (isUser ||
146
+ head.includes('"type":"system"') ||
147
+ /^\{"type":"(attachment|pr-link|queue-operation)"/.test(head)) {
148
+ const tail = buf.toString('utf8', Math.max(pos, lineEnd - 400), lineEnd);
149
+ setEnvelope(matchLast(/"timestamp":"([^"]+)"/g, tail), matchLast(/"gitBranch":"([^"]*)"/g, tail), matchLast(/"cwd":"([^"]*)"/g, tail));
150
+ }
151
+ else if (head.includes('"type":"custom-title"')) {
152
+ try {
153
+ const r = JSON.parse(buf.toString('utf8', pos, lineEnd));
154
+ if (r.customTitle)
155
+ title = r.customTitle;
156
+ }
157
+ catch { }
158
+ }
159
+ }
160
+ if (!cwd)
161
+ return null;
162
+ const totals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
163
+ for (const k in models) {
164
+ totals.input += models[k].input;
165
+ totals.output += models[k].output;
166
+ totals.cacheRead += models[k].cacheRead;
167
+ totals.cacheWrite += models[k].cacheWrite;
168
+ }
169
+ const throughput = throughputOf(totals);
170
+ return {
171
+ sessionId,
172
+ title,
173
+ cwd,
174
+ gitBranch,
175
+ lastUserMessage,
176
+ contextTokens,
177
+ models,
178
+ totals,
179
+ throughput,
180
+ searchText: searchParts.join(' ').toLowerCase(),
181
+ mtime: fileStats.mtimeMs,
182
+ lastTimestamp: lastTimestamp ? new Date(lastTimestamp).getTime() : fileStats.mtimeMs,
183
+ filePath
184
+ };
185
+ }
186
+ catch {
187
+ return null;
188
+ }
189
+ }
190
+ // All session files with stats, newest first. mtime proxies the last record's
191
+ // timestamp (files are append-only), so the head is what a recency sort needs first.
192
+ export async function listSessionFiles() {
193
+ let projects;
194
+ try {
195
+ projects = await readdir(projectsDir());
196
+ }
197
+ catch {
198
+ return [];
199
+ }
200
+ const files = (await Promise.all(projects.map(async (project) => {
201
+ const projectPath = join(projectsDir(), project);
202
+ try {
203
+ const names = await readdir(projectPath);
204
+ return names.filter((f) => f.endsWith('.jsonl')).map((f) => join(projectPath, f));
205
+ }
206
+ catch {
207
+ return [];
208
+ }
209
+ }))).flat();
210
+ const stats = await Promise.all(files.map(async (filePath) => {
211
+ try {
212
+ return { filePath, stats: await stat(filePath) };
213
+ }
214
+ catch {
215
+ return null;
216
+ }
217
+ }));
218
+ return stats
219
+ .filter((s) => s !== null)
220
+ .sort((a, b) => b.stats.mtimeMs - a.stats.mtimeMs);
221
+ }
222
+ export async function parseSessions(files) {
223
+ const sessions = await Promise.all(files.map((f) => parseSession(f.filePath, f.stats)));
224
+ return sessions.filter((s) => s !== null);
225
+ }
226
+ export async function loadSessions() {
227
+ const sessions = await parseSessions(await listSessionFiles());
228
+ return sessions.sort((a, b) => b.lastTimestamp - a.lastTimestamp);
229
+ }
230
+ export async function getSessionMessages(filePath) {
231
+ try {
232
+ const raw = await readFile(filePath, 'utf8');
233
+ const messages = [];
234
+ for (const line of raw.split('\n').filter(Boolean)) {
235
+ try {
236
+ const r = JSON.parse(line);
237
+ if (isRealUserMessage(r)) {
238
+ messages.push({
239
+ role: 'user',
240
+ text: extractText(r.message?.content),
241
+ timestamp: r.timestamp
242
+ });
243
+ }
244
+ else if (r.type === 'assistant') {
245
+ const content = r.message?.content;
246
+ let text = '';
247
+ if (Array.isArray(content))
248
+ text = content
249
+ .filter((b) => b.type === 'text')
250
+ .map((b) => b.text ?? '')
251
+ .join('');
252
+ else if (typeof content === 'string')
253
+ text = content;
254
+ if (text.trim())
255
+ messages.push({ role: 'assistant', text: text.trim(), timestamp: r.timestamp });
256
+ }
257
+ }
258
+ catch { }
259
+ }
260
+ return messages;
261
+ }
262
+ catch {
263
+ return [];
264
+ }
265
+ }
266
+ // Trash everything Claude Code keys by session id under ~/.claude, plus the
267
+ // session's history.jsonl lines. Goes to Trash (recoverable). Skips plans/ and
268
+ // paste-cache/ (shared) and sessions/<pid>.json (ephemeral).
269
+ export async function deleteSession(filePath, trashFn = trashPaths) {
270
+ const sessionId = basename(filePath, '.jsonl');
271
+ const dir = claudeDir();
272
+ const candidates = [
273
+ filePath,
274
+ filePath.replace(/\.jsonl$/, ''), // sibling dir (e.g. subagent transcripts)
275
+ join(dir, 'tasks', sessionId),
276
+ join(dir, 'file-history', sessionId),
277
+ join(dir, 'session-env', sessionId),
278
+ join(dir, 'debug', `${sessionId}.txt`)
279
+ ];
280
+ // telemetry is keyed by a filename prefix, not an exact path
281
+ const telemetryDir = join(dir, 'telemetry');
282
+ try {
283
+ const prefix = `1p_failed_events.${sessionId}.`;
284
+ for (const name of await readdir(telemetryDir)) {
285
+ if (name.startsWith(prefix))
286
+ candidates.push(join(telemetryDir, name));
287
+ }
288
+ }
289
+ catch { }
290
+ const toTrash = [];
291
+ for (const p of candidates) {
292
+ try {
293
+ await stat(p);
294
+ toTrash.push(p);
295
+ }
296
+ catch { }
297
+ }
298
+ await trashFn(toTrash);
299
+ await scrubHistory(sessionId, trashFn);
300
+ }
301
+ // Remove the session's prompt lines from history.jsonl, writing the removed lines
302
+ // to a file that's trashed too, so even this stays recoverable.
303
+ async function scrubHistory(sessionId, trashFn) {
304
+ const historyPath = join(claudeDir(), 'history.jsonl');
305
+ let raw;
306
+ try {
307
+ raw = await readFile(historyPath, 'utf8');
308
+ }
309
+ catch {
310
+ return;
311
+ }
312
+ const needle = `"sessionId":"${sessionId}"`;
313
+ if (!raw.includes(needle))
314
+ return;
315
+ const kept = [];
316
+ const removed = [];
317
+ for (const line of raw.split('\n')) {
318
+ if (line.includes(needle))
319
+ removed.push(line);
320
+ else
321
+ kept.push(line);
322
+ }
323
+ const removedPath = join(claudeDir(), `history-removed-${sessionId}.jsonl`);
324
+ await writeFile(removedPath, `${removed.join('\n')}\n`);
325
+ await writeFile(historyPath, kept.join('\n'));
326
+ await trashFn([removedPath]);
327
+ }
328
+ export const MONTHS = [
329
+ 'Jan',
330
+ 'Feb',
331
+ 'Mar',
332
+ 'Apr',
333
+ 'May',
334
+ 'Jun',
335
+ 'Jul',
336
+ 'Aug',
337
+ 'Sep',
338
+ 'Oct',
339
+ 'Nov',
340
+ 'Dec'
341
+ ];
342
+ export function relativeTime(ms) {
343
+ const now = new Date();
344
+ const then = new Date(ms);
345
+ const sameDay = now.getFullYear() === then.getFullYear() &&
346
+ now.getMonth() === then.getMonth() &&
347
+ now.getDate() === then.getDate();
348
+ if (sameDay) {
349
+ const diff = Date.now() - ms;
350
+ if (diff < 60000)
351
+ return 'now';
352
+ const mins = Math.floor(diff / 60000);
353
+ if (mins < 60)
354
+ return `${mins}m`;
355
+ return `${Math.floor(mins / 60)}h`;
356
+ }
357
+ const label = `${MONTHS[then.getMonth()]} ${then.getDate()}`;
358
+ return then.getFullYear() === now.getFullYear() ? label : `${label} ${then.getFullYear()}`;
359
+ }
360
+ export function shortPath(p) {
361
+ return p.replace(homedir(), '~');
362
+ }
363
+ export function fmtTokens(n) {
364
+ if (n >= 1e9)
365
+ return `${(n / 1e9).toFixed(1)}B`;
366
+ if (n >= 1e6)
367
+ return `${(n / 1e6).toFixed(1)}M`;
368
+ if (n >= 1e3)
369
+ return `${Math.round(n / 1e3)}k`;
370
+ return String(n);
371
+ }
package/dist/stats.js ADDED
@@ -0,0 +1,57 @@
1
+ import { throughputOf } from "./sessions.js";
2
+ const SPARK = ' ▁▂▃▄▅▆▇█';
3
+ export function bar(value, max, width) {
4
+ const n = max > 0 ? Math.round((value / max) * width) : 0;
5
+ return '█'.repeat(n);
6
+ }
7
+ export function sparkline(values) {
8
+ const max = Math.max(0, ...values);
9
+ return values
10
+ .map((v) => (max > 0 && v > 0 ? SPARK[Math.min(8, Math.ceil((v / max) * 8))] : SPARK[0]))
11
+ .join('');
12
+ }
13
+ export function computeStats(sessions) {
14
+ const breakdown = { input: 0, output: 0, cacheWrite: 0, cacheRead: 0 };
15
+ let totalThroughput = 0;
16
+ const byModel = {};
17
+ const byProject = new Map();
18
+ const byDay = new Map();
19
+ for (const s of sessions) {
20
+ const t = s.totals;
21
+ breakdown.input += t.input;
22
+ breakdown.output += t.output;
23
+ breakdown.cacheWrite += t.cacheWrite;
24
+ breakdown.cacheRead += t.cacheRead;
25
+ totalThroughput += s.throughput || 0;
26
+ for (const k in s.models) {
27
+ byModel[k] ??= { throughput: 0 };
28
+ byModel[k].throughput += throughputOf(s.models[k]);
29
+ }
30
+ const p = byProject.get(s.cwd) ?? { cwd: s.cwd, throughput: 0 };
31
+ p.throughput += s.throughput || 0;
32
+ byProject.set(s.cwd, p);
33
+ const d = new Date(s.lastTimestamp);
34
+ const key = `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
35
+ byDay.set(key, (byDay.get(key) ?? 0) + (s.throughput || 0));
36
+ }
37
+ // last 30 days of throughput, oldest first
38
+ const now = new Date();
39
+ const days = [];
40
+ for (let i = 29; i >= 0; i--) {
41
+ const d = new Date(now);
42
+ d.setDate(d.getDate() - i);
43
+ const key = `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
44
+ days.push({ date: d, tokens: byDay.get(key) ?? 0 });
45
+ }
46
+ return {
47
+ totalSessions: sessions.length,
48
+ totalThroughput,
49
+ grandTotal: totalThroughput + breakdown.cacheRead,
50
+ breakdown,
51
+ byModel: Object.entries(byModel)
52
+ .map(([name, v]) => ({ name, ...v }))
53
+ .sort((a, b) => b.throughput - a.throughput),
54
+ byProject: [...byProject.values()].sort((a, b) => b.throughput - a.throughput),
55
+ days
56
+ };
57
+ }
package/dist/trash.js ADDED
@@ -0,0 +1,6 @@
1
+ // The real side effect, isolated so deleteSession can take a fake in tests and
2
+ // this adapter stays out of the coverage gate.
3
+ export const trashPaths = async (paths) => {
4
+ const { default: trash } = await import('trash'); // lazy: only deletes need it
5
+ await trash(paths);
6
+ };
package/dist/ui.js ADDED
@@ -0,0 +1,365 @@
1
+ import { Box, Text, useApp, useInput, useStdout } from 'ink';
2
+ import React from 'react';
3
+ import { saveConfig } from "./config.js";
4
+ import { buildDisplayItems, computeNavigate, computePage, computeRowLayout, ctxStr, filterItems, findAdjacentSessionId, nextSortMode, pad, truncate, usedStr } from "./list.js";
5
+ import { deleteSession, fmtTokens, getSessionMessages, MONTHS, relativeTime, shortPath } from "./sessions.js";
6
+ import { bar, computeStats, sparkline } from "./stats.js";
7
+ const h = React.createElement;
8
+ const { useState, useEffect, useMemo, memo } = React;
9
+ const HINT_HEIGHT = 1;
10
+ const HEADER_HEIGHT = 2;
11
+ const SNIPPET_HEIGHT = 3;
12
+ // ─── Row ─────────────────────────────────────────────────────────────────────
13
+ const SessionRow = memo(function SessionRow({ session, selected, termWidth, sortMode, timeWidth, usedWidth, ctxWidth }) {
14
+ const { title, branchCol, dirCol, usedCol, ctxCol, timeCol } = computeRowLayout({
15
+ session,
16
+ termWidth,
17
+ sortMode,
18
+ timeWidth,
19
+ usedWidth,
20
+ ctxWidth
21
+ });
22
+ if (selected) {
23
+ const branchPart = branchCol ? ` ${branchCol}` : '';
24
+ const dirPart = dirCol ? ` ${dirCol}` : '';
25
+ const line = `> ${title}${branchPart}${dirPart} ${usedCol} ${ctxCol} ${timeCol}`;
26
+ const full = pad(line, termWidth);
27
+ return h(Box, {}, h(Text, { backgroundColor: 'grey', color: 'white', bold: true }, full));
28
+ }
29
+ return h(Box, { flexDirection: 'row' }, h(Text, {}, ' '), h(Text, {}, title), branchCol ? h(Text, { color: 'yellow', dimColor: true }, ` ${branchCol}`) : null, dirCol ? h(Text, { color: 'cyan', dimColor: true }, ` ${dirCol}`) : null, h(Text, { dimColor: true }, ` ${usedCol}`), h(Text, { color: 'green', dimColor: true }, ` ${ctxCol}`), h(Text, { dimColor: true }, ` ${timeCol}`));
30
+ });
31
+ // ─── Directory header ─────────────────────────────────────────────────────────
32
+ function DirectoryHeader({ cwd }) {
33
+ return h(Box, { paddingLeft: 1 }, h(Text, { color: 'yellow' }, shortPath(cwd)));
34
+ }
35
+ // ─── Preview mode ─────────────────────────────────────────────────────────────
36
+ function PreviewMode({ session, onBack, termWidth, termHeight }) {
37
+ const [messages, setMessages] = useState(null);
38
+ const [scroll, setScroll] = useState(0);
39
+ useEffect(() => {
40
+ getSessionMessages(session.filePath).then((msgs) => {
41
+ setMessages(msgs);
42
+ setScroll(Math.max(0, msgs.length - 1));
43
+ });
44
+ }, [session.filePath]);
45
+ const viewHeight = termHeight - HEADER_HEIGHT - HINT_HEIGHT - 2;
46
+ useInput((input, key) => {
47
+ if (input === 'q' || input === ' ' || key.escape || key.backspace) {
48
+ onBack();
49
+ return;
50
+ }
51
+ if (!messages)
52
+ return;
53
+ if (key.downArrow)
54
+ setScroll((s) => Math.min(s + 1, Math.max(0, messages.length - 1)));
55
+ if (key.upArrow)
56
+ setScroll((s) => Math.max(0, s - 1));
57
+ });
58
+ const headerTitle = truncate(session.title || 'Untitled', termWidth - 10);
59
+ return h(Box, { flexDirection: 'column' }, h(Box, { flexDirection: 'row', paddingX: 1 }, h(Text, { color: 'white', bold: true }, `Preview: ${headerTitle}`)), h(Box, { flexDirection: 'column', height: viewHeight }, messages === null
60
+ ? h(Box, { padding: 1 }, h(Text, { dimColor: true }, 'Loading…'))
61
+ : messages.length === 0
62
+ ? h(Box, { padding: 1 }, h(Text, { dimColor: true }, 'No messages found.'))
63
+ : renderMessages(messages, scroll, viewHeight, termWidth)), h(Box, {}, h(Text, { dimColor: true }, '↑↓ scroll q/esc back')));
64
+ }
65
+ function renderMessages(messages, scroll, viewHeight, termWidth) {
66
+ // scroll is the index of the last visible message; show the window ending there
67
+ const start = Math.max(0, scroll - viewHeight + 2);
68
+ const visible = messages.slice(start, start + viewHeight);
69
+ return h(Box, { flexDirection: 'column' }, ...visible.map((msg, i) => {
70
+ const isUser = msg.role === 'user';
71
+ const prefix = isUser ? 'you: ' : ' AI: ';
72
+ const maxText = termWidth - prefix.length - 2;
73
+ const text = truncate(msg.text.replace(/\n+/g, ' '), maxText);
74
+ return h(Box, { key: i, flexDirection: 'row', paddingX: 1 }, h(Text, { color: isUser ? 'white' : 'cyan', dimColor: !isUser }, prefix + text));
75
+ }));
76
+ }
77
+ // ─── Delete confirm ───────────────────────────────────────────────────────────
78
+ function DeleteConfirm({ session, onConfirm, onCancel, termWidth, termHeight }) {
79
+ const [messages, setMessages] = useState(null);
80
+ useEffect(() => {
81
+ getSessionMessages(session.filePath).then(setMessages);
82
+ }, [session.filePath]);
83
+ useInput((input) => {
84
+ if (input === 'y')
85
+ onConfirm();
86
+ else
87
+ onCancel();
88
+ });
89
+ const previewHeight = termHeight - 6; // header + id + prompt + status
90
+ const previewMessages = messages?.slice(-previewHeight) ?? [];
91
+ return h(Box, { flexDirection: 'column' }, h(Box, { paddingX: 1 }, h(Text, { color: 'white', bold: true }, `Delete: ${truncate(session.title || 'Untitled', termWidth - 10)}`)), h(Box, { paddingX: 1 }, h(Text, { dimColor: true }, session.sessionId)), h(Box, { flexDirection: 'column', height: previewHeight, paddingX: 1 }, messages === null
92
+ ? h(Text, { dimColor: true }, 'Loading…')
93
+ : previewMessages.length === 0
94
+ ? h(Text, { dimColor: true }, 'No messages.')
95
+ : previewMessages.map((msg, i) => {
96
+ const isUser = msg.role === 'user';
97
+ const prefix = isUser ? 'you: ' : ' AI: ';
98
+ const text = truncate(msg.text.replace(/\n+/g, ' '), termWidth - prefix.length - 4);
99
+ return h(Text, { key: i, color: isUser ? undefined : 'cyan', dimColor: !isUser }, prefix + text);
100
+ })), h(Box, {
101
+ borderStyle: 'single',
102
+ borderColor: 'red',
103
+ borderLeft: false,
104
+ borderRight: false,
105
+ borderBottom: false
106
+ }, h(Text, { color: 'red' }, 'y delete n/esc cancel')));
107
+ }
108
+ // ─── Usage dashboard ────────────────────────────────────────────────────────
109
+ function StatsView({ sessions, onBack, termWidth, termHeight }) {
110
+ const stats = useMemo(() => computeStats(sessions), [sessions]);
111
+ useInput((input, key) => {
112
+ if (input === 'q' || input === 'u' || key.escape)
113
+ onBack();
114
+ });
115
+ const labelW = 9;
116
+ const barW = Math.min(24, Math.max(10, termWidth - 40));
117
+ const modelMax = Math.max(0, ...stats.byModel.map((m) => m.throughput));
118
+ const bd = stats.breakdown;
119
+ const bdRows = [
120
+ { label: 'Input', value: bd.input },
121
+ { label: 'Output', value: bd.output },
122
+ { label: 'Cache wr', value: bd.cacheWrite },
123
+ { label: 'Cache rd', value: bd.cacheRead }
124
+ ];
125
+ const bdMax = Math.max(0, ...bdRows.map((r) => r.value));
126
+ const projMax = Math.max(0, ...stats.byProject.map((p) => p.throughput));
127
+ const maxProjects = Math.max(3, termHeight - 16);
128
+ const projects = stats.byProject.slice(0, maxProjects);
129
+ const projLabelW = Math.min(34, Math.max(12, termWidth - barW - 16));
130
+ const spark = sparkline(stats.days.map((d) => d.tokens));
131
+ const sparkStart = `${MONTHS[stats.days[0].date.getMonth()]} ${stats.days[0].date.getDate()}`;
132
+ const sparkEnd = 'today';
133
+ const section = (label) => h(Box, { marginTop: 1 }, h(Text, { bold: true, color: 'cyan' }, label));
134
+ return h(Box, { flexDirection: 'column' }, h(Box, { paddingX: 1 }, h(Text, { color: 'white', bold: true }, 'Usage · real throughput (cache reads excluded)')), h(Box, { paddingX: 1, flexDirection: 'column' }, h(Text, {}, `${stats.totalSessions} sessions `, h(Text, { color: 'green', bold: true }, `${fmtTokens(stats.totalThroughput)} throughput`), h(Text, { dimColor: true }, ` ${fmtTokens(stats.grandTotal)} incl. cache reads`)), section('Token breakdown'), ...bdRows.map((r) => h(Text, { key: r.label }, pad(r.label, labelW), h(Text, { color: r.label === 'Cache rd' ? 'gray' : 'green' }, bar(r.value, bdMax, barW)), h(Text, { dimColor: true }, ` ${fmtTokens(r.value)}`))), section('Throughput / day (30d)'), h(Text, {}, h(Text, { dimColor: true }, `${pad(sparkStart, 7)} `), h(Text, { color: 'green' }, spark), h(Text, { dimColor: true }, ` ${sparkEnd}`)), section('By model'), ...stats.byModel.map((m) => h(Text, { key: m.name }, pad(m.name, labelW), h(Text, { color: 'green' }, bar(m.throughput, modelMax, barW)), h(Text, { dimColor: true }, ` ${fmtTokens(m.throughput)}`))), section('Top projects by throughput'), ...projects.map((p) => h(Text, { key: p.cwd }, pad(truncate(shortPath(p.cwd), projLabelW), projLabelW), ' ', h(Text, { color: 'green' }, bar(p.throughput, projMax, barW)), h(Text, { dimColor: true }, ` ${fmtTokens(p.throughput)}`)))), h(Box, { marginTop: 1 }, h(Text, { dimColor: true }, 'q/esc/u back')));
135
+ }
136
+ export default function App({ loadFirst, loadRest, initialSortMode, onResume, onDelete = deleteSession }) {
137
+ const { exit } = useApp();
138
+ const { stdout } = useStdout();
139
+ const termWidth = stdout?.columns || 80;
140
+ const termHeight = stdout?.rows || 24;
141
+ const [sessions, setSessions] = useState([]);
142
+ const [selectedId, setSelectedId] = useState(null);
143
+ const [viewStart, setViewStart] = useState(0);
144
+ const [mode, setMode] = useState('list');
145
+ const [sortMode, setSortMode] = useState(initialSortMode ?? 'recent');
146
+ const [searchQuery, setSearchQuery] = useState('');
147
+ const [isSearching, setIsSearching] = useState(false);
148
+ const [loading, setLoading] = useState(true);
149
+ // Paint before any session is parsed: newest batch first, the rest in one later
150
+ // batch (disjoint from the first, so a delete can't be resurrected by the merge).
151
+ useEffect(() => {
152
+ ;
153
+ (async () => {
154
+ setSessions(await loadFirst());
155
+ if (loadRest) {
156
+ const more = await loadRest();
157
+ setSessions((cur) => [...cur, ...more]);
158
+ }
159
+ setLoading(false);
160
+ })();
161
+ }, []);
162
+ const listHeight = termHeight - HEADER_HEIGHT - SNIPPET_HEIGHT - HINT_HEIGHT - 1;
163
+ // shared column widths so count/time align across every row
164
+ const timeWidth = useMemo(() => sessions.reduce((m, s) => Math.max(m, relativeTime(s.lastTimestamp).length), 4), [sessions]);
165
+ const usedWidth = useMemo(() => sessions.reduce((m, s) => Math.max(m, usedStr(s).length), 1), [sessions]);
166
+ const ctxWidth = useMemo(() => sessions.reduce((m, s) => Math.max(m, ctxStr(s).length), 1), [sessions]);
167
+ const displayItems = useMemo(() => buildDisplayItems(sessions, sortMode), [sessions, sortMode]);
168
+ const filteredItems = useMemo(() => filterItems(displayItems, searchQuery), [displayItems, searchQuery]);
169
+ const selectedIdx = useMemo(() => filteredItems.findIndex((item) => item.type === 'session' && item.session.sessionId === selectedId), [filteredItems, selectedId]);
170
+ const currentItem = filteredItems[selectedIdx];
171
+ const current = currentItem?.type === 'session' ? currentItem.session : undefined;
172
+ useEffect(() => {
173
+ if (selectedIdx === -1) {
174
+ const first = filteredItems.find((i) => i.type === 'session');
175
+ if (first && first.type === 'session')
176
+ setSelectedId(first.session.sessionId);
177
+ }
178
+ }, [filteredItems]);
179
+ useEffect(() => {
180
+ setViewStart((vs) => Math.min(vs, Math.max(0, filteredItems.length - listHeight)));
181
+ }, [termHeight]);
182
+ function navigate(dir) {
183
+ const r = computeNavigate(filteredItems, selectedIdx, viewStart, listHeight, dir);
184
+ if (r) {
185
+ setSelectedId(r.selectedId);
186
+ setViewStart(r.viewStart);
187
+ }
188
+ }
189
+ function page(dir) {
190
+ const r = computePage(filteredItems, selectedIdx, viewStart, listHeight, dir);
191
+ if (r) {
192
+ setSelectedId(r.selectedId);
193
+ setViewStart(r.viewStart);
194
+ }
195
+ }
196
+ useInput((input, key) => {
197
+ if (mode !== 'list')
198
+ return;
199
+ if (isSearching) {
200
+ if (key.escape) {
201
+ setIsSearching(false);
202
+ setSearchQuery('');
203
+ setViewStart(0);
204
+ return;
205
+ }
206
+ if (key.backspace || key.delete || input === '\x7f') {
207
+ if (searchQuery.length === 0) {
208
+ setIsSearching(false);
209
+ }
210
+ else {
211
+ setSearchQuery((q) => q.slice(0, -1));
212
+ setViewStart(0);
213
+ }
214
+ return;
215
+ }
216
+ if (key.upArrow) {
217
+ navigate(-1);
218
+ return;
219
+ }
220
+ if (key.downArrow) {
221
+ navigate(1);
222
+ return;
223
+ }
224
+ if (key.pageUp) {
225
+ page(-1);
226
+ return;
227
+ }
228
+ if (key.pageDown) {
229
+ page(1);
230
+ return;
231
+ }
232
+ if (key.return) {
233
+ if (current) {
234
+ onResume(current);
235
+ exit();
236
+ }
237
+ return;
238
+ }
239
+ if (input && input !== '\x7f' && !key.ctrl && !key.meta) {
240
+ setSearchQuery((q) => q + input);
241
+ setViewStart(0);
242
+ }
243
+ return;
244
+ }
245
+ if (key.upArrow)
246
+ navigate(-1);
247
+ else if (key.downArrow)
248
+ navigate(1);
249
+ else if (key.pageUp)
250
+ page(-1);
251
+ else if (key.pageDown)
252
+ page(1);
253
+ else if (input === '/')
254
+ setIsSearching(true);
255
+ else if (input === ' ' && current)
256
+ setMode('preview');
257
+ else if (input === 'u')
258
+ setMode('stats');
259
+ else if (key.return && current) {
260
+ onResume(current);
261
+ exit();
262
+ }
263
+ else if (input === 'D' && current)
264
+ setMode('deleting');
265
+ else if (input === 's') {
266
+ const next = nextSortMode(sortMode);
267
+ setSortMode(next);
268
+ setViewStart(0);
269
+ saveConfig({ sortMode: next }); // persist for next launch (fire and forget)
270
+ }
271
+ else if (input === 'q' || key.escape)
272
+ exit();
273
+ });
274
+ const viewSlice = filteredItems.slice(viewStart, viewStart + listHeight);
275
+ if (mode === 'preview' && current) {
276
+ return h(PreviewMode, {
277
+ session: current,
278
+ onBack: () => setMode('list'),
279
+ termWidth,
280
+ termHeight
281
+ });
282
+ }
283
+ if (mode === 'stats') {
284
+ return h(StatsView, {
285
+ sessions,
286
+ onBack: () => setMode('list'),
287
+ termWidth,
288
+ termHeight
289
+ });
290
+ }
291
+ if (mode === 'deleting' && current) {
292
+ return h(DeleteConfirm, {
293
+ session: current,
294
+ termWidth,
295
+ termHeight,
296
+ onConfirm: async () => {
297
+ try {
298
+ await onDelete(current.filePath);
299
+ }
300
+ catch {
301
+ setMode('list');
302
+ return;
303
+ }
304
+ const next = sessions.filter((s) => s.sessionId !== current.sessionId);
305
+ setSessions(next);
306
+ if (next.length === 0) {
307
+ exit();
308
+ return;
309
+ }
310
+ const remaining = new Set(next.map((s) => s.sessionId));
311
+ const adjId = findAdjacentSessionId(filteredItems, selectedIdx, remaining);
312
+ if (adjId)
313
+ setSelectedId(adjId);
314
+ setViewStart((vs) => Math.min(vs, Math.max(0, next.length - 1 - listHeight)));
315
+ setMode('list');
316
+ },
317
+ onCancel: () => setMode('list')
318
+ });
319
+ }
320
+ const snippet = current?.lastUserMessage
321
+ ? truncate(current.lastUserMessage.replace(/\n+/g, ' '), termWidth - 6)
322
+ : loading && !current
323
+ ? '…'
324
+ : 'no user messages';
325
+ const sortLabel = {
326
+ directory: 'grouped by directory',
327
+ recent: 'sorted by most recent',
328
+ lexic: 'sorted lexicographically'
329
+ };
330
+ const matchCount = filteredItems.filter((i) => i.type === 'session').length;
331
+ const searchLabel = isSearching || searchQuery
332
+ ? ` │ /${searchQuery}${isSearching ? '█' : ''} ${matchCount} matches`
333
+ : '';
334
+ const headerText = pad(sessions.length === 0 && loading
335
+ ? ' clod │ loading sessions…'
336
+ : ` clod │ ${sessions.length}${loading ? '+' : ''} sessions │ ${sortLabel[sortMode]}${searchLabel}${loading ? ' │ loading…' : ''}`, termWidth);
337
+ const navText = pad(' ↑↓ nav / search space preview enter resume u usage s sort D delete q quit', termWidth);
338
+ return h(Box, { flexDirection: 'column' }, h(Box, {
339
+ borderStyle: 'single',
340
+ borderLeft: false,
341
+ borderRight: false,
342
+ borderTop: false,
343
+ borderColor: 'gray'
344
+ }, h(Text, { backgroundColor: 'black', color: 'white', bold: true }, headerText)), h(Box, { flexDirection: 'column', height: listHeight }, viewSlice.length === 0 && loading
345
+ ? h(Box, { paddingX: 2 }, h(Text, { dimColor: true }, 'Loading…'))
346
+ : null, ...viewSlice.map((item) => item.type === 'header'
347
+ ? h(DirectoryHeader, { key: item.cwd, cwd: item.cwd })
348
+ : h(SessionRow, {
349
+ key: item.session.sessionId,
350
+ session: item.session,
351
+ selected: item.session.sessionId === selectedId,
352
+ termWidth,
353
+ sortMode,
354
+ timeWidth,
355
+ usedWidth,
356
+ ctxWidth
357
+ }))), h(Box, {
358
+ flexDirection: 'row',
359
+ borderStyle: 'single',
360
+ borderColor: 'gray',
361
+ borderLeft: false,
362
+ borderRight: false,
363
+ paddingX: 1
364
+ }, h(Text, { color: 'cyan', dimColor: true }, '" '), h(Text, { dimColor: true, italic: true }, snippet)), h(Box, {}, h(Text, { backgroundColor: 'black', color: 'white', dimColor: true }, navText)));
365
+ }
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@hype/clod",
3
+ "description": "Terminal UI for managing Claude Code sessions.",
4
+ "version": "1.0.0",
5
+ "author": "Nate Goldman <ungoldman@gmail.com>",
6
+ "bin": {
7
+ "clod": "./dist/index.js"
8
+ },
9
+ "bugs": "https://github.com/ungoldman/clod/issues",
10
+ "dependencies": {
11
+ "ink": "^7.1.0",
12
+ "react": "^19.2.7",
13
+ "trash": "^10.1.1"
14
+ },
15
+ "devDependencies": {
16
+ "@biomejs/biome": "^2.5.2",
17
+ "@types/node": "^22.20.0",
18
+ "@types/react": "^19.2.17",
19
+ "ink-testing-library": "^4.0.0",
20
+ "typescript": "^6.0.3"
21
+ },
22
+ "engines": {
23
+ "node": ">=22"
24
+ },
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "homepage": "https://github.com/ungoldman/clod",
29
+ "keywords": [
30
+ "claude",
31
+ "claude-code",
32
+ "cli",
33
+ "ink",
34
+ "sessions",
35
+ "tui"
36
+ ],
37
+ "license": "ISC",
38
+ "publishConfig": {
39
+ "access": "public",
40
+ "registry": "https://registry.npmjs.org/"
41
+ },
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "git+https://github.com/ungoldman/clod.git"
45
+ },
46
+ "type": "module",
47
+ "scripts": {
48
+ "build": "tsc -p tsconfig.build.json",
49
+ "coverage": "node --test --experimental-test-coverage --test-coverage-exclude='test/**' --test-coverage-exclude='src/index.ts' --test-coverage-exclude='src/trash.ts' --test-coverage-exclude='src/ui.ts' --test-coverage-lines=100 --test-coverage-branches=100 --test-coverage-functions=100 test/*.test.ts",
50
+ "dev": "node --watch src/index.ts",
51
+ "format": "biome check --write .",
52
+ "lint": "biome check .",
53
+ "prebuild": "rm -rf dist",
54
+ "start": "node src/index.ts",
55
+ "test": "pnpm lint && pnpm typecheck && pnpm build && node --test test/*.test.ts",
56
+ "typecheck": "tsc"
57
+ }
58
+ }