@sejuneoh/aitop 0.32.0 → 0.33.1

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
@@ -37,7 +37,9 @@ Native Windows support is early (Windows Terminal recommended): Claude Code and
37
37
 
38
38
  ## Features
39
39
 
40
- - **Live status** of every session and its subagents: thinking, running a tool, waiting for you, idle. Subagent rows show how long they have run ([details](#subagents))
40
+ - **Live status** of every session and its subagents: thinking, running a tool, waiting for you, idle, or stopped by an error (`! Login needed`, `! Connection lost`, read from the API error lines Claude Code already logs; it sorts right under waiting and pinned sessions and never counts as done). Subagent rows show how long they have run ([details](#subagents))
41
+ - **Prompt cache countdown** for Claude sessions waiting on you or idle: `cache 3:12` after the status text (warning color under a minute, dim `cache expired` after), estimated from the log's `cache_creation` 5m/1h tokens and the last request start, per the [prompt caching docs](https://platform.claude.com/docs/en/build-with-claude/prompt-caching). Dropped first on narrow screens; `--json` has `cacheExpiresAt`
42
+ - **Tool run time** while a session runs a tool: `Tool · Bash · 4m12s`, from the open tool call's start (Claude `tool_use`, Codex `function_call`, Antigravity running step). Shown after one minute, dim warning color from ten minutes (Claude Code's Bash timeout max), not counted while waiting for approval. Dropped first on narrow screens; `--json` has `toolStartedAt`
41
43
  - **Waiting alerts**: blocked sessions jump to the top, with optional bell, desktop notification or hook command
42
44
  - **Tokens and cost** per session and for today / last 7 days, estimated at public API list prices. This is not your bill
43
45
  - **Changed files and diffs** per session and per prompt
@@ -64,7 +66,7 @@ The language is picked from `--lang`, then `AITOP_LANG`, then `lang` in the conf
64
66
 
65
67
  To 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 to the clipboard with OSC 52: Claude `cd <dir> && claude --resume <id>`, Codex `cd <dir> && codex resume <id>`, Antigravity `cd <dir> && agy --conversation <id>` (none for Gemini CLI). A session from a data folder other than `~/.claude` / `~/.codex` (or any session while `CLAUDE_CONFIG_DIR` / `CODEX_HOME` is set) gets `CLAUDE_CONFIG_DIR=<dir>` / `CODEX_HOME=<dir>` before the tool so it finds the right history. Claude finds sessions per folder, so without a known folder no command is made; ids that are not UUIDs make none either. A short detail panel leaves the command out; use `y` or `--json` then. Paths and ids are shell quoted and control characters are stripped. Windows Terminal, WezTerm, iTerm2 and kitty accept OSC 52; tmux needs `set -g set-clipboard on`; other terminals ignore it silently, so copy the command from the panel. Nothing is sent to the session. `--json` has the same command as `resumeCmd` per session (`null` if none).
66
68
 
67
- In `--json`, `phase` stays the Korean status text in every language (as does `AITOP_WAITING_FOR` for `--on-waiting`). Session `name` uses the same user-given names as the table: a Codex session's `name` changes from the folder name to its `thread_name` once it has one. For scripts, use `phaseKind`, a stable state name: `think`, `write`, `tool`, `team`, `waiting`, `idle`, `done`, `ended` (or `null`). Other text fields follow their own rules: with English selected, `--doctor --json` has Korean `tools.*.hint` but English `config.problems`.
69
+ In `--json`, `phase` stays the Korean status text in every language (as does `AITOP_WAITING_FOR` for `--on-waiting`). Session `name` uses the same user-given names as the table: a Codex session's `name` changes from the folder name to its `thread_name` once it has one. For scripts, use `phaseKind`, a stable state name: `think`, `write`, `tool`, `team`, `waiting`, `idle`, `stopped`, `done`, `ended` (or `null`). `stopped` is an idle Claude session whose last log entry is an API error; `stopReason` then says why (`{ "kind": "auth" }` login needed, `network` connection lost, `api` any other API error), `null` otherwise. Other text fields follow their own rules: with English selected, `--doctor --json` has Korean `tools.*.hint` but English `config.problems`.
68
70
 
69
71
  ### Subagents
70
72
 
@@ -91,7 +93,11 @@ aitop --report monthly --by model --months 6
91
93
 
92
94
  ### Session report
93
95
 
94
- `aitop --report sessions [--since yesterday|today|Nd|YYYY-MM-DD] [--plan USD] [--md|--json] [--show-prompts]` lists every session that used tokens in the period (default: since midnight yesterday; at most 30 days back), highest cost first: tool, main model (`+N` more), project (same rule as `--by project`), session name (your `/rename` name, then the tool's title, then the folder), start and end of activity within the period, tokens, cost (API list price; unpriced models are left out, not guessed, and `--json` marks them with `unpriced`) and files changed (`-` when unknown, always for agy). A summary card on top shows the total, the share per tool and the session count; `--plan 200` adds how many times the period's share of a $200/month subscription (period days / 30) you used, still in API list price and not your bill. Claude subagents are counted in their parent session. `--md` prints Markdown you can paste (`|` and line breaks escaped), `--json` the same numbers for scripts. First prompts are hidden unless you pass `--show-prompts`, so they do not end up in shared output (session names still show).
96
+ `aitop --report sessions [--since yesterday|today|Nd|YYYY-MM-DD] [--plan USD] [--md|--json] [--show-prompts]` lists every session that used tokens in the period (default: since midnight yesterday; at most 30 days back), highest cost first: tool, main model (`+N` more), project (same rule as `--by project`), session name (your `/rename` name, then the tool's title, then the folder), start and end of activity within the period, time the agent waited for you, tokens, cost (API list price; unpriced models are left out, not guessed, and `--json` marks them with `unpriced`) and files changed (`-` when unknown, always for agy). A summary card on top shows the total, the share per tool and the session count; `--plan 200` adds how many times the period's share of a $200/month subscription (period days / 30) you used, still in API list price and not your bill. Claude subagents are counted in their parent session. The card's last line totals the waits (`Agents waited for you 1h12m (estimate)`).
97
+
98
+ Waited is an **estimate**: the sum of gaps from the agent's last line (reply or tool result) to your next input. Inputs are, for Claude, prompts you typed (slash commands included) and answers you picked in a permission dialog or AskUserQuestion; for Codex, `user_message`. Prompts queued while the agent worked and background task notifications do not count, and an interrupt restarts the clock. The logs do not say whether you were at the screen, so **time away cannot be told apart** from waiting; each gap counts for at most 2 hours, so a session left open overnight does not swamp the total. A Claude permission dialog's start time is not logged, so the gap runs from the tool call to its result and includes the tool's run time after approval. Codex does not log approvals, so only prompts count there. Gaps crossing the period start count only the part inside, and subagents are not counted (parent session only). Each session is summed on its own, so with sessions running side by side the total can exceed wall-clock time. agy shows `-`. `--json` has `waitedMs` (milliseconds, `null` when unknown) per session and in `summary`.
99
+
100
+ `--md` prints Markdown you can paste (`|` and line breaks escaped), `--json` the same numbers for scripts. First prompts are hidden unless you pass `--show-prompts`, so they do not end up in shared output (session names still show).
95
101
 
96
102
  ```
97
103
  aitop --report sessions --md --plan 200
@@ -103,17 +109,19 @@ aitop --report sessions --since 7d --json
103
109
  Off by default and only on the live screen. Sessions already waiting (or already over 90% context) when aitop starts are not reported.
104
110
 
105
111
  ```
106
- aitop --notify desktop notification when a session starts waiting (notify-send on Linux/WSL, osascript on macOS)
112
+ aitop --notify desktop notification when a session starts waiting (notify-send on Linux, Windows notification on WSL, osascript on macOS)
107
113
  aitop --notify=waiting,done,context pick the kinds; plain --notify uses the config file kinds, or waiting only when none are set
108
114
  aitop --on-waiting 'my-hook.sh' run a command with /bin/sh -c for the same events (10 second limit, runs as you)
109
115
  ```
110
116
 
111
117
  - `waiting`: a session starts waiting for your approval or answer.
112
- - `done`: a session that was busy for over 3 minutes in one turn (config `doneMinutes`; time spent waiting for approval does not count) goes idle and stays idle for 5 seconds. Brief idle gaps between tool calls, approval waits, ended sessions, subagents and sessions whose status is guessed from file times are not reported. Once per turn.
118
+ - `done`: a session that was busy for over 3 minutes in one turn (config `doneMinutes`; time spent waiting for approval does not count) goes idle and stays idle for 5 seconds. Brief idle gaps between tool calls, approval waits, ended sessions, subagents, sessions stopped by an API error and sessions whose status is guessed from file times are not reported. Once per turn.
113
119
  - `context`: context use passes 90%, once; it re-arms after it drops below 85% (for example after compaction).
114
120
 
115
121
  The hook keeps its name: it gets `AITOP_EVENT` (`waiting`, `done` or `context`) plus `AITOP_TOOL`, `AITOP_PROJECT`, `AITOP_SESSION_ID`, `AITOP_CWD` and `AITOP_WAITING_FOR` in its environment. Config file: `"notify": true` or `"notify": ["waiting", "done", "context"]`, `"onWaiting": "..."` (file must be `chmod 600`), `"doneMinutes": 5`. Plain `--notify` keeps the kinds from the config `notify` list (waiting only when there is none). `--no-notify` turns off only the desktop notification: the hook still follows those kinds. `--bell` stays waiting only.
116
122
 
123
+ On WSL, aitop shows a Windows notification through `powershell.exe` (as Windows PowerShell, no setup needed) and falls back to notify-send when `powershell.exe` is not on the PATH. notify-send needs a D-Bus session bus: when `DBUS_SESSION_BUS_ADDRESS` is unset or its socket file is missing, notifications cannot show and `--doctor` marks the line with `!`. A missing tool or a failed notification is skipped quietly.
124
+
117
125
  The notification body shows the session's own name when it has one (Claude Code `/rename`, or a name given by a peer session; Codex `thread_name`), otherwise the project. Desktop notifications can appear on the lock screen, so the name is visible there too.
118
126
 
119
127
  ### tmux status line
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sejuneoh/aitop",
3
- "version": "0.32.0",
3
+ "version": "0.33.1",
4
4
  "description": "터미널에서 Claude Code · Codex · Antigravity · Gemini 세션과 토큰을 실시간으로 보는 읽기 전용 모니터",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/attention.mjs CHANGED
@@ -11,7 +11,8 @@ export function updateAttention(state, sessions, selectedId) {
11
11
  ids.add(s.id);
12
12
  const before = state.prev.get(s.id);
13
13
  // 상태를 기록 수정 시각으로 추측한 세션(statusGuessed)은, 작업이 아닌 줄이 붙어도 잠깐 작업 중으로 보이므로 확인 전으로 치지 않는다.
14
- if (s.id === selectedId || s.status === 'busy' || s.status === 'shell' || !s.live) state.unseen.delete(s.id);
14
+ // 오류로 멈춘 세션(stopReason)은 끝난 게 아니므로 확인 전으로 치지 않는다 (화면에 멈춘 이유가 그대로 보인다).
15
+ if (s.id === selectedId || s.status === 'busy' || s.status === 'shell' || !s.live || s.stopReason) state.unseen.delete(s.id);
15
16
  else if ((before === 'busy' || before === 'shell') && s.status === 'idle' && !s.statusGuessed) state.unseen.add(s.id);
16
17
  state.prev.set(s.id, s.status);
17
18
  }
@@ -74,6 +75,7 @@ export function takeNewlyWaiting(watch, sessions) {
74
75
  // 도구 호출 사이의 잠깐 대기는 settleMs 안에 다시 작업 중이 되므로 같은 작업으로 이어 센다 (그 틈도 작업 시간에 넣는다).
75
76
  // 응답 대기(waiting)는 따로 알리므로 끝남으로 치지 않는다. 같은 작업은 이어지지만 기다린 시간은 작업 시간에 넣지 않는다.
76
77
  // 상태를 추측한 세션(statusGuessed), 끝난 세션, 하위 에이전트 줄은 알리지 않는다.
78
+ // 오류로 멈춘 세션(stopReason: 로그인 만료, 연결 끊김 등)도 끝난 게 아니므로 알리지 않고 그 작업을 잊는다.
77
79
  // context: 사용률이 ctxHigh 이상이 되면 한 번 알리고, ctxRearm 아래로 내려가면(압축 등) 다시 알릴 수 있게 한다.
78
80
  // 기록을 다 읽기 전(s.loading)의 세션은 기준선만 잡고, 다 읽은 첫 갱신에 이미 높으면 알리지 않는다.
79
81
  export const DONE_MS = 3 * 60_000;
@@ -101,7 +103,7 @@ export function takeEvents(watch, sessions, { now = Date.now(), ready = true } =
101
103
  const reset = () => Object.assign(st, { run: false, busyMs: 0, busyAt: null, idleSince: null });
102
104
 
103
105
  // done
104
- if (s.statusGuessed) reset();
106
+ if (s.statusGuessed || s.stopReason) reset();
105
107
  else if (isBusy(s)) {
106
108
  st.run = true;
107
109
  st.busyAt ??= now;
package/src/doctor.mjs CHANGED
@@ -10,7 +10,7 @@ import { loadSqlite, openReadOnly } from './sqlite.mjs';
10
10
  import { fmtAgo, pad, stripControl } from './text.mjs';
11
11
  import { BRAND } from './brand.mjs';
12
12
  import { tildeIn } from './paths.mjs';
13
- import { findNotifier, isWsl } from './notify.mjs';
13
+ import { busProblem, findNotifier, isWsl } from './notify.mjs';
14
14
  import { getLang, t as tr } from './i18n.mjs';
15
15
  import { candidateDirs, claudeDirs, codexHomes } from './sources/dirs.mjs';
16
16
 
@@ -213,17 +213,32 @@ export function checkTools({ home = HOME } = {}) {
213
213
  r.hint = hintOf(r, 'ko');
214
214
  tools[r.tool] = r;
215
215
  }
216
- const n = findNotifier();
217
- return { platform: platform(), processes: canListProcesses(), tools, notifier: n ? { kind: n.kind, path: tilde(n.path) } : null };
216
+ return { platform: platform(), processes: canListProcesses(), tools, notifier: notifierCheck() };
218
217
  }
219
218
 
220
- // --notify 에 쓸 데스크톱 알림 도구.
221
- export function notifierText(n, plat = platform(), lang = getLang()) {
219
+ // 알림 도구와, notify-send 면 D-Bus 세션 버스를 찾을 수 있는지 (#250). 알림을 실제로 보내 보지는 않는다.
220
+ // bus: 문제가 있을 때만 { reason, path? }. 테스트에서 platform·env·wsl·exists 를 바꿔 끼운다.
221
+ export function notifierCheck({ platform: plat = platform(), env = process.env, wsl = plat === 'linux' && isWsl(env), exists } = {}) {
222
+ const n = findNotifier({ platform: plat, env, wsl });
223
+ if (!n) return null;
224
+ const bus = n.kind === 'notify-send' ? busProblem(env, exists) : null;
225
+ return { kind: n.kind, path: tilde(n.path), ...(bus ? { bus: bus.path ? { ...bus, path: tilde(bus.path) } : bus } : {}) };
226
+ }
227
+
228
+ // --notify 에 쓸 데스크톱 알림 도구. 알림이 뜨지 않을 것이 확실하면 ! 와 안내 줄(→)을 붙인다.
229
+ export function notifierText(n, plat = platform(), lang = getLang(), wsl = plat === 'linux' && isWsl()) {
222
230
  const o = { lang };
231
+ const hint = (k) => ` → ${tr(k, null, o)}`;
232
+ if (n?.bus) {
233
+ const why = n.bus.reason === 'socket' ? tr('doctor.busSocket', { path: n.bus.path }, o) : tr('doctor.busMissing', null, o);
234
+ const out = [tr('doctor.busBad', { kind: n.kind, path: n.path, why }, o), hint('doctor.busHint')];
235
+ if (wsl) out.push(hint('doctor.wslHint'));
236
+ return out.join('\n');
237
+ }
223
238
  if (n) return tr('doctor.notifier', { kind: n.kind, path: n.path }, o);
239
+ if (wsl) return [tr('doctor.noNotifierWsl', null, o), hint('doctor.wslHint')].join('\n');
224
240
  const want = plat === 'darwin' ? 'osascript' : 'notify-send';
225
- const wsl = plat === 'linux' && isWsl() ? tr('doctor.wsl', null, o) : '';
226
- return tr('doctor.noNotifier', { want, wsl }, o);
241
+ return tr('doctor.noNotifier', { want }, o);
227
242
  }
228
243
 
229
244
  // JSON 용: 시각은 ISO 문자열로.
package/src/i18n.mjs CHANGED
@@ -79,7 +79,7 @@ const HELP_KO = `{logo} aitop - 터미널에서 Claude Code · Codex · Antigrav
79
79
  --plan 월 구독료를 주면 기간 몫의 몇 배인지 보인다. --md 는 붙여 넣을 Markdown. 첫 지시는 --show-prompts 일 때만
80
80
  aitop --doctor Claude · Codex · Antigravity · Gemini 기록과 실행 중인 프로세스, 설정 파일을 점검한다 (--json 과 함께 쓸 수 있다)
81
81
  aitop --bell 응답 대기 세션이 새로 생기면 터미널 벨을 울린다
82
- aitop --notify 응답 대기 세션이 새로 생기면 데스크톱 알림을 띄운다 (notify-send · osascript, 없으면 건너뜀)
82
+ aitop --notify 응답 대기 세션이 새로 생기면 데스크톱 알림을 띄운다 (Linux notify-send · macOS osascript · WSL 은 powershell.exe 로 Windows 알림, 없으면 건너뜀)
83
83
  aitop --notify=waiting,done,context 알릴 종류를 고른다 (--notify 만 주면 설정 파일 notify 배열, 없으면 waiting). done: 3분(설정 파일 doneMinutes, 응답 대기 시간 빼고) 넘게 작업하던 세션이 다음 지시를
84
84
  기다리면 한 번. context: 컨텍스트가 90% 를 넘으면 한 번 (85% 아래로 내려가면 다시)
85
85
  aitop --on-waiting <명령> 알릴 일이 생기면 /bin/sh -c 로 명령을 실행한다 (내 권한으로 실행, 10초 제한). 종류는 --notify 를 따른다 (--no-notify 여도)
@@ -138,7 +138,7 @@ const HELP_EN = `{logo} aitop - watch Claude Code, Codex, Antigravity and Gemini
138
138
  First prompts are shown only with --show-prompts
139
139
  aitop --doctor check Claude, Codex, Antigravity and Gemini logs, running processes and the config file (works with --json)
140
140
  aitop --bell ring the terminal bell when a session starts waiting for you
141
- aitop --notify show a desktop notification when a session starts waiting (notify-send or osascript, skipped if missing)
141
+ aitop --notify show a desktop notification when a session starts waiting (notify-send on Linux, osascript on macOS, a Windows toast via powershell.exe on WSL; skipped if missing)
142
142
  aitop --notify=waiting,done,context pick what to notify about (plain --notify: the config notify list, else waiting). done: once when a session that worked for
143
143
  over 3 minutes (config doneMinutes, approval waits not counted) waits for its next instruction. context: once when context passes 90% (again after it drops below 85%)
144
144
  aitop --on-waiting <cmd> run a command with /bin/sh -c when there is something to notify (runs as you, 10 second limit). Follows the --notify kinds (even with --no-notify)
@@ -276,18 +276,20 @@ export const STRINGS = {
276
276
  'sessions.cardTools': '도구별 비용 비중: {tools}',
277
277
  'sessions.cardToolsTokens': '도구별 토큰 비중: {tools}',
278
278
  'sessions.cardPlan': '구독료 {plan}/월의 {days}일 몫 {prorated} 대비 {ratio} (API 정가 환산, 실제 청구액이 아님)',
279
+ 'sessions.cardWaited': '에이전트가 기다린 시간 {waited} (추정)',
279
280
  'sessions.col.tool': '도구',
280
281
  'sessions.col.model': '모델',
281
282
  'sessions.col.project': '프로젝트',
282
283
  'sessions.col.name': '세션',
283
284
  'sessions.col.start': '시작',
284
285
  'sessions.col.end': '끝',
286
+ 'sessions.col.waited': '기다림',
285
287
  'sessions.col.tokens': '토큰',
286
288
  'sessions.col.cost': '비용',
287
289
  'sessions.col.files': '파일',
288
290
  'sessions.col.prompt': '첫 지시',
289
291
  'sessions.empty': '이 기간에 사용량이 있는 세션이 없습니다',
290
- 'sessions.noteBasis': '비용은 API 정가 환산이며 실제 청구액이 아닙니다. 시작·끝은 기간 안의 활동 시각, 파일은 고친 파일 수 (- 는 모름)',
292
+ 'sessions.noteBasis': '비용은 API 정가 환산이며 실제 청구액이 아닙니다. 시작·끝은 기간 안의 활동 시각, 파일은 고친 파일 수 (- 는 모름). 기다림은 응답을 끝낸 뒤 다음 입력·허락까지의 추정 (간격 하나당 2시간까지, 자리 비움과 구분하지 못함)',
291
293
  'sessions.capped': '--since 는 장부가 남기는 {n}일 전까지만 볼 수 있어 {n}일 전으로 줄입니다',
292
294
 
293
295
  'cfg.notFile': '설정 파일이 일반 파일이 아니라 읽지 않습니다',
@@ -333,8 +335,13 @@ export const STRINGS = {
333
335
  'doctor.hint.gemini': '프로세스만 감지합니다 (세션·토큰은 아직 지원하지 않음)',
334
336
  'doctor.hint.agyNode': 'Node {node} 에서는 기록을 읽기 전용으로 열 수 없어 프로세스만 감지합니다 (Node 22.15 이상 필요)',
335
337
  'doctor.notifier': '✓ 알림 {kind} ({path}) · --notify 로 켬 (끝남·context 경고는 --notify=waiting,done,context)',
336
- 'doctor.noNotifier': '○ 알림 {want} 없음 · --notify 를 켜도 알림을 건너뜀{wsl}',
337
- 'doctor.wsl': ' (WSL 은 notify-send 만 쓴다)',
338
+ 'doctor.noNotifier': '○ 알림 {want} 없음 · --notify 를 켜도 알림을 건너뜀',
339
+ 'doctor.noNotifierWsl': '! 알림 powershell.exe·notify-send 없음 · --notify 를 켜도 알림을 건너뜀',
340
+ 'doctor.wslHint': 'WSL 은 powershell.exe 로 Windows 알림을 띄운다. Windows PATH 를 넣었는지(/etc/wsl.conf 의 appendWindowsPath) 확인한다',
341
+ 'doctor.busBad': '! 알림 {kind} ({path}) · D-Bus 세션 버스가 없어 알림이 뜨지 않음 ({why})',
342
+ 'doctor.busMissing': 'DBUS_SESSION_BUS_ADDRESS 없음',
343
+ 'doctor.busSocket': '{path} 소켓 없음',
344
+ 'doctor.busHint': '데스크톱 세션 안에서 실행하거나 사용자 D-Bus(systemctl --user, dbus-launch)를 켠다. 대신 --on-waiting 으로 다른 알림 명령을 부를 수 있다',
338
345
  'doctor.config': '{mark} 설정 {state}{path}',
339
346
  'doctor.configExists': '있음',
340
347
  'doctor.configMissing': '없음 (기본값)',
@@ -354,6 +361,17 @@ export const STRINGS = {
354
361
  'phase.geminiLimited': '실행 중 (세부 정보 미지원)',
355
362
  'phase.agyOldNode': '실행 중 (세부 정보는 Node 22.15 이상)',
356
363
  'phase.waiting': '응답 대기',
364
+ // 오류로 멈춤 (kind stopped, claude.mjs stoppedPhase). 사용 한도는 기록 표본이 없어 아직 가르지 않는다.
365
+ 'phase.stopAuth': '로그인 필요',
366
+ 'phase.stopNetwork': '연결 끊김',
367
+ 'phase.stopApi': 'API 오류로 멈춤',
368
+ // 프롬프트 캐시 만료까지 남은 시간 (STATUS 칸 뒤, 상세 패널). 비용·한도는 단정하지 않는다.
369
+ 'cache.left': '캐시 {t}',
370
+ 'cache.expired': '캐시 만료',
371
+ 'cache.ttl5m': '5분',
372
+ 'cache.ttl1h': '1시간',
373
+ 'detail.cacheLeft': '프롬프트 캐시 {t} 남음 ({ttl} TTL, 마지막 요청 시작 기준 추정)',
374
+ 'detail.cacheExpired': '프롬프트 캐시 만료 ({ttl} TTL, 마지막 요청 시작 기준 추정)',
357
375
  'phase.shell': '쉘 명령 실행 중',
358
376
  'phase.tool': '도구 실행 · {what}',
359
377
  'phase.toolUnknown': '도구 실행 · 도구',
@@ -443,6 +461,7 @@ export const STRINGS = {
443
461
  'legend.waiting': '응답 대기 (권한·질문). 행 배경이 강조된다',
444
462
  'legend.unseen': '완료 · 확인 전 (작업이 끝났는데 아직 선택해 보지 않음)',
445
463
  'legend.idle': '다음 지시 대기',
464
+ 'legend.stopped': '오류로 멈춤 (로그인 필요, 연결 끊김 등). 기록의 API 오류 줄로 판단한다',
446
465
  'legend.ended': '종료',
447
466
  'legend.pin': '고정한 세션 (p). SESSION 칸 앞에 붙는다',
448
467
  'legend.status': '지금 단계. 큰 기록을 처음 읽는 동안은 기록 읽는 중 N%',
@@ -678,18 +697,20 @@ export const STRINGS = {
678
697
  'sessions.cardTools': 'Cost share by tool: {tools}',
679
698
  'sessions.cardToolsTokens': 'Token share by tool: {tools}',
680
699
  'sessions.cardPlan': '{ratio} the {days}-day share {prorated} of a {plan}/month subscription (API list price, not your actual bill)',
700
+ 'sessions.cardWaited': 'Agents waited for you {waited} (estimate)',
681
701
  'sessions.col.tool': 'Tool',
682
702
  'sessions.col.model': 'Model',
683
703
  'sessions.col.project': 'Project',
684
704
  'sessions.col.name': 'Session',
685
705
  'sessions.col.start': 'Start',
686
706
  'sessions.col.end': 'End',
707
+ 'sessions.col.waited': 'Waited',
687
708
  'sessions.col.tokens': 'Tokens',
688
709
  'sessions.col.cost': 'Cost',
689
710
  'sessions.col.files': 'Files',
690
711
  'sessions.col.prompt': 'First prompt',
691
712
  'sessions.empty': 'No session used tokens in this period',
692
- 'sessions.noteBasis': 'Cost is the API list price, not your actual bill. Start and end are activity times within the period; Files is the number of files changed (- means unknown)',
713
+ 'sessions.noteBasis': 'Cost is the API list price, not your actual bill. Start and end are activity times within the period; Files is the number of files changed (- means unknown). Waited estimates the time from a finished reply to your next prompt or approval (up to 2 hours per gap; time away is counted too)',
693
714
  'sessions.capped': '--since is limited to {n} days back, which the ledger keeps, using {n} days',
694
715
 
695
716
  'cfg.notFile': 'config file is not a regular file, not reading it',
@@ -735,8 +756,13 @@ export const STRINGS = {
735
756
  'doctor.hint.gemini': 'detects processes only (sessions and tokens not supported yet)',
736
757
  'doctor.hint.agyNode': 'Node {node} cannot open the logs read-only, so only processes are detected (needs Node 22.15 or later)',
737
758
  'doctor.notifier': '✓ notify {kind} ({path}) · turn on with --notify (done and context alerts: --notify=waiting,done,context)',
738
- 'doctor.noNotifier': '○ notify {want} not found · --notify will skip notifications{wsl}',
739
- 'doctor.wsl': ' (WSL uses notify-send only)',
759
+ 'doctor.noNotifier': '○ notify {want} not found · --notify will skip notifications',
760
+ 'doctor.noNotifierWsl': '! notify powershell.exe and notify-send not found · --notify will skip notifications',
761
+ 'doctor.wslHint': 'WSL shows Windows notifications through powershell.exe. Check that the Windows PATH is added (appendWindowsPath in /etc/wsl.conf)',
762
+ 'doctor.busBad': '! notify {kind} ({path}) · no D-Bus session bus, notifications will not show ({why})',
763
+ 'doctor.busMissing': 'DBUS_SESSION_BUS_ADDRESS not set',
764
+ 'doctor.busSocket': 'no socket at {path}',
765
+ 'doctor.busHint': 'run inside a desktop session or start a user D-Bus (systemctl --user, dbus-launch). Or call another notifier with --on-waiting',
740
766
  'doctor.config': '{mark} config {state}{path}',
741
767
  'doctor.configExists': 'found',
742
768
  'doctor.configMissing': 'not found',
@@ -755,6 +781,15 @@ export const STRINGS = {
755
781
  'phase.geminiLimited': { long: 'Running (no details yet)', short: 'Running' },
756
782
  'phase.agyOldNode': { long: 'Running (details need Node 22.15+)', short: 'Running' },
757
783
  'phase.waiting': { long: 'Waiting for you', short: 'Waiting' },
784
+ 'phase.stopAuth': 'Login needed',
785
+ 'phase.stopNetwork': 'Connection lost',
786
+ 'phase.stopApi': { long: 'Stopped by API error', short: 'API error' },
787
+ 'cache.left': 'cache {t}',
788
+ 'cache.expired': 'cache expired',
789
+ 'cache.ttl5m': '5m',
790
+ 'cache.ttl1h': '1h',
791
+ 'detail.cacheLeft': 'Prompt cache {t} left ({ttl} TTL, estimated from the last request start)',
792
+ 'detail.cacheExpired': 'Prompt cache expired ({ttl} TTL, estimated from the last request start)',
758
793
  'phase.shell': { long: 'Running shell command', short: 'Shell' },
759
794
  'phase.tool': { long: 'Running tool · {what}', short: 'Tool · {what}' },
760
795
  'phase.toolUnknown': { long: 'Running tool', short: 'Tool' },
@@ -843,6 +878,7 @@ export const STRINGS = {
843
878
  'legend.waiting': 'Waiting for you (permission or question)',
844
879
  'legend.unseen': 'Done, unseen (not selected yet)',
845
880
  'legend.idle': 'Idle, ready for the next prompt',
881
+ 'legend.stopped': 'Stopped by an error (login needed, connection lost)',
846
882
  'legend.ended': 'Ended',
847
883
  'legend.pin': 'Pinned session (p), before SESSION',
848
884
  'legend.status': 'Current step (Reading log N% on first load)',
package/src/json.mjs CHANGED
@@ -46,6 +46,12 @@ export function toJson(data, version = null, opts = {}) {
46
46
  // phase 는 화면 언어와 상관없이 늘 한국어 문구(예전과 같은 글)로 두고, 언어와 상관없는 상태 이름은 phaseKind 로 준다.
47
47
  phase: koPhase(s.phase),
48
48
  phaseKind: s.phase?.kind ?? null,
49
+ // 오류로 멈춘 이유 { kind: 'auth'|'network'|'api' } (phaseKind 가 stopped 일 때만), 아니면 null.
50
+ stopReason: s.stopReason ?? null,
51
+ // 프롬프트 캐시가 만료되는 시각 (Claude 의 응답 대기·다음 지시 대기 세션만, 마지막 요청 시작 기준 추정). 이미 지난 시각일 수 있다.
52
+ cacheExpiresAt: iso(s.cacheExpiresAt),
53
+ // 지금 도는 도구가 시작된 시각 (작업 중이고 진행 단계가 도구 실행일 때만, 허락 대기 중이면 null). 화면과 달리 1분 미만도 나간다.
54
+ toolStartedAt: iso(s.toolStartedAt),
49
55
  waitingFor: s.waitingFor ?? null,
50
56
  // 이 세션을 이어 여는 셸 명령 (resume.mjs). 만들 수 없으면 null.
51
57
  resumeCmd: resumeCmd(s),
package/src/notify.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  // 알림: --notify[=종류] (데스크톱 알림), --on-waiting <명령> (사용자 명령 실행). 종류는 waiting(기본)·done·context.
2
2
  // 세션 정보는 명령 문자열에 넣지 않는다. 알림 도구에는 인자로, 사용자 명령에는 AITOP_* 환경변수로만 넘긴다.
3
3
  import { spawn } from 'node:child_process';
4
- import { accessSync, constants, readFileSync } from 'node:fs';
5
- import { join, delimiter } from 'node:path';
4
+ import { accessSync, constants, existsSync, readFileSync } from 'node:fs';
5
+ import { join, delimiter, posix } from 'node:path';
6
6
  import { mask, stripControl } from './text.mjs';
7
7
  import { getLang, phaseText, t } from './i18n.mjs';
8
8
 
@@ -95,7 +95,7 @@ export function which(name, envPath = process.env.PATH ?? '') {
95
95
  return null;
96
96
  }
97
97
 
98
- // WSL 인지. --doctor 의 알림 안내에 쓴다. readVersion 은 테스트에서 /proc/version 대신 넣는다.
98
+ // WSL 인지. 알림 수단 고르기와 --doctor 의 알림 안내에 쓴다. readVersion 은 테스트에서 /proc/version 대신 넣는다.
99
99
  export function isWsl(env = process.env, readVersion = () => readFileSync('/proc/version', 'utf8')) {
100
100
  if (env.WSL_DISTRO_NAME || env.WSL_INTEROP) return true;
101
101
  try {
@@ -106,24 +106,85 @@ export function isWsl(env = process.env, readVersion = () => readFileSync('/proc
106
106
  }
107
107
 
108
108
  // 쓸 수 있는 데스크톱 알림 도구. 없으면 null (조용히 건너뛴다).
109
- // Linux·WSL 은 notify-send 만 쓴다. WSL 에서 없으면 powershell 로 대신하지 않는다.
110
- export function findNotifier({ platform = process.platform, env = process.env } = {}) {
109
+ // WSL 은 powershell.exe 로 Windows 토스트를 먼저 띄운다 (WSL 에는 D-Bus 세션 버스가 없는 일이 흔하다, #250).
110
+ // powershell.exe 가 없으면 notify-send 를 쓴다. 일반 Linux 는 notify-send 만 쓴다.
111
+ // wsl 은 테스트에서 바꿔 끼운다.
112
+ export function findNotifier({ platform = process.platform, env = process.env, wsl = platform === 'linux' && isWsl(env) } = {}) {
111
113
  if (platform === 'darwin') {
112
114
  const path = which('osascript', env.PATH);
113
115
  return path ? { kind: 'osascript', path } : null;
114
116
  }
115
117
  if (platform === 'linux') {
118
+ if (wsl) {
119
+ const ps = which('powershell.exe', env.PATH);
120
+ if (ps) return { kind: 'powershell', path: ps };
121
+ }
116
122
  const path = which('notify-send', env.PATH);
117
123
  return path ? { kind: 'notify-send', path } : null;
118
124
  }
119
125
  return null;
120
126
  }
121
127
 
128
+ // notify-send 가 기대는 D-Bus 세션 버스를 찾을 수 있는지. 알림을 실제로 보내 보지는 않는다 (--doctor 가 알림을 띄우면 안 된다).
129
+ // 문제가 없거나 확인할 수 없으면 null, 주소가 없으면 { reason: 'missing' }, unix:path= 소켓이 모두 없으면 { reason: 'socket', path }.
130
+ // 주소가 없을 때 GLib 처럼 $XDG_RUNTIME_DIR/bus 를 먼저 본다. abstract 소켓·tcp 등은 파일로 확인할 수 없으니 문제로 보지 않는다. 버스 경로는 늘 POSIX 경로라 posix.join 으로 잇는다 (Windows 에서 돌려도 같은 결과).
131
+ export function busProblem(env = process.env, exists = existsSync) {
132
+ const addr = env.DBUS_SESSION_BUS_ADDRESS;
133
+ if (!addr) {
134
+ if (env.XDG_RUNTIME_DIR && exists(posix.join(env.XDG_RUNTIME_DIR, 'bus'))) return null;
135
+ return { reason: 'missing' };
136
+ }
137
+ let firstPath = null;
138
+ for (const entry of addr.split(';')) {
139
+ const m = /^unix:(.*)$/.exec(entry.trim());
140
+ if (!m) return null;
141
+ const keys = Object.fromEntries(m[1].split(',').map((kv) => [kv.slice(0, kv.indexOf('=')), kv.slice(kv.indexOf('=') + 1)]));
142
+ if (keys.path == null) return null;
143
+ let path;
144
+ try {
145
+ path = decodeURIComponent(keys.path);
146
+ } catch {
147
+ path = keys.path;
148
+ }
149
+ if (exists(path)) return null;
150
+ firstPath ??= path;
151
+ }
152
+ return firstPath ? { reason: 'socket', path: firstPath } : null;
153
+ }
154
+
155
+ // Windows PowerShell 의 AUMID. 시작 메뉴에 등록되어 있어 따로 등록하지 않아도 토스트가 뜬다 (Get-StartApps 로 확인).
156
+ export const PS_APP_ID = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe';
157
+ const TOAST_MAX = 250;
158
+
159
+ // Windows 토스트를 띄우는 PowerShell 스크립트. Windows 네이티브(#197)에서도 그대로 쓸 수 있게 따로 둔다.
160
+ // 제목·본문은 UTF-8 base64 로만 스크립트에 들어가고(글자는 A-Z a-z 0-9 + / = 뿐), 스크립트 안에서 풀어
161
+ // XML 글 노드(CreateTextNode)로 넣는다. 그래서 따옴표·$()·XML 특수문자가 명령이나 XML 구조를 바꾸지 못한다.
162
+ export function toastScript(title, body, appId = PS_APP_ID) {
163
+ const b64 = (v) => Buffer.from(String(v).slice(0, TOAST_MAX), 'utf8').toString('base64');
164
+ const id = b64(appId);
165
+ return [
166
+ "$ErrorActionPreference = 'Stop'",
167
+ '$d = { param($s) [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($s)) }',
168
+ '[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null',
169
+ '$x = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)',
170
+ "$n = $x.GetElementsByTagName('text')",
171
+ `$n.Item(0).AppendChild($x.CreateTextNode((& $d '${b64(title)}'))) > $null`,
172
+ `$n.Item(1).AppendChild($x.CreateTextNode((& $d '${b64(body)}'))) > $null`,
173
+ `[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier((& $d '${id}')).Show([Windows.UI.Notifications.ToastNotification]::new($x))`,
174
+ ].join('\n');
175
+ }
176
+
177
+ // powershell.exe -EncodedCommand 의 값: 스크립트를 UTF-16LE 로 바꿔 base64.
178
+ export const encodePowerShell = (script) => Buffer.from(script, 'utf16le').toString('base64');
179
+
122
180
  // 알림 도구 실행 인자. 제목·본문은 인자로만 넘긴다 (셸·AppleScript 문자열에 넣지 않는다).
123
181
  export function notifierCommand(notifier, title, body) {
124
182
  if (notifier.kind === 'osascript') {
125
183
  return [notifier.path, ['-e', 'on run argv', '-e', 'display notification (item 2 of argv) with title (item 1 of argv)', '-e', 'end run', title, body]];
126
184
  }
185
+ if (notifier.kind === 'powershell') {
186
+ return [notifier.path, ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', encodePowerShell(toastScript(title, body))]];
187
+ }
127
188
  // notify-send 는 본문을 마크업으로 읽으므로 <, >, & 를 바꿔 넣는다.
128
189
  return [notifier.path, ['--app-name=aitop', '--', escapeMarkup(title), escapeMarkup(body)]];
129
190
  }
@@ -176,6 +237,7 @@ export function notifyText(sessions, lang = getLang(), kind = 'waiting') {
176
237
  // 실행 중에 새 일이 오면 하나만 대기열에 두고(가장 최근 것으로 덮어씀), 끝나면 그것을 실행한다.
177
238
  // 출력은 버리고, timeoutMs 가 지나면 프로세스 그룹째(셸과 그 자식) SIGKILL 한다.
178
239
  // 자식은 'exit' 를 받아 거두므로 좀비가 남지 않는다. UI 루프는 기다리지 않는다.
240
+ // WSL 의 powershell.exe 는 Windows 쪽 프로세스지만, Linux 쪽 중계 프로세스를 SIGKILL 하면 Windows 프로세스도 함께 끝난다 (#250 에서 확인).
179
241
  function killGroup(c, sig) {
180
242
  try {
181
243
  process.kill(-c.pid, sig);
package/src/order.mjs CHANGED
@@ -4,6 +4,9 @@
4
4
  // 대기 세션이 제 프로젝트 묶음 안에 흩어지면 맨 위라는 약속이 깨지고, 묶음 머리 위에 따로 두면 어느 묶음 소속인지 헷갈린다.
5
5
  // 고정(p)한 세션은 응답 대기 바로 아래에 고정한 순서대로 둔다. 정렬을 바꿔도 그 순서는 바뀌지 않고, 묶을 때는 '고정' 묶음 하나로 모은다.
6
6
  // 응답 대기를 고정보다 위에 두는 것은 사람이 할 일이 고정 목록에 가려지지 않게 하려는 것이다. 고정한 세션이 응답 대기가 되면 대기 쪽으로 올라간다.
7
+ // 오류로 멈춘 세션(phase stopped: 로그인 필요·연결 끊김 등)은 고정 바로 아래, 나머지 세션의 맨 위에 둔다 (#240).
8
+ // 끝난 줄 알고 지나치지 않게 올리되, 지금 바로 답해야 하는 응답 대기와 사람이 정한 고정 순서보다는 아래다.
9
+ // 묶을 때는 따로 모으지 않고 제 묶음의 맨 위에 두므로, 그 묶음도 앞으로 온다.
7
10
  import { costOf } from './ui/draw.mjs';
8
11
  import { lastName } from './paths.mjs';
9
12
 
@@ -54,7 +57,8 @@ export function arrange(sessions, { sort = 'default', group = 'none', costMode =
54
57
  const rank = new Map((pins ?? []).map((id, i) => [id, i]));
55
58
  const waiting = sessions.filter((s) => s.status === 'waiting').sort(cmp);
56
59
  const pinned = sessions.filter((s) => s.status !== 'waiting' && rank.has(s.id)).sort((a, b) => rank.get(a.id) - rank.get(b.id));
57
- const rest = sessions.filter((s) => s.status !== 'waiting' && !rank.has(s.id)).sort(cmp);
60
+ const stopped = (s) => (s.phase?.kind === 'stopped' ? 0 : 1);
61
+ const rest = sessions.filter((s) => s.status !== 'waiting' && !rank.has(s.id)).sort((a, b) => stopped(a) - stopped(b) || cmp(a, b));
58
62
  const keyOf = GROUP_KEY[group];
59
63
  if (!keyOf) return { sessions: [...waiting, ...pinned, ...rest], groups: null };
60
64
  const byName = new Map();
@@ -3,10 +3,12 @@
3
3
  // 토큰·비용·모델·프로젝트는 날짜별 장부(--report daily 와 같은 값, 같은 프로젝트 규칙)에서, 시작·끝 시각·고친 파일·첫 지시·세션 이름은
4
4
  // 기록 요약(sources/sheets.mjs)에서 온다. agy 는 시작·끝을 장부의 호출 시각에서 얻고, 고친 파일과 첫 지시는 모른다 ('-').
5
5
  // 첫 지시는 --show-prompts 일 때만 낸다 (공유용 출력에 개인 내용이 섞이지 않게).
6
+ // 기다린 시간(waited)은 기록 요약의 날짜별 w 합이다 (에이전트가 끝낸 뒤 사용자 입력까지, 간격 하나당 2시간 상한, sheets.mjs).
7
+ // 부모 세션 기록에서만 세고(서브에이전트는 넣지 않는다), agy 는 모른다 ('-').
6
8
  import { existsSync } from 'node:fs';
7
9
  import { basename, dirname, join } from 'node:path';
8
10
  import { t } from './i18n.mjs';
9
- import { fmtTokens, mask, oneLine, pad, stripControl, truncate, width } from './text.mjs';
11
+ import { fmtElapsed, fmtTokens, mask, oneLine, pad, stripControl, truncate, width } from './text.mjs';
10
12
  import { money } from './line.mjs';
11
13
  import { tildeIn } from './paths.mjs';
12
14
  import { dayKey } from './sources/common.mjs';
@@ -169,6 +171,8 @@ export function buildSessions(books, { since, now = Date.now(), extra = new Map(
169
171
  }
170
172
  if (g.tool === 'claude') paths.add(g.mainPath);
171
173
  let prompt = null;
174
+ // 기다린 시간: 부모 기록의 기록 요약이 있을 때만 (없으면 모름).
175
+ let waited = g.tool !== 'agy' && extra.has(g.mainPath) ? 0 : null;
172
176
  for (const p of paths) {
173
177
  const e = extra.get(p);
174
178
  if (!e) {
@@ -181,6 +185,7 @@ export function buildSessions(books, { since, now = Date.now(), extra = new Map(
181
185
  for (const f of x.f ?? []) files.add(f);
182
186
  if (x.more) more = true;
183
187
  if (p === g.mainPath && x.p && prompt == null) prompt = x.p;
188
+ if (p === g.mainPath && waited != null) waited += x.w ?? 0;
184
189
  }
185
190
  }
186
191
  const main = g.tool === 'agy' ? agy.get(g.mainPath) : extra.get(g.mainPath);
@@ -206,6 +211,7 @@ export function buildSessions(books, { since, now = Date.now(), extra = new Map(
206
211
  files: filesKnown ? files.size : null,
207
212
  filesMore: filesKnown && more,
208
213
  prompt,
214
+ waited,
209
215
  });
210
216
  }
211
217
  const rank = (x) => TOOLS.indexOf(x.tool);
@@ -214,8 +220,10 @@ export function buildSessions(books, { since, now = Date.now(), extra = new Map(
214
220
  }
215
221
 
216
222
  function summaryOf(sessions, since, now, plan) {
217
- const total = { sessions: sessions.length, tokens: 0, cost: 0, unpriced: false, tools: {} };
223
+ // waited: 아는 세션의 기다린 시간 합. 아는 세션이 하나도 없으면 null.
224
+ const total = { sessions: sessions.length, tokens: 0, cost: 0, unpriced: false, tools: {}, waited: null };
218
225
  for (const s of sessions) {
226
+ if (s.waited != null) total.waited = (total.waited ?? 0) + s.waited;
219
227
  total.tokens += s.tokens;
220
228
  total.cost += s.cost;
221
229
  if (s.unpriced) total.unpriced = true;
@@ -259,6 +267,8 @@ export function sessionsJson(r, version, { partial = false, prompts = false } =
259
267
  shareBy: s.shareBy,
260
268
  tools: s.tools,
261
269
  plan: s.plan,
270
+ // 기다린 시간 합 (ms, 추정). 모르면 null.
271
+ waitedMs: s.waited,
262
272
  },
263
273
  sessions: r.sessions.map((x) => ({
264
274
  tool: x.tool,
@@ -274,6 +284,8 @@ export function sessionsJson(r, version, { partial = false, prompts = false } =
274
284
  cost: x.cost,
275
285
  unpriced: x.unpriced,
276
286
  files: x.files,
287
+ // 기다린 시간 (ms, 추정). agy 처럼 모르면 null.
288
+ waitedMs: x.waited,
277
289
  ...(prompts ? { prompt: x.prompt } : {}),
278
290
  })),
279
291
  };
@@ -289,6 +301,7 @@ const mdhm = (ms) => {
289
301
  const endText = (x) => (x.end == null ? '-' : x.start != null && dayKey(x.start) === dayKey(x.end) ? hm(new Date(x.end)) : mdhm(x.end));
290
302
  const startText = (x) => (x.start == null ? '-' : mdhm(x.start));
291
303
  const costText = (x) => (used(x) && !(x.unpriced && !(x.cost > 0)) ? money(x.cost) : '-');
304
+ const waitedText = (ms) => (ms == null ? '-' : fmtElapsed(ms));
292
305
  const filesText = (x) => (x.files == null ? '-' : `${x.files}${x.filesMore ? '+' : ''}`);
293
306
  const modelText = (x) => (x.model ? `${x.model}${x.models.length > 1 ? ` +${x.models.length - 1}` : ''}` : '-');
294
307
  const projectText = (x) => (x.project === UNKNOWN ? t('report.unknown') : x.project);
@@ -311,6 +324,7 @@ function cardLines(r, md = false) {
311
324
  const p = s.plan;
312
325
  out.push(t('sessions.cardPlan', { plan: money(p.monthly), days: daysText(p.days), prorated: money(p.prorated), ratio: b(p.ratio == null ? '-' : `${p.ratio >= 10 ? Math.round(p.ratio) : p.ratio.toFixed(1)}x`) }));
313
326
  }
327
+ if (s.waited != null) out.push(t('sessions.cardWaited', { waited: b(waitedText(s.waited)) }));
314
328
  return out;
315
329
  }
316
330
 
@@ -318,9 +332,10 @@ function titleOf(r) {
318
332
  return t('sessions.title', { from: `${dayKey(r.since)} 00:00`, to: `${dayKey(r.now)} ${hm(new Date(r.now))}`, days: daysText(r.days) });
319
333
  }
320
334
 
321
- const HEAD_KEYS = ['tool', 'model', 'project', 'name', 'start', 'end', 'tokens', 'cost', 'files'];
322
- const rowCells = (x) => [x.tool, clean(modelText(x)), clean(projectText(x)), clean(x.name), startText(x), endText(x), used(x) ? fmtTokens(Math.round(x.tokens)) : '-', costText(x), filesText(x)];
323
- const RIGHT = new Set([6, 7, 8]);
335
+ // 기다림 칸은 시작·끝 옆에 둔다 (시간끼리). 좁은 터미널에서는 다른 칸처럼 그대로 두고 세션 이름 칸이 줄어든다.
336
+ const HEAD_KEYS = ['tool', 'model', 'project', 'name', 'start', 'end', 'waited', 'tokens', 'cost', 'files'];
337
+ const rowCells = (x) => [x.tool, clean(modelText(x)), clean(projectText(x)), clean(x.name), startText(x), endText(x), waitedText(x.waited), used(x) ? fmtTokens(Math.round(x.tokens)) : '-', costText(x), filesText(x)];
338
+ const RIGHT = new Set([6, 7, 8, 9]);
324
339
  // 칸 폭 상한 (세션 이름은 터미널 폭에 맞춘다).
325
340
  const MAX_W = { 1: 24, 2: 20 };
326
341
  const NAME_MIN = 12;
@@ -677,6 +677,18 @@ export function phaseOf(live, r, g, runningMembers = 0, kidWait = null) {
677
677
  return runningMembers ? { ...p, args: { ...p.args, ...extra } } : p;
678
678
  }
679
679
 
680
+ // phaseOf 가 '도구 실행' 으로 보이는 단계가 아직 바뀌는 중인 도구 단계(steps status 2)면 그 단계를 만든 시각(ms), 아니면 null.
681
+ // 답변이 낸 도구 호출만 있고 도구 단계가 아직 없을 때(실행할 차례)는 시작 시각을 모르므로 null.
682
+ // 허락 대기(status 9)를 본 단계면(g.resume, collectAgy 가 적는다) 대기를 마지막으로 본 시각부터 잰다.
683
+ export function toolStartOf(phase, g) {
684
+ if (phase?.kind !== 'tool') return null;
685
+ const s = g.open;
686
+ const open = s && (!g.last || (s.idx ?? Infinity) > (g.last.idx ?? -1));
687
+ if (!open || s.type !== STEP.TOOL || !Number.isFinite(s.at)) return null;
688
+ const resumed = g.resume?.idx === s.idx ? g.resume.at : null;
689
+ return Number.isFinite(resumed) ? Math.max(s.at, resumed) : s.at;
690
+ }
691
+
680
692
  function placeholder(p, msg) {
681
693
  return {
682
694
  tool: 'gemini',
@@ -753,6 +765,8 @@ export function collectAgy({ showEnded, budget }) {
753
765
  // 나머지 서브에이전트의 대기는 각자의 팀원 행에 보인다.
754
766
  // 대기 정렬·--notify·--line·summary.json 은 세션의 status·waitingFor·waitSince 를 쓰므로 이것으로 함께 바뀐다.
755
767
  const own = isLive ? waitingFor(g) : null;
768
+ // 허락 대기를 본 도구 단계와 그 시각. 허락한 뒤의 실행 경과 시간은 여기서부터 잰다 (toolStartOf).
769
+ if (own) g.resume = { idx: g.wait.idx, at: Date.now() };
756
770
  let kidIdx = -1;
757
771
  if (!own) {
758
772
  for (let i = 0; i < kids.length; i++) {
@@ -761,6 +775,7 @@ export function collectAgy({ showEnded, budget }) {
761
775
  }
762
776
  const kidWait = kidIdx >= 0 ? `${kids[kidIdx].agent || 'agent'}: ${kidWaits[kidIdx]}` : null;
763
777
  const wait = own ?? kidWait;
778
+ const phase = phaseOf(isLive, r, g, running, kidWait);
764
779
  const waitDetail = own ? (g.wait.detail ?? own) : kidWait ? (kidUsage[kidIdx].wait?.detail ?? kidWaits[kidIdx]) : null;
765
780
  out.push({
766
781
  tool: 'gemini',
@@ -774,7 +789,9 @@ export function collectAgy({ showEnded, budget }) {
774
789
  model: g.model,
775
790
  live: isLive,
776
791
  status: !isLive ? 'ended' : wait ? 'waiting' : r.running ? 'busy' : 'idle',
777
- phase: phaseOf(isLive, r, g, running, kidWait),
792
+ phase,
793
+ // 지금 도는 도구 단계가 시작된 시각(ms) 또는 null (toolStartOf).
794
+ toolStartedAt: wait ? null : toolStartOf(phase, g),
778
795
  cost,
779
796
  costNoCache,
780
797
  costUnknown,