@hype/clod 1.3.2 → 1.4.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/README.md +27 -11
- package/dist/git.js +170 -0
- package/dist/harnesses/claude.js +445 -0
- package/dist/harnesses/index.js +27 -0
- package/dist/harnesses/omp.js +477 -0
- package/dist/index.js +7 -3
- package/dist/list.js +38 -15
- package/dist/proc.js +51 -0
- package/dist/sessions.js +5 -352
- package/dist/ui.js +88 -35
- package/package.json +5 -3
package/dist/sessions.js
CHANGED
|
@@ -1,65 +1,10 @@
|
|
|
1
|
-
import { appendFile, readdir, readFile, stat, writeFile } from 'node:fs/promises';
|
|
2
1
|
import { homedir } from 'node:os';
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
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
|
-
// Claude Code writes "[Request interrupted by user]" and the like as user records
|
|
13
|
-
const NOTICE = /^\[[^\]]*\]$/;
|
|
14
|
-
// A slash command arrives as one injected block, with what the user typed inside
|
|
15
|
-
// <command-args>; without this the whole prompt reads as system content.
|
|
16
|
-
const COMMAND = /<command-name>([^<]*)<\/command-name>(?:\s*<command-args>([\s\S]*?)<\/command-args>)?/;
|
|
17
|
-
function rawText(content) {
|
|
18
|
-
if (typeof content === 'string')
|
|
19
|
-
return content;
|
|
20
|
-
if (Array.isArray(content))
|
|
21
|
-
return content.find((b) => b.type === 'text')?.text ?? '';
|
|
22
|
-
return '';
|
|
23
|
-
}
|
|
24
|
-
function userText(record) {
|
|
25
|
-
if (record.type !== 'user' || record.isMeta)
|
|
26
|
-
return null;
|
|
27
|
-
const content = record.message?.content;
|
|
28
|
-
if (hasRealText(content))
|
|
29
|
-
return extractText(content);
|
|
30
|
-
const m = COMMAND.exec(rawText(content));
|
|
31
|
-
if (!m)
|
|
32
|
-
return null;
|
|
33
|
-
const args = m[2]?.trim();
|
|
34
|
-
return args ? `${m[1].trim()} ${args}` : m[1].trim();
|
|
35
|
-
}
|
|
36
|
-
function hasRealText(content) {
|
|
37
|
-
if (typeof content === 'string')
|
|
38
|
-
return !INJECTED.test(content);
|
|
39
|
-
if (Array.isArray(content))
|
|
40
|
-
return content.some((b) => b.type === 'text' && !INJECTED.test(b.text ?? ''));
|
|
41
|
-
return false;
|
|
42
|
-
}
|
|
43
|
-
export function extractText(content) {
|
|
44
|
-
if (typeof content === 'string')
|
|
45
|
-
return content;
|
|
46
|
-
if (Array.isArray(content)) {
|
|
47
|
-
return content.find((b) => b.type === 'text' && !INJECTED.test(b.text ?? ''))?.text ?? '';
|
|
48
|
-
}
|
|
49
|
-
return '';
|
|
50
|
-
}
|
|
51
|
-
// All text blocks of a message, joined; used to build the searchable content blob.
|
|
52
|
-
export function textBlocks(content) {
|
|
53
|
-
if (typeof content === 'string')
|
|
54
|
-
return content;
|
|
55
|
-
if (Array.isArray(content))
|
|
56
|
-
return content
|
|
57
|
-
.filter((b) => b.type === 'text')
|
|
58
|
-
.map((b) => b.text ?? '')
|
|
59
|
-
.join(' ');
|
|
60
|
-
return '';
|
|
2
|
+
// Real throughput: new tokens processed + generated, excluding cache re-reads.
|
|
3
|
+
// Matches the figure shown in the shell status line.
|
|
4
|
+
export function throughputOf(usage) {
|
|
5
|
+
return (usage.input || 0) + (usage.output || 0) + (usage.cacheWrite || 0);
|
|
61
6
|
}
|
|
62
|
-
function modelKey(modelId) {
|
|
7
|
+
export function modelKey(modelId) {
|
|
63
8
|
if (!modelId)
|
|
64
9
|
return null;
|
|
65
10
|
if (modelId.includes('opus'))
|
|
@@ -70,298 +15,6 @@ function modelKey(modelId) {
|
|
|
70
15
|
return 'haiku';
|
|
71
16
|
return null;
|
|
72
17
|
}
|
|
73
|
-
// Fold one assistant turn's usage into the per-model accumulator. cacheRead is
|
|
74
|
-
// tracked apart: it re-counts the cached context every turn and dwarfs the rest
|
|
75
|
-
// (~10x). Returns this turn's context size (input + cache), or null if no usage.
|
|
76
|
-
function accumulateUsage(message, acc) {
|
|
77
|
-
const u = message?.usage;
|
|
78
|
-
if (!u)
|
|
79
|
-
return null;
|
|
80
|
-
const input = u.input_tokens || 0;
|
|
81
|
-
const output = u.output_tokens || 0;
|
|
82
|
-
const cacheRead = u.cache_read_input_tokens || 0;
|
|
83
|
-
const cacheWrite = u.cache_creation_input_tokens || 0;
|
|
84
|
-
const key = modelKey(message?.model);
|
|
85
|
-
if (key) {
|
|
86
|
-
acc[key] ??= { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
87
|
-
const m = acc[key];
|
|
88
|
-
m.input += input;
|
|
89
|
-
m.output += output;
|
|
90
|
-
m.cacheRead += cacheRead;
|
|
91
|
-
m.cacheWrite += cacheWrite;
|
|
92
|
-
}
|
|
93
|
-
return input + cacheRead + cacheWrite;
|
|
94
|
-
}
|
|
95
|
-
// Real throughput: new tokens processed + generated, excluding cache re-reads.
|
|
96
|
-
// Matches the figure shown in the shell status line.
|
|
97
|
-
export function throughputOf(usage) {
|
|
98
|
-
return (usage.input || 0) + (usage.output || 0) + (usage.cacheWrite || 0);
|
|
99
|
-
}
|
|
100
|
-
// last capture of re in str; re must have the g flag
|
|
101
|
-
function matchLast(re, str) {
|
|
102
|
-
let last = null;
|
|
103
|
-
for (const m of str.matchAll(re))
|
|
104
|
-
last = m[1]; // single capture group, always present on a match
|
|
105
|
-
return last;
|
|
106
|
-
}
|
|
107
|
-
export async function parseSession(filePath, fileStats) {
|
|
108
|
-
const sessionId = basename(filePath, '.jsonl');
|
|
109
|
-
try {
|
|
110
|
-
// Read as a Buffer and decode per line only as far as the sniff needs; skipped
|
|
111
|
-
// lines (most of the bytes) are never decoded, which is the big startup cost.
|
|
112
|
-
const buf = await readFile(filePath);
|
|
113
|
-
let title = null;
|
|
114
|
-
let cwd = null;
|
|
115
|
-
let gitBranch = null;
|
|
116
|
-
let firstUserMessage = null;
|
|
117
|
-
let lastUserMessage = null;
|
|
118
|
-
let lastTimestamp = null;
|
|
119
|
-
let contextTokens = null; // input context of the most recent assistant turn
|
|
120
|
-
const models = {};
|
|
121
|
-
const searchParts = []; // prose for content search, lowercased at the end
|
|
122
|
-
const setEnvelope = (ts, branch, dir) => {
|
|
123
|
-
if (ts)
|
|
124
|
-
lastTimestamp = ts;
|
|
125
|
-
if (branch && branch !== 'HEAD')
|
|
126
|
-
gitBranch = branch; // last-write: captures branch switches
|
|
127
|
-
if (dir && !cwd)
|
|
128
|
-
cwd = dir; // first-write: cwd doesn't change mid-session
|
|
129
|
-
};
|
|
130
|
-
// Most bytes are tool results and attachments clod never shows. Sniff each line's
|
|
131
|
-
// head to decide whether to JSON.parse it; the sniff only gates parsing, so a
|
|
132
|
-
// false positive costs one wasted parse, never wrong data. Assistant records
|
|
133
|
-
// serialize "message" before "type", so their early marker is the message "role";
|
|
134
|
-
// skipped lines get their envelope (timestamp/branch/cwd) from a tail regex.
|
|
135
|
-
const NL = 10;
|
|
136
|
-
for (let pos = 0, lineEnd = 0; pos < buf.length; pos = lineEnd + 1) {
|
|
137
|
-
lineEnd = buf.indexOf(NL, pos);
|
|
138
|
-
if (lineEnd === -1)
|
|
139
|
-
lineEnd = buf.length;
|
|
140
|
-
if (lineEnd === pos)
|
|
141
|
-
continue;
|
|
142
|
-
const head = buf.toString('utf8', pos, Math.min(pos + 600, lineEnd));
|
|
143
|
-
const isAssistant = head.includes('"role":"assistant"') || head.includes('"type":"assistant"');
|
|
144
|
-
const isUser = !isAssistant && (head.includes('"type":"user"') || head.includes('"role":"user"'));
|
|
145
|
-
const isProse = isAssistant ||
|
|
146
|
-
(isUser &&
|
|
147
|
-
!head.includes('"isMeta":true') &&
|
|
148
|
-
!head.includes('"tool_use_id"') &&
|
|
149
|
-
!head.includes('"type":"tool_result"'));
|
|
150
|
-
if (isProse) {
|
|
151
|
-
try {
|
|
152
|
-
const r = JSON.parse(buf.toString('utf8', pos, lineEnd));
|
|
153
|
-
setEnvelope(r.timestamp, r.gitBranch, r.cwd);
|
|
154
|
-
if (r.type === 'assistant') {
|
|
155
|
-
const ctx = accumulateUsage(r.message, models); // usage on every turn, incl. tool-only
|
|
156
|
-
if (ctx != null)
|
|
157
|
-
contextTokens = ctx;
|
|
158
|
-
searchParts.push(textBlocks(r.message?.content));
|
|
159
|
-
}
|
|
160
|
-
else {
|
|
161
|
-
const text = userText(r);
|
|
162
|
-
if (text !== null) {
|
|
163
|
-
lastUserMessage = text;
|
|
164
|
-
searchParts.push(text);
|
|
165
|
-
const trimmed = text.trim();
|
|
166
|
-
if (!firstUserMessage && trimmed && !NOTICE.test(trimmed))
|
|
167
|
-
firstUserMessage = trimmed;
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
catch { }
|
|
172
|
-
}
|
|
173
|
-
else if (isUser ||
|
|
174
|
-
head.includes('"type":"system"') ||
|
|
175
|
-
/^\{"type":"(attachment|pr-link|queue-operation)"/.test(head)) {
|
|
176
|
-
const tail = buf.toString('utf8', Math.max(pos, lineEnd - 400), lineEnd);
|
|
177
|
-
setEnvelope(matchLast(/"timestamp":"([^"]+)"/g, tail), matchLast(/"gitBranch":"([^"]*)"/g, tail), matchLast(/"cwd":"([^"]*)"/g, tail));
|
|
178
|
-
}
|
|
179
|
-
else if (head.includes('"type":"custom-title"')) {
|
|
180
|
-
try {
|
|
181
|
-
const r = JSON.parse(buf.toString('utf8', pos, lineEnd));
|
|
182
|
-
if (r.customTitle)
|
|
183
|
-
title = r.customTitle;
|
|
184
|
-
}
|
|
185
|
-
catch { }
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
if (!cwd)
|
|
189
|
-
return null;
|
|
190
|
-
const totals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
191
|
-
for (const k in models) {
|
|
192
|
-
totals.input += models[k].input;
|
|
193
|
-
totals.output += models[k].output;
|
|
194
|
-
totals.cacheRead += models[k].cacheRead;
|
|
195
|
-
totals.cacheWrite += models[k].cacheWrite;
|
|
196
|
-
}
|
|
197
|
-
const throughput = throughputOf(totals);
|
|
198
|
-
return {
|
|
199
|
-
sessionId,
|
|
200
|
-
title,
|
|
201
|
-
cwd,
|
|
202
|
-
gitBranch,
|
|
203
|
-
firstUserMessage,
|
|
204
|
-
lastUserMessage,
|
|
205
|
-
contextTokens,
|
|
206
|
-
models,
|
|
207
|
-
totals,
|
|
208
|
-
throughput,
|
|
209
|
-
searchText: searchParts.join(' ').toLowerCase(),
|
|
210
|
-
mtime: fileStats.mtimeMs,
|
|
211
|
-
lastTimestamp: lastTimestamp ? new Date(lastTimestamp).getTime() : fileStats.mtimeMs,
|
|
212
|
-
filePath
|
|
213
|
-
};
|
|
214
|
-
}
|
|
215
|
-
catch {
|
|
216
|
-
return null;
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
// All session files with stats, newest first. mtime proxies the last record's
|
|
220
|
-
// timestamp (files are append-only), so the head is what a recency sort needs first.
|
|
221
|
-
export async function listSessionFiles() {
|
|
222
|
-
let projects;
|
|
223
|
-
try {
|
|
224
|
-
projects = await readdir(projectsDir());
|
|
225
|
-
}
|
|
226
|
-
catch {
|
|
227
|
-
return [];
|
|
228
|
-
}
|
|
229
|
-
const files = (await Promise.all(projects.map(async (project) => {
|
|
230
|
-
const projectPath = join(projectsDir(), project);
|
|
231
|
-
try {
|
|
232
|
-
const names = await readdir(projectPath);
|
|
233
|
-
return names.filter((f) => f.endsWith('.jsonl')).map((f) => join(projectPath, f));
|
|
234
|
-
}
|
|
235
|
-
catch {
|
|
236
|
-
return [];
|
|
237
|
-
}
|
|
238
|
-
}))).flat();
|
|
239
|
-
const stats = await Promise.all(files.map(async (filePath) => {
|
|
240
|
-
try {
|
|
241
|
-
return { filePath, stats: await stat(filePath) };
|
|
242
|
-
}
|
|
243
|
-
catch {
|
|
244
|
-
return null;
|
|
245
|
-
}
|
|
246
|
-
}));
|
|
247
|
-
return stats
|
|
248
|
-
.filter((s) => s !== null)
|
|
249
|
-
.sort((a, b) => b.stats.mtimeMs - a.stats.mtimeMs);
|
|
250
|
-
}
|
|
251
|
-
export async function parseSessions(files) {
|
|
252
|
-
const sessions = await Promise.all(files.map((f) => parseSession(f.filePath, f.stats)));
|
|
253
|
-
return sessions.filter((s) => s !== null);
|
|
254
|
-
}
|
|
255
|
-
export async function loadSessions() {
|
|
256
|
-
const sessions = await parseSessions(await listSessionFiles());
|
|
257
|
-
return sessions.sort((a, b) => b.lastTimestamp - a.lastTimestamp);
|
|
258
|
-
}
|
|
259
|
-
export async function getSessionMessages(filePath) {
|
|
260
|
-
try {
|
|
261
|
-
const raw = await readFile(filePath, 'utf8');
|
|
262
|
-
const messages = [];
|
|
263
|
-
for (const line of raw.split('\n').filter(Boolean)) {
|
|
264
|
-
try {
|
|
265
|
-
const r = JSON.parse(line);
|
|
266
|
-
const text = userText(r);
|
|
267
|
-
if (text !== null) {
|
|
268
|
-
messages.push({ role: 'user', text, timestamp: r.timestamp });
|
|
269
|
-
}
|
|
270
|
-
else if (r.type === 'assistant') {
|
|
271
|
-
const content = r.message?.content;
|
|
272
|
-
let text = '';
|
|
273
|
-
if (Array.isArray(content))
|
|
274
|
-
text = content
|
|
275
|
-
.filter((b) => b.type === 'text')
|
|
276
|
-
.map((b) => b.text ?? '')
|
|
277
|
-
.join('');
|
|
278
|
-
else if (typeof content === 'string')
|
|
279
|
-
text = content;
|
|
280
|
-
if (text.trim())
|
|
281
|
-
messages.push({ role: 'assistant', text: text.trim(), timestamp: r.timestamp });
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
catch { }
|
|
285
|
-
}
|
|
286
|
-
return messages;
|
|
287
|
-
}
|
|
288
|
-
catch {
|
|
289
|
-
return [];
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
// Rename by appending the records Claude Code's /rename writes; the last one
|
|
293
|
-
// wins on parse. custom-title feeds the resume picker, agent-name the title
|
|
294
|
-
// shown inside a resumed session.
|
|
295
|
-
export async function renameSession(filePath, title) {
|
|
296
|
-
const sessionId = basename(filePath, '.jsonl');
|
|
297
|
-
const records = [
|
|
298
|
-
{ type: 'custom-title', customTitle: title, sessionId },
|
|
299
|
-
{ type: 'agent-name', agentName: title, sessionId }
|
|
300
|
-
];
|
|
301
|
-
await appendFile(filePath, records.map((r) => `${JSON.stringify(r)}\n`).join(''));
|
|
302
|
-
}
|
|
303
|
-
// Trash everything Claude Code keys by session id under ~/.claude, plus the
|
|
304
|
-
// session's history.jsonl lines. Goes to Trash (recoverable). Skips plans/ and
|
|
305
|
-
// paste-cache/ (shared) and sessions/<pid>.json (ephemeral).
|
|
306
|
-
export async function deleteSession(filePath, trashFn = trashPaths) {
|
|
307
|
-
const sessionId = basename(filePath, '.jsonl');
|
|
308
|
-
const dir = claudeDir();
|
|
309
|
-
const candidates = [
|
|
310
|
-
filePath,
|
|
311
|
-
filePath.replace(/\.jsonl$/, ''), // sibling dir (e.g. subagent transcripts)
|
|
312
|
-
join(dir, 'tasks', sessionId),
|
|
313
|
-
join(dir, 'file-history', sessionId),
|
|
314
|
-
join(dir, 'session-env', sessionId),
|
|
315
|
-
join(dir, 'debug', `${sessionId}.txt`)
|
|
316
|
-
];
|
|
317
|
-
// telemetry is keyed by a filename prefix, not an exact path
|
|
318
|
-
const telemetryDir = join(dir, 'telemetry');
|
|
319
|
-
try {
|
|
320
|
-
const prefix = `1p_failed_events.${sessionId}.`;
|
|
321
|
-
for (const name of await readdir(telemetryDir)) {
|
|
322
|
-
if (name.startsWith(prefix))
|
|
323
|
-
candidates.push(join(telemetryDir, name));
|
|
324
|
-
}
|
|
325
|
-
}
|
|
326
|
-
catch { }
|
|
327
|
-
const toTrash = [];
|
|
328
|
-
for (const p of candidates) {
|
|
329
|
-
try {
|
|
330
|
-
await stat(p);
|
|
331
|
-
toTrash.push(p);
|
|
332
|
-
}
|
|
333
|
-
catch { }
|
|
334
|
-
}
|
|
335
|
-
await trashFn(toTrash);
|
|
336
|
-
await scrubHistory(sessionId, trashFn);
|
|
337
|
-
}
|
|
338
|
-
// Remove the session's prompt lines from history.jsonl, writing the removed lines
|
|
339
|
-
// to a file that's trashed too, so even this stays recoverable.
|
|
340
|
-
async function scrubHistory(sessionId, trashFn) {
|
|
341
|
-
const historyPath = join(claudeDir(), 'history.jsonl');
|
|
342
|
-
let raw;
|
|
343
|
-
try {
|
|
344
|
-
raw = await readFile(historyPath, 'utf8');
|
|
345
|
-
}
|
|
346
|
-
catch {
|
|
347
|
-
return;
|
|
348
|
-
}
|
|
349
|
-
const needle = `"sessionId":"${sessionId}"`;
|
|
350
|
-
if (!raw.includes(needle))
|
|
351
|
-
return;
|
|
352
|
-
const kept = [];
|
|
353
|
-
const removed = [];
|
|
354
|
-
for (const line of raw.split('\n')) {
|
|
355
|
-
if (line.includes(needle))
|
|
356
|
-
removed.push(line);
|
|
357
|
-
else
|
|
358
|
-
kept.push(line);
|
|
359
|
-
}
|
|
360
|
-
const removedPath = join(claudeDir(), `history-removed-${sessionId}.jsonl`);
|
|
361
|
-
await writeFile(removedPath, `${removed.join('\n')}\n`);
|
|
362
|
-
await writeFile(historyPath, kept.join('\n'));
|
|
363
|
-
await trashFn([removedPath]);
|
|
364
|
-
}
|
|
365
18
|
export const MONTHS = [
|
|
366
19
|
'Jan',
|
|
367
20
|
'Feb',
|
package/dist/ui.js
CHANGED
|
@@ -1,17 +1,19 @@
|
|
|
1
1
|
import { Box, Text, useApp, useInput, useWindowSize } from 'ink';
|
|
2
2
|
import React from 'react';
|
|
3
3
|
import { saveConfig } from './config.js';
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
4
|
+
import { deleteSession, getSessionMessages, HARNESSES, harnessOf, liveSessions, renameSession } from './harnesses/index.js';
|
|
5
|
+
import { buildDisplayItems, computeNavigate, computePage, computeRowLayout, ctxStr, displayTitle, filterItems, findAdjacentSessionId, GUTTER, nextSortMode, pad, truncate, usedStr, width } from './list.js';
|
|
6
|
+
import { fmtTokens, MONTHS, relativeTime, shortPath } from './sessions.js';
|
|
6
7
|
import { bar, computeStats, sparkline } from './stats.js';
|
|
7
8
|
const h = React.createElement;
|
|
8
|
-
const { useState, useEffect, useMemo, memo } = React;
|
|
9
|
+
const { useState, useEffect, useMemo, useRef, memo } = React;
|
|
9
10
|
const HINT_HEIGHT = 1;
|
|
10
11
|
const HEADER_HEIGHT = 2;
|
|
11
12
|
const SNIPPET_HEIGHT = 3;
|
|
13
|
+
const LIVE_REFRESH_MS = 5000;
|
|
12
14
|
// ─── Row ─────────────────────────────────────────────────────────────────────
|
|
13
|
-
const SessionRow = memo(function SessionRow({ session, selected, termWidth, sortMode, timeWidth, usedWidth, ctxWidth }) {
|
|
14
|
-
const { title,
|
|
15
|
+
const SessionRow = memo(function SessionRow({ session, selected, termWidth, sortMode, timeWidth, usedWidth, ctxWidth, live = false }) {
|
|
16
|
+
const { title, titleKind, branchCol, dirCol, usedCol, ctxCol, timeCol } = computeRowLayout({
|
|
15
17
|
session,
|
|
16
18
|
termWidth,
|
|
17
19
|
sortMode,
|
|
@@ -19,61 +21,73 @@ const SessionRow = memo(function SessionRow({ session, selected, termWidth, sort
|
|
|
19
21
|
usedWidth,
|
|
20
22
|
ctxWidth
|
|
21
23
|
});
|
|
24
|
+
// each harness's own glyph, lit while a running harness has the session open
|
|
25
|
+
const mark = harnessOf(session).mark;
|
|
22
26
|
if (selected) {
|
|
23
27
|
const branchPart = branchCol ? ` ${branchCol}` : '';
|
|
24
28
|
const dirPart = dirCol ? ` ${dirCol}` : '';
|
|
25
29
|
const rest = `${branchPart}${dirPart} ${usedCol} ${ctxCol} ${timeCol}`;
|
|
26
30
|
const hl = { backgroundColor: 'grey', color: 'white', bold: true };
|
|
27
|
-
return h(Box, {}, h(Text, hl, '> '), h(Text, { ...hl, bold:
|
|
31
|
+
return h(Box, {}, h(Text, hl, '>'), h(Text, live ? { ...hl, color: 'greenBright' } : hl, `${mark} `), h(Text, { ...hl, bold: titleKind === 'named', italic: titleKind === 'prompt' }, title), h(Text, hl, pad(rest, Math.max(0, termWidth - GUTTER - width(title)))));
|
|
28
32
|
}
|
|
29
|
-
return h(Box, { flexDirection: 'row' }, h(Text, {}, '
|
|
33
|
+
return h(Box, { flexDirection: 'row' }, h(Text, {}, ' '), h(Text, live ? { color: 'greenBright', bold: true } : { dimColor: true }, `${mark} `), h(Text, {
|
|
34
|
+
bold: titleKind === 'named',
|
|
35
|
+
dimColor: titleKind === 'prompt',
|
|
36
|
+
italic: titleKind === 'prompt'
|
|
37
|
+
}, 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
38
|
});
|
|
31
39
|
// ─── Row rename field ────────────────────────────────────────────────────────
|
|
32
|
-
function InputText({ value, cursor, termWidth }) {
|
|
40
|
+
function InputText({ value, cursor, termWidth, mark }) {
|
|
33
41
|
const style = { backgroundColor: 'grey', color: 'white', bold: true };
|
|
42
|
+
const chars = [...value];
|
|
43
|
+
const prefix = `>${mark} `;
|
|
34
44
|
// Past the end there is no character to sit on: show a block instead
|
|
35
45
|
// (ink trims trailing whitespace, so an inverse space would be invisible).
|
|
36
|
-
if (cursor >=
|
|
37
|
-
return h(Box, {}, h(Text, style, pad(
|
|
46
|
+
if (cursor >= chars.length) {
|
|
47
|
+
return h(Box, {}, h(Text, style, pad(`${prefix}${value}█`, termWidth)));
|
|
38
48
|
}
|
|
39
49
|
// The cursor is the inverse-video cell over the character it sits on.
|
|
40
|
-
return h(Box, {}, h(Text, style,
|
|
50
|
+
return h(Box, {}, h(Text, style, `${prefix}${chars.slice(0, cursor).join('')}`), h(Text, { ...style, inverse: true }, chars[cursor]), h(Text, style, pad(chars.slice(cursor + 1).join(''), Math.max(0, termWidth - GUTTER - width(chars.slice(0, cursor + 1).join(''))))));
|
|
41
51
|
}
|
|
42
52
|
function openRename(title) {
|
|
43
|
-
return { value: title, cursor: title
|
|
53
|
+
return { value: title, cursor: width(title) };
|
|
44
54
|
}
|
|
45
55
|
function cursorLeft({ value, cursor }) {
|
|
46
56
|
return { value, cursor: Math.max(0, cursor - 1) };
|
|
47
57
|
}
|
|
48
58
|
function cursorRight({ value, cursor }) {
|
|
49
|
-
return { value, cursor: Math.min(value
|
|
59
|
+
return { value, cursor: Math.min(width(value), cursor + 1) };
|
|
50
60
|
}
|
|
51
61
|
// Start of the word left of the cursor: skip spaces, then the word itself.
|
|
52
62
|
function cursorPrevWord({ value, cursor }) {
|
|
63
|
+
const c = [...value];
|
|
53
64
|
let i = cursor;
|
|
54
|
-
while (i > 0 &&
|
|
65
|
+
while (i > 0 && c[i - 1] === ' ')
|
|
55
66
|
i--;
|
|
56
|
-
while (i > 0 &&
|
|
67
|
+
while (i > 0 && c[i - 1] !== ' ')
|
|
57
68
|
i--;
|
|
58
69
|
return { value, cursor: i };
|
|
59
70
|
}
|
|
60
71
|
// Start of the word right of the cursor: skip the rest of this word, then spaces.
|
|
61
72
|
function cursorNextWord({ value, cursor }) {
|
|
73
|
+
const c = [...value];
|
|
62
74
|
let i = cursor;
|
|
63
|
-
while (i <
|
|
75
|
+
while (i < c.length && c[i] !== ' ')
|
|
64
76
|
i++;
|
|
65
|
-
while (i <
|
|
77
|
+
while (i < c.length && c[i] === ' ')
|
|
66
78
|
i++;
|
|
67
79
|
return { value, cursor: i };
|
|
68
80
|
}
|
|
69
81
|
function backspace({ value, cursor }) {
|
|
70
|
-
const c =
|
|
71
|
-
|
|
82
|
+
const c = [...value];
|
|
83
|
+
const at = Math.max(0, cursor - 1);
|
|
84
|
+
return { value: [...c.slice(0, at), ...c.slice(cursor)].join(''), cursor: at };
|
|
72
85
|
}
|
|
73
86
|
function insert({ value, cursor }, text) {
|
|
87
|
+
const c = [...value];
|
|
74
88
|
return {
|
|
75
|
-
value:
|
|
76
|
-
cursor: cursor + text
|
|
89
|
+
value: [...c.slice(0, cursor), text, ...c.slice(cursor)].join(''),
|
|
90
|
+
cursor: cursor + width(text)
|
|
77
91
|
};
|
|
78
92
|
}
|
|
79
93
|
// ─── Directory header ─────────────────────────────────────────────────────────
|
|
@@ -85,11 +99,11 @@ function PreviewMode({ session, onBack, termWidth, termHeight, loadMessages }) {
|
|
|
85
99
|
const [messages, setMessages] = useState(null);
|
|
86
100
|
const [scroll, setScroll] = useState(0);
|
|
87
101
|
useEffect(() => {
|
|
88
|
-
loadMessages(session
|
|
102
|
+
loadMessages(session).then((msgs) => {
|
|
89
103
|
setMessages(msgs);
|
|
90
104
|
setScroll(Math.max(0, msgs.length - 1));
|
|
91
105
|
});
|
|
92
|
-
}, [session
|
|
106
|
+
}, [session, loadMessages]);
|
|
93
107
|
const viewHeight = termHeight - HEADER_HEIGHT - HINT_HEIGHT - 2;
|
|
94
108
|
useInput((input, key) => {
|
|
95
109
|
if (input === 'q' || input === ' ' || key.escape || key.backspace) {
|
|
@@ -129,8 +143,8 @@ function renderMessages(messages, scroll, viewHeight, termWidth) {
|
|
|
129
143
|
function DeleteConfirm({ session, onConfirm, onCancel, termWidth, termHeight, loadMessages }) {
|
|
130
144
|
const [messages, setMessages] = useState(null);
|
|
131
145
|
useEffect(() => {
|
|
132
|
-
loadMessages(session
|
|
133
|
-
}, [session
|
|
146
|
+
loadMessages(session).then(setMessages);
|
|
147
|
+
}, [session, loadMessages]);
|
|
134
148
|
useInput((input) => {
|
|
135
149
|
if (input === 'y')
|
|
136
150
|
onConfirm();
|
|
@@ -184,7 +198,7 @@ function StatsView({ sessions, onBack, termWidth, termHeight }) {
|
|
|
184
198
|
const section = (label) => h(Box, { marginTop: 1 }, h(Text, { bold: true, color: 'cyan' }, label));
|
|
185
199
|
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')));
|
|
186
200
|
}
|
|
187
|
-
export default function App({ loadFirst, loadRest, initialSortMode, onResume, onDelete = deleteSession, onRename = renameSession, loadMessages = getSessionMessages, onSaveConfig = saveConfig }) {
|
|
201
|
+
export default function App({ loadFirst, loadRest, initialSortMode, onResume, onDelete = deleteSession, onRename = renameSession, loadMessages = getSessionMessages, onSaveConfig = saveConfig, loadLive = liveSessions, liveRefreshMs = LIVE_REFRESH_MS }) {
|
|
188
202
|
const { exit } = useApp();
|
|
189
203
|
const { columns: termWidth, rows: termHeight } = useWindowSize();
|
|
190
204
|
const [sessions, setSessions] = useState([]);
|
|
@@ -197,6 +211,27 @@ export default function App({ loadFirst, loadRest, initialSortMode, onResume, on
|
|
|
197
211
|
const [rename, setRename] = useState(null);
|
|
198
212
|
const [error, setError] = useState(null);
|
|
199
213
|
const [loading, setLoading] = useState(true);
|
|
214
|
+
const [harness, setHarness] = useState(null);
|
|
215
|
+
const [live, setLive] = useState(new Set());
|
|
216
|
+
const sessionsRef = useRef(sessions);
|
|
217
|
+
sessionsRef.current = sessions;
|
|
218
|
+
// Which sessions a running harness has open, read off the render path once the
|
|
219
|
+
// list has loaded and then on an interval. Rename and delete check afresh.
|
|
220
|
+
useEffect(() => {
|
|
221
|
+
if (loading)
|
|
222
|
+
return;
|
|
223
|
+
let stopped = false;
|
|
224
|
+
const refresh = () => loadLive(sessionsRef.current).then((ids) => {
|
|
225
|
+
if (!stopped)
|
|
226
|
+
setLive(ids);
|
|
227
|
+
}, () => { });
|
|
228
|
+
refresh();
|
|
229
|
+
const timer = setInterval(refresh, liveRefreshMs);
|
|
230
|
+
return () => {
|
|
231
|
+
stopped = true;
|
|
232
|
+
clearInterval(timer);
|
|
233
|
+
};
|
|
234
|
+
}, [loading]);
|
|
200
235
|
// Paint before any session is parsed: newest batch first, the rest in one later
|
|
201
236
|
// batch (disjoint from the first, so a delete can't be resurrected by the merge).
|
|
202
237
|
useEffect(() => {
|
|
@@ -215,7 +250,8 @@ export default function App({ loadFirst, loadRest, initialSortMode, onResume, on
|
|
|
215
250
|
const timeWidth = useMemo(() => sessions.reduce((m, s) => Math.max(m, relativeTime(s.lastTimestamp).length), 4), [sessions]);
|
|
216
251
|
const usedWidth = useMemo(() => sessions.reduce((m, s) => Math.max(m, usedStr(s).length), 1), [sessions]);
|
|
217
252
|
const ctxWidth = useMemo(() => sessions.reduce((m, s) => Math.max(m, ctxStr(s).length), 1), [sessions]);
|
|
218
|
-
const
|
|
253
|
+
const shown = useMemo(() => (harness ? sessions.filter((s) => s.harness === harness) : sessions), [sessions, harness]);
|
|
254
|
+
const displayItems = useMemo(() => buildDisplayItems(shown, sortMode), [shown, sortMode]);
|
|
219
255
|
const filteredItems = useMemo(() => filterItems(displayItems, searchQuery), [displayItems, searchQuery]);
|
|
220
256
|
const selectedIdx = useMemo(() => filteredItems.findIndex((item) => item.type === 'session' && item.session.sessionId === selectedId), [filteredItems, selectedId]);
|
|
221
257
|
const currentItem = filteredItems[selectedIdx];
|
|
@@ -257,12 +293,20 @@ export default function App({ loadFirst, loadRest, initialSortMode, onResume, on
|
|
|
257
293
|
if (key.return) {
|
|
258
294
|
const title = rename.value.trim();
|
|
259
295
|
setRename(null);
|
|
260
|
-
|
|
296
|
+
// confirming an unchanged auto title keeps it as the user's own
|
|
297
|
+
if (current &&
|
|
298
|
+
title &&
|
|
299
|
+
title !== (current.title || (current.aiTitle ? null : 'Untitled'))) {
|
|
261
300
|
// update the row in the same frame the input closes
|
|
262
301
|
const updateRow = (s) => s.sessionId === current.sessionId ? { ...s, title } : s;
|
|
263
302
|
setSessions((cur) => cur.map(updateRow));
|
|
264
303
|
// persist in the background; revert and warn if it fails
|
|
265
|
-
onRename(current
|
|
304
|
+
onRename(current, title).then((stored) => {
|
|
305
|
+
if (stored === title)
|
|
306
|
+
return;
|
|
307
|
+
const storedRow = (s) => s.sessionId === current.sessionId ? { ...s, title: stored } : s;
|
|
308
|
+
setSessions((cur) => cur.map(storedRow));
|
|
309
|
+
}, (err) => {
|
|
266
310
|
const revertRow = (s) => s.sessionId === current.sessionId ? { ...s, title: current.title } : s;
|
|
267
311
|
setSessions((cur) => cur.map(revertRow));
|
|
268
312
|
setError(`could not save rename: ${err.message}`);
|
|
@@ -349,12 +393,18 @@ export default function App({ loadFirst, loadRest, initialSortMode, onResume, on
|
|
|
349
393
|
setMode('preview');
|
|
350
394
|
else if (input === 'u')
|
|
351
395
|
setMode('stats');
|
|
396
|
+
else if (input === 'h') {
|
|
397
|
+
// all -> each harness in turn -> all
|
|
398
|
+
const ids = HARNESSES.map((x) => x.id);
|
|
399
|
+
setHarness(harness === null ? ids[0] : (ids[ids.indexOf(harness) + 1] ?? null));
|
|
400
|
+
setViewStart(0);
|
|
401
|
+
}
|
|
352
402
|
else if (key.return && current) {
|
|
353
403
|
onResume(current);
|
|
354
404
|
exit();
|
|
355
405
|
}
|
|
356
406
|
else if (input === 'r' && current) {
|
|
357
|
-
setRename(openRename(current.title || 'Untitled'));
|
|
407
|
+
setRename(openRename(current.title || current.aiTitle || 'Untitled'));
|
|
358
408
|
}
|
|
359
409
|
else if (input === 'D' && current)
|
|
360
410
|
setMode('deleting');
|
|
@@ -379,7 +429,7 @@ export default function App({ loadFirst, loadRest, initialSortMode, onResume, on
|
|
|
379
429
|
}
|
|
380
430
|
if (mode === 'stats') {
|
|
381
431
|
return h(StatsView, {
|
|
382
|
-
sessions,
|
|
432
|
+
sessions: shown,
|
|
383
433
|
onBack: () => setMode('list'),
|
|
384
434
|
termWidth,
|
|
385
435
|
termHeight
|
|
@@ -392,7 +442,7 @@ export default function App({ loadFirst, loadRest, initialSortMode, onResume, on
|
|
|
392
442
|
termHeight,
|
|
393
443
|
onConfirm: async () => {
|
|
394
444
|
try {
|
|
395
|
-
await onDelete(current
|
|
445
|
+
await onDelete(current);
|
|
396
446
|
}
|
|
397
447
|
catch (err) {
|
|
398
448
|
setError(`could not delete: ${err.message}`);
|
|
@@ -426,15 +476,16 @@ export default function App({ loadFirst, loadRest, initialSortMode, onResume, on
|
|
|
426
476
|
recent: 'sorted by most recent',
|
|
427
477
|
lexic: 'sorted lexicographically'
|
|
428
478
|
};
|
|
479
|
+
const harnessLabel = harness ? HARNESSES.find((x) => x.id === harness)?.name : 'all harnesses';
|
|
429
480
|
const matchCount = filteredItems.filter((i) => i.type === 'session').length;
|
|
430
481
|
// searchQuery is only ever non-empty while searching, so the label tracks isSearching
|
|
431
482
|
const searchLabel = isSearching ? ` │ /${searchQuery}█ ${matchCount} matches` : '';
|
|
432
483
|
const headerText = pad(sessions.length === 0 && loading
|
|
433
484
|
? ' clod │ loading sessions…'
|
|
434
|
-
: ` clod │ ${
|
|
485
|
+
: ` clod │ ${shown.length}${loading ? '+' : ''} sessions │ ${harnessLabel} │ ${sortLabel[sortMode]}${searchLabel}${loading ? ' │ loading…' : ''}`, termWidth);
|
|
435
486
|
const navText = pad(rename !== null
|
|
436
487
|
? ' enter confirm esc cancel'
|
|
437
|
-
: ' ↑↓ nav / search space preview enter resume r rename u usage s sort D delete q quit', termWidth);
|
|
488
|
+
: ' ↑↓ nav / search space preview enter resume r rename u usage s sort h harness D delete q quit', termWidth);
|
|
438
489
|
return h(Box, { flexDirection: 'column' }, h(Box, {
|
|
439
490
|
borderStyle: 'single',
|
|
440
491
|
borderLeft: false,
|
|
@@ -450,12 +501,14 @@ export default function App({ loadFirst, loadRest, initialSortMode, onResume, on
|
|
|
450
501
|
key: item.session.sessionId,
|
|
451
502
|
value: rename.value,
|
|
452
503
|
cursor: rename.cursor,
|
|
453
|
-
termWidth
|
|
504
|
+
termWidth,
|
|
505
|
+
mark: harnessOf(item.session).mark
|
|
454
506
|
})
|
|
455
507
|
: h(SessionRow, {
|
|
456
508
|
key: item.session.sessionId,
|
|
457
509
|
session: item.session,
|
|
458
510
|
selected: item.session.sessionId === selectedId,
|
|
511
|
+
live: live.has(item.session.sessionId),
|
|
459
512
|
termWidth,
|
|
460
513
|
sortMode,
|
|
461
514
|
timeWidth,
|