@sejuneoh/aitop 0.32.0 → 0.33.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
@@ -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
@@ -109,7 +115,7 @@ aitop --on-waiting 'my-hook.sh' run a command with /bin/sh -c for the same
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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sejuneoh/aitop",
3
- "version": "0.32.0",
3
+ "version": "0.33.0",
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/i18n.mjs CHANGED
@@ -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': '설정 파일이 일반 파일이 아니라 읽지 않습니다',
@@ -354,6 +356,17 @@ export const STRINGS = {
354
356
  'phase.geminiLimited': '실행 중 (세부 정보 미지원)',
355
357
  'phase.agyOldNode': '실행 중 (세부 정보는 Node 22.15 이상)',
356
358
  'phase.waiting': '응답 대기',
359
+ // 오류로 멈춤 (kind stopped, claude.mjs stoppedPhase). 사용 한도는 기록 표본이 없어 아직 가르지 않는다.
360
+ 'phase.stopAuth': '로그인 필요',
361
+ 'phase.stopNetwork': '연결 끊김',
362
+ 'phase.stopApi': 'API 오류로 멈춤',
363
+ // 프롬프트 캐시 만료까지 남은 시간 (STATUS 칸 뒤, 상세 패널). 비용·한도는 단정하지 않는다.
364
+ 'cache.left': '캐시 {t}',
365
+ 'cache.expired': '캐시 만료',
366
+ 'cache.ttl5m': '5분',
367
+ 'cache.ttl1h': '1시간',
368
+ 'detail.cacheLeft': '프롬프트 캐시 {t} 남음 ({ttl} TTL, 마지막 요청 시작 기준 추정)',
369
+ 'detail.cacheExpired': '프롬프트 캐시 만료 ({ttl} TTL, 마지막 요청 시작 기준 추정)',
357
370
  'phase.shell': '쉘 명령 실행 중',
358
371
  'phase.tool': '도구 실행 · {what}',
359
372
  'phase.toolUnknown': '도구 실행 · 도구',
@@ -443,6 +456,7 @@ export const STRINGS = {
443
456
  'legend.waiting': '응답 대기 (권한·질문). 행 배경이 강조된다',
444
457
  'legend.unseen': '완료 · 확인 전 (작업이 끝났는데 아직 선택해 보지 않음)',
445
458
  'legend.idle': '다음 지시 대기',
459
+ 'legend.stopped': '오류로 멈춤 (로그인 필요, 연결 끊김 등). 기록의 API 오류 줄로 판단한다',
446
460
  'legend.ended': '종료',
447
461
  'legend.pin': '고정한 세션 (p). SESSION 칸 앞에 붙는다',
448
462
  'legend.status': '지금 단계. 큰 기록을 처음 읽는 동안은 기록 읽는 중 N%',
@@ -678,18 +692,20 @@ export const STRINGS = {
678
692
  'sessions.cardTools': 'Cost share by tool: {tools}',
679
693
  'sessions.cardToolsTokens': 'Token share by tool: {tools}',
680
694
  'sessions.cardPlan': '{ratio} the {days}-day share {prorated} of a {plan}/month subscription (API list price, not your actual bill)',
695
+ 'sessions.cardWaited': 'Agents waited for you {waited} (estimate)',
681
696
  'sessions.col.tool': 'Tool',
682
697
  'sessions.col.model': 'Model',
683
698
  'sessions.col.project': 'Project',
684
699
  'sessions.col.name': 'Session',
685
700
  'sessions.col.start': 'Start',
686
701
  'sessions.col.end': 'End',
702
+ 'sessions.col.waited': 'Waited',
687
703
  'sessions.col.tokens': 'Tokens',
688
704
  'sessions.col.cost': 'Cost',
689
705
  'sessions.col.files': 'Files',
690
706
  'sessions.col.prompt': 'First prompt',
691
707
  '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)',
708
+ '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
709
  'sessions.capped': '--since is limited to {n} days back, which the ledger keeps, using {n} days',
694
710
 
695
711
  'cfg.notFile': 'config file is not a regular file, not reading it',
@@ -755,6 +771,15 @@ export const STRINGS = {
755
771
  'phase.geminiLimited': { long: 'Running (no details yet)', short: 'Running' },
756
772
  'phase.agyOldNode': { long: 'Running (details need Node 22.15+)', short: 'Running' },
757
773
  'phase.waiting': { long: 'Waiting for you', short: 'Waiting' },
774
+ 'phase.stopAuth': 'Login needed',
775
+ 'phase.stopNetwork': 'Connection lost',
776
+ 'phase.stopApi': { long: 'Stopped by API error', short: 'API error' },
777
+ 'cache.left': 'cache {t}',
778
+ 'cache.expired': 'cache expired',
779
+ 'cache.ttl5m': '5m',
780
+ 'cache.ttl1h': '1h',
781
+ 'detail.cacheLeft': 'Prompt cache {t} left ({ttl} TTL, estimated from the last request start)',
782
+ 'detail.cacheExpired': 'Prompt cache expired ({ttl} TTL, estimated from the last request start)',
758
783
  'phase.shell': { long: 'Running shell command', short: 'Shell' },
759
784
  'phase.tool': { long: 'Running tool · {what}', short: 'Tool · {what}' },
760
785
  'phase.toolUnknown': { long: 'Running tool', short: 'Tool' },
@@ -843,6 +868,7 @@ export const STRINGS = {
843
868
  'legend.waiting': 'Waiting for you (permission or question)',
844
869
  'legend.unseen': 'Done, unseen (not selected yet)',
845
870
  'legend.idle': 'Idle, ready for the next prompt',
871
+ 'legend.stopped': 'Stopped by an error (login needed, connection lost)',
846
872
  'legend.ended': 'Ended',
847
873
  'legend.pin': 'Pinned session (p), before SESSION',
848
874
  '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/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,
@@ -15,8 +15,8 @@ const LOADING_MIN_BYTES = 4 * 1024 * 1024;
15
15
  const TAIL_BYTES = 256 * 1024;
16
16
  const CUSTOM_TITLE = '"type":"custom-title"';
17
17
 
18
- // 기록 끝 TAIL_BYTES 에서 마지막 custom-title 이름. 줄이 없으면 undefined, 이름이 비었으면 null.
19
- export function tailCustomTitle(path) {
18
+ // 기록 끝 TAIL_BYTES 의 줄들. 읽지 못하면 null.
19
+ function tailLines(path) {
20
20
  let text;
21
21
  try {
22
22
  const fd = openSync(path, 'r');
@@ -30,9 +30,15 @@ export function tailCustomTitle(path) {
30
30
  }
31
31
  } catch (e) {
32
32
  debugIo('claude', 'transcript tail read failed', e, path);
33
- return undefined;
33
+ return null;
34
34
  }
35
- const lines = text.split('\n');
35
+ return text.split('\n');
36
+ }
37
+
38
+ // 기록 끝 TAIL_BYTES 에서 마지막 custom-title 이름. 줄이 없으면 undefined, 이름이 비었으면 null.
39
+ export function tailCustomTitle(path) {
40
+ const lines = tailLines(path);
41
+ if (!lines) return undefined;
36
42
  for (let i = lines.length - 1; i >= 0; i--) {
37
43
  if (!lines[i].includes(CUSTOM_TITLE)) continue;
38
44
  try {
@@ -43,6 +49,106 @@ export function tailCustomTitle(path) {
43
49
  return undefined;
44
50
  }
45
51
 
52
+ // API 오류 줄(isApiErrorMessage)이 말하는 멈춘 이유. 이 PC 기록 표본에서 확인한 형식만 가른다.
53
+ // error: 'authentication_failed' (본문 'Login expired · Please run /login', 'OAuth session expired ...') → auth
54
+ // apiError: 'connection_failed' (error: 'server_error', 본문 'API Error: Connection lost mid-response ...') → network
55
+ // 사용 한도 줄은 표본이 없어 따로 가르지 않고(재개 시각도 읽지 않는다) 그 밖의 오류와 함께 api 로 둔다.
56
+ export function stopReasonOf(x) {
57
+ if (x?.type !== 'assistant' || x.isApiErrorMessage !== true) return null;
58
+ if (x.error === 'authentication_failed') return { kind: 'auth' };
59
+ if (x.apiError === 'connection_failed') return { kind: 'network' };
60
+ return { kind: 'api' };
61
+ }
62
+
63
+ // 기록 끝에서 멈춘 이유를 다시 찾는다: 마지막 대화 줄(assistant·user, isMeta 제외)이 API 오류면 그 이유, 아니면 null.
64
+ // 이 필드가 생기기 전 캐시를 위해서다. 오류 뒤에는 대화가 아닌 줄(last-prompt, turn_duration 등)만 붙는다.
65
+ export function tailStopReason(path) {
66
+ const lines = tailLines(path);
67
+ if (!lines) return null;
68
+ for (let i = lines.length - 1; i >= 0; i--) {
69
+ const l = lines[i];
70
+ if (!l.includes('"type":"assistant"') && !l.includes('"type":"user"')) continue;
71
+ try {
72
+ const x = JSON.parse(l);
73
+ if ((x.type === 'assistant' || x.type === 'user') && x.message && !x.isMeta) return stopReasonOf(x);
74
+ } catch {}
75
+ }
76
+ return null;
77
+ }
78
+
79
+ // 프롬프트 캐시 수명. 공식 문서(https://platform.claude.com/docs/en/build-with-claude/prompt-caching) 기준:
80
+ // 기본 5분, 1시간은 선택. 캐시를 쓰거나 읽을 때마다 수명이 새로 시작되고, 수명은 응답 끝이 아니라 그 요청이 시작된 때부터 잰다.
81
+ // 요청 시작 시각은 기록에 없으므로 그 응답 바로 앞의 사용자 줄(지시·도구 결과) 시각으로 잡는다. 없으면 응답 줄 시각.
82
+ export const CACHE_TTL_5M = 300;
83
+ export const CACHE_TTL_1H = 3600;
84
+
85
+ // 응답 한 줄의 usage 로 캐시 상태를 갱신한다. st: { cacheAt, cacheTtl, inputAt, inputFor }. 바꾸면 true.
86
+ // inputAt 은 한 요청(message.id)에만 쓴다. 사용자 줄 없이 다른 응답이 이어지면 그 응답 줄 시각을 쓴다.
87
+ // 1시간 쓰기 토큰이 있으면 1시간, 5분 쓰기 토큰(또는 쪼갠 값이 없는 쓰기)이 있으면 5분.
88
+ // 읽기만 있으면 읽은 항목의 수명이 다시 시작되므로 앞서 정한 TTL 을 그대로 쓴다 (모르면 기본 5분).
89
+ // 캐시를 쓰지도 읽지도 않은 응답은 캐시를 건드리지 않는다.
90
+ export function applyCacheUsage(st, u, at, id = null) {
91
+ if (!u || !Number.isFinite(at)) return false;
92
+ const cc = u.cache_creation;
93
+ const h1 = cc?.ephemeral_1h_input_tokens ?? 0;
94
+ const m5 = cc?.ephemeral_5m_input_tokens ?? 0;
95
+ const write = u.cache_creation_input_tokens ?? 0;
96
+ const read = u.cache_read_input_tokens ?? 0;
97
+ let ttl;
98
+ if (h1 > 0) ttl = CACHE_TTL_1H;
99
+ else if (m5 > 0 || write > 0) ttl = CACHE_TTL_5M;
100
+ else if (read > 0) ttl = st.cacheTtl ?? CACHE_TTL_5M;
101
+ else return false;
102
+ const fresh = Number.isFinite(st.inputAt) && st.inputAt <= at && (st.inputFor == null || st.inputFor === id);
103
+ st.cacheAt = fresh ? st.inputAt : at;
104
+ st.inputFor = fresh ? id : null;
105
+ if (!fresh) st.inputAt = null;
106
+ st.cacheTtl = ttl;
107
+ return true;
108
+ }
109
+
110
+ // 기록 끝 TAIL_BYTES 를 앞에서부터 다시 읽어 캐시 상태를 만든다. 이 필드가 생기기 전 캐시를 위해서다.
111
+ export function tailCacheState(path) {
112
+ const st = { cacheAt: null, cacheTtl: null, inputAt: null, inputFor: null };
113
+ for (const l of tailLines(path) ?? []) {
114
+ if (!l.includes('"type":"assistant"') && !l.includes('"type":"user"')) continue;
115
+ try {
116
+ cacheStep(st, JSON.parse(l));
117
+ } catch {}
118
+ }
119
+ return st;
120
+ }
121
+
122
+ // 대화 줄 하나를 캐시 상태에 반영한다 (apply 와 tailCacheState 가 같이 쓴다).
123
+ function cacheStep(st, x) {
124
+ if (x.isMeta || !x.message) return;
125
+ if (x.type === 'user') {
126
+ st.inputAt = parseTs(x.timestamp);
127
+ st.inputFor = null;
128
+ }
129
+ // API 오류 줄은 사용량이 0 이라 캐시를 건드리지 않는다.
130
+ else if (x.type === 'assistant' && x.message.usage) applyCacheUsage(st, x.message.usage, parseTs(x.timestamp), x.message.id ?? null);
131
+ }
132
+
133
+ // 결과가 아직 없는 tool_use 의 시작 시각(at)을 기록 끝에서 찾아 채운다. at 필드가 생기기 전 캐시를 위해서다.
134
+ // pending: Map(tool_use id → 열린 호출). at 이 없는 것만 고치고, 고친 것이 있으면 true.
135
+ export function tailToolStarts(path, pending) {
136
+ const want = [...pending].filter(([, p]) => !('at' in p));
137
+ if (!want.length) return false;
138
+ for (const [, p] of want) p.at = null;
139
+ const ids = new Map(want);
140
+ for (const l of tailLines(path) ?? []) {
141
+ if (!l.includes('"tool_use"')) continue;
142
+ try {
143
+ const x = JSON.parse(l);
144
+ for (const c of Array.isArray(x.message?.content) ? x.message.content : []) {
145
+ if (c.type === 'tool_use' && ids.has(c.id)) ids.get(c.id).at = parseTs(x.timestamp);
146
+ }
147
+ } catch {}
148
+ }
149
+ return true;
150
+ }
151
+
46
152
  export class ClaudeTracker {
47
153
  constructor(path) {
48
154
  this.tail = new JsonlTail(path);
@@ -56,7 +162,7 @@ export class ClaudeTracker {
56
162
  const c = loadCache(path);
57
163
  if (c) {
58
164
  this.tail.offset = c.offset;
59
- Object.assign(this, { tokens: c.tokens, cost: c.cost, costNoCache: c.costNoCache, costUnknown: c.costUnknown, context: c.context, model: c.model, title: c.title, customTitle: c.customTitle ?? null, branch: c.branch, events: c.events, lastTool: c.lastTool, lastKind: c.lastKind, files: c.files ?? [], turns: c.turns ?? [], turnCount: c.turnCount ?? 0, firstAt: c.firstAt ?? null, activity: c.activity ?? {} });
165
+ Object.assign(this, { tokens: c.tokens, cost: c.cost, costNoCache: c.costNoCache, costUnknown: c.costUnknown, context: c.context, model: c.model, title: c.title, customTitle: c.customTitle ?? null, branch: c.branch, events: c.events, lastTool: c.lastTool, lastKind: c.lastKind, files: c.files ?? [], turns: c.turns ?? [], turnCount: c.turnCount ?? 0, firstAt: c.firstAt ?? null, activity: c.activity ?? {}, stopReason: c.stopReason ?? null, cacheAt: c.cacheAt ?? null, cacheTtl: c.cacheTtl ?? null, inputAt: c.inputAt ?? null, inputFor: c.inputFor ?? null });
60
166
  this.recent = new Map(c.recent);
61
167
  this.pending = new Map(c.pending);
62
168
  // 이 필드가 생기기 전 캐시는 이미 지나간 custom-title 을 모른다. 끝부분을 한 번 훑어 채우고 캐시에 다시 적어
@@ -65,6 +171,19 @@ export class ClaudeTracker {
65
171
  this.customTitle = tailCustomTitle(path) ?? null;
66
172
  markDirty(path, () => this.snapshot());
67
173
  }
174
+ // 멈춘 이유도 같은 방식으로 한 번만 채운다 (캐시 버전은 그대로).
175
+ if (!('stopReason' in c)) {
176
+ this.stopReason = tailStopReason(path);
177
+ markDirty(path, () => this.snapshot());
178
+ }
179
+ // 프롬프트 캐시 상태도 같은 방식으로 한 번만 채운다 (캐시 버전은 그대로).
180
+ if (!('cacheAt' in c)) {
181
+ const { cacheAt, cacheTtl } = tailCacheState(path);
182
+ Object.assign(this, { cacheAt, cacheTtl });
183
+ markDirty(path, () => this.snapshot());
184
+ }
185
+ // 열린 도구 호출의 시작 시각도 같은 방식으로 한 번만 채운다 (캐시 버전은 그대로).
186
+ if (tailToolStarts(path, this.pending)) markDirty(path, () => this.snapshot());
68
187
  }
69
188
  }
70
189
 
@@ -91,6 +210,19 @@ export class ClaudeTracker {
91
210
  this.firstAt = null;
92
211
  // 시간별 토큰 (common.mjs addActivity)
93
212
  this.activity = {};
213
+ // 마지막 대화 줄이 API 오류면 멈춘 이유 { kind: 'auth'|'network'|'api' } (stopReasonOf), 아니면 null.
214
+ // 그 뒤 정상 assistant 줄이나 사용자 줄이 오면 지운다.
215
+ this.stopReason = null;
216
+ // 프롬프트 캐시 (applyCacheUsage): 수명이 시작된 시각(ms), TTL(초), 마지막 사용자 줄 시각(다음 요청 시작으로 본다).
217
+ this.cacheAt = null;
218
+ this.cacheTtl = null;
219
+ this.inputAt = null;
220
+ this.inputFor = null;
221
+ }
222
+
223
+ // 프롬프트 캐시가 만료되는 시각(ms). 캐시를 쓴 응답이 없으면 null.
224
+ get cacheExpiresAt() {
225
+ return Number.isFinite(this.cacheAt) && this.cacheTtl ? this.cacheAt + this.cacheTtl * 1000 : null;
94
226
  }
95
227
 
96
228
  get path() {
@@ -135,6 +267,11 @@ export class ClaudeTracker {
135
267
  turnCount: this.turnCount,
136
268
  firstAt: this.firstAt,
137
269
  activity: this.activity,
270
+ stopReason: this.stopReason,
271
+ cacheAt: this.cacheAt,
272
+ cacheTtl: this.cacheTtl,
273
+ inputAt: this.inputAt,
274
+ inputFor: this.inputFor,
138
275
  };
139
276
  }
140
277
 
@@ -167,6 +304,11 @@ export class ClaudeTracker {
167
304
  if (this.firstAt == null && x.timestamp) this.firstAt = parseTs(x.timestamp);
168
305
  if (x.isMeta) return;
169
306
 
307
+ if ((x.type === 'assistant' || x.type === 'user') && x.message) {
308
+ this.stopReason = stopReasonOf(x);
309
+ cacheStep(this, x);
310
+ }
311
+
170
312
  if (x.type === 'assistant' && x.message) {
171
313
  const m = x.message;
172
314
  if (m.model && !m.model.startsWith('<')) this.model = m.model;
@@ -177,7 +319,8 @@ export class ClaudeTracker {
177
319
  for (const c of Array.isArray(m.content) ? m.content : []) {
178
320
  if (c.type === 'tool_use') {
179
321
  this.lastTool = describeTool(c.name, c.input);
180
- this.pending.set(c.id, { name: c.name, what: this.lastTool, detail: toolDetail(c.name, c.input), agent: c.input?.subagent_type ?? null });
322
+ // at: 호출을 낸 줄의 시각 (도구 실행 경과 시간의 기준). resumeAt: 허락 대기를 마지막으로 본 시각 (markWaiting).
323
+ this.pending.set(c.id, { name: c.name, what: this.lastTool, detail: toolDetail(c.name, c.input), agent: c.input?.subagent_type ?? null, at: parseTs(x.timestamp) });
181
324
  pushEvent(this, x.timestamp, 'tool', this.lastTool);
182
325
  this.lastKind = 'tool';
183
326
  } else if (c.type === 'text' && c.text?.trim()) {
@@ -213,6 +356,19 @@ export class ClaudeTracker {
213
356
  return (named.at(-1) ?? tools.at(-1))?.detail ?? null;
214
357
  }
215
358
 
359
+ // 허락 대기를 보는 동안 열린 도구 호출마다 그 시각을 적는다. 허락한 뒤의 경과 시간은 여기서부터 잰다 (toolStartedAt).
360
+ // 기록에는 허락한 시각이 없으므로 대기를 마지막으로 본 시각(갱신 1초 간격)으로 갈음한다. 기록이 바뀐 것은 아니라 캐시에 따로 적지 않는다.
361
+ markWaiting(now = Date.now()) {
362
+ for (const p of this.pending.values()) if (p.name !== 'Agent' && p.name !== 'Task') p.resumeAt = now;
363
+ }
364
+
365
+ // phase() 가 보이는 도구(열린 도구 호출 가운데 마지막 것)가 돌기 시작한 시각(ms). 허락을 기다렸으면 대기가 끝난 뒤부터. 모르면 null.
366
+ toolStartedAt() {
367
+ const p = [...this.pending.values()].filter((p) => p.name !== 'Agent' && p.name !== 'Task').at(-1);
368
+ if (!p || !Number.isFinite(p.at)) return null;
369
+ return Number.isFinite(p.resumeAt) ? Math.max(p.at, p.resumeAt) : p.at;
370
+ }
371
+
216
372
  // 지금 무엇을 하는 단계인지: 도구 실행 / 팀원 대기 / 생각 중 / 답변 작성 중.
217
373
  phase() {
218
374
  const open = [...this.pending.values()];
@@ -182,12 +182,39 @@ function phaseOf(status, entry, t) {
182
182
  case 'shell':
183
183
  return { kind: 'tool', msg: 'shell' };
184
184
  case 'idle':
185
- return { kind: 'idle' };
185
+ return stoppedPhase(t) ?? { kind: 'idle' };
186
186
  default:
187
187
  return loadingPhase(t) ?? (t ? t.phase() : { kind: 'think', msg: 'working' });
188
188
  }
189
189
  }
190
190
 
191
+ // 대기(idle) 중인 세션의 마지막 대화 줄이 API 오류면 '멈춤' 으로 보인다 (claude-tracker.mjs stopReasonOf).
192
+ // 응답 대기·작업 중·종료는 그대로 두고, 기록을 다 읽기 전에는 판단하지 않는다.
193
+ const STOP_MSG = { auth: 'stopAuth', network: 'stopNetwork', api: 'stopApi' };
194
+ function stoppedPhase(t) {
195
+ const r = t?.loading == null ? t?.stopReason : null;
196
+ return r ? { kind: 'stopped', msg: STOP_MSG[r.kind] ?? 'stopApi' } : null;
197
+ }
198
+
199
+ function cacheOf(alive, status, t) {
200
+ const at = t?.cacheExpiresAt;
201
+ if (!alive || at == null || t.loading != null || (status !== 'waiting' && status !== 'idle') || (status === 'idle' && stoppedPhase(t))) return { cacheExpiresAt: null, cacheTtl: null };
202
+ return { cacheExpiresAt: at, cacheTtl: t.cacheTtl };
203
+ }
204
+
205
+ // 도구가 돌기 시작한 시각(ms). 작업 중(busy)이고 진행 단계가 열린 도구 실행일 때만 둔다 (claude-tracker.mjs toolStartedAt).
206
+ // 허락 대기 중에는 두지 않고, 그동안 본 시각을 적어 두어 허락한 뒤에는 그때부터 잰다 (markWaiting).
207
+ // 쉘 명령(! 입력, status 'shell')은 기록에 tool_use 가 없어 빼고, 기록을 다 읽기 전에도 뺀다.
208
+ function toolStartOf(status, phase, t) {
209
+ if (!t) return null;
210
+ if (status === 'waiting') {
211
+ t.markWaiting();
212
+ return null;
213
+ }
214
+ if (status !== 'busy' || phase?.kind !== 'tool' || t.loading != null) return null;
215
+ return t.toolStartedAt();
216
+ }
217
+
191
218
  // sessions/<pid>.json 은 세션이 끝나면 지워지므로, 끝난 세션은 최근에 바뀐 기록 파일로 찾는다.
192
219
  // 폴더를 매번 훑지 않게 목록은 잠깐 재사용하고, 기록 앞부분에서 이름·폴더만 읽어 둔다.
193
220
  const DISCOVER_TTL_MS = 10_000;
@@ -469,6 +496,7 @@ export function collectClaude({ showEnded, budget, selectedId }) {
469
496
  const { members, sub } = transcript ? readMembers(transcript, t, budget) : { members: [], sub: emptySub() };
470
497
  const mtime = Math.max(t?.mtimeMs ?? 0, touched);
471
498
  const status = statusOf(e, e.alive, mtime);
499
+ const phase = withRunningMembers(phaseOf(status, e, t), status, members);
472
500
 
473
501
  out.push({
474
502
  tool: 'claude',
@@ -486,7 +514,14 @@ export function collectClaude({ showEnded, budget, selectedId }) {
486
514
  status,
487
515
  // Claude Code 가 상태를 남기지 않아 기록 수정 시각으로 추측한 경우
488
516
  statusGuessed: e.alive && !e.waitingFor && !['busy', 'shell', 'idle'].includes(e.status),
489
- phase: withRunningMembers(phaseOf(status, e, t), status, members),
517
+ phase,
518
+ // 지금 도는 도구가 시작된 시각(ms) 또는 null. 화면은 1분이 지나야 STATUS 글 뒤에 경과 시간을 붙인다 (draw.mjs toolElapsed).
519
+ toolStartedAt: toolStartOf(status, phase, t),
520
+ // 멈춘 이유 (phase 가 stopped 일 때만). 끝남(done) 알림과 확인 전(●)을 이 동안 막는다 (attention.mjs).
521
+ stopReason: status === 'idle' && stoppedPhase(t) ? t.stopReason : null,
522
+ // 프롬프트 캐시 만료 시각(ms)과 TTL(초). 응답 대기·다음 지시 대기인 살아 있는 세션에만 둔다 (claude-tracker.mjs applyCacheUsage).
523
+ // 오류로 멈춘 세션과 기록을 다 읽기 전의 세션은 빼고, 시간이 지나 만료돼도 그대로 둔다 (화면이 '캐시 만료' 로 보인다).
524
+ ...cacheOf(e.alive, status, t),
490
525
  waitingFor: e.waitingFor ?? null,
491
526
  waitDetail: status === 'waiting' ? (t?.waitDetail(e.waitingFor) ?? null) : null,
492
527
  now: t?.lastTool ?? t?.events.at(-1)?.text ?? '',
@@ -222,10 +222,10 @@ function indexName(path, id) {
222
222
  return null;
223
223
  }
224
224
 
225
- const SAVED = ['id', 'threadName', 'cwd', 'branch', 'model', 'busy', 'tokens', 'context', 'window', 'events', 'lastTool', 'startedAt', 'lastKind', 'files', 'turns', 'turnCount', 'activity'];
225
+ const SAVED = ['id', 'threadName', 'cwd', 'branch', 'model', 'busy', 'tokens', 'context', 'window', 'events', 'lastTool', 'startedAt', 'lastKind', 'files', 'turns', 'turnCount', 'activity', 'pendingAt'];
226
226
 
227
227
  function newState(path) {
228
- const st = { tail: new JsonlTail(path), id: basename(path), threadName: null, cwd: null, branch: null, model: null, busy: false, tokens: emptyTokens(), context: 0, window: 0, events: [], lastTool: null, startedAt: null, pending: new Map(), lastKind: null, files: [], turns: [], turnCount: 0, patches: {}, activity: {} };
228
+ const st = { tail: new JsonlTail(path), id: basename(path), threadName: null, cwd: null, branch: null, model: null, busy: false, tokens: emptyTokens(), context: 0, window: 0, events: [], lastTool: null, startedAt: null, pending: new Map(), lastKind: null, files: [], turns: [], turnCount: 0, patches: {}, activity: {}, pendingAt: {} };
229
229
  const c = loadCache(path);
230
230
  if (c) {
231
231
  st.tail.offset = c.offset;
@@ -249,6 +249,14 @@ function phaseOf(st, live) {
249
249
  return st.lastKind === 'reply' ? { kind: 'write' } : { kind: 'think' };
250
250
  }
251
251
 
252
+ // phaseOf 가 보이는 도구(열린 호출 가운데 마지막 것)가 시작된 시각(ms). function_call·custom_tool_call 줄의 시각이다.
253
+ // pendingAt 이 생기기 전 캐시에서 이어 읽는 호출은 시각을 몰라 null. Codex 기록에는 허락 대기 상태가 없어 따로 빼지 않는다.
254
+ function toolStartOf(st, phase) {
255
+ if (phase.kind !== 'tool') return null;
256
+ const at = st.pendingAt?.[[...st.pending.keys()].at(-1)];
257
+ return Number.isFinite(at) ? at : null;
258
+ }
259
+
252
260
  function applyLine(st, x) {
253
261
  const p = x.payload ?? {};
254
262
  if (x.type === 'session_meta') {
@@ -269,6 +277,7 @@ function applyLine(st, x) {
269
277
  case 'turn_aborted':
270
278
  st.busy = false;
271
279
  st.pending.clear();
280
+ st.pendingAt = {};
272
281
  st.patches = {};
273
282
  break;
274
283
  case 'token_count': {
@@ -328,11 +337,15 @@ function applyLine(st, x) {
328
337
  if (patchSucceeded(p.output)) for (const r of parsePatch(patch.text, st.cwd)) addChange(st.files, r, patch.at);
329
338
  }
330
339
  st.pending.delete(p.call_id);
340
+ if (st.pendingAt) delete st.pendingAt[p.call_id];
331
341
  st.lastKind = 'result';
332
342
  }
333
343
  if (what) {
334
344
  st.lastTool = what;
335
- if (p.call_id && p.type !== 'web_search_call') st.pending.set(p.call_id, p.name);
345
+ if (p.call_id && p.type !== 'web_search_call') {
346
+ st.pending.set(p.call_id, p.name);
347
+ (st.pendingAt ??= {})[p.call_id] = parseTs(x.timestamp);
348
+ }
336
349
  pushEvent(st, x.timestamp, 'tool', what);
337
350
  st.lastKind = 'tool';
338
351
  }
@@ -346,7 +359,7 @@ export function codexIndexName(path, id) {
346
359
  return indexName(path, id);
347
360
  }
348
361
 
349
- export const _test = { newState, applyLine, phaseOf, snapshot, readIndex, indexName };
362
+ export const _test = { newState, applyLine, phaseOf, toolStartOf, snapshot, readIndex, indexName };
350
363
 
351
364
  export function collectCodex({ showEnded, budget, filesOf = openFiles, startOf = processStart, canList = canListProcesses }) {
352
365
  // 프로세스를 못 세면 숨기지 않고 최근에 바뀐 기록으로 판정한다 (pid 는 null).
@@ -424,6 +437,7 @@ export function collectCodex({ showEnded, budget, filesOf = openFiles, startOf =
424
437
  const used = st.tokens.total > 0;
425
438
  // 기록 안의 이름 바꾸기 이벤트가 먼저, 없으면 session_index.jsonl 의 thread_name.
426
439
  const customName = st.threadName ?? indexName(f.path, st.id);
440
+ const phase = phaseOf(st, live);
427
441
  out.push({
428
442
  tool: 'codex',
429
443
  id: st.id,
@@ -439,7 +453,9 @@ export function collectCodex({ showEnded, budget, filesOf = openFiles, startOf =
439
453
  model: st.model,
440
454
  live,
441
455
  status: !live ? 'ended' : st.busy ? 'busy' : 'idle',
442
- phase: phaseOf(st, live),
456
+ phase,
457
+ // 지금 도는 도구가 시작된 시각(ms) 또는 null (toolStartOf).
458
+ toolStartedAt: toolStartOf(st, phase),
443
459
  cost: cost?.total ?? (used ? 0 : null),
444
460
  costNoCache: cost?.noCache ?? null,
445
461
  costUnknown: used && !cost,
@@ -2,6 +2,8 @@
2
2
  // 세션 이름(사용자 이름, 그 밖 이름)을 모은다. 사용량(토큰·비용)은 장부(claude-ledger.mjs 등)가 세고, 여기서는 세지 않는다.
3
3
  // 장부 캐시 모양은 그대로 두고 따로 읽는다 (장부를 다시 세지 않게). 리포트가 기간 안에 사용량이 있는 기록만 부른다.
4
4
  // 기록은 읽기만 하고, 어디까지 읽었는지는 aitop 캐시에 둔다.
5
+ // 날짜별로 "나를 기다린 시간"(w, ms)도 모은다: 에이전트 쪽 마지막 줄(응답·도구 결과) 시각부터 다음 사용자 입력(지시, 허락·질문 답)
6
+ // 시각까지의 간격 합이다. 기록에는 화면 앞에 있었는지가 없어 자리를 비운 시간과 가르지 못하는 추정값이다.
5
7
  import { JsonlTail } from '../tail.mjs';
6
8
  import { loadCache, markDirty } from '../cache.mjs';
7
9
  import { dayKey, isNoisePrompt, recentDays, sessionName } from './common.mjs';
@@ -9,7 +11,9 @@ import { readChange } from './files.mjs';
9
11
  import { parsePatch, extractPatch, patchSucceeded } from './patch.mjs';
10
12
  import { mask, oneLine } from '../text.mjs';
11
13
 
12
- const KIND = 'sheet1';
14
+ // 2: 날짜별 기다린 시간(w)과 이어 읽기용 상태(agentAt)를 더했다 (#243). 예전 캐시는 이미 읽은 줄의 w 가 없어
15
+ // 0 으로 보이므로 kind 를 올려 기록을 한 번 다시 읽는다.
16
+ const KIND = 'sheet2';
13
17
  // 하루에 남기는 고친 파일 수 상한 (캐시가 커지지 않게). 넘으면 more 에 표시해 '200+' 처럼 보인다.
14
18
  export const FILES_MAX = 200;
15
19
  // 캐시에 남기는 지시 글 길이. 화면에는 더 짧게 자른다.
@@ -18,6 +22,28 @@ const PROMPT_MAX = 200;
18
22
  const PENDING_MAX = 50;
19
23
  // 날짜를 남기는 일수 (리포트가 보는 30일보다 조금 길게).
20
24
  const KEEP = 32;
25
+ // 간격 하나에서 세는 기다린 시간 상한 (2시간). 그보다 긴 간격은 대개 자리를 비웠거나 다음 날 이어 쓴 것이라,
26
+ // 그대로 더하면 밤새 열어 둔 세션 하나가 합계를 덮는다. 버리지 않고 앞 2시간만 센다 (에이전트가 끝낸 직후가 실제로 기다린 몫에 가깝다).
27
+ export const WAIT_CAP_MS = 2 * 3600_000;
28
+
29
+ // 다음 로컬 0시 (기다린 시간을 날짜별로 나눌 때 쓴다).
30
+ const nextMidnight = (at) => {
31
+ const d = new Date(at);
32
+ d.setHours(24, 0, 0, 0);
33
+ return d.getTime();
34
+ };
35
+ // Claude 사용자 줄의 글.
36
+ const textOf = (c) => (typeof c === 'string' ? c : Array.isArray(c) ? c.filter((p) => p?.type === 'text').map((p) => p.text).join(' ') : '');
37
+ // 사람이 직접 낸 지시인지. 새 기록은 origin.kind(human, task-notification 등)나 turnOrigin 이 있고, 예전 기록은 글로 가른다
38
+ // (꺾쇠로 시작하는 글 가운데 슬래시 명령만 사람 입력이다).
39
+ function isHumanPrompt(x, text) {
40
+ if (x.origin?.kind) return x.origin.kind === 'human';
41
+ if (x.turnOrigin) return x.turnOrigin === 'human';
42
+ return Boolean(text) && (!isNoisePrompt(text) || /^\s*<command-(name|message)>/.test(text));
43
+ }
44
+ // 도구 결과가 사용자의 답인지: 허락 창에서 사용자가 고른 결과(permissionDecision.source 가 user_ 로 시작)와 질문 도구(AskUserQuestion)의 답.
45
+ // 허락 창이 뜬 시각은 기록에 없어, 도구 호출 줄부터 결과 줄까지를 기다림으로 센다 (허락 뒤 도구가 돈 시간도 섞인다).
46
+ const isUserAnswer = (x) => /^user/.test(x.permissionDecision?.source ?? '') || (x.toolUseResult?.questions != null && x.toolUseResult?.answers != null);
21
47
 
22
48
  const clip = (s) => {
23
49
  const one = mask(oneLine(s));
@@ -41,6 +67,7 @@ export class SessionSheet {
41
67
  this.id = c.id ?? null;
42
68
  this.cwd = c.cwd ?? null;
43
69
  this.pending = c.pending ?? {};
70
+ this.agentAt = c.agentAt ?? null;
44
71
  }
45
72
  }
46
73
 
@@ -55,6 +82,8 @@ export class SessionSheet {
55
82
  this.cwd = null;
56
83
  // Codex: 결과를 기다리는 패치 호출 id → 고칠 파일 경로들.
57
84
  this.pending = {};
85
+ // 에이전트 쪽 마지막 줄 시각. 그 뒤 사용자 입력이 오면 그 사이를 기다린 시간으로 센다. 사용자 입력 뒤에는 null.
86
+ this.agentAt = null;
58
87
  }
59
88
 
60
89
  // 아직 읽지 않은 크기.
@@ -73,16 +102,54 @@ export class SessionSheet {
73
102
  }
74
103
 
75
104
  snapshot() {
76
- return { offset: this.tail.lineOffset, days: recentDays(this.days, KEEP), custom: this.custom, title: this.title, id: this.id, cwd: this.cwd, pending: this.pending };
105
+ return { offset: this.tail.lineOffset, days: recentDays(this.days, KEEP), custom: this.custom, title: this.title, id: this.id, cwd: this.cwd, pending: this.pending, agentAt: this.agentAt };
77
106
  }
78
107
 
79
108
  day(at) {
80
109
  const d = (this.days[dayKey(at)] ??= { a: at, z: at, f: [] });
81
- if (at < d.a) d.a = at;
82
- if (at > d.z) d.z = at;
110
+ // 기다린 시간만 넘어온 날(answer)은 a·z 가 없다.
111
+ if (!(d.a <= at)) d.a = at;
112
+ if (!(d.z >= at)) d.z = at;
83
113
  return d;
84
114
  }
85
115
 
116
+ // 에이전트 쪽 줄: 여기부터 사용자를 기다린다.
117
+ agent(at) {
118
+ this.agentAt = at;
119
+ }
120
+
121
+ // 사용자 입력: 에이전트 쪽 마지막 줄부터 지금까지(상한 WAIT_CAP_MS)를 날짜별로 나눠 더한다.
122
+ // 기간은 로컬 0시에 끊기므로 날짜별로 나눠 두면 기간 경계에 걸친 간격도 기간 안 몫만 세어진다.
123
+ answer(at) {
124
+ const from = this.agentAt;
125
+ this.agentAt = null;
126
+ if (from == null || !(at > from)) return;
127
+ const end = from + Math.min(at - from, WAIT_CAP_MS);
128
+ for (let t = from; t < end; ) {
129
+ const cut = Math.min(end, nextMidnight(t));
130
+ const d = (this.days[dayKey(t)] ??= { f: [] });
131
+ d.w = (d.w ?? 0) + (cut - t);
132
+ t = cut;
133
+ }
134
+ }
135
+
136
+ // Claude 줄 하나로 기다린 시간 상태를 바꾼다. 서브에이전트 기록은 세지 않는다 (부모 세션에서만 센다, 이중 계산 방지).
137
+ waitClaude(x, at) {
138
+ // 예전 기록은 서브에이전트 줄(isSidechain)을 부모 기록 안에 섞어 썼다.
139
+ if (this.sub || x.isSidechain) return;
140
+ if (x.type === 'assistant') return this.agent(at);
141
+ if (x.isMeta || x.isCompactSummary || !x.message) return;
142
+ const c = x.message.content;
143
+ if (Array.isArray(c) && c.some((p) => p?.type === 'tool_result')) return isUserAnswer(x) ? this.answer(at) : this.agent(at);
144
+ const text = textOf(c);
145
+ // 사용자가 끊으면 에이전트는 그때 멈추고 다음 지시를 기다린다. 끊기 전은 에이전트가 일하던 시간이다.
146
+ if (/^\s*\[Request interrupted/.test(text)) return this.agent(at);
147
+ if (!isHumanPrompt(x, text)) return;
148
+ // 에이전트가 일하는 동안 미리 넣어 둔 지시(queued)는 기다림이 아니다.
149
+ if (x.promptSource === 'queued') this.agentAt = null;
150
+ else this.answer(at);
151
+ }
152
+
86
153
  addFile(at, path) {
87
154
  if (typeof path !== 'string' || !path) return;
88
155
  const d = this.day(at);
@@ -105,14 +172,14 @@ export class SessionSheet {
105
172
  const at = Date.parse(x.timestamp);
106
173
  if (!Number.isFinite(at)) return;
107
174
  this.day(at);
175
+ this.waitClaude(x, at);
108
176
  if (x.type !== 'user' || x.isMeta || !x.message) return;
109
177
  if (x.toolUseResult) {
110
178
  const c = readChange(x.toolUseResult, at);
111
179
  if (c) this.addFile(at, c.path);
112
180
  }
113
181
  const c = x.message.content;
114
- const text = typeof c === 'string' ? c : Array.isArray(c) ? c.filter((p) => p?.type === 'text').map((p) => p.text).join(' ') : '';
115
- this.prompt(at, text);
182
+ this.prompt(at, textOf(c));
116
183
  }
117
184
 
118
185
  applyCodex(x) {
@@ -129,9 +196,16 @@ export class SessionSheet {
129
196
  this.day(at);
130
197
  if (x.type === 'event_msg') {
131
198
  if (p.type === 'thread_name_updated') this.custom = sessionName(p.thread_name);
132
- if (p.type === 'user_message') this.prompt(at, p.message);
199
+ if (p.type === 'user_message') {
200
+ this.prompt(at, p.message);
201
+ this.answer(at);
202
+ } else if (p.type === 'turn_aborted') this.agent(at);
203
+ // 차례 시작 알림은 사용자 지시와 함께 오므로 에이전트 줄로 보지 않는다. 그 밖(agent_message, token_count 등)은 에이전트 쪽이다.
204
+ else if (p.type !== 'thread_name_updated' && p.type !== 'task_started' && p.type !== 'turn_started') this.agent(at);
133
205
  return;
134
206
  }
207
+ // Codex 는 허락 요청·답을 기록에 남기지 않아 user_message 만 사용자 입력으로 센다. 사용자·개발자 메시지 줄은 에이전트 쪽이 아니다.
208
+ if (!(p.type === 'message' && p.role !== 'assistant')) this.agent(at);
135
209
  // 패치는 결과가 성공일 때만 고친 파일로 센다 (codex.mjs 와 같다).
136
210
  let text = null;
137
211
  if (p.type === 'custom_tool_call' && p.name === 'apply_patch') text = String(p.input ?? '');
package/src/ui/chrome.mjs CHANGED
@@ -22,6 +22,7 @@ const LEGEND_IDS = [
22
22
  ['◆', 'legend.waiting'],
23
23
  ['●', 'legend.unseen'],
24
24
  ['○', 'legend.idle'],
25
+ ['!', 'legend.stopped'],
25
26
  ['·', 'legend.ended'],
26
27
  ['★', 'legend.pin'],
27
28
  ['', ''],
package/src/ui/detail.mjs CHANGED
@@ -3,7 +3,7 @@ import { ellipsis, fmtAgo, fmtTokens, pad, truncateLeft, width } from '../text.m
3
3
  import { currentTab, filesForTab, turnTabs } from '../turns.mjs';
4
4
  import { isAbsolute, relative } from 'node:path';
5
5
  import { PALETTE, PHASE_COLOR } from './theme.mjs';
6
- import { NOW, box, clock, fill, gauge, glyph, hhmm, levelBar, money, rule, segsWidth, tilde } from './draw.mjs';
6
+ import { NOW, box, cacheState, clock, fill, gauge, glyph, hhmm, levelBar, money, rule, segsWidth, tilde } from './draw.mjs';
7
7
  import { activitySeries } from '../sources/common.mjs';
8
8
  import { glyphs } from './glyphs.mjs';
9
9
  import { STRINGS, phaseText, t as tr } from '../i18n.mjs';
@@ -287,10 +287,13 @@ export function summaryLines(s, w, frame, view) {
287
287
  const g = glyph(s, frame);
288
288
  const phase = [{ ...g, t: g.t + ' ' }, { t: phaseText(s.phase) || s.status, fg: PHASE_COLOR[s.phase?.kind] ?? PALETTE.text, bold: true }];
289
289
  const sep = { t: ' · ', fg: PALETTE.info };
290
+ const cache = cacheState(s);
290
291
  const optional = [
291
292
  s.branch && [sep, { t: s.branch, fg: PALETTE.info }],
292
293
  s.kind && [sep, { t: s.kind, fg: PALETTE.info }],
293
294
  s.startedAt && [sep, { t: tr('detail.startedAgo', { at: hhmm(s.startedAt), ago: fmtAgo(NOW - s.startedAt) }), fg: PALETTE.info }],
295
+ // 캐시 남은 시간은 표의 STATUS 칸과 같은 짧은 글로, 가장 먼저 뺀다.
296
+ cache && [sep, { t: cache.text, fg: cache.fg, bold: cache.bold }],
294
297
  ].filter(Boolean);
295
298
  // 폴더가 FOLDER_MIN 칸(짧으면 제 길이)을 얻을 때까지 시작 → 종류 → 브랜치 순으로 뺀다. 폴더는 왼쪽부터 줄여 끝 이름을 남긴다.
296
299
  const path = tilde(s.cwd ?? '');
@@ -364,6 +367,8 @@ export function detail(s, W, H, frame, view) {
364
367
 
365
368
  const g = glyph(s, frame);
366
369
  L.push([{ ...g, t: g.t + ' ' }, { t: phaseText(s.phase) || s.status, fg: PHASE_COLOR[s.phase?.kind] ?? PALETTE.text, bold: true }]);
370
+ const cache = cacheState(s);
371
+ if (cache) L.push([{ t: ' ' }, { t: cache.expired ? tr('detail.cacheExpired', { ttl: cache.ttl }) : tr('detail.cacheLeft', { t: cache.left, ttl: cache.ttl }), fg: cache.expired ? PALETTE.info : cache.fg, bold: cache.bold }]);
367
372
  section(tr('detail.session'));
368
373
  kv(tr('detail.folder'), tilde(s.cwd));
369
374
  if (s.branch) kv(tr('detail.branch'), s.branch);
package/src/ui/draw.mjs CHANGED
@@ -1,9 +1,11 @@
1
1
  // 그리기 기본: 조각(segment) 줄 만들기·자르기·채우기, 상자, 가로줄, 게이지, 시각·금액 표기.
2
- import { pad, stripControl, truncate, width } from '../text.mjs';
2
+ import { fmtElapsed, pad, stripControl, truncate, width } from '../text.mjs';
3
3
  import { homedir } from 'node:os';
4
4
  import { tildeIn } from '../paths.mjs';
5
5
  import { NO_COLOR, PALETTE, PHASE_COLOR, RESET, style } from './theme.mjs';
6
6
  import { glyphs } from './glyphs.mjs';
7
+ import { t as tr } from '../i18n.mjs';
8
+ import { MEMBER_STALL_LONG_MS } from '../sources/common.mjs';
7
9
 
8
10
  // segs: [{ t: 텍스트, ...style }]. 폭 W 에 맞춰 자르고, 남는 칸은 bg 로 채운다.
9
11
  // 화면에 나가는 글자는 모두 여기를 지나므로, 기록에서 온 제어문자도 여기서 한 번 더 지운다.
@@ -43,12 +45,14 @@ export function glyph(s, frame) {
43
45
  if (k === 'ended') return { t: G.ended, fg: PALETTE.ended };
44
46
  if (k === 'done') return { t: '✓', fg: PALETTE.info };
45
47
  if (k === 'unseen') return { t: G.unseen, fg: PALETTE.busy, bold: true };
48
+ // 오류로 멈춤: 돌지 않는 ! 로 작업 중(스피너)과 구분한다.
49
+ if (k === 'stopped') return { t: '!', fg: PALETTE.alert, bold: true };
46
50
  if (k === 'idle') return s.status === 'live' ? { t: G.live, fg: PALETTE.tools[s.tool] } : { t: G.idle, fg: PALETTE.idle };
47
51
  return { t: SPIN[frame % SPIN.length], fg: PHASE_COLOR[k] ?? PALETTE.busy, bold: true };
48
52
  }
49
53
 
50
54
  // glyph 가 frame 에 따라 모양을 바꾸는지 (응답 대기 깜빡임, 작업 중 스피너).
51
- export const glyphMoves = (s) => s.status === 'waiting' || !['ended', 'done', 'unseen', 'idle'].includes(s.phase?.kind);
55
+ export const glyphMoves = (s) => s.status === 'waiting' || !['ended', 'done', 'unseen', 'idle', 'stopped'].includes(s.phase?.kind);
52
56
 
53
57
  // 막대는 같은 높이의 얇은 블록(▃)으로 그리고 채운 칸과 빈칸은 색으로 나눈다. 칸 높이가 모두 같아 끝이 튀어나오지 않는다.
54
58
  // 색이 없으면 빈칸을 가장 얇은 ▁ 로 그려 모양으로 구분한다. 기호는 glyphs().bar 에 있다.
@@ -153,3 +157,31 @@ export function levelBar(values) {
153
157
  const max = Math.max(0, ...v);
154
158
  return v.map((x) => (!(x > 0) || !(max > 0) ? { t: bars[0], fg: PALETTE.faint } : { t: bars[Math.min(7, Math.max(1, Math.ceil((x / max) * 7)))], fg: PALETTE.info }));
155
159
  }
160
+
161
+ // 프롬프트 캐시 만료까지 남은 시간 (claude.mjs cacheOf). 남은 시간은 m:ss 로, 1분 미만이면 경고색, 만료면 흐린 '캐시 만료'.
162
+ // 초 단위로 바뀌지만 타이머를 따로 두지 않는다: 실시간 화면은 데이터 갱신(1초마다)에 맞춰 다시 그리므로 그때 바뀐다.
163
+ // 그래서 animating() 에 넣지 않고, 스피너가 없는 화면에서 120ms 프레임 타이머를 깨우지 않는다.
164
+ export const CACHE_WARN_MS = 60_000;
165
+ export function cacheState(s, now = NOW) {
166
+ if (s?.cacheExpiresAt == null || !s.live || (s.status !== 'waiting' && s.status !== 'idle')) return null;
167
+ const left = s.cacheExpiresAt - now;
168
+ const ttl = tr(s.cacheTtl >= 3600 ? 'cache.ttl1h' : 'cache.ttl5m');
169
+ if (left <= 0) return { expired: true, ttl, text: tr('cache.expired'), fg: PALETTE.faint };
170
+ const sec = Math.ceil(left / 1000);
171
+ const t = `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, '0')}`;
172
+ return { expired: false, ttl, left: t, text: tr('cache.left', { t }), fg: left < CACHE_WARN_MS ? PALETTE.alert : PALETTE.info, bold: left < CACHE_WARN_MS };
173
+ }
174
+
175
+ // 지금 도는 도구의 경과 시간 (수집기의 toolStartedAt). 작업 중이고 진행 단계가 도구 실행인 세션만 본다.
176
+ // 1분 미만은 대부분의 도구 호출이 끝나는 시간이라 보이지 않는다 (짧은 도구마다 숫자가 깜빡이지 않게).
177
+ // TOOL_LONG_MS(10분) 이상이면 흐린 경고색: Claude Code 의 Bash 시간 제한이 최대 10분이라 #233 의 '멈춘 듯' 긴 기준과 같은 값을 쓴다.
178
+ // 형식은 팀원 행 경과 시간과 같은 fmtElapsed 다. 이 세션은 작업 중이라 스피너가 돌고(animating) 그 틱에 실려 바뀌므로 타이머를 따로 두지 않는다.
179
+ export const TOOL_SHOW_MS = 60_000;
180
+ export const TOOL_LONG_MS = MEMBER_STALL_LONG_MS;
181
+ export function toolElapsed(s, now = NOW) {
182
+ if (!Number.isFinite(s?.toolStartedAt) || s.status !== 'busy' || s.phase?.kind !== 'tool') return null;
183
+ const ms = now - s.toolStartedAt;
184
+ if (ms < TOOL_SHOW_MS) return null;
185
+ const long = ms >= TOOL_LONG_MS;
186
+ return { text: fmtElapsed(ms), fg: long ? PALETTE.alert : PALETTE.info, dim: long, long };
187
+ }
package/src/ui/table.mjs CHANGED
@@ -5,7 +5,7 @@ import { projectBudget } from '../budget.mjs';
5
5
  import { fmtAgo, fmtElapsed, fmtTokens, pad, truncate, width } from '../text.mjs';
6
6
  import { memberStalled } from '../sources/common.mjs';
7
7
  import { BUDGET_COLOR, PALETTE, PHASE_COLOR, RESET, style } from './theme.mjs';
8
- import { NOW, SPIN, clock, costOf, gauge, glyph, levelBar, line, money, segsWidth, shortModel } from './draw.mjs';
8
+ import { NOW, SPIN, cacheState, clock, toolElapsed, costOf, gauge, glyph, levelBar, line, money, segsWidth, shortModel } from './draw.mjs';
9
9
  import { glyphs } from './glyphs.mjs';
10
10
  import { phaseText, t } from '../i18n.mjs';
11
11
  import { NO_FOLDER } from '../order.mjs';
@@ -350,7 +350,7 @@ export function sessionRow(s, c, W, selected, frame, hot, costMode = 'api', pinn
350
350
  segs.push(...pin, { t: pad(s.name ?? '', c.name - segsWidth(pin)) + ' ', fg: ended ? PALETTE.ended : PALETTE.text, bold: selected });
351
351
  if (c.showProject) segs.push({ t: pad(s.project ?? '', c.project) + ' ', fg: ended ? PALETTE.ended : PALETTE.muted });
352
352
  segs.push(
353
- { t: pad(status, c.status) + ' ', fg: pc, bold: s.status === 'waiting' },
353
+ ...statusCell(status, cacheState(s) ?? toolElapsed(s), c.status, { fg: pc, bold: s.status === 'waiting' }),
354
354
  { t: pad(partial ? '…' : blank ? '' : fmtTokens(s.tokens.total), c.tokens, 'right') + ' ', fg: ended ? PALETTE.ended : partial ? PALETTE.info : PALETTE.muted },
355
355
  );
356
356
  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)) });
@@ -359,6 +359,20 @@ export function sessionRow(s, c, W, selected, frame, hot, costMode = 'api', pinn
359
359
  return line(ended ? segs.map((x) => ({ ...x, italic: true })) : segs, W, bg);
360
360
  }
361
361
 
362
+ // 세션 행의 STATUS 칸 (뒤 공백 포함). 덧붙일 짧은 글(tag)이 있으면 상태 글 뒤에 ' · 캐시 3:12' 처럼 붙인다.
363
+ // tag 는 기다리는 세션의 캐시 남은 시간(cacheState) 또는 작업 중 세션의 도구 경과 시간(toolElapsed)이다. 두 상태가 달라 함께 붙지 않는다.
364
+ // 덧붙인 글이 먼저 빠지는 정보다: 다 들어가면 그대로, 상태 글을 TAG_STATUS_MIN 칸까지 줄여 들어가면 줄여서 붙이고, 아니면 뺀다.
365
+ const TAG_STATUS_MIN = 12;
366
+ export function statusCell(status, tag, w, look) {
367
+ const plain = [{ t: pad(status, w) + ' ', ...look }];
368
+ if (!tag) return plain;
369
+ const segs = [{ t: ' · ', fg: PALETTE.info }, { t: tag.text, fg: tag.fg, bold: tag.bold, dim: tag.dim }];
370
+ const room = w - segsWidth(segs);
371
+ if (room < Math.min(width(status), TAG_STATUS_MIN)) return plain;
372
+ const head = truncate(status, room);
373
+ return [{ t: head, ...look }, ...segs, { t: ' '.repeat(Math.max(0, room - width(head))) + ' ' }];
374
+ }
375
+
362
376
  // 기록을 읽는 중인 세션의 CONTEXT 칸: 빈 막대와 … (gauge 와 같은 폭).
363
377
  const pendingGauge = (cells) => [{ t: glyphs().bar.empty.repeat(cells), fg: PALETTE.faint }, { t: pad('…', 5, 'right'), fg: PALETTE.info }];
364
378
 
package/src/ui/theme.mjs CHANGED
@@ -128,7 +128,7 @@ export const RESET = NO_COLOR ? '' : '\x1b[0m';
128
128
  export const BUDGET_TOKEN = { caution: 'team', warn: 'alert' };
129
129
  export const BUDGET_COLOR = { caution: PALETTE[BUDGET_TOKEN.caution], warn: PALETTE[BUDGET_TOKEN.warn] };
130
130
 
131
- export const PHASE_COLOR = { tool: PALETTE.tool, team: PALETTE.team, think: PALETTE.busy, write: PALETTE.busy, waiting: PALETTE.waiting, idle: PALETTE.idle, ended: PALETTE.ended, done: PALETTE.info, unseen: PALETTE.busy };
131
+ export const PHASE_COLOR = { tool: PALETTE.tool, team: PALETTE.team, think: PALETTE.busy, write: PALETTE.busy, waiting: PALETTE.waiting, idle: PALETTE.idle, ended: PALETTE.ended, done: PALETTE.info, unseen: PALETTE.busy, stopped: PALETTE.alert };
132
132
 
133
133
  // 상자 테두리. 포커스가 있으면 강조색으로, 색이 없으면 굵은 선으로 구분한다.
134
134
  export const EDGE = {