@sejuneoh/aitop 0.36.1 → 0.37.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 CHANGED
@@ -46,6 +46,7 @@
46
46
  > `aitop --once`
47
47
 
48
48
  - Print the current state once and exit.
49
+ - Piped or redirected to a file, it prints only the content: no padding lines to fill the screen height, no trailing spaces and no key bar.
49
50
 
50
51
  > `aitop --json`
51
52
 
@@ -66,11 +67,12 @@
66
67
  > `aitop --help`
67
68
 
68
69
  - All options.
70
+ - A mistyped option prints the error with the closest match and a pointer to `aitop --help` (two lines, no full help), like `unknown option --notfy (did you mean --notify?)`, and exits with 2. A bad `--theme` value works the same way.
69
71
 
70
72
  **Keys on the live screen**
71
73
 
72
74
  - `↑↓` select · `n` next session to check · `/` search · `s` sort · `g` group
73
- - `p` pin · `f` changed files · `?` help · `q` quit
75
+ - `p` pin · `f` changed files · `a` waiting alerts on/off · `?` help · `q` quit
74
76
 
75
77
  **Config file**
76
78
 
@@ -90,7 +92,7 @@
90
92
  - **Read-only**: no network, no ports, no dependencies. It only reads the session logs each CLI already writes.
91
93
 
92
94
  <details>
93
- <summary>Details: stopped sessions, cache countdown, tool run time</summary>
95
+ <summary>Details: stopped sessions, cache countdown, tool run time, context gauge, tool line</summary>
94
96
 
95
97
  **Stopped by an error**
96
98
 
@@ -110,7 +112,17 @@
110
112
  - Measured from the open tool call's start (Claude `tool_use`, Codex `function_call`, Antigravity running step).
111
113
  - Shown after one minute, in a dim warning color from ten minutes (Claude Code's Bash timeout max).
112
114
  - Not counted while waiting for approval.
113
- - Dropped first on narrow screens; `--json` has `toolStartedAt`.
115
+ - Dropped first on narrow screens, after the verb: a narrow STATUS cell keeps the target and time (`Bash $ npm test · 9m55s`). `--json` has `toolStartedAt`.
116
+
117
+ **Context gauge**
118
+
119
+ - `~` marks 60% and up, `!` 85% and up, so the levels show without color. Under `NO_COLOR` the bar is `███░░`, and a gauge that reads 0% has no filled cell.
120
+
121
+ **Tool line and empty screen**
122
+
123
+ - Tools with no live session and no use for 7 days leave the tool line. Its end tells the two kinds apart: `not installed: codex unused 7d: gemini` (counts when space is short). Turn it off with `"hideIdleTools": false`.
124
+ - When a tool's process runs but it has no session records yet, the empty screen says so first (`agy running, but no session records to read yet.`) and what to do next.
125
+ - The `?` key is always labeled `help`, at any width.
114
126
 
115
127
  </details>
116
128
 
@@ -291,6 +303,8 @@ Alerts when a session starts waiting, finishes a long turn or fills its context.
291
303
  - `--notify=waiting,done,context`: pick the kinds. Plain `--notify` uses the config file kinds, or waiting only when none are set.
292
304
  - `--on-waiting`: run a command with `/bin/sh -c` (`cmd.exe /d /v:on /s /c` on Windows) for the same events (10 second limit, runs as you).
293
305
  - Sessions already waiting (or already over 90% context) when aitop starts are not reported.
306
+ - Press `a` on the live screen to turn desktop alerts on or off for this run only. The config file is not changed. The state (`alerts:on` or `alerts:off`) shows on the key line when there is room, and always on the "now" line of the `?` help. If no alert tool is found, it shows off.
307
+ - When alerts are off and a waiting session first shows up (including one already waiting when aitop starts), the key line shows `turn on waiting alerts: a` once per run. If the help or search is open, it waits until you close it. It does not show when you turned alerts off yourself (config file `"notify": false` or `--no-notify`).
294
308
 
295
309
  **Kinds**
296
310
 
@@ -355,6 +369,7 @@ set -g status-interval 15
355
369
  - The Claude Code sessions stopped by an API error (`stop 1`, read live).
356
370
  - The number of sessions running (`run 3`).
357
371
  - Spend over the last hour.
372
+ - `aitop idle` when there is nothing to show (`idle` or `-` in a very narrow `--line-width`), so an empty line never looks like a broken setup.
358
373
 
359
374
  **Options**
360
375
 
@@ -418,7 +433,7 @@ aitop reads `~/.claude` and `~/.codex` by default. List more profiles to read th
418
433
 
419
434
  ## Resume a session elsewhere
420
435
 
421
- Continue a session elsewhere, for example when you cannot jump to its tab, as in Windows Terminal with WSL. The detail panel shows a `Resume` command and `y` copies it.
436
+ Continue a session elsewhere, for example when you cannot jump to its tab, as in Windows Terminal with WSL. The detail panel shows a `Resume` command and `y` copies it. The panel wraps it at spaces, `/` and `\`, keeps the resume part (`claude --resume <id>`) on the last line(s), and keeps the session id on one line when the width allows. A long `cd` part is shortened in the middle with `…`; `y` still copies the whole command.
422
437
 
423
438
  > Claude: `cd <dir> && claude --resume <id>`
424
439
  >
package/bin/aitop.mjs CHANGED
@@ -5,10 +5,13 @@ import { langOption, pickLang, setLang, t } from '../src/i18n.mjs';
5
5
  import { notifyOptions } from '../src/notify.mjs';
6
6
  import { lineOption } from '../src/line.mjs';
7
7
  import { reportOption } from '../src/report.mjs';
8
+ import { suggest } from '../src/suggest.mjs';
8
9
  import { mask, setAmbiguous, stripControl } from '../src/text.mjs';
9
10
 
10
11
  const KNOWN = new Set(['-h', '--help', '-v', '--version', '--once', '--all', '--json', '--doctor', '--bell', '--show-requests', '--print-config', '--no-bell', '--no-all', '--no-show-requests', '--debug', '--no-debug', '--color-blind', '--no-color-blind']);
11
12
  const THEMES = ['light', 'dark'];
13
+ // 잘못 친 옵션에 제안할 후보. KNOWN 의 긴 옵션과, 다른 모듈이 먼저 꺼내는 값 옵션을 합친다.
14
+ const OPTIONS = [...[...KNOWN].filter((o) => o.startsWith('--')), '--theme', '--lang', '--notify', '--no-notify', '--on-waiting', '--no-on-waiting', '--budget-day', '--no-budget-day', '--line', '--line-width', '--report', '--by', '--days', '--months', '--since', '--plan', '--md', '--show-prompts'];
12
15
  const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
13
16
 
14
17
  // 언어는 다른 옵션의 오류 문구보다 먼저 정한다: --lang > AITOP_LANG > 설정 파일 lang > LC_ALL > LC_MESSAGES > LANG.
@@ -109,10 +112,17 @@ if (theme === '') {
109
112
  process.stderr.write(`aitop: ${t('cli.themeMissing')}\n`);
110
113
  process.exit(2);
111
114
  }
112
- const unknown = [...args].filter((a) => !KNOWN.has(a));
113
- if (theme != null && !THEMES.includes(theme)) unknown.push(`--theme ${theme}`);
115
+ // 모르는 옵션은 도움말 전체 대신 가까운 옵션 제안과 --help 안내 한 줄만 낸다 (#291).
116
+ const unknown = [...args].filter((a) => !KNOWN.has(a)).map((a) => {
117
+ const near = a.startsWith('-') ? suggest(a, OPTIONS) : null;
118
+ return near ? `${a} ${t('cli.didYouMean', { opt: near })}` : a;
119
+ });
120
+ if (theme != null && !THEMES.includes(theme)) {
121
+ const near = suggest(theme, THEMES);
122
+ unknown.push(`--theme ${theme} ${near ? t('cli.didYouMean', { opt: `--theme ${near}` }) : t('cli.themeValues')}`);
123
+ }
114
124
  if (unknown.length) {
115
- process.stderr.write(`aitop: ${t('cli.unknown', { opts: unknown.join(' ') })}\n\n${HELP}\n`);
125
+ process.stderr.write(`aitop: ${t('cli.unknown', { opts: stripControl(unknown.join(', ')) })}\naitop: ${t('cli.seeHelp')}\n`);
116
126
  process.exit(2);
117
127
  }
118
128
  if (args.has('-h') || args.has('--help')) {
@@ -265,14 +275,14 @@ if (args.has('--doctor')) {
265
275
  if (cfgFile.onWaitingIgnored && !cli.onWaiting) process.stderr.write(`aitop: ${cfgFile.onWaitingIgnored}\n`);
266
276
 
267
277
  const { collect } = await import('../src/collect.mjs');
268
- const { render, filterSessions, animating } = await import('../src/ui.mjs');
278
+ const { render, pipeLines, filterSessions, animating } = await import('../src/ui.mjs');
269
279
  const { arrange } = await import('../src/order.mjs');
270
280
  const { frameTimer } = await import('../src/frames.mjs');
271
281
  const { flushCache } = await import('../src/cache.mjs');
272
282
  const { toJson } = await import('../src/json.mjs');
273
283
  const { createSummaryWriter, summarize, writeSummary } = await import('../src/summary.mjs');
274
284
  const { createAttention, updateAttention, markSeen, nextAttention, windowTitle, createWaitWatch, takeNewlyWaiting, attentionCounts, createEventWatch, takeEvents } = await import('../src/attention.mjs');
275
- const { createNotifier } = await import('../src/notify.mjs');
285
+ const { applyNotifyToggle, createNotifier, createNotifyToggle, notifyExplicitOff, notifyHintDue } = await import('../src/notify.mjs');
276
286
  const { onKey, fixFocus } = await import('../src/keys.mjs');
277
287
  const { admit, createLoading, latchReady } = await import('../src/loading.mjs');
278
288
  const { osc52, resumeCmd } = await import('../src/resume.mjs');
@@ -300,7 +310,13 @@ let tools = null;
300
310
  // --bell · --notify · --on-waiting: 실시간 화면에서만, 첫 갱신에서 이미 응답 대기인 세션은 알리지 않는다.
301
311
  const bell = opt.bell;
302
312
  const waitWatch = createWaitWatch();
303
- const notifier = !once && (alerts.notify || alerts.onWaiting) ? createNotifier(alerts) : null;
313
+ // 실시간 화면에서는 알림이 꺼져 있어도 알리미를 둔다. a 키로 데스크톱 알림을 이번 실행에만 켤 수 있게 (#294).
314
+ const notifier = !once ? createNotifier(alerts) : null;
315
+ // 켜기 힌트는 설정 파일이나 --no-notify 로 직접 끄지 않았을 때만 띄운다.
316
+ // --notify 로 켰어도 알림 도구가 없으면 키 줄·도움말에 꺼짐으로 보인다 (알리미에 desk 가 없다).
317
+ const notifyToggle = createNotifyToggle({ on: alerts.notify, explicitOff: notifyExplicitOff(config.values.notify, alerts.notify), available: once || Boolean(notifier?.desk) });
318
+ settings.notify = notifyToggle.on;
319
+ if (!once) view.notify = notifyToggle.on;
304
320
  // 끝남(done)·context 경고는 켠 경우에만 센다 (#204). 벨은 늘 응답 대기만 울린다.
305
321
  const eventKinds = alerts.events.filter((k) => k !== 'waiting');
306
322
  const eventWatch = notifier && eventKinds.length ? createEventWatch({ doneMs: opt.doneMinutes * 60_000 }) : null;
@@ -326,6 +342,9 @@ function refresh({ throttle = false } = {}) {
326
342
  if (fresh.length && bell) process.stdout.write('\x07');
327
343
  if (alerts.events.includes('waiting')) notifier?.fire(fresh);
328
344
  }
345
+ // 알림이 꺼진 채로 응답 대기 세션이 처음 보이면 키 줄에 켜기 힌트를 한 번 띄운다 (기록을 다 읽은 뒤).
346
+ // 도움말·검색 중에는 키 줄이 힌트를 그리지 않으므로 닫힐 때까지 미룬다.
347
+ if (!once && loading.ready && notifyHintDue(notifyToggle, data.sessions, { visible: !view.help && !view.searching })) toast('foot.notifyHint', HINT_MS);
329
348
  if (eventWatch) {
330
349
  const evs = takeEvents(eventWatch, data.sessions, { ready: loading.ready });
331
350
  for (const kind of eventKinds) notifier.fire(evs.filter((e) => e.kind === kind).map((e) => e.session), kind);
@@ -343,6 +362,19 @@ function refresh({ throttle = false } = {}) {
343
362
  }
344
363
  let lastMore = false;
345
364
 
365
+ // 키 줄 왼쪽에 잠깐 보이는 알림 (y 복사 결과, 알림 켜기 힌트). ms 가 지나면 지운다.
366
+ const TOAST_MS = 2000;
367
+ const HINT_MS = 10_000;
368
+ let toastTimer = null;
369
+ function toast(key, ms = TOAST_MS) {
370
+ view.toast = { key, until: Date.now() + ms };
371
+ clearTimeout(toastTimer);
372
+ toastTimer = setTimeout(() => {
373
+ view.toast = null;
374
+ draw();
375
+ }, ms);
376
+ }
377
+
346
378
  function select(id) {
347
379
  if (id !== view.selectedId) {
348
380
  view.focus = null;
@@ -360,7 +392,9 @@ if (once) {
360
392
  const size = (v) => (Number(v) > 0 ? Math.floor(Number(v)) : 0);
361
393
  const W = process.stdout.columns || size(process.env.COLUMNS) || 140;
362
394
  const H = process.stdout.rows || size(process.env.LINES) || 40;
363
- await printAndExit(args.has('--json') ? JSON.stringify(toJson(view.data, VERSION, { showRequests, budgetDay: opt.budgetDay }), null, 2) : render(view, W, H).join('\n'));
395
+ // 터미널이 아니면(파이프·파일) 높이 맞춤 빈 줄과 쓸 수 없는 키 안내를 빼고 내용만 낸다 (#292).
396
+ const screen = () => (process.stdout.isTTY ? render(view, W, H) : pipeLines(render(view, W, H)));
397
+ await printAndExit(args.has('--json') ? JSON.stringify(toJson(view.data, VERSION, { showRequests, budgetDay: opt.budgetDay }), null, 2) : screen().join('\n'));
364
398
  }
365
399
 
366
400
  const out = process.stdout;
@@ -470,23 +504,26 @@ function keepSelectionVisible() {
470
504
  }
471
505
 
472
506
  // y: 이어 여는 명령을 OSC 52 로 클립보드에 쓴다. 터미널이 아니면 아무것도 하지 않는다. 알림은 2초 보인다.
473
- const TOAST_MS = 2000;
474
- let toastTimer = null;
475
507
  function copy(s) {
476
508
  if (!out.isTTY) return;
477
509
  const cmd = resumeCmd(s);
478
510
  if (cmd) out.write(osc52(cmd));
479
- view.toast = { key: cmd ? 'foot.copied' : 'foot.copyNone', until: Date.now() + TOAST_MS };
480
- clearTimeout(toastTimer);
481
- toastTimer = setTimeout(() => {
482
- view.toast = null;
483
- draw();
484
- }, TOAST_MS);
511
+ toast(cmd ? 'foot.copied' : 'foot.copyNone');
512
+ }
513
+
514
+ // a: 데스크톱 알림을 이번 실행에만 켜고 끈다. 설정 파일은 바꾸지 않는다 (#294).
515
+ // 알릴 종류는 시작할 때 정한 값(설정 파일·--notify=<종류>, 없으면 waiting)을 그대로 쓴다.
516
+ function flipNotify() {
517
+ const key = applyNotifyToggle(notifyToggle, notifier);
518
+ view.notify = notifyToggle.on;
519
+ settings.notify = notifyToggle.on;
520
+ toast(key);
485
521
  }
486
522
 
487
523
  stdin.setEncoding('utf8');
488
524
  const act = {
489
525
  copy,
526
+ toggleNotify: flipNotify,
490
527
  quit,
491
528
  refresh,
492
529
  move,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sejuneoh/aitop",
3
- "version": "0.36.1",
3
+ "version": "0.37.0",
4
4
  "description": "터미널에서 Claude Code · Codex · Antigravity · Gemini 세션과 토큰을 실시간으로 보는 읽기 전용 모니터",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/doctor.mjs CHANGED
@@ -7,7 +7,7 @@ import { homedir, platform } from 'node:os';
7
7
  import { findProcesses, isCodex, isGemini, isAgy, canListProcesses, isAlive, isSessionAlive, processMethod } from './procs.mjs';
8
8
  import { AGY_ROOT } from './sources/antigravity.mjs';
9
9
  import { loadSqlite, openReadOnly } from './sqlite.mjs';
10
- import { fmtAgo, pad, stripControl } from './text.mjs';
10
+ import { fmtAgo, pad, stripControl, width } from './text.mjs';
11
11
  import { BRAND } from './brand.mjs';
12
12
  import { tildeIn } from './paths.mjs';
13
13
  import { busProblem, findNotifier, isWsl } from './notify.mjs';
@@ -302,14 +302,17 @@ export function doctorText(result, version, now = Date.now(), lang = getLang())
302
302
  if (result.console?.legacy) out.push('', tr('doctor.legacyConsole', null, o), ` → ${tr('doctor.legacyConsoleHint', null, o)}`);
303
303
  // 설정 파일: 무시한 키와 값, 받지 않은 onWaiting 을 알린다.
304
304
  const cfg = result.config;
305
+ // 설정·디버그 줄의 상태 칸 폭. 10칸보다 긴 상태 글("not found (defaults)")은 자르지 않고, 두 줄의 경로 열을 맞춘다.
306
+ const cfgWord = cfg && tr(cfg.exists ? 'doctor.configExists' : 'doctor.configMissing', null, o);
307
+ const logWord = result.log && tr(result.log.on ? 'doctor.debugOn' : 'doctor.debugOff', null, o);
308
+ const stateW = Math.max(10, ...[cfgWord, logWord].filter(Boolean).map((w) => width(w) + 1));
305
309
  if (cfg) {
306
- const state = pad(tr(cfg.exists ? 'doctor.configExists' : 'doctor.configMissing', null, o), 10);
307
- out.push('', tr('doctor.config', { mark: cfg.problems.length ? '!' : '✓', state, path: tilde(cfg.path) }, o));
310
+ out.push('', tr('doctor.config', { mark: cfg.problems.length ? '!' : '✓', state: pad(cfgWord, stateW), path: tilde(cfg.path) }, o));
308
311
  for (const p of cfg.problems) out.push(` ! ${p}`);
309
312
  }
310
313
  if (result.log) {
311
314
  const on = result.log.on;
312
- out.push('', tr('doctor.debug', { mark: on ? '✓' : '○', state: pad(tr(on ? 'doctor.debugOn' : 'doctor.debugOff', null, o), 10), path: tilde(result.log.path), tail: on ? '' : tr('doctor.debugTail', null, o) }, o));
315
+ out.push('', tr('doctor.debug', { mark: on ? '✓' : '○', state: pad(logWord, stateW), path: tilde(result.log.path), tail: on ? '' : tr('doctor.debugTail', null, o) }, o));
313
316
  }
314
317
  return stripControl(out.join('\n'));
315
318
  }
package/src/help.mjs CHANGED
@@ -20,6 +20,7 @@ export const VIEWS = {
20
20
  k('table.sort', 's', 'sort'),
21
21
  k('table.group', 'g', 'group'),
22
22
  k('table.costMode', 'c', 'costMode'),
23
+ k('table.notify', 'a', 'notify'),
23
24
  k('table.pin', 'p', 'pin'),
24
25
  k('table.files', 'f Tab', 'files'),
25
26
  k('table.detail', 'd', 'detail'),
package/src/i18n.mjs CHANGED
@@ -196,6 +196,7 @@ export const STRINGS = {
196
196
  'key.sort': '정렬',
197
197
  'key.group': '묶기',
198
198
  'key.costMode': '비용 기준',
199
+ 'key.notify': '알림',
199
200
  'key.pin': '고정',
200
201
  'key.files': '변경 파일',
201
202
  'key.detail': '상세',
@@ -220,7 +221,10 @@ export const STRINGS = {
220
221
  'key.help': '도움말',
221
222
  'key.quit': '나가기',
222
223
 
223
- 'cli.unknown': '모르는 옵션 {opts}',
224
+ 'cli.unknown': '알 수 없는 옵션 {opts}',
225
+ 'cli.didYouMean': '(혹시 {opt}?)',
226
+ 'cli.themeValues': '(light 또는 dark)',
227
+ 'cli.seeHelp': '전체 옵션은 aitop --help',
224
228
  'cli.themeMissing': '--theme 값이 없습니다 (light 또는 dark)',
225
229
  'cli.unhandled': '처리되지 않은 오류로 끝냅니다 ({why})',
226
230
  'cli.logOff': '디버그 로그를 열 수 없어 끕니다 ({path})',
@@ -445,7 +449,8 @@ export const STRINGS = {
445
449
  'hdr.netShort': '캐시제외',
446
450
 
447
451
  'tools.missing': '미설치',
448
- 'tools.hidden': '숨김 {list}',
452
+ 'tools.hiddenMissing': '미설치: {list}',
453
+ 'tools.hiddenIdle': '7일 미사용: {list}',
449
454
  'tools.ended': '종료된 세션 포함 (24시간)',
450
455
  'table.title': '세션 {n}',
451
456
  'member.stalled': '멈춘 듯',
@@ -464,12 +469,12 @@ export const STRINGS = {
464
469
  'groupBy.tool': '도구',
465
470
  'empty.none': '실행 중인 AI 세션이 없습니다.',
466
471
  'empty.none24': '지난 24시간 안에 AI 세션이 없습니다.',
472
+ 'empty.procs': '{list} 실행 중이지만 읽을 세션 기록이 아직 없습니다.',
473
+ 'empty.procsHint': '그 도구에 요청을 보내면 여기에 나옵니다. 점검: aitop --doctor',
467
474
  'empty.show': '지난 24시간 세션 보기: ',
468
475
  'empty.or': ' 또는 ',
469
476
 
470
477
  'foot.help': '도움',
471
- // 폭이 모자라 키 안내가 빠졌을 때 ? 칩 라벨.
472
- 'foot.helpAll': '키 전체',
473
478
  'foot.closeHelp': '도움 닫기',
474
479
  'foot.readOnly': '⊘ 읽기전용',
475
480
  'foot.count': '{n}개',
@@ -489,6 +494,11 @@ export const STRINGS = {
489
494
  'foot.costMode': '비용 기준',
490
495
  'foot.copied': '이어 여는 명령을 클립보드로 보냄 (OSC 52)',
491
496
  'foot.copyNone': '이 세션은 이어 여는 명령이 없다',
497
+ 'foot.notify': '알림:{v}',
498
+ 'foot.notifyHint': '응답 대기 알림 켜기: a',
499
+ 'foot.notifyOn': '응답 대기 알림 켬 (이번 실행만)',
500
+ 'foot.notifyOff': '응답 대기 알림 끔 (이번 실행만)',
501
+ 'foot.notifyNone': '알림 도구를 찾지 못함. aitop --doctor 로 확인',
492
502
  'foot.clearSearch': '검색 지우기',
493
503
 
494
504
  'help.title': '도움말 · ? 또는 Esc 로 닫기',
@@ -526,7 +536,9 @@ export const STRINGS = {
526
536
  'legend.cost': 'API 정가로 환산한 비용 (Codex 는 OpenAI 정가 추정). 가격표에 없는 모델은 빼고 센다',
527
537
  'legend.context': '마지막 요청의 컨텍스트 사용률 (모델별 창 크기 기준)',
528
538
  'legend.idleCol': '마지막 활동 후 지난 시간. 작업 중이면 now',
529
- 'legend.hiddenKey': '숨김 N',
539
+ 'legend.missingKey': '미설치: N',
540
+ 'legend.missing': '도구 줄 끝: 기록 폴더가 없어 숨긴 도구',
541
+ 'legend.hiddenKey': '7일 미사용: N',
530
542
  'legend.hidden': '도구 줄 끝: 7일 동안 안 쓴 도구를 숨김. 다시 보려면 설정 파일에 "hideIdleTools": false',
531
543
  'legend.folded': '도구 줄 끝: 화면이 좁아 접은 도구 수 (넓히면 보인다)',
532
544
  'legend.periodKey': '오늘 / 7일',
@@ -541,6 +553,7 @@ export const STRINGS = {
541
553
  'hk.table.sort': '정렬: 기본 → 비용순 → 컨텍스트순 → 최근순. 응답 대기는 늘 맨 위',
542
554
  'hk.table.group': '묶기: 없음 → 프로젝트 → 도구. 묶음 머리에 세션 수·비용',
543
555
  'hk.table.costMode': '비용 기준: API 환산 ↔ 캐시 제외. 표·헤더·상세가 같이 바뀐다 (예산은 늘 API 환산)',
556
+ 'hk.table.notify': '응답 대기 데스크톱 알림 켜기·끄기. 이번 실행에만, 설정 파일은 그대로',
544
557
  'hk.table.pin': '고른 세션을 맨 위(응답 대기 아래)에 고정·해제. 여러 개는 고정한 순서, 이번 실행에만',
545
558
  'hk.table.files': '고른 세션의 변경 파일 목록으로',
546
559
  'hk.table.detail': '상세 패널 열기·닫기',
@@ -670,6 +683,7 @@ export const STRINGS = {
670
683
  'key.sort': 'sort',
671
684
  'key.group': 'group',
672
685
  'key.costMode': 'cost basis',
686
+ 'key.notify': 'alerts',
673
687
  'key.pin': 'pin',
674
688
  'key.files': 'changed files',
675
689
  'key.detail': 'detail',
@@ -695,6 +709,9 @@ export const STRINGS = {
695
709
  'key.quit': 'quit',
696
710
 
697
711
  'cli.unknown': 'unknown option {opts}',
712
+ 'cli.didYouMean': '(did you mean {opt}?)',
713
+ 'cli.themeValues': '(light or dark)',
714
+ 'cli.seeHelp': 'all options: aitop --help',
698
715
  'cli.themeMissing': '--theme needs a value (light or dark)',
699
716
  'cli.unhandled': 'stopping on an unhandled error ({why})',
700
717
  'cli.logOff': 'cannot open the debug log, turning it off ({path})',
@@ -849,7 +866,7 @@ export const STRINGS = {
849
866
  'doctor.legacyConsoleHint': 'Windows Terminal is recommended. In this console, run with AITOP_AMBIGUOUS=wide (ASCII tables and bars) or NO_COLOR (progress bar as [#.])',
850
867
  'doctor.config': '{mark} config {state}{path}',
851
868
  'doctor.configExists': 'found',
852
- 'doctor.configMissing': 'not found',
869
+ 'doctor.configMissing': 'not found (defaults)',
853
870
  'doctor.debug': '{mark} debug {state}{path}{tail}',
854
871
  'doctor.debugOn': 'on',
855
872
  'doctor.debugOff': 'off',
@@ -910,7 +927,8 @@ export const STRINGS = {
910
927
  'hdr.netShort': 'no cache',
911
928
 
912
929
  'tools.missing': 'not installed',
913
- 'tools.hidden': 'hidden {list}',
930
+ 'tools.hiddenMissing': 'not installed: {list}',
931
+ 'tools.hiddenIdle': 'unused 7d: {list}',
914
932
  'tools.ended': 'with ended sessions (24h)',
915
933
  'table.title': 'Sessions {n}',
916
934
  'member.stalled': 'stalled?',
@@ -929,11 +947,12 @@ export const STRINGS = {
929
947
  'groupBy.tool': 'tool',
930
948
  'empty.none': 'No AI sessions running.',
931
949
  'empty.none24': 'No AI sessions in the last 24 hours.',
950
+ 'empty.procs': '{list} running, but no session records to read yet.',
951
+ 'empty.procsHint': 'Send it a request to see it here. Check: aitop --doctor',
932
952
  'empty.show': 'Show the last 24 hours: ',
933
953
  'empty.or': ' or ',
934
954
 
935
955
  'foot.help': 'help',
936
- 'foot.helpAll': 'all keys',
937
956
  'foot.closeHelp': 'close help',
938
957
  'foot.readOnly': '⊘ read-only',
939
958
  'foot.count': '{n} found',
@@ -953,6 +972,11 @@ export const STRINGS = {
953
972
  'foot.costMode': 'cost',
954
973
  'foot.copied': 'resume command sent to clipboard (OSC 52)',
955
974
  'foot.copyNone': 'no resume command for this session',
975
+ 'foot.notify': 'alerts:{v}',
976
+ 'foot.notifyHint': 'turn on waiting alerts: a',
977
+ 'foot.notifyOn': 'waiting alerts on (this run only)',
978
+ 'foot.notifyOff': 'waiting alerts off (this run only)',
979
+ 'foot.notifyNone': 'no alert tool found. Check with aitop --doctor',
956
980
  'foot.clearSearch': 'clear search',
957
981
 
958
982
  'help.title': 'Help · ? or Esc to close',
@@ -990,7 +1014,9 @@ export const STRINGS = {
990
1014
  'legend.cost': 'API cost (Codex estimated). Unpriced models not counted',
991
1015
  'legend.context': 'Context used by the last request',
992
1016
  'legend.idleCol': 'Time since last activity. now while working',
993
- 'legend.hiddenKey': 'hidden N',
1017
+ 'legend.missingKey': 'not installed: N',
1018
+ 'legend.missing': 'Tools hidden because their log folder is missing',
1019
+ 'legend.hiddenKey': 'unused 7d: N',
994
1020
  'legend.hidden': 'Tools unused for 7 days (hideIdleTools)',
995
1021
  'legend.folded': 'Tools folded on a narrow screen',
996
1022
  'legend.periodKey': 'today / 7d',
@@ -1004,6 +1030,7 @@ export const STRINGS = {
1004
1030
  'hk.table.sort': 'Sort: cost, context, recent. Waiting on top',
1005
1031
  'hk.table.group': 'Group by project or tool, with cost',
1006
1032
  'hk.table.costMode': 'Cost basis: API cost or no cache',
1033
+ 'hk.table.notify': 'Turn waiting alerts on or off (this run only)',
1007
1034
  'hk.table.pin': 'Pin on top, below waiting (this run only)',
1008
1035
  'hk.table.files': 'Changed files of the session',
1009
1036
  'hk.table.detail': 'Show or hide the detail panel',
package/src/keys.mjs CHANGED
@@ -144,6 +144,8 @@ export function onKey(view, key, act) {
144
144
  }
145
145
  // y: 고른 세션을 이어 여는 명령을 복사한다 (bin 이 OSC 52 로 쓴다). 세션에는 아무것도 보내지 않는다.
146
146
  else if (key === 'y') act.copy?.(selectedSession(view));
147
+ // a: 응답 대기 데스크톱 알림을 켜고 끈다 (#294). 이번 실행에만, 설정 파일은 바꾸지 않는다. 실제 켜기·끄기는 bin 이 한다.
148
+ else if (key === 'a') act.toggleNotify?.();
147
149
  else if (key === 'c') view.costMode = view.costMode === 'net' ? 'api' : 'net';
148
150
  else if (key === 'd') {
149
151
  // view.rows: 마지막으로 그린 화면 높이. 'auto' 일 때 지금 보이는 상태를 뒤집는 데 쓴다.
package/src/line.mjs CHANGED
@@ -14,6 +14,8 @@ export const CAP_MS = 1500;
14
14
  export const STOP_MIN_MS = 300;
15
15
  // 캐시가 없거나 시간 상한을 넘었을 때 내는 글.
16
16
  export const PENDING = '...';
17
+ // 오늘 비용·대기·작업 중 등 보일 항목이 하나도 없을 때 내는 글.
18
+ export const IDLE = 'aitop idle';
17
19
  // 기다리는 세션 이름의 최대 폭 (칸). 기본 폭 40 에 오늘 비용·예산·대기(이름과 시간)·작업 중이 함께 들어가는 길이.
18
20
  export const NAME_WIDTH = 12;
19
21
  // 이름을 자른 자리 표시. … 는 ASCII 가 아니다.
@@ -22,7 +24,8 @@ const CUT = '~';
22
24
  // tmux 256색 번호. 응답 대기는 눈에 띄는 주황, 돈은 화면 헤더와 같은 연두. 색약용은 노랑·파랑 계열로 가른다.
23
25
  // 작업 중은 눈에 덜 띄는 회색 계열로 둔다 (주목할 것은 대기다).
24
26
  // 멈춤(오류로 멈춘 세션)은 화면의 경고색과 같은 빨강, 색약용은 주홍. 색이 없어도 'stop' 글자로 갈린다.
25
- const COLOURS = { normal: { waiting: 'colour214', stopped: 'colour203', money: 'colour154', running: 'colour250' }, colorBlind: { waiting: 'colour226', stopped: 'colour209', money: 'colour75', running: 'colour250' } };
27
+ // 쉬는 중(aitop idle)은 작업 중보다 더 흐린 회색.
28
+ const COLOURS = { normal: { waiting: 'colour214', stopped: 'colour203', money: 'colour154', running: 'colour250', idle: 'colour242' }, colorBlind: { waiting: 'colour226', stopped: 'colour209', money: 'colour75', running: 'colour250', idle: 'colour242' } };
26
29
 
27
30
  // --line, --line=plain|tmux, --line-width <N>, --line-width=<N> 를 꺼낸다. line 은 켜지 않았으면 null.
28
31
  export function lineOption(argv) {
@@ -98,6 +101,8 @@ export function formatLine({ today = 0, budgetDay = null, waiting = 0, longest =
98
101
  if (stopped > 0) parts.push({ texts: [`stop ${stopped}`], fg: c.stopped });
99
102
  if (running > 0) parts.push({ texts: [`run ${running}`], fg: c.running });
100
103
  if (!zero(perHour)) parts.push({ texts: [`${rate(perHour)}/h`], fg: c.money });
104
+ // 보일 항목이 하나도 없으면 빈 줄 대신 IDLE 을 낸다 (고장과 구분되게). 폭이 모자라면 짧은 글, 그래도 모자라면 - (#292).
105
+ if (!parts.length) parts.push({ texts: [IDLE, 'idle', '-'], fg: c.idle });
101
106
  while (parts.length && width(parts.map((p) => p.texts[0]).join(' ')) > max) {
102
107
  if (parts.at(-1).texts.length > 1) parts.at(-1).texts.shift();
103
108
  else parts.pop();
package/src/notify.mjs CHANGED
@@ -5,6 +5,7 @@ import { accessSync, constants, existsSync, readFileSync } from 'node:fs';
5
5
  import { join, delimiter, posix, win32 } from 'node:path';
6
6
  import { mask, stripControl } from './text.mjs';
7
7
  import { getLang, phaseText, t } from './i18n.mjs';
8
+ import { callsYou } from './attention.mjs';
8
9
 
9
10
  export const HOOK_TIMEOUT_MS = 10_000;
10
11
  const LABEL_MAX = 120;
@@ -388,20 +389,36 @@ export function createRunner({ timeoutMs = HOOK_TIMEOUT_MS, spawnFn = spawn, pla
388
389
 
389
390
  // --notify, --on-waiting 을 묶은 알리미. 알릴 세션 목록과 종류(waiting·done·context)를 받는다.
390
391
  // --on-waiting 명령에는 AITOP_EVENT 로 종류를 넘긴다 (예전 명령은 waiting 만 받으므로 그대로 동작한다).
391
- export function createNotifier({ notify = false, onWaiting = null, platform = process.platform, notifier = notify ? findNotifier({ platform }) : null, env = process.env, timeoutMs = HOOK_TIMEOUT_MS, spawnFn = spawn, spawnSyncFn = spawnSync } = {}) {
392
+ // setNotify(on): 실행 중 a 키로 데스크톱 알림을 켜고 끈다 (#294). 처음 켤 때 알림 도구를 찾고(find), 없으면 false 를 돌려준다.
393
+ export function createNotifier({ notify = false, onWaiting = null, platform = process.platform, find = findNotifier, notifier = notify ? find({ platform }) : null, env = process.env, timeoutMs = HOOK_TIMEOUT_MS, spawnFn = spawn, spawnSyncFn = spawnSync } = {}) {
392
394
  const hook = onWaiting ? createRunner({ timeoutMs, spawnFn, platform, spawnSyncFn }) : null;
393
- const desk = notify && notifier ? createRunner({ timeoutMs, spawnFn, platform, spawnSyncFn }) : null;
395
+ let desk = notify && notifier ? createRunner({ timeoutMs, spawnFn, platform, spawnSyncFn }) : null;
396
+ let deskOn = notify;
397
+ let searched = notify;
394
398
  const [shell, shellArgs, shellOpts] = onWaiting ? hookCommand(onWaiting, { platform, env }) : [];
395
399
  return {
396
400
  hook,
397
- desk,
401
+ get desk() {
402
+ return desk;
403
+ },
404
+ setNotify(on) {
405
+ deskOn = Boolean(on);
406
+ if (deskOn && !desk && !searched) {
407
+ searched = true;
408
+ notifier = find({ platform });
409
+ if (notifier) desk = createRunner({ timeoutMs, spawnFn, platform, spawnSyncFn });
410
+ }
411
+ // 끌 때는 대기열만 비운다. 이미 뜬 알림 도구는 HOOK_TIMEOUT_MS 안에 끝난다.
412
+ if (!deskOn) desk?.killAll();
413
+ return Boolean(deskOn && desk);
414
+ },
398
415
  killAll() {
399
416
  hook?.killAll();
400
417
  desk?.killAll();
401
418
  },
402
419
  fire(fresh, kind = 'waiting') {
403
420
  if (!fresh.length) return;
404
- if (desk) {
421
+ if (desk && deskOn) {
405
422
  const { title, body } = notifyText(fresh, getLang(), kind);
406
423
  const [file, args] = notifierCommand(notifier, title, body);
407
424
  desk.run({ file, args, env });
@@ -410,3 +427,44 @@ export function createNotifier({ notify = false, onWaiting = null, platform = pr
410
427
  },
411
428
  };
412
429
  }
430
+
431
+ // 실행 중 알림 켜기·끄기 상태 (#294). 이번 실행에만 쓰고 설정 파일은 바꾸지 않는다.
432
+ // explicitOff: 설정 파일이나 --no-notify 로 직접 끈 경우. 그때는 켜기 힌트를 띄우지 않는다.
433
+ // hinted: 힌트를 이미 띄웠거나 사용자가 a 를 눌러 본 적이 있는지 (실행당 한 번).
434
+ // available: 알림 도구를 찾았는지. --notify 로 켰어도 도구가 없으면 꺼짐으로 보인다 (설정은 건드리지 않는다).
435
+ // 이때는 사용자가 직접 켠 것이라 켜기 힌트도 띄우지 않는다.
436
+ export function createNotifyToggle({ on = false, explicitOff = false, available = true } = {}) {
437
+ const missing = Boolean(on) && !available;
438
+ return { on: Boolean(on) && !missing, explicitOff: Boolean(explicitOff), hinted: missing };
439
+ }
440
+
441
+ // 설정 값(resolveConfig 의 values.notify)으로 직접 껐는지 본다. 기본값(source: 'default')으로 꺼진 것만 직접 끄지 않은 것이다.
442
+ export const notifyExplicitOff = (entry, on) => !on && entry != null && entry.source !== 'default';
443
+
444
+ export function toggleNotify(state) {
445
+ state.on = !state.on;
446
+ state.hinted = true;
447
+ return state.on;
448
+ }
449
+
450
+ // a 키: 상태를 뒤집고 알리미(setNotify)에 반영한다. 켜려 했는데 알림 도구가 없으면 꺼짐으로 되돌린다.
451
+ // 돌려주는 값은 키 줄에 잠깐 보일 문구의 i18n 키.
452
+ export function applyNotifyToggle(state, notifier) {
453
+ const want = toggleNotify(state);
454
+ const ok = notifier.setNotify(want);
455
+ if (want && !ok) {
456
+ state.on = false;
457
+ notifier.setNotify(false);
458
+ return 'foot.notifyNone';
459
+ }
460
+ return want ? 'foot.notifyOn' : 'foot.notifyOff';
461
+ }
462
+
463
+ // 알림이 꺼져 있고 직접 끄지 않았을 때, 실행 중인 응답 대기 세션이 처음 보이면 한 번만 true (시작 때 이미 대기 중인 세션 포함).
464
+ // visible: 키 줄에 힌트를 그릴 수 있는지 (도움말·검색 중에는 키 줄이 힌트를 그리지 않는다). false 면 소비하지 않고 다음 갱신에 다시 본다.
465
+ export function notifyHintDue(state, sessions = [], { visible = true } = {}) {
466
+ if (state.on || state.explicitOff || state.hinted || !visible) return false;
467
+ if (!sessions.some((s) => s.live && callsYou(s))) return false;
468
+ state.hinted = true;
469
+ return true;
470
+ }
@@ -0,0 +1,31 @@
1
+ // 잘못 친 옵션에 가까운 옵션 하나를 고른다. 의존성 없이 짧은 편집 거리(이웃 글자 자리바꿈 포함)로 잰다.
2
+
3
+ // 삽입·삭제·바꾸기·이웃 두 글자 자리바꿈을 1 로 센 거리 (optimal string alignment).
4
+ export function editDistance(a, b) {
5
+ const d = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
6
+ for (let j = 1; j <= b.length; j++) d[0][j] = j;
7
+ for (let i = 1; i <= a.length; i++) {
8
+ for (let j = 1; j <= b.length; j++) {
9
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
10
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
11
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
12
+ }
13
+ }
14
+ return d[a.length][b.length];
15
+ }
16
+
17
+ // 앞의 - 와 = 뒤 값을 떼고 비교한다. 거리 상한은 4글자 이하 1, 그보다 길면 2 (엉뚱한 제안을 막는다).
18
+ // 상한 안에서 가장 가까운 후보(같은 거리면 앞의 것)를 돌려주고, 없으면 null. 입력과 똑같은 후보는 제안하지 않는다.
19
+ export function suggest(word, candidates) {
20
+ const core = (s) => s.replace(/^-+/, '').replace(/=.*$/, '').toLowerCase();
21
+ const w = core(word);
22
+ if (!w) return null;
23
+ let best = null;
24
+ let bestD = (w.length <= 4 ? 1 : 2) + 1;
25
+ for (const c of candidates) {
26
+ if (c === word) continue;
27
+ const dist = editDistance(w, core(c));
28
+ if (dist < bestD) [best, bestD] = [c, dist];
29
+ }
30
+ return best;
31
+ }
package/src/ui/chrome.mjs CHANGED
@@ -33,6 +33,8 @@ const LEGEND_IDS = [
33
33
  ['COST', 'legend.cost'],
34
34
  ['CONTEXT', 'legend.context'],
35
35
  ['IDLE', 'legend.idleCol'],
36
+ // 도구 줄 끝의 숨김 표시. 미설치와 7일 미사용을 나눠 적는다 (#290).
37
+ ['legend.missingKey', 'legend.missing'],
36
38
  ['legend.hiddenKey', 'legend.hidden'],
37
39
  ['+N', 'legend.folded'],
38
40
  ['legend.periodKey', 'legend.period'],
@@ -132,7 +134,7 @@ export const keyChip = (k) => (NO_COLOR ? { t: `[${k}]` } : { t: ` ${k} `, fg: P
132
134
  export const keyLabel = (v) => ({ t: ` ${v} `, fg: PALETTE.muted });
133
135
 
134
136
  // items: { k, t, keep, cut } 또는 { segs, keep }. 폭이 모자라면 keep 이 아닌 항목을 오른쪽부터 뺀다.
135
- // cut: 항목을 하나라도 뺐을 때 바꿔 쓸 라벨. ? 칩이 '키 전체' 로 바뀌어 빠진 키를 도움말에서 찾게 한다 (#265).
137
+ // cut: 항목을 하나라도 뺐을 때 바꿔 쓸 라벨 (#265). ? 칩은 폭마다 이름이 바뀌지 않게 쓰지 않는다 (#290).
136
138
  export function hintBar(items, W, right = '') {
137
139
  const segsOf = (list) => [{ t: ' ' }, ...list.flatMap((i) => i.segs ?? [keyChip(i.k), keyLabel(i.t)])];
138
140
  const wOf = (list) => segsWidth(segsOf(list));
@@ -168,17 +170,27 @@ function orderHint(view) {
168
170
  }
169
171
 
170
172
  // y 를 누른 뒤 잠깐 보이는 알림 (view.toast = { key, until }). 시간이 지나면 빠진다.
173
+ // 알림 켜기 힌트(foot.notifyHint)와 a 키 결과도 같은 자리에 보인다 (#294). 켠 결과는 초록, 나머지는 노랑.
174
+ const TOAST_OK = ['foot.copied', 'foot.notifyOn'];
171
175
  function toastItem(view, now = Date.now()) {
172
176
  const x = view.toast;
173
177
  if (!x || now >= x.until) return [];
174
- return [{ segs: [{ t: t(x.key), fg: x.key === 'foot.copied' ? PALETTE.busy : PALETTE.waiting, bold: true }, { t: ' ' }], keep: true }];
178
+ return [{ segs: [{ t: t(x.key, x.vars), fg: TOAST_OK.includes(x.key) ? PALETTE.busy : PALETTE.waiting, bold: true }, { t: ' ' }], keep: true }];
179
+ }
180
+
181
+ // 알림 상태 칩: a 알림:꺼짐. 키 줄 맨 끝(? q 앞)에 두어 넘칠 때 가장 먼저 빠진다. view.notify 는 bin 이 실시간 화면에서만 둔다 (--once 출력과 스냅숏에는 없다).
182
+ // 색이 없어도 글자로 켜짐·꺼짐을 읽을 수 있다.
183
+ function notifyItem(view) {
184
+ if (typeof view.notify !== 'boolean') return [];
185
+ return [{ k: 'a', t: t('foot.notify', { v: t(view.notify ? 'set.on' : 'set.off') }) }];
175
186
  }
176
187
 
177
188
  export function footer(view, W, matched, sel) {
178
189
  const RO = t('foot.readOnly');
179
190
  const toast = toastItem(view);
180
191
  const tail = [
181
- { k: '?', t: t('foot.help'), cut: t('foot.helpAll'), keep: true },
192
+ // ? 라벨은 폭과 상관없이 하나로 둔다 (#290).
193
+ { k: '?', t: t('foot.help'), keep: true },
182
194
  { k: 'q', t: t('key.quit'), keep: true },
183
195
  ];
184
196
  const ended = { k: 'e', t: t(view.showEnded ? 'foot.hideEnded' : 'foot.showEnded') };
@@ -215,6 +227,9 @@ export function footer(view, W, matched, sel) {
215
227
  ...(sel ? [{ k: 'p', t: t(view.pins?.includes(sel.id) ? 'foot.unpin' : 'key.pin') }] : []),
216
228
  // 복사(y)는 상세 패널에 이어 여는 명령이 보일 때만 안내하고, 폭이 모자라면 가장 먼저 빠진다.
217
229
  ...(view.showDetail && resumeCmd(sel) ? [{ k: 'y', t: t('key.copy') }] : []),
230
+ // 알림 상태 칩은 폭이 모자라면 가장 먼저 빠진다. 고정 해제·비용 기준처럼 고른 행에 쓰는 키 안내를 밀어내지 않게 (#294).
231
+ // 빠져도 a 키는 그대로 듣고, 지금 상태는 도움말(?)의 '지금' 줄에서 볼 수 있다.
232
+ ...notifyItem(view),
218
233
  ...tail,
219
234
  ];
220
235
  return hintBar(items, W, RO);
package/src/ui/detail.mjs CHANGED
@@ -192,6 +192,35 @@ export function wrapText(text, w) {
192
192
  return out;
193
193
  }
194
194
 
195
+ // 이어 열기 명령 줄바꿈: 공백·/·\ 뒤에서 끊어 경로 조각과 세션 id 가 폭이 허락하면 한 줄에 온전히 남는다 (&& 는 앞 공백에서 끊긴다).
196
+ // 한 조각이 폭보다 길면 지금 줄에 이어 붙이며 그 조각만 글자 단위로 끊는다. 요청 내용은 wrapText 로 글자 단위를 유지한다 (#293).
197
+ export function wrapCommand(text, w) {
198
+ const out = [];
199
+ let cur = '';
200
+ for (const piece of String(text).match(/[^ /\\]*[ /\\]|[^ /\\]+/g) ?? []) {
201
+ if (width((cur + piece).trimEnd()) <= w) {
202
+ cur += piece;
203
+ continue;
204
+ }
205
+ // 새 줄에 온전히 들어가면 줄을 바꾼다.
206
+ if (width(piece.trimEnd()) <= w) {
207
+ if (cur.trimEnd()) out.push(cur.trimEnd());
208
+ cur = piece;
209
+ continue;
210
+ }
211
+ // 폭보다 긴 조각: 지금 줄 남은 칸부터 글자 단위로 채운다.
212
+ for (const ch of piece) {
213
+ if (cur && width((cur + ch).trimEnd()) > w) {
214
+ out.push(cur.trimEnd());
215
+ cur = '';
216
+ }
217
+ if (cur || ch !== ' ') cur += ch;
218
+ }
219
+ }
220
+ if (cur.trimEnd() || !out.length) out.push(cur.trimEnd());
221
+ return out;
222
+ }
223
+
195
224
  // ── 요청 ── 구획: 응답 대기 중이고 요청 내용을 알 때만. 최대 max 줄, 넘치면 마지막 줄 끝을 … 로 바꾼다.
196
225
  export function requestBlock(s, w, max = REQUEST_LINES) {
197
226
  if (s.status !== 'waiting' || !s.waitDetail || max < 1) return [];
@@ -322,18 +351,103 @@ export function summaryLines(s, w, frame, view) {
322
351
  return [first, [{ t: ' ' }, ...second]];
323
352
  }
324
353
 
325
- // 이어 열기 명령을 폭에 맞춰 max 줄로 나눈다. 넘치면 마지막 줄 끝을 … 로 바꾼다 (복사하면 전체가 들어간다).
354
+ // 이어 열기 명령의 꼬리: 도구별 이어 여는 부분 ('claude --resume <id>', 'codex resume <id>', 'agy --conversation <id>').
355
+ const RESUME_TAIL = /(?:^| )((?:claude|codex|agy) \S+ \S+)$/;
356
+
357
+ // 글 가운데를 … 로 줄이는 함수를 만든다. 돌려준 함수(k)는 폭 k 안에 앞(cd 경로 머리)과 끝(&& 앞)을 남긴다.
358
+ // 글자 폭은 한 번만 재 두고, k 마다 앞과 끝을 번갈아 한 글자씩 채운다 (O(k)).
359
+ function middleCutter(text) {
360
+ const chars = [...text];
361
+ const ws = chars.map((ch) => width(ch));
362
+ const total = ws.reduce((a, b) => a + b, 0);
363
+ return (k) => {
364
+ if (total <= k) return text;
365
+ const mark = ellipsis(k);
366
+ const budget = k - width(mark);
367
+ let used = 0;
368
+ let i = 0;
369
+ let j = chars.length - 1;
370
+ for (let turn = 0; i <= j; turn++) {
371
+ const front = turn % 2 === 0;
372
+ const cw = front ? ws[i] : ws[j];
373
+ if (used + cw > budget) break;
374
+ used += cw;
375
+ if (front) i++;
376
+ else j--;
377
+ }
378
+ return chars.slice(0, i).join('') + mark + chars.slice(j + 1).join('');
379
+ };
380
+ }
381
+
382
+ // 폭 k 를 위에서부터 줄여 가며 make(k) 가 room 줄 안에 들어가는 첫 결과. 없으면 null.
383
+ // room 줄에는 폭 room*(w+1) 넘는 글이 들어갈 수 없으므로(줄 끝 공백 하나씩만 빠진다) 거기서부터 센다.
384
+ function fitLines(make, from, w, room) {
385
+ for (let k = Math.min(from, room * (w + 1) + 2); k >= 2; k--) {
386
+ const lines = wrapCommand(make(k), w);
387
+ if (lines.length <= room) return lines;
388
+ }
389
+ return null;
390
+ }
391
+
392
+ // 앞부분이 'cd <경로> && 변수=<값>' 이면 경로와 값만 줄여 && 와 변수 이름이 남게 한다 (변수가 없으면 앞부분 전체를 줄인다).
393
+ const CD_HEAD = /^(cd )('(?:[^']|'\\'')*'|\S+)( && [A-Za-z_][A-Za-z0-9_]*=)('(?:[^']|'\\'')*'|\S+)$/;
394
+
395
+ // 경로와 값에 폭 k 를 반씩 나눠 준다. 한쪽이 짧으면 남는 칸은 다른 쪽이 쓴다.
396
+ function envHead(cd) {
397
+ const [, pre, path, mid, value] = cd;
398
+ const cutPath = middleCutter(path);
399
+ const cutValue = middleCutter(value);
400
+ const pw = width(path);
401
+ const vw = width(value);
402
+ const fixed = width(pre) + width(mid);
403
+ return {
404
+ from: fixed + pw + vw,
405
+ make: (k) => {
406
+ const room = k - fixed;
407
+ const p = Math.min(pw, Math.max(2, room - Math.min(vw, Math.ceil(room / 2))));
408
+ const v = room - p;
409
+ return pre + cutPath(Math.max(2, p)) + mid + cutValue(Math.max(2, v));
410
+ },
411
+ };
412
+ }
413
+
414
+ // 마지막 줄 끝을 … 로 바꾼다.
415
+ function cutLast(lines, w) {
416
+ const mark = ellipsis(w);
417
+ const last = [...lines.at(-1)];
418
+ while (last.length && width(last.join('')) + width(mark) > w) last.pop();
419
+ return [...lines.slice(0, -1), last.join('') + mark];
420
+ }
421
+
422
+ // 이어 열기 명령을 폭에 맞춰 max 줄로 나눈다. 한 줄에 들어가면 그대로 둔다.
423
+ // 아니면 꼬리(도구 이름·옵션·세션 id)를 마지막 줄(들)에 두고, 앞부분(cd 경로, CLAUDE_CONFIG_DIR=…)은 남은 줄에 넣되 넘치면 가운데를 … 로 줄인다.
424
+ // 세션 id 는 폭이 id 보다 좁을 때만 글자 단위로 끊긴다.
425
+ // 꼬리만으로도 넘치면 마지막 줄 끝을 … 로 바꾼다. 화면만 줄이고 복사(y)에는 명령 전체가 들어간다.
326
426
  export function resumeLines(cmd, w, max) {
327
427
  if (!cmd || max < 1) return [];
328
- let lines = wrapText(cmd, Math.max(1, w));
329
- if (lines.length > max) {
330
- lines = lines.slice(0, max);
331
- const mark = ellipsis(w);
332
- const last = [...lines[max - 1]];
333
- while (last.length && width(last.join('')) + width(mark) > w) last.pop();
334
- lines[max - 1] = last.join('') + mark;
428
+ w = Math.max(1, w);
429
+ if (width(cmd) <= w) return [cmd];
430
+ const m = RESUME_TAIL.exec(cmd);
431
+ if (!m) {
432
+ const all = wrapCommand(cmd, w);
433
+ return all.length <= max ? all : cutLast(all.slice(0, max), w);
434
+ }
435
+ const tail = wrapCommand(m[1], w);
436
+ if (tail.length > max) return cutLast(tail.slice(0, max), w);
437
+ const room = max - tail.length;
438
+ const head = cmd.slice(0, m.index + m[0].length - m[1].length).trimEnd();
439
+ // 앞부분을 남은 줄에 들어갈 때까지 가운데부터 줄인다. 남은 줄이 없으면 꼬리만.
440
+ if (room > 0 && head) {
441
+ const cd = CD_HEAD.exec(head);
442
+ if (cd) {
443
+ const { from, make } = envHead(cd);
444
+ const lines = fitLines(make, from, w, room);
445
+ if (lines) return [...lines, ...tail];
446
+ }
447
+ const lines = fitLines(middleCutter(head), width(head), w, room);
448
+ if (lines) return [...lines, ...tail];
335
449
  }
336
- return lines;
450
+ return tail;
337
451
  }
338
452
 
339
453
  // 좁은 화면의 셋째 요약 줄: '이어 열기 y …/repo && claude --resume <id>'. 한 줄을 넘으면 앞을 잘라 세션 id 를 남긴다.
package/src/ui/draw.mjs CHANGED
@@ -56,7 +56,7 @@ export function glyph(s, frame) {
56
56
  export const glyphMoves = (s) => (s.status === 'waiting' ? glyphs().waiting !== glyphs().waitingBlink : !['ended', 'done', 'unseen', 'idle', 'stopped'].includes(s.phase?.kind));
57
57
 
58
58
  // 막대는 같은 높이의 얇은 블록(▃)으로 그리고 채운 칸과 빈칸은 색으로 나눈다. 칸 높이가 모두 같아 끝이 튀어나오지 않는다.
59
- // 색이 없으면 빈칸을 가장 얇은 ▁ 로 그려 모양으로 구분한다. 기호는 glyphs().bar 에 있다.
59
+ // 색이 없으면 █ 와 ░ 로 모양을 가른다. 기호는 glyphs().bar 에 있다.
60
60
 
61
61
  // 0% 보다 크면 최소 1칸, 100% 가 아니면 마지막 칸은 비워 둔다.
62
62
  export function filledCells(r, cells) {
@@ -69,13 +69,16 @@ export function gauge(used, total, cells) {
69
69
  const BAR = glyphs().bar;
70
70
  if (!total) return [{ t: BAR.empty.repeat(cells) + ' ', fg: PALETTE.faint }];
71
71
  const r = Math.min(1, Math.max(0, used / total || 0));
72
- const full = cells ? filledCells(r, cells) : 0;
72
+ const pct = Math.round(r * 100);
73
+ // 0% 로 보이면 칸도 채우지 않는다.
74
+ const full = cells && pct > 0 ? filledCells(r, cells) : 0;
73
75
  const color = r >= 0.85 ? PALETTE.alert : r >= 0.6 ? PALETTE.text : PALETTE.busy;
76
+ // 색이 없어도 보이게 60% 이상은 ~, 85% 이상은 ! 를 붙인다.
77
+ const mark = r >= 0.85 ? '!' : r >= 0.6 ? '~' : '';
74
78
  return [
75
79
  { t: BAR.fill.repeat(full), fg: color },
76
80
  { t: BAR.empty.repeat(cells - full), fg: PALETTE.faint },
77
- // 85% 이상은 색이 없어도 보이게 ! 를 붙인다.
78
- { t: pad(`${r >= 0.85 ? '!' : ''}${Math.round(r * 100)}%`, 5, 'right'), fg: r >= 0.85 ? PALETTE.alert : PALETTE.muted },
81
+ { t: pad(`${mark}${pct}%`, 5, 'right'), fg: r >= 0.85 ? PALETTE.alert : PALETTE.muted },
79
82
  ];
80
83
  }
81
84
 
package/src/ui/glyphs.mjs CHANGED
@@ -8,7 +8,8 @@ import { EDGE, NO_COLOR } from './theme.mjs';
8
8
  const NORMAL = {
9
9
  edge: EDGE,
10
10
  rule: '─',
11
- bar: { fill: '▃', empty: NO_COLOR ? '▁' : '▃' },
11
+ // 색이 없으면 채운 칸(█)과 빈칸(░)을 모양으로 가른다 (#293).
12
+ bar: NO_COLOR ? { fill: '█', empty: '░' } : { fill: '▃', empty: '▃' },
12
13
  week: '▁▂▃▄▅▆▇█',
13
14
  // 시작할 때 헤더의 집계 진행 막대. 색이 없으면 채운 칸과 빈칸이 모양으로 갈리도록 ASCII 로 그린다.
14
15
  progress: NO_COLOR ? { l: '[', r: ']', fill: '#', empty: '.' } : { l: '▕', r: '▏', fill: '█', empty: '░' },
package/src/ui/table.mjs CHANGED
@@ -221,7 +221,8 @@ function toolPart(p, level, showEnded) {
221
221
  if (!p.live) {
222
222
  // 종료 세션을 함께 볼 때는 그 도구의 누적 토큰을 흐리게 남긴다. 기록 폴더가 없으면 미설치로 보인다.
223
223
  const more = !extra ? [] : p.missing ? [{ t: ` ${t('tools.missing')}`, fg: PALETTE.info, italic: true }] : showEnded && p.count ? [{ t: ` · ${fmtTokens(p.tok)}`, fg: PALETTE.info }] : [];
224
- return [{ t: ` ${name}`, fg: PALETTE.info }, ...more];
224
+ // 실행 중 표시(▍) 자리를 비우지 않아 조각 사이가 고르게 2칸이다.
225
+ return [{ t: name, fg: PALETTE.info }, ...more];
225
226
  }
226
227
  const tc = PALETTE.tools[p.tool];
227
228
  return [{ t: glyphs().tool, fg: tc }, { t: name, fg: tc, bold: true }, { t: ` ${p.live}`, fg: PALETTE.text }, ...(extra ? [{ t: ` · ${fmtTokens(p.tok)}`, fg: PALETTE.muted }] : [])];
@@ -242,10 +243,10 @@ export function toolLastUsed(data, tool, now) {
242
243
  return times.length ? Math.max(...times) : 0;
243
244
  }
244
245
 
245
- // 도구 줄: 도구마다 실행 중 세션 수와 누적 토큰. 실행 중 세션도 없고 7일 동안 쓰지 않은 도구는 숨기고 끝에 '숨김 codex gemini'
246
- // (자리가 모자라면 '숨김 2') 를 적는다. 기록 폴더가 없는 도구(미설치)도 7일 동안 쓰지 않은 것이라 함께 숨긴다.
246
+ // 도구 줄: 도구마다 실행 중 세션 수와 누적 토큰. 실행 중 세션도 없고 7일 동안 쓰지 않은 도구는 숨기고 끝에
247
+ // '미설치: codex 7일 미사용: gemini' 처럼 미설치(기록 폴더 없음)와 미사용을 나눠 적는다 (자리가 모자라면 '미설치: 1 7일 미사용: 1').
247
248
  // 숨기면 줄에 남는 도구가 하나도 없을 때는 숨기지 않고 예전처럼 흐리게 (미설치 포함) 다 보인다.
248
- // 폭이 모자라면 간격 → 토큰 수 → 이름 순으로 줄이고, 그래도 넘치면 세션이 없는 도구부터 빼고 +N 으로 뺀 수를 적는다.
249
+ // 조각 사이 간격은 2칸. 폭이 모자라면 토큰 수 → 이름 순으로 줄이고, 그래도 넘치면 세션이 없는 도구부터 빼고 +N 으로 뺀 수를 적는다.
249
250
  // 아주 좁으면 실행 중인 도구가 숨김 표시보다 먼저 남고, 숨김 표시는 중간에서 자르지 않고 뺀다.
250
251
  export function toolStrip(view, W) {
251
252
  const now = view.data.at ?? Date.now();
@@ -266,17 +267,19 @@ export function toolStrip(view, W) {
266
267
  const visible = all.filter((p) => !p.idle);
267
268
  const parts = visible.length ? visible : all;
268
269
  const hidden = all.filter((p) => !parts.includes(p));
269
- // 숨김 표시: 도구 이름을 적고, 자리가 모자라면 개수만 적는다.
270
- const notes = hidden.length ? [[{ t: t('tools.hidden', { list: hidden.map((p) => p.tool).join(' ') }), fg: PALETTE.info }], [{ t: t('tools.hidden', { list: hidden.length }), fg: PALETTE.info }]] : [[]];
270
+ // 숨김 표시: 미설치와 미사용을 나눠 도구 이름을 적고, 자리가 모자라면 개수만 적는다.
271
+ const groups = [['tools.hiddenMissing', hidden.filter((p) => p.missing)], ['tools.hiddenIdle', hidden.filter((p) => !p.missing)]].filter(([, g]) => g.length);
272
+ const note = (named) => groups.map(([key, g]) => ({ t: t(key, { list: named ? g.map((p) => p.tool).join(' ') : g.length }), fg: PALETTE.info }));
273
+ const notes = hidden.length ? [note(true), note(false)] : [[]];
271
274
  const plus = (n) => (n ? [{ t: `+${n}`, fg: PALETTE.info }] : []);
272
275
  const build = (shown, level, tail = []) => {
273
- const gap = { t: level ? ' ' : ' ' };
276
+ const gap = { t: ' ' };
274
277
  const end = tail.flatMap((x, i) => [...(i ? [{ t: ' ' }] : []), x]);
275
278
  return [{ t: ' ' }, ...shown.flatMap((p, i) => [...(i ? [gap] : []), ...toolPart(p, level, view.showEnded)]), ...(end.length ? [...(shown.length ? [gap] : []), ...end] : [])];
276
279
  };
277
280
  const fits = (x) => segsWidth(x) <= W;
278
281
  let segs = null;
279
- for (const level of [0, 1, 2, 3]) {
282
+ for (const level of [0, 2, 3]) {
280
283
  for (const note of notes) {
281
284
  const s = build(parts, level, note);
282
285
  if (fits(s)) {
@@ -306,7 +309,7 @@ export function toolStrip(view, W) {
306
309
  segs = fits(noted.segs) && liveOf(noted) >= liveOf(bare) ? noted.segs : bare.segs;
307
310
  }
308
311
  // 종료 세션 표시는 다 들어갈 때만 붙인다 (잘린 조각이 남지 않게).
309
- const ended = [{ t: ' ' }, { t: t('tools.ended'), fg: PALETTE.info, italic: true }];
312
+ const ended = [{ t: ' ' }, { t: t('tools.ended'), fg: PALETTE.info, italic: true }];
310
313
  if (view.showEnded && segsWidth(segs) + segsWidth(ended) <= W) segs.push(...ended);
311
314
  return line(segs, W);
312
315
  }
@@ -357,7 +360,7 @@ export function sessionRow(s, c, W, selected, frame, hot, costMode = 'api', pinn
357
360
  segs.push(...pin, ...auto, { t: pad(s.name ?? '', c.name - segsWidth(pin) - segsWidth(auto)) + ' ', fg: ended ? PALETTE.ended : PALETTE.text, bold: selected });
358
361
  if (c.showProject) segs.push({ t: pad(s.project ?? '', c.project) + ' ', fg: ended ? PALETTE.ended : PALETTE.muted });
359
362
  segs.push(
360
- ...statusCell(status, cacheState(s) ?? toolElapsed(s), c.status, { fg: pc, bold: s.status === 'waiting' }, briefStatus(s)),
363
+ ...statusCell(status, cacheState(s) ?? toolElapsed(s), c.status, { fg: pc, bold: s.status === 'waiting' }, briefStatus(s), status === statusText(s.phase) ? toolTarget(s.phase) : null),
361
364
  { t: pad(partial ? '…' : blank ? '' : fmtTokens(s.tokens.total), c.tokens, 'right') + ' ', fg: ended ? PALETTE.ended : partial ? PALETTE.info : PALETTE.muted },
362
365
  );
363
366
  if (c.showCost) segs.push(partial ? { t: pad('…', c.cost, 'right') + ' ', fg: PALETTE.info } : { t: pad(blank ? '' : (hot?.has(s.id) ? glyphs().hot : '') + money(costOf(s, costMode), s.costUnknown), c.cost, 'right') + ' ', fg: s.cost == null || ended ? PALETTE.info : hot?.has(s.id) ? PALETTE.money : PALETTE.muted, bold: Boolean(hot?.has(s.id)) });
@@ -371,12 +374,15 @@ export function sessionRow(s, c, W, selected, frame, hot, costMode = 'api', pinn
371
374
  // 덧붙인 글이 먼저 빠지는 정보다: 다 들어가면 그대로, 상태 글을 TAG_STATUS_MIN 칸까지 줄여 들어가면 줄여서 붙이고, 아니면 뺀다.
372
375
  // 경고 단계의 덧붙임(tag.warn: 캐시 1분 미만, 도구 10분 이상)은 거꾸로 상태 글보다 오래 남는다 (#264).
373
376
  // 그때 상태 글은 짧은 문구(brief, 예: '지시 대기')로 바꾸고, 그래도 넘치면 줄이고, 4칸도 안 남으면 덧붙임만 둔다.
377
+ // target: 도구 실행 중이면 동사('도구 실행')를 뺀 대상('Bash $ npm test'). 칸이 모자라면 동사부터 빼고 대상과 덧붙임을 남긴다 (#293).
374
378
  const TAG_STATUS_MIN = 12;
375
379
  // 경고 덧붙임 앞에 남길 상태 글의 최소 칸. 이보다 좁으면 '지…' 처럼 줄임표만 남으므로 덧붙임만 둔다.
376
380
  const WARN_HEAD_MIN = 4;
377
- export function statusCell(status, tag, w, look, brief = null) {
381
+ export function statusCell(status, tag, w, look, brief = null, target = null) {
378
382
  const plain = [{ t: pad(status, w) + ' ', ...look }];
379
- if (!tag) return plain;
383
+ // 대상은 상태 글보다 짧을 때만 쓴다.
384
+ const tgt = target && width(target) < width(status) ? target : null;
385
+ if (!tag) return width(status) > w && tgt ? [{ t: pad(tgt, w) + ' ', ...look }] : plain;
380
386
  const tagSeg = { t: tag.text, fg: tag.fg, bold: tag.bold, dim: tag.dim };
381
387
  const withHead = (text, sep = ' · ') => {
382
388
  const room = w - width(sep) - width(tag.text);
@@ -387,17 +393,28 @@ export function statusCell(status, tag, w, look, brief = null) {
387
393
  if (room >= width(status)) return withHead(status);
388
394
  if (tag.warn) {
389
395
  // 경고 단계: 원문을 자르기보다 짧은 문구를 먼저 쓴다. · 와 함께 들어가지 않으면 사이를 한 칸으로 줄여 본다.
390
- const head = brief && width(brief) < width(status) ? brief : status;
396
+ const head = tgt ?? (brief && width(brief) < width(status) ? brief : status);
391
397
  if (room >= width(head)) return withHead(head);
392
398
  if (room + width(' · ') - 1 >= width(head)) return withHead(head, ' ');
393
399
  // 줄임표만 남을 만큼 좁으면 상태 글을 빼고 덧붙임만 둔다.
394
400
  if (room >= WARN_HEAD_MIN) return withHead(head);
395
401
  return [{ ...tagSeg, t: pad(truncate(tag.text, w), w) + ' ' }];
396
402
  }
403
+ // 대상이 있으면 동사를 빼고 대상(줄여서라도)과 덧붙임을 남긴다. 4칸도 안 남으면 대상만.
404
+ if (tgt) return room >= WARN_HEAD_MIN ? withHead(tgt) : [{ t: pad(tgt, w) + ' ', ...look }];
397
405
  if (room >= Math.min(width(status), TAG_STATUS_MIN)) return withHead(status);
398
406
  return plain;
399
407
  }
400
408
 
409
+ // 도구 실행 상태 글에서 동사를 뺀 대상: 'Bash $ npm test' (팀원 수가 있으면 뒤에 붙인다). 도구 실행이 아니면 null.
410
+ export function toolTarget(phase) {
411
+ if (phase?.kind !== 'tool' || phase.msg || !phase.args?.what) return null;
412
+ const full = statusText(phase);
413
+ // '도구 실행 · Bash' 에서 '도구 실행 · ' 를 뗀다. 문구 모양이 다르면 쓰지 않는다.
414
+ const verb = statusText({ kind: 'tool', args: { what: '\0' } }).split('\0')[0];
415
+ return verb && full.startsWith(verb) ? full.slice(verb.length) : null;
416
+ }
417
+
401
418
  // 경고 덧붙임 앞에 둘 짧은 상태 글. 다음 지시 대기만 짧은 문구가 따로 있고, 나머지는 상태 글을 줄여 쓴다.
402
419
  const briefStatus = (s) => (s.phase?.kind === 'idle' && s.status === 'idle' ? t('status.idleBrief') : null);
403
420
 
@@ -464,8 +481,13 @@ export function memberRow(m, last, c, W, frame, parentModel, costMode = 'api', p
464
481
  export const MARK_COLOR = { ok: PALETTE.busy, missing: PALETTE.alert, limited: PALETTE.muted };
465
482
 
466
483
  export function emptyLines(view, W) {
467
- const out = [line([{ t: ` ${t(view.showEnded ? 'empty.none24' : 'empty.none')}`, fg: PALETTE.muted, italic: true }], W), line([], W)];
468
484
  const tools = Object.values(view.data.tools?.tools ?? {});
485
+ // 프로세스는 실행 중인데 읽을 기록이 없으면 그 사실과 다음 할 일을 첫 줄에 적는다 (실행 1 과 '세션 없음' 이 엇갈리지 않게).
486
+ const running = tools.filter((r) => r.running > 0 && !r.records).map((r) => r.tool);
487
+ const head = running.length
488
+ ? [line([{ t: ` ${t('empty.procs', { list: running.join(' ') })}`, fg: PALETTE.muted, italic: true }], W), line([{ t: ` → ${t('empty.procsHint')}`, fg: PALETTE.info }], W)]
489
+ : [line([{ t: ` ${t(view.showEnded ? 'empty.none24' : 'empty.none')}`, fg: PALETTE.muted, italic: true }], W)];
490
+ const out = [...head, line([], W)];
469
491
  const pathW = Math.max(0, ...tools.map((r) => width(r.path)));
470
492
  for (const r of tools) {
471
493
  const d = describe(r, NOW);
package/src/ui.mjs CHANGED
@@ -3,6 +3,7 @@ import { width } from './text.mjs';
3
3
  import { BRAND } from './brand.mjs';
4
4
  import { PALETTE } from './ui/theme.mjs';
5
5
  import { glyphMoves, line, setNow } from './ui/draw.mjs';
6
+ import { glyphs } from './ui/glyphs.mjs';
6
7
  import { TABLE_BOX_H, columns, emptyLines, filterSessions, groupRow, header, memberRow, sessionRow, tableBox, tableHeader, toolStrip, topCost } from './ui/table.mjs';
7
8
  import { detail } from './ui/detail.mjs';
8
9
  import { detailOpen, footer, help } from './ui/chrome.mjs';
@@ -22,6 +23,33 @@ export function animating(view) {
22
23
  return filterSessions(view.data.sessions, view.filter).some((s) => glyphMoves(s) || (s.members ?? []).some((m) => m.status !== 'done'));
23
24
  }
24
25
 
26
+ // 터미널이 아닌 곳(파이프·파일)으로 내는 --once 용 (#292). render 결과에서 맨 아래 키 안내 줄과,
27
+ // 화면 높이를 맞추려고 채운 빈 줄(끝의 빈 줄, 상세 상자 아래쪽의 테두리만 있는 줄)과 줄 끝 공백을 뺀다.
28
+ // 테두리 글자는 지금 기호 세트(AITOP_AMBIGUOUS=wide 면 ASCII)에서 고른다.
29
+ const ANSI = /\x1b\[[0-9;]*m/g;
30
+ const plain = (l) => l.replace(ANSI, '');
31
+ // 줄 끝의 공백과 색 코드를 지운다. 색 코드가 있던 줄은 끝에 초기화(ESC[0m)를 붙여 색이 다음 줄로 번지지 않게 한다.
32
+ const trimEnd = (l) => {
33
+ const cut = l.replace(/(?:\s|\x1b\[[0-9;]*m)+$/, '');
34
+ return cut !== l && /\x1b\[/.test(l) && /\x1b\[/.test(cut) ? cut + '\x1b[0m' : cut;
35
+ };
36
+ export function pipeLines(lines) {
37
+ const E = Object.values(glyphs().edge);
38
+ const vert = new Set(E.map((e) => e.v));
39
+ const filler = (l) => [...plain(l)].every((ch) => /\s/.test(ch) || vert.has(ch));
40
+ const isBottom = (l) => E.some((e) => plain(l).startsWith(e.bl + e.h));
41
+ const out = lines.slice(0, -1);
42
+ while (out.length && !plain(out.at(-1)).trim()) out.pop();
43
+ // 마지막 줄이 상자 아래 테두리면 그 바로 위의 빈 칸 줄들을 지운다.
44
+ const bottom = out.length - 1;
45
+ if (bottom >= 1 && isBottom(out[bottom])) {
46
+ let top = bottom;
47
+ while (top > 1 && filler(out[top - 1])) top--;
48
+ out.splice(top, bottom - top);
49
+ }
50
+ return out.map(trimEnd);
51
+ }
52
+
25
53
  // 로딩 중(준비 완료 전이거나 7일 집계 중)에는 경과 시간(IDLE 등)을 데이터를 받은 시각에 맞춰, 스피너 프레임마다 숫자가 따로 바뀌지 않게 한다.
26
54
  const settling = (view) => view.data && (view.ready === false || view.data.usage?.loading != null);
27
55