@sejuneoh/aitop 0.38.0 → 0.39.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
@@ -89,10 +89,11 @@
89
89
  - **Waiting alerts**: blocked sessions jump to the top, with optional bell, desktop notification or hook command.
90
90
  - **Tokens and cost** per session and for today / last 7 days, estimated at public API list prices. This is not your bill.
91
91
  - **Changed files and diffs** per session and per prompt.
92
+ - **Artifacts** a Claude or Cowork session (or its subagents) published with the Artifact tool, with clickable links.
92
93
  - **Read-only**: no network, no ports, no dependencies. It only reads the session logs each CLI already writes.
93
94
 
94
95
  <details>
95
- <summary>Details: stopped sessions, cache countdown, tool run time, context gauge, tool line</summary>
96
+ <summary>Details: stopped sessions, cache countdown, tool run time, context gauge, artifacts, tool line</summary>
96
97
 
97
98
  **Stopped by an error**
98
99
 
@@ -118,6 +119,12 @@
118
119
 
119
120
  - `~` marks 60% and up, `!` 85% and up, so the levels show without color. Under `NO_COLOR` the bar is `███░░`, and a gauge that reads 0% has no filled cell.
120
121
 
122
+ **Artifacts**
123
+
124
+ - The detail panel shows `── Artifacts N ──` when a session published any: `title · v1→v3 · 14:02 · claude.ai/…`, plus `edited in place` for an `edits` publish `org` for an org-shared link and `public` for a public one (nothing for `owner`). The version range comes from the publish sequence number; without one it is left out. When space is short, the latest few and `+N`.
125
+ - Only `https://claude.ai/` addresses become OSC 8 links. Under `NO_COLOR`, in piped output and in terminals not known to support links they are plain text; `FORCE_HYPERLINK=1` or `0` overrides. Only the title, address, publish sequence number, time, audience and whether `edits` was used are read (no file paths or edit contents).
126
+ - `--json` has `artifacts` per session (`title`, `url`, `versionFrom`, `versionTo`, `updatedAt`, `audience`, `viaEdits`); `url` is `null` unless it is a `https://claude.ai/` address.
127
+
121
128
  **Tool line and empty screen**
122
129
 
123
130
  - Tools with no live session and no use for 7 days leave the tool line. Its end tells the two kinds apart: `not installed: codex unused 7d: gemini` (counts when space is short). Turn it off with `"hideIdleTools": false`.
@@ -473,6 +480,7 @@ Claude Desktop agent mode (Cowork) sessions show in the table as `cowork` in the
473
480
  - The name is the app's session title. Tokens, cost, progress and subagents come from the same jsonl log Claude Code writes. The detail panel and `--json` `entrypoint` show `local-agent`.
474
481
  - Header today and 7-day totals, the monthly archive and `--report` (daily, sessions, trace) add them to Claude. A log that is also in `~/.claude/projects` is counted once.
475
482
  - A pending permission request shows as waiting (◆) and counts for `--notify`, `--on-waiting`, `n`, the header, the window title and `--line`.
483
+ - The PROJECT column and `--report ... --by project` group them as `cowork`, or under the folder picked for the session (the column shows its last name). On WSL a Windows working folder (`C:\…`) shows as `/mnt/c/…`.
476
484
 
477
485
  <details>
478
486
  <summary>Details: running and waiting, files read</summary>
@@ -480,7 +488,8 @@ Claude Desktop agent mode (Cowork) sessions show in the table as `cowork` in the
480
488
  - Cowork runs in a VM the app starts, so its process is not visible. A session is running when the later of its `lastActivityAt` and its log's modified time is within 2 minutes. Archived sessions (`isArchived`) are ended.
481
489
  - Waiting: if no answer (`permission_response`, `permission_denied`, `permission_auto_approved`), turn end (`result`) or restart (`init`) line follows the last `permission_request` at the end of the session's `audit.jsonl`, the session waits for that `tool_name`. There is no id linking requests and answers, so only the order counts, and a session whose log has no open tool call is not waiting.
482
490
  - Waiting lasts regardless of the 2-minute rule for up to 1 hour after the request. Older requests count as abandoned and the session as ended.
483
- - Only three kinds of files are opened: the session meta `local_<id>.json` (only title, model, folder, times, archived flag and log id are used), logs under `.claude/projects/**/*.jsonl`, and `audit.jsonl`. Cookies, Local Storage, settings and subagent meta files in the same app folder are not opened.
491
+ - The session's log folder is `local_<id>/`, else the folder named after the first 8 characters of the id (scheduled tasks, meta `hostLoopMode`), else the parent folder name of the meta's working folder, at the same level. Only real folders (not symlinks) are used.
492
+ - Only three kinds of files are opened: the session meta `local_<id>.json` (only title, model, folder, picked folder, times, archived flag and log id are used), logs under `.claude/projects/**/*.jsonl`, and `audit.jsonl`. `.audit-key`, `.claude.json`, `policy-limits.json`, `outputs/`, `uploads/` and the like in the log folder are not opened either. Cookies, Local Storage, settings and subagent meta files in the same app folder are not opened.
484
493
  - From `audit.jsonl` only the kind, tool name and time of permission lines are taken. Request contents (`tool_input`), signatures (`_audit_hmac`) and messages never reach the screen, the cache or `--json`. Cost comes from log usage, not `total_cost_usd`.
485
494
  - To keep a slow `/mnt/c` cheap, the session list, meta, log list and `audit.jsonl` are checked at most every 10 seconds, so waiting can show up to 10 seconds late. The 2-minute running check still uses the current time.
486
495
  - Sessions idle for over 7 days are known from their meta only; their log folders are not listed.
@@ -552,6 +561,7 @@ Continue a session elsewhere, for example when you cannot jump to its tab, as in
552
561
  - `cacheExpiresAt`, `toolStartedAt`: [Features](#features).
553
562
  - `stalled`, `startedAt`, `lastActivityAt`, `entrypoint`, `auto`, `parentId`: [Subagents](#subagents).
554
563
  - `resumeCmd`: [Resume a session elsewhere](#resume-a-session-elsewhere).
564
+ - `artifacts`: [Features](#features).
555
565
  - Report output (`month`, `current`, `status`, `paths`, `unpriced`, `waitedMs`): [Daily and monthly reports](#daily-and-monthly-reports), [Session report](#session-report).
556
566
 
557
567
  </details>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sejuneoh/aitop",
3
- "version": "0.38.0",
3
+ "version": "0.39.0",
4
4
  "description": "터미널에서 Claude Code · Codex · Antigravity · Gemini 세션과 토큰을 실시간으로 보는 읽기 전용 모니터",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/cache.mjs CHANGED
@@ -11,8 +11,10 @@ import { debug, debugIo } from './log.mjs';
11
11
 
12
12
  // 캐시 형식이 바뀌면 VERSION 을, 가격표가 바뀌면 PRICE_TAG 가 폴더 이름을 바꿔서 예전 캐시를 버린다.
13
13
  // 14: 장부의 하루 합계에 모델별 몫(models)을 더하고, 날짜를 10일이 아니라 30일 남긴다 (#128).
14
+ // 15: 세션 기록 캐시에 Artifact 게시 목록(artifacts, artCalls)을 더한다 (#305). 이미 읽은 부분의 게시를 놓치지 않게 다시 읽는다.
15
+ // 16: 15 의 첫 판(3a1eb62)이 version 을 숫자로 잘못 읽어 남긴 캐시를 버린다. 그대로 두면 업데이트 뒤에도 아티팩트 버전이 null 로 읽힌다.
14
16
  // 장부(ledger)만 형식이 바뀔 때는 VERSION 대신 장부의 kind 이름을 바꿔 장부만 다시 센다 (세션 화면 캐시는 그대로).
15
- const VERSION = 14;
17
+ const VERSION = 16;
16
18
  // Windows 는 XDG_CACHE_HOME 이 없으면 %LOCALAPPDATA%\aitop\cache (paths.mjs).
17
19
  const ROOT = appDir('cache', { home: homedir() });
18
20
  export const CACHE_ROOT = ROOT;
package/src/i18n.mjs CHANGED
@@ -629,6 +629,10 @@ export const STRINGS = {
629
629
  'detail.noTurn': '지시 기록 없음',
630
630
  'detail.editCount': ' 편집 {n}회',
631
631
  'detail.request': '요청',
632
+ 'detail.artifacts': '아티팩트 {n}',
633
+ 'detail.artEdits': '바로 수정',
634
+ 'detail.artPublic': '공개',
635
+ 'detail.artOrg': '조직 공유',
632
636
  'detail.activity': '최근 활동',
633
637
  'detail.files': '변경 파일',
634
638
  'detail.tabNone': ' · {tab} 0개',
@@ -1114,6 +1118,10 @@ export const STRINGS = {
1114
1118
  'detail.noTurn': 'No prompt found',
1115
1119
  'detail.editCount': { one: ' {n} edit', other: ' {n} edits' },
1116
1120
  'detail.request': 'Request',
1121
+ 'detail.artifacts': 'Artifacts {n}',
1122
+ 'detail.artEdits': 'edited in place',
1123
+ 'detail.artPublic': 'public',
1124
+ 'detail.artOrg': 'org',
1117
1125
  'detail.activity': 'Recent activity',
1118
1126
  'detail.files': 'Changed files',
1119
1127
  'detail.tabNone': ' · {tab}: none',
package/src/json.mjs CHANGED
@@ -3,6 +3,7 @@ import { toolsJson } from './doctor.mjs';
3
3
  import { phaseText } from './i18n.mjs';
4
4
  import { resumeCmd } from './resume.mjs';
5
5
  import { memberStalled } from './sources/common.mjs';
6
+ import { artifactLink } from './sources/artifacts.mjs';
6
7
 
7
8
  // aitop --json 출력. 다른 스크립트나 AI 가 읽기 쉬운 모양으로 세션 목록과 사용량 합계를 담는다.
8
9
  // 텍스트는 수집 단계에서 이미 비밀값 가림이 적용돼 있다.
@@ -73,6 +74,9 @@ export function toJson(data, version = null, opts = {}) {
73
74
  context: { used: s.context?.used ?? 0, window: s.context?.window ?? null },
74
75
  // 변경 내용(diff)은 넣지 않고 파일별 통계만 넣는다. 줄 수는 편집마다 더한 누적값이다 (git diff 아님).
75
76
  files: (s.files ?? []).map((f) => ({ path: f.path, created: Boolean(f.created), edits: f.edits, writtenLines: f.add, deletedLines: f.del, updatedAt: iso(f.at), agents: f.agents ?? [] })),
77
+ // Artifact 도구로 게시한 것 (Claude·Cowork, 서브에이전트 포함, 마지막 게시가 최근인 것부터). url 은 https://claude.ai/ 주소만 두고 나머지는 null, audience 는 기록 값 그대로('owner'·'org' 등).
78
+ // versionFrom·versionTo 는 이 세션에서 본 게시 버전 범위, viaEdits 는 마지막 게시가 edits 로 바로 고친 것인지다.
79
+ artifacts: (s.artifacts ?? []).map((a) => ({ title: a.title ?? null, url: artifactLink(a.url), versionFrom: a.from ?? null, versionTo: a.to ?? null, updatedAt: iso(a.at), audience: a.audience ?? null, viaEdits: Boolean(a.edits) })),
76
80
  // startedAt·lastActivityAt 은 세션의 startedAt·updatedAt 과 같은 ISO 시각이다 (모르면 null).
77
81
  // stalled 는 화면의 '멈춘 듯' 과 같은 짐작(common.mjs memberStalled)을 data.at 기준으로 본 값이다.
78
82
  members: (s.members ?? []).map((m) => ({ ...(m.sdk ? { id: m.id, entrypoint: m.entrypoint ?? null, parentId: m.parentId ?? s.id } : {}), name: m.name, task: m.task ?? null, model: m.model ?? null, status: m.status, phase: koPhase(m.phase), phaseKind: m.phase?.kind ?? null, tokens: m.tokens ?? 0, cost: money(m.cost), startedAt: iso(m.startedAt), lastActivityAt: iso(m.lastActivityAt), stalled: memberStalled(m, data.at ?? Date.now(), s.status) })),
@@ -13,7 +13,7 @@ import { addActivity, emptyTokens, mergeActivity, pushEvent, describeTool, toolD
13
13
  import { contextWindow, geminiCost } from '../pricing.mjs';
14
14
  import { debug, debugIo } from '../log.mjs';
15
15
  import { isWsl } from '../notify.mjs';
16
- import { agyAppEnv, agyAppSetting, expandHome, wslWindowsHomes } from './dirs.mjs';
16
+ import { agyAppEnv, agyAppSetting, expandHome, wslPathOf, wslWindowsHomes } from './dirs.mjs';
17
17
 
18
18
  const isDir = (p) => {
19
19
  try {
@@ -586,7 +586,7 @@ export function cwdOf(workspaceUris, { wsl = null } = {}) {
586
586
  // Windows 의 file:///c%3A/… 는 c:\… 가 되므로 드라이브 문자를 대문자로 맞춘다 (Claude·Codex 의 C:\ 와 같은 프로젝트로 묶이게).
587
587
  if (process.platform === 'win32') return p.replace(/^[a-z](?=:)/, (d) => d.toUpperCase());
588
588
  const drive = /^\/?([A-Za-z]):(?:[\\/](.*))?$/.exec(p);
589
- if (drive && (wsl ?? wslNow())) return ['/mnt', drive[1].toLowerCase(), ...(drive[2] ?? '').split(/[\\/]+/).filter(Boolean)].join('/');
589
+ if (drive && (wsl ?? wslNow())) return wslPathOf(p);
590
590
  return p;
591
591
  } catch (e) {
592
592
  debug('agy', 'workspace_uris parse failed', e);
@@ -0,0 +1,84 @@
1
+ // Claude 기록의 Artifact 도구 게시 결과 (#305). 상세 패널 아티팩트 구획과 --json 의 artifacts 가 쓴다.
2
+ // 게시(publish, action 이 없으면 publish) 호출과 짝이 되는 결과 줄의 toolUseResult 에서 몇 값만 꺼낸다.
3
+ // 입력의 file_path·edits 내용·prompt 와 결과의 나머지 값(path 등)은 담지 않는다.
4
+ import { createHash } from 'node:crypto';
5
+ import { mask, stripControl } from '../text.mjs';
6
+
7
+ // 세션마다 남기는 아티팩트 수 (마지막 게시가 최근인 것부터).
8
+ export const ARTIFACT_MAX = 20;
9
+ // 짝을 기다리는 게시 호출 수 상한. 결과가 오지 않은 호출이 쌓이지 않게 한다.
10
+ export const ARTIFACT_CALLS_MAX = 16;
11
+
12
+ const TITLE_MAX = 120;
13
+ const URL_MAX = 300;
14
+ const ID_MAX = 80;
15
+ const AUDIENCE_MAX = 24;
16
+
17
+ // 링크로 내보내는 주소: https://claude.ai/ 로 시작하고 URL 에 쓰는 ASCII 글자만 있는 것.
18
+ const SAFE_URL = /^https:\/\/claude\.ai\/[A-Za-z0-9\-._~:/?#[\]@!$&'()*+,;=%]*$/;
19
+
20
+ const str = (v, max) => (typeof v === 'string' ? stripControl(v).replace(/\s+/g, ' ').trim().slice(0, max) || null : null);
21
+
22
+ // 게시 호출인지. action 이 없으면 게시다.
23
+ export const isPublish = (input) => input?.action == null || input.action === 'publish';
24
+
25
+ // 허용 목록을 지난 링크 주소, 아니면 null. 기록에서 온 값이라 화면·--json 에 내기 전에 늘 여기를 지난다.
26
+ export function artifactLink(url) {
27
+ return typeof url === 'string' && url.length <= URL_MAX && SAFE_URL.test(url) ? url : null;
28
+ }
29
+
30
+ // 공유 범위 표시: 'org' 는 조직 공유, 'public'·'anyone' 은 공개, 그 밖('owner' 등)은 표시하지 않는다.
31
+ // 화면은 이 이름을 i18n 키로 바꾸고, --json 의 audience 는 기록의 원래 값을 그대로 낸다.
32
+ export function audienceKind(audience) {
33
+ const a = String(audience ?? '').toLowerCase();
34
+ if (a === 'org') return 'org';
35
+ if (a === 'public' || a === 'anyone') return 'public';
36
+ return null;
37
+ }
38
+
39
+ function timeOf(v) {
40
+ if (typeof v === 'number' && Number.isFinite(v)) return v < 1e12 ? v * 1000 : v;
41
+ const t = typeof v === 'string' ? Date.parse(v) : NaN;
42
+ return Number.isFinite(t) ? t : null;
43
+ }
44
+
45
+ // 결과 한 건 → 저장할 값. id 도 주소도 없으면 null.
46
+ export function pickArtifact(r, at, edits) {
47
+ if (!r || typeof r !== 'object' || Array.isArray(r)) return null;
48
+ // 주소는 원래 값이 허용 목록을 지날 때만 담는다. 제어 문자를 지워서 통과하게 만들지 않는다.
49
+ const url = artifactLink(r.url);
50
+ // 허용 목록 밖 주소는 묶는 데만 쓰고 값은 남기지 않는다 (해시).
51
+ const id = str(r.artifact_id, ID_MAX) ?? url ?? (typeof r.url === 'string' && r.url ? `h:${createHash('sha1').update(r.url).digest('hex').slice(0, 16)}` : null);
52
+ if (!id) return null;
53
+ // 사람이 보는 버전 번호는 seq (1, 2, …) 다. version 은 '1794205685-b571' 같은 내부 문자열이라 읽지 않는다.
54
+ const v = Number.isInteger(r.seq) && r.seq > 0 ? r.seq : null;
55
+ const title = str(r.title, TITLE_MAX);
56
+ // 제목은 화면 공유 때 새지 않게 비밀값처럼 보이는 글을 가린다.
57
+ return { id, title: title && mask(title), url, from: v, to: v, at: timeOf(r.updated) ?? at, audience: str(r.audience, AUDIENCE_MAX), edits: Boolean(edits) };
58
+ }
59
+
60
+ // 같은 아티팩트(id)면 버전 범위를 넓히고 제목·주소·공개·바로 수정은 마지막 게시 것을 쓴다.
61
+ function fold(map, a) {
62
+ const m = map.get(a.id);
63
+ if (!m) return map.set(a.id, { ...a });
64
+ const min = (x, y) => (x == null ? y : y == null ? x : Math.min(x, y));
65
+ const max = (x, y) => (x == null ? y : y == null ? x : Math.max(x, y));
66
+ const late = a.at >= m.at ? a : m;
67
+ map.set(a.id, { id: a.id, title: late.title ?? m.title ?? a.title, url: late.url ?? m.url ?? a.url, from: min(m.from, a.from), to: max(m.to, a.to), at: Math.max(m.at, a.at), audience: late.audience ?? null, edits: late.edits });
68
+ }
69
+
70
+ const newest = (map) => [...map.values()].sort((a, b) => b.at - a.at).slice(0, ARTIFACT_MAX);
71
+
72
+ // list 에 한 건을 더한 새 목록 (최근 순, ARTIFACT_MAX 개까지).
73
+ export function addArtifact(list, a) {
74
+ const map = new Map((list ?? []).map((x) => [x.id, x]));
75
+ fold(map, a);
76
+ return newest(map);
77
+ }
78
+
79
+ // 메인과 서브에이전트(또는 붙은 claude -p 실행)의 목록을 합친다.
80
+ export function mergeArtifacts(lists) {
81
+ const map = new Map();
82
+ for (const list of lists) for (const a of list ?? []) fold(map, a);
83
+ return newest(map);
84
+ }
@@ -6,6 +6,7 @@ import { claudeCost } from '../pricing.mjs';
6
6
  import { addActivity, emptyTokens, pushEvent, describeTool, toolDetail, isNoisePrompt, parseTs, sessionName } from './common.mjs';
7
7
  import { debugIo } from '../log.mjs';
8
8
  import { addChange } from './files.mjs';
9
+ import { ARTIFACT_CALLS_MAX, addArtifact, isPublish, pickArtifact } from './artifacts.mjs';
9
10
 
10
11
  const MAX_TURNS = 50;
11
12
 
@@ -191,7 +192,8 @@ export class ClaudeTracker {
191
192
  const c = loadCache(path);
192
193
  if (c) {
193
194
  this.tail.offset = c.offset;
194
- 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 });
195
+ 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, artifacts: c.artifacts ?? [] });
196
+ this.artCalls = new Map(c.artCalls ?? []);
195
197
  this.recent = new Map(c.recent);
196
198
  this.pending = new Map(c.pending);
197
199
  // 이 필드가 생기기 전 캐시는 이미 지나간 custom-title 을 모른다. 끝부분을 한 번 훑어 채우고 캐시에 다시 적어
@@ -253,6 +255,10 @@ export class ClaudeTracker {
253
255
  this.cacheTtl = null;
254
256
  this.inputAt = null;
255
257
  this.inputFor = null;
258
+ // Artifact 도구로 게시한 것 (artifacts.mjs): 최근 순, 묶은 아티팩트마다 { id, title, url, from, to, at, audience, edits }.
259
+ this.artifacts = [];
260
+ // 결과를 기다리는 게시 호출: tool_use id → edits 로 고쳤는지.
261
+ this.artCalls = new Map();
256
262
  }
257
263
 
258
264
  // 프롬프트 캐시가 만료되는 시각(ms). 캐시를 쓴 응답이 없으면 null.
@@ -308,6 +314,8 @@ export class ClaudeTracker {
308
314
  cacheTtl: this.cacheTtl,
309
315
  inputAt: this.inputAt,
310
316
  inputFor: this.inputFor,
317
+ artifacts: this.artifacts,
318
+ artCalls: [...this.artCalls],
311
319
  };
312
320
  }
313
321
 
@@ -358,6 +366,10 @@ export class ClaudeTracker {
358
366
  this.lastTool = describeTool(c.name, c.input);
359
367
  // at: 호출을 낸 줄의 시각 (도구 실행 경과 시간의 기준). resumeAt: 허락 대기를 마지막으로 본 시각 (markWaiting).
360
368
  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) });
369
+ if (c.name === 'Artifact' && isPublish(c.input)) {
370
+ this.artCalls.set(c.id, Boolean(c.input?.edits));
371
+ if (this.artCalls.size > ARTIFACT_CALLS_MAX) this.artCalls.delete(this.artCalls.keys().next().value);
372
+ }
361
373
  pushEvent(this, x.timestamp, 'tool', this.lastTool);
362
374
  this.lastKind = 'tool';
363
375
  } else if (c.type === 'text' && c.text?.trim()) {
@@ -371,6 +383,7 @@ export class ClaudeTracker {
371
383
  if (x.toolUseResult) addChange(this.files, x.toolUseResult, x.timestamp);
372
384
  const c = x.message.content;
373
385
  if (Array.isArray(c)) for (const p of c) if (p.type === 'tool_result') this.pending.delete(p.tool_use_id);
386
+ if (Array.isArray(c) && this.artCalls.size) this.applyArtifact(x, c);
374
387
  const text = typeof c === 'string' ? c : Array.isArray(c) ? c.filter((p) => p.type === 'text').map((p) => p.text).join(' ') : '';
375
388
  if (text && !isNoisePrompt(text)) {
376
389
  const e = pushEvent(this, x.timestamp, 'prompt', text);
@@ -384,6 +397,18 @@ export class ClaudeTracker {
384
397
  }
385
398
  }
386
399
 
400
+ // 게시 호출의 결과 줄이면 아티팩트 목록에 더한다. 오류 결과는 빼고, 결과 값은 artifacts.mjs pickArtifact 가 고른 것만 담는다.
401
+ applyArtifact(x, content) {
402
+ for (const p of content) {
403
+ if (p.type !== 'tool_result' || !this.artCalls.has(p.tool_use_id)) continue;
404
+ const edits = this.artCalls.get(p.tool_use_id);
405
+ this.artCalls.delete(p.tool_use_id);
406
+ if (p.is_error) continue;
407
+ const a = pickArtifact(x.toolUseResult, parseTs(x.timestamp), edits);
408
+ if (a) this.artifacts = addArtifact(this.artifacts, a);
409
+ }
410
+ }
411
+
387
412
  // 허락을 기다리는 동안 보일 요청 내용. 열린 도구 호출 가운데 대기 문구(approve Bash 등)에 이름이 나온 것을 먼저,
388
413
  // 없으면 가장 최근 것을 고른다. 팀원(Agent·Task) 호출만 열려 있으면 없음.
389
414
  waitDetail(waitingFor = '') {
@@ -10,6 +10,7 @@ import { isSessionAlive, parentPid } from '../procs.mjs';
10
10
  import { ClaudeTracker, headEntrypoint, tailCustomTitle, tailStopReason } from './claude-tracker.mjs';
11
11
  import { emptyTokens, isLongTool, mergeActivity, MEMBER_FADE_MS, sessionName } from './common.mjs';
12
12
  import { mergeFiles } from './files.mjs';
13
+ import { mergeArtifacts } from './artifacts.mjs';
13
14
  import { debug, debugIo } from '../log.mjs';
14
15
  import { claudeDirs, claudeProjectRoots, dedupeBy } from './dirs.mjs';
15
16
 
@@ -96,7 +97,7 @@ function loadingPhase(t) {
96
97
 
97
98
  // 서브에이전트 전체(끝난 것 포함)의 토큰·비용 합계. 메인 세션 합계에 더해 화면에 보인다.
98
99
  export function emptySub() {
99
- return { count: 0, tokens: emptyTokens(), cost: 0, costNoCache: 0, costUnknown: false, loading: false, files: [], activity: [] };
100
+ return { count: 0, tokens: emptyTokens(), cost: 0, costNoCache: 0, costUnknown: false, loading: false, files: [], activity: [], artifacts: [] };
100
101
  }
101
102
 
102
103
  // 메인 tracker 와 서브에이전트 합계를 화면에 보일 세션 숫자로 합친다. 기록을 아직 읽지 않았으면(t 없음) 비용은 null.
@@ -117,6 +118,8 @@ export function sessionTotals(t, sub) {
117
118
  turns: t?.turns ?? [],
118
119
  // 시간별 토큰: 메인과 서브에이전트를 칸별로 더한다.
119
120
  activity: mergeActivity([t?.activity, ...sub.activity]),
121
+ // Artifact 도구로 게시한 것: 메인과 서브에이전트를 아티팩트별로 묶는다 (artifacts.mjs).
122
+ artifacts: mergeArtifacts([t?.artifacts, ...sub.artifacts]),
120
123
  };
121
124
  }
122
125
 
@@ -141,6 +144,8 @@ export function readMembers(transcript, parent, budget, { track = (p, b) => trac
141
144
  sub.costUnknown ||= t.costUnknown;
142
145
  sub.loading ||= t.loading != null;
143
146
  sub.activity.push(t.activity);
147
+ // 서브에이전트가 게시한 아티팩트도 부모 세션 목록에 합친다 (#305).
148
+ sub.artifacts.push(t.artifacts ?? []);
144
149
  if (t.files.length) sub.files.push({ agent: meta.agentType ?? 'agent', files: t.files, startedAt: t.firstAt ?? undefined });
145
150
  const age = Date.now() - t.mtimeMs;
146
151
  const awaited = Boolean(meta.toolUseId && parent?.pending.has(meta.toolUseId));
@@ -776,6 +781,7 @@ function absorb(root, c) {
776
781
  root.costUnknown ||= Boolean(c.costUnknown);
777
782
  root.loading ||= Boolean(c.loading);
778
783
  root.activity = mergeActivity([root.activity, c.activity]);
784
+ if (c.artifacts?.length) root.artifacts = mergeArtifacts([root.artifacts, c.artifacts]);
779
785
  }
780
786
 
781
787
  // 팀원 행 모양 (readMembers 와 같은 칸). sdk: true 면 화면이 이름 앞에 -p 를 붙인다.
@@ -3,16 +3,18 @@
3
3
  // <앱>/local-agent-mode-sessions/<uuid>/<uuid>/local_<id>.json 세션 메타 (제목, 모델, 마지막 활동 시각 등)
4
4
  // <앱>/local-agent-mode-sessions/<uuid>/<uuid>/local_<id>/.claude/projects/*/*.jsonl Claude Code 와 같은 대화 기록 (+ <id>/subagents/)
5
5
  // <앱>/local-agent-mode-sessions/<uuid>/<uuid>/local_<id>/audit.jsonl 권한 요청·응답이 든 감사 기록
6
+ // 예약 작업(메타 hostLoopMode: true, #313)은 기록 폴더가 local_<id>/ 가 아니라 id 앞 8자리 폴더(<uuid>/<uuid>/2c7ea83c/)이고
7
+ // 대화 기록은 그 아래 .claude/projects/session/<cliSessionId>.jsonl 이다. 메타 cwd 는 Windows 경로(C:\…\2c7ea83c\outputs)다.
6
8
  // 앱 폴더에는 쿠키·Local Storage·설정 같은 다른 파일도 있으므로 위 세 가지만 연다 (허용 목록). 폴더는 목록만 읽는다.
7
9
  // 프로세스가 VM 안이라 보이지 않으므로 실행 중은 메타의 lastActivityAt 과 기록 수정 시각 중 늦은 쪽이 2분 안이면으로 본다.
8
10
  // 세션은 TOOL 칸에 cowork 로 보이고(색은 claude), 기록 파서는 Claude 것(claude-tracker.mjs)을 그대로 쓴다.
9
- import { readdirSync, readFileSync, statSync, openSync, readSync, closeSync, realpathSync } from 'node:fs';
10
- import { join, basename, resolve } from 'node:path';
11
+ import { readdirSync, readFileSync, statSync, lstatSync, openSync, readSync, closeSync, realpathSync } from 'node:fs';
12
+ import { join, basename, resolve, sep } from 'node:path';
11
13
  import { homedir } from 'node:os';
12
14
  import { ClaudeTracker } from './claude-tracker.mjs';
13
15
  import { sessionName } from './common.mjs';
14
16
  import { emptySub, sessionTotals, readMembers, withRunningMembers, phaseOf, stoppedPhase, cacheOf, toolStartOf } from './claude.mjs';
15
- import { coworkEnv, coworkSetting, expandHome, wslWindowsHomes } from './dirs.mjs';
17
+ import { coworkEnv, coworkSetting, expandHome, wslPathOf, wslWindowsHomes } from './dirs.mjs';
16
18
  import { loadCache } from '../cache.mjs';
17
19
  import { isWsl } from '../notify.mjs';
18
20
  import { debugIo } from '../log.mjs';
@@ -118,6 +120,8 @@ export function pickMeta(m) {
118
120
  title: str(m.title),
119
121
  model: str(m.model),
120
122
  cwd: str(m.cwd),
123
+ // 사용자가 고른 폴더 중 첫 번째 (PROJECT 칸에 쓴다, #313).
124
+ folder: Array.isArray(m.userSelectedFolders) ? (m.userSelectedFolders.map(str).find(Boolean) ?? null) : null,
121
125
  createdAt: num(m.createdAt),
122
126
  lastActivityAt: num(m.lastActivityAt),
123
127
  isArchived: m.isArchived === true,
@@ -160,6 +164,45 @@ function readMeta(path) {
160
164
  return out;
161
165
  }
162
166
 
167
+ // 세션의 기록 폴더 (#313). 후보 순서: local_<id>/ → id 앞 8자리 폴더(예약 작업) → 메타 cwd 의 상위 폴더 이름
168
+ // (cwd 가 local-agent-mode-sessions 아래일 때만). 메타와 같은 층의 폴더 목록(entries)에 있고 실제 폴더(심볼릭 링크 아님)인 것만 쓴다.
169
+ // 하나도 없으면 local_<id>/ (없는 폴더라 기록 목록이 비고, 예전과 같다).
170
+ const NAME_RE = /^[\w.-]{1,128}$/;
171
+ function sessionDir(dir2, localId, meta, entries) {
172
+ const segs = String(meta.cwd ?? '').split(/[\\/]+/).filter(Boolean);
173
+ const cands = [localId, localId.slice(6, 14)];
174
+ if (segs.length >= 2 && segs.includes(SESSIONS_DIR)) cands.push(segs.at(-2));
175
+ for (const name of cands) {
176
+ if (!NAME_RE.test(name) || name === '.' || name === '..') continue;
177
+ const e = entries.get(name);
178
+ if (!e) continue;
179
+ const p = join(dir2, name);
180
+ let ok = e.isDirectory();
181
+ if (!ok && !e.isFile() && !e.isSymbolicLink()) {
182
+ try {
183
+ ok = lstatSync(p).isDirectory();
184
+ } catch {}
185
+ }
186
+ if (ok) return p;
187
+ }
188
+ return join(dir2, localId);
189
+ }
190
+
191
+ // 작업 폴더 경로를 이 컴퓨터에서 보이는 모양으로. WSL 에서 Windows 경로(C:\…)는 /mnt/c/… 로 바꾼다 (#313).
192
+ let wslForce = null;
193
+ let onWsl = null;
194
+ const wslNow = () => wslForce ?? (onWsl ??= process.platform === 'linux' && isWsl());
195
+ const hostPath = (p) => (p && wslNow() ? (wslPathOf(p) ?? p) : p);
196
+ const lastName = (p) => String(p ?? '').split(/[\\/]+/).filter(Boolean).at(-1) ?? null;
197
+
198
+ // PROJECT 칸: 사용자가 고른 폴더가 있으면 그 마지막 이름, 없으면 cowork (#313).
199
+ // path: --by project 장부에 쓰는 값 (고른 폴더의 경로, 없으면 'cowork').
200
+ export function coworkProject(meta) {
201
+ const folder = hostPath(meta?.folder ?? null);
202
+ const name = folder ? lastName(folder) : null;
203
+ return name ? { name, path: folder } : { name: 'cowork', path: 'cowork' };
204
+ }
205
+
163
206
  // 세션 폴더의 대화 기록 목록: .claude/projects/<폴더>/*.jsonl 과 <id>/subagents/*.jsonl.
164
207
  // key 는 projects/ 아래 상대 경로 (claude-ledger.mjs 와 같은 모양이라 ~/.claude/projects 에 같은 기록이 있으면 한 번만 센다).
165
208
  function listTranscripts(dir) {
@@ -334,21 +377,23 @@ function scanRoot(root, days, now) {
334
377
  for (const b of ls(join(base, a.name), 'sessions read failed')) {
335
378
  if (!dirEnt(b, join(base, a.name, b.name))) continue;
336
379
  const dir2 = join(base, a.name, b.name);
337
- for (const f of ls(dir2, 'sessions read failed')) {
380
+ const ents = ls(dir2, 'sessions read failed');
381
+ const byName = new Map(ents.map((e) => [e.name, e]));
382
+ for (const f of ents) {
338
383
  const m = /^(local_[\w-]+)\.json$/.exec(f.name);
339
384
  if (!m || !fileEnt(f)) continue;
340
385
  const metaPath = join(dir2, f.name);
341
386
  const got = readMeta(metaPath);
342
387
  if (!got?.meta) continue;
343
388
  const meta = got.meta;
344
- const dir = join(dir2, m[1]);
389
+ const dir = sessionDir(dir2, m[1], meta, byName);
345
390
  const touched = Math.max(meta.lastActivityAt ?? 0, got.mtime);
346
391
  const recent = now - touched < days * 86400_000;
347
392
  const list = recent ? transcriptsOf(dir, meta, got.mtime) : { files: [], main: null };
348
393
  const newest = Math.max(0, ...list.files.map((x) => x.mtime));
349
394
  const activity = Math.max(meta.lastActivityAt ?? 0, newest);
350
395
  const maybe = !meta.isArchived && now - activity <= COWORK_WAIT_MAX_MS + COWORK_TTL_MS;
351
- out.push({ localId: m[1], root, dir, meta, metaMtime: got.mtime, files: list.files, main: list.main, wait: maybe ? readAudit(join(dir, 'audit.jsonl')) : null, audited: maybe });
396
+ out.push({ localId: m[1], root, dir, metaPath, meta, metaMtime: got.mtime, files: list.files, main: list.main, wait: maybe ? readAudit(join(dir, 'audit.jsonl')) : null, audited: maybe });
352
397
  }
353
398
  }
354
399
  }
@@ -368,8 +413,8 @@ export function coworkSnapshot({ roots = coworkRoots(), days = DAYS, now = Date.
368
413
  // 이번 목록에 없는 세션(지워진 세션, 이제 읽지 않는 앱 폴더)의 캐시는 지운다. 기간이 다른 목록(리포트)은 세션이 같으므로 7일 목록 때만 한다.
369
414
  if (days === DAYS) {
370
415
  const dirs = new Set(snap.sessions.map((s) => s.dir));
371
- const dirOf = (p, tail) => p.slice(0, -tail.length);
372
- for (const p of metas.keys()) if (!dirs.has(dirOf(p, '.json'))) metas.delete(p);
416
+ const metaPaths = new Set(snap.sessions.map((s) => s.metaPath));
417
+ for (const p of metas.keys()) if (!metaPaths.has(p)) metas.delete(p);
373
418
  for (const d of listings.keys()) if (!dirs.has(d)) listings.delete(d);
374
419
  // audit 는 이번에 보지 않은 것(대기 기간이 지났거나 보관한 세션)도 지운다.
375
420
  const audited = new Set(snap.sessions.filter((s) => s.audited).map((s) => join(s.dir, 'audit.jsonl')));
@@ -384,6 +429,14 @@ export function coworkLedgerFiles(days = DAYS, now = Date.now()) {
384
429
  return coworkSnapshot({ days: Math.max(DAYS, days), now }).sessions.flatMap((s) => s.files.filter((f) => f.mtime >= cutoff).map(({ key, path, mtime }) => ({ key, path, mtime })));
385
430
  }
386
431
 
432
+ // --by project 용: Cowork 기록 파일이면 그 세션의 프로젝트(coworkProject 의 path), 아니면 null (#313).
433
+ // 앱 폴더의 세션 목록 밖이어도 앱 폴더의 local-agent-mode-sessions 아래면 cowork 로 둔다.
434
+ export function coworkProjectOf(path, roots = coworkRoots()) {
435
+ if (!path || !roots.some((r) => path.startsWith(join(r, SESSIONS_DIR) + sep))) return null;
436
+ const s = coworkSnapshot({ roots }).sessions.find((x) => path.startsWith(x.dir + sep));
437
+ return coworkProject(s?.meta).path;
438
+ }
439
+
387
440
  // --report trace 가 세션 id 로 기록을 찾을 때 쓰는 projects/ 폴더 목록.
388
441
  export function coworkProjectRoots() {
389
442
  return coworkSnapshot().sessions.map((s) => join(s.dir, '.claude', 'projects'));
@@ -458,7 +511,8 @@ function row(s, { budget, now, want, timeLive }) {
458
511
  const waitingFor = wait ? `approve ${wait.tool}` : null;
459
512
  const status = statusOf(live, wait, t, mtime, now);
460
513
  const phase = withRunningMembers(phaseOf(status, { waitingFor }, t), status, members);
461
- const name = sessionName(m.title ?? '') ?? t?.customTitle ?? t?.title ?? `${basename(m.cwd ?? '') || 'cowork'} · ${s.localId.slice(6, 14)}`;
514
+ const project = coworkProject(m).name;
515
+ const name = sessionName(m.title ?? '') ?? t?.customTitle ?? t?.title ?? `${project} · ${s.localId.slice(6, 14)}`;
462
516
  return {
463
517
  tool: 'cowork',
464
518
  id: m.cliSessionId ?? m.sessionId ?? s.localId,
@@ -466,8 +520,8 @@ function row(s, { budget, now, want, timeLive }) {
466
520
  kind: 'interactive',
467
521
  name,
468
522
  customName: null,
469
- cwd: m.cwd,
470
- project: basename(m.cwd ?? ''),
523
+ cwd: hostPath(m.cwd),
524
+ project,
471
525
  branch: t?.branch ?? null,
472
526
  model: t?.model ?? m.model,
473
527
  // Cowork 기록의 실행 방식 ('local-agent').
@@ -548,6 +602,10 @@ export const _test = {
548
602
  keys() {
549
603
  return { metas: [...metas.keys()], listings: [...listings.keys()], audits: [...audits.keys()] };
550
604
  },
605
+ // WSL 인지 정해 둔다 (null 이면 저절로).
606
+ wsl(v) {
607
+ wslForce = v;
608
+ },
551
609
  reset() {
552
610
  snaps.clear();
553
611
  metas.clear();
@@ -155,6 +155,12 @@ export function candidateDirs({ home = homedir(), claude = claudeDirs(), codex =
155
155
  };
156
156
  }
157
157
 
158
+ // Windows 드라이브 경로(C:\…, C:/…, /c:/…)를 WSL 의 /mnt/c/… 로 바꾼다 (#303, #313). 드라이브 경로가 아니면 null.
159
+ export function wslPathOf(p) {
160
+ const m = /^\/?([A-Za-z]):(?:[\\/](.*))?$/.exec(typeof p === 'string' ? p : '');
161
+ return m ? ['/mnt', m[1].toLowerCase(), ...(m[2] ?? '').split(/[\\/]+/).filter(Boolean)].join('/') : null;
162
+ }
163
+
158
164
  // WSL 에서 Windows 사용자 홈 폴더 후보 (#303). Windows 앱의 기록은 /mnt/c/Users/<사용자> 아래에 있다.
159
165
  // USERPROFILE 이 WSLENV 로 넘어와 있으면(C:\Users\me) 그 폴더만, 없으면 usersDir 아래 사용자 폴더 전부.
160
166
  // 공용·기본 프로필 폴더는 건너뛴다. 폴더 이름과 존재만 보고 안은 읽지 않는다.
@@ -1,5 +1,5 @@
1
1
  // 기간 리포트 --by project 용: 기록 파일 하나가 어느 프로젝트(작업 폴더)의 것인지 찾는다.
2
- // Claude 는 기록 앞부분 줄의 cwd (없으면 projects/ 아래 폴더 이름), Codex 는 turn_context.cwd (없으면 session_meta.cwd),
2
+ // Claude 는 기록 앞부분 줄의 cwd (없으면 projects/ 아래 폴더 이름, Cowork 기록은 cowork 또는 고른 폴더), Codex 는 turn_context.cwd (없으면 session_meta.cwd),
3
3
  // agy 는 conversation_summaries.db 의 workspace_uris (서브에이전트는 부모 대화의 것) 를 쓴다. 못 찾으면 null.
4
4
  // agy 기록은 immutable 로 열어 -wal 에만 있는 막 생긴 대화는 아직 안 보이므로, 그 대화는 (unknown) 으로 나올 수 있다.
5
5
  // 장부 캐시 모양은 그대로 두고, 리포트를 낼 때만 파일 앞부분을 조금 읽는다.
@@ -9,6 +9,7 @@ import { agyRoots, cwdOf } from './antigravity.mjs';
9
9
  import { openReadOnly } from '../sqlite.mjs';
10
10
  import { debugIo } from '../log.mjs';
11
11
  import { claudeProjectRoots } from './dirs.mjs';
12
+ import { coworkProjectOf } from './cowork.mjs';
12
13
 
13
14
  // 앞부분에서 cwd 를 찾을 때 읽는 최대 크기. Codex 의 첫 줄(session_meta)은 지침 글이 들어 있어 길 수 있다.
14
15
  const HEAD_BYTES = 256 * 1024;
@@ -160,7 +161,8 @@ export function attachProjects(books, root) {
160
161
  let fallback = null;
161
162
  if (b.path) {
162
163
  if (b.tool === 'claude') {
163
- project = claudeProject(b.path);
164
+ // Claude Desktop Cowork 기록은 기록 안의 cwd(VM·outputs 폴더) 대신 cowork 또는 사용자가 고른 폴더로 묶는다 (#313).
165
+ project = coworkProjectOf(b.path) ?? claudeProject(b.path);
164
166
  if (!project) fallback = claudeFolder(b.path, root);
165
167
  } else if (b.tool === 'codex') project = codexProject(b.path);
166
168
  else if (b.tool === 'agy') project = (agy ??= agyWorkspaces()).get(basename(b.path, '.db')) ?? null;
package/src/ui/detail.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  // 선택한 세션 상세 패널: 왼쪽 요약, 오른쪽 변경 파일·지시 탭·diff·최근 활동. 100칸 미만에서는 요약을 위쪽 두 줄로 접는다.
2
- import { ellipsis, fmtAgo, fmtTokens, pad, truncateLeft, width } from '../text.mjs';
2
+ import { ellipsis, fmtAgo, fmtTokens, pad, truncate, truncateLeft, width } from '../text.mjs';
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';
@@ -8,6 +8,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';
10
10
  import { resumeCmd } from '../resume.mjs';
11
+ import { artifactLink, audienceKind } from '../sources/artifacts.mjs';
11
12
 
12
13
  // 탭 이름: 이번 지시·전체 탭은 turns.mjs 가 ko 이름을 붙이므로 지금 언어로 바꾼다. 지시 탭(T5)은 그대로.
13
14
  const tabLabel = (tab, short = false) => (tab.key === 'now' ? tr('detail.tabNow', null, { short }) : tab.key === 'all' ? tr('detail.tabAll') : tab.label);
@@ -236,12 +237,64 @@ export function requestBlock(s, w, max = REQUEST_LINES) {
236
237
  return [rule([{ t: tr('detail.request'), fg: PALETTE.waiting, bold: true }], '', w), ...lines.map((l) => [INDENT, { t: l, fg: PALETTE.text }])];
237
238
  }
238
239
 
240
+ // ── 아티팩트 N ── 구획 (#305): Artifact 도구로 게시한 것이 있을 때만. 한 줄에 제목 · v1→v3 · 시각 · 링크 · 바로 수정 · 공개(조직 공유).
241
+ // 버전(seq)을 모르면 버전 칸을 뺀다.
242
+ // 최근 순으로 max-1 줄까지 보이고, 넘치면 가로줄 끝에 +N 을 붙인다.
243
+ export const ARTIFACT_LINES = 4;
244
+ const TITLE_MIN = 12;
245
+
246
+ // 링크 글: 주소 전체(https:// 뺌)가 들어가면 그대로, 아니면 claude.ai/… 뒤에 마지막 조각 끝 8자.
247
+ function linkLabel(url, full) {
248
+ const bare = url.replace(/^https:\/\//, '');
249
+ if (full) return bare;
250
+ const last = bare.split(/[/?#]/).filter(Boolean).at(-1) ?? '';
251
+ return `claude.ai/…${last.slice(-8)}`;
252
+ }
253
+
254
+ export function artifactRow(a, w) {
255
+ const textW = Math.max(1, w - width(INDENT.t));
256
+ const sep = { t: ' · ', fg: PALETTE.info };
257
+ const url = artifactLink(a.url);
258
+ const ver = a.to == null ? null : a.from != null && a.from !== a.to ? `v${a.from}→v${a.to}` : `v${a.to}`;
259
+ const tags = [a.edits && { t: tr('detail.artEdits'), fg: PALETTE.muted }, audienceKind(a.audience) && { t: tr(audienceKind(a.audience) === 'org' ? 'detail.artOrg' : 'detail.artPublic'), fg: PALETTE.waiting, bold: true }].filter(Boolean);
260
+ const link = (full) => (url ? [sep, { t: linkLabel(url, full), fg: PALETTE.info, link: url }] : []);
261
+ const title = a.title || (url ? linkLabel(url, false) : '-');
262
+ const head = [...(ver ? [sep, { t: ver, fg: PALETTE.muted }] : [])];
263
+ const time = Number.isFinite(a.at) ? [sep, { t: hhmm(a.at), fg: PALETTE.info }] : [];
264
+ const tagSegs = tags.flatMap((x) => [sep, x]);
265
+ // 자리가 모자라면 주소 전체 → 표시(바로 수정·공개) → 시각 → 버전 순으로 줄이고, 짧은 링크는 끝까지 남긴다.
266
+ const options = [
267
+ [...head, ...time, ...link(true), ...tagSegs],
268
+ [...head, ...time, ...link(false), ...tagSegs],
269
+ [...head, ...time, ...link(false)],
270
+ [...head, ...link(false)],
271
+ [...link(false)],
272
+ [],
273
+ ];
274
+ // 주소 전체는 제목이 잘리지 않을 때만 쓴다. 나머지는 제목이 TITLE_MIN 칸(짧으면 제 길이)을 얻는 첫 모양.
275
+ const want = (k) => (k === 0 ? width(title) : Math.min(width(title), TITLE_MIN));
276
+ const rest = options.find((o, k) => textW - segsWidth(o) >= want(k)) ?? [];
277
+ const titleW = Math.max(1, textW - segsWidth(rest));
278
+ return [INDENT, { t: truncate(title, titleW), fg: PALETTE.text, bold: true }, ...rest];
279
+ }
280
+
281
+ export function artifactBlock(s, w, max = ARTIFACT_LINES + 1) {
282
+ const list = s.artifacts ?? [];
283
+ if (!list.length || max < 2) return [];
284
+ const shown = list.slice(0, max - 1);
285
+ const more = list.length - shown.length;
286
+ return [rule([{ t: tr('detail.artifacts', { n: list.length }), fg: PALETTE.text, bold: true }], more ? `+${more}` : '', w), ...shown.map((a) => artifactRow(a, w))];
287
+ }
288
+
239
289
  // 오른쪽 칸: 고친 파일이 없으면 최근 활동만, 있으면 위쪽 절반까지 변경 파일 구획(배경 띠), 파일을 열면 diff.
240
290
  // 머리는 안쪽 줄 수에 따라: 16 이상 가로줄+탭+지시, 11~15 가로줄+탭(지시는 탭 줄 오른쪽), 10 이하 가로줄만.
241
291
  export function rightColumn(s, w, rows, view) {
242
292
  // --show-requests 를 켰고 응답 대기 중이면 요청 내용을 맨 위에 두고, 아래 구획에는 적어도 4줄을 남긴다.
243
293
  const req = view?.showRequests ? requestBlock(s, w, Math.min(REQUEST_LINES, rows - 5)) : [];
244
294
  if (req.length) return [...req, ...rightColumn({ ...s, waitDetail: null }, w, rows - req.length, view)];
295
+ // 아티팩트 구획은 diff 를 열지 않았을 때 그 아래에 둔다. 아래 구획(변경 파일·최근 활동)에 적어도 6줄을 남긴다.
296
+ const art = view?.focus === 'diff' ? [] : artifactBlock(s, w, Math.min(ARTIFACT_LINES + 1, rows - 6));
297
+ if (art.length) return [...art, ...rightColumn({ ...s, waitDetail: null, artifacts: [] }, w, rows - art.length, view)];
245
298
  const all = s.files ?? [];
246
299
  const focused = view?.focus === 'files';
247
300
  // 가로줄 끝에 '─' 두 칸은 남긴다 (── 3칸 + 최근 활동 이름(한국어 9칸) + 막대 + ' ─' 2칸).
package/src/ui/draw.mjs CHANGED
@@ -2,7 +2,8 @@
2
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
- import { NO_COLOR, PALETTE, PHASE_COLOR, RESET, style } from './theme.mjs';
5
+ import { NO_COLOR, PALETTE, PHASE_COLOR, RESET, linksOn, osc8, style } from './theme.mjs';
6
+ import { artifactLink } from '../sources/artifacts.mjs';
6
7
  import { glyphs } from './glyphs.mjs';
7
8
  import { t as tr } from '../i18n.mjs';
8
9
  import { MEMBER_STALL_LONG_MS } from '../sources/common.mjs';
@@ -15,7 +16,9 @@ export function line(segs, W, bg) {
15
16
  for (const seg of segs) {
16
17
  if (used >= W) break;
17
18
  const t = truncate(stripControl(seg.t ?? ''), W - used);
18
- out += style({ bg, ...seg }) + t;
19
+ // link: 아티팩트 주소 (#305). 허용 목록을 다시 지난 주소만, 링크를 켠 터미널에서만 OSC 8 로 감싼다. 폭은 t 로만 센다.
20
+ const url = seg.link && linksOn() ? artifactLink(seg.link) : null;
21
+ out += style({ bg, ...seg }) + (url && t ? osc8(url, t) : t);
19
22
  used += width(t);
20
23
  }
21
24
  return out + style({ bg }) + ' '.repeat(Math.max(0, W - used)) + RESET;
package/src/ui/theme.mjs CHANGED
@@ -126,6 +126,32 @@ export function style({ fg, bg, bold, dim, italic } = {}) {
126
126
 
127
127
  export const RESET = NO_COLOR ? '' : '\x1b[0m';
128
128
 
129
+ // OSC 8 클릭 링크 (#305). 색을 끈 화면(NO_COLOR, 파이프·파일 출력은 bin 이 NO_COLOR 를 켠다)과 터미널이 아닌 출력에서는 늘 평문이다.
130
+ // 그 밖에는 FORCE_HYPERLINK(1/0, supports-hyperlinks 관례)가 있으면 따르고, 없으면 OSC 8 을 그린다고 알려진 터미널만 켠다.
131
+ // tmux 는 3.4 부터 링크를 넘기고 그 전 판은 모르는 OSC 를 삼키므로 켠다. GNU screen 과 리눅스 콘솔은 끈다.
132
+ export function hyperlinks(env = process.env, tty = Boolean(process.stdout?.isTTY)) {
133
+ if (env.NO_COLOR || !tty) return false;
134
+ const force = env.FORCE_HYPERLINK;
135
+ if (force != null && force !== '') return !['0', 'false'].includes(force);
136
+ const term = env.TERM ?? '';
137
+ if (term === 'dumb' || term === 'linux' || env.STY) return false;
138
+ if (env.TMUX || env.WT_SESSION || env.KITTY_WINDOW_ID || env.WEZTERM_PANE || env.KONSOLE_VERSION || env.DOMTERM) return true;
139
+ if (Number(env.VTE_VERSION) >= 5000) return true;
140
+ if (/^(iTerm\.app|WezTerm|vscode|ghostty|Hyper|Tabby|rio|WarpTerminal)$/.test(env.TERM_PROGRAM ?? '')) return true;
141
+ return /kitty|alacritty|foot|ghostty|wezterm/.test(term);
142
+ }
143
+
144
+ let LINKS = hyperlinks();
145
+ export const linksOn = () => LINKS;
146
+ // 테스트용: 링크 그리기를 켜고 끈다. 이전 값을 돌려준다.
147
+ export function _setLinks(on) {
148
+ const prev = LINKS;
149
+ LINKS = Boolean(on);
150
+ return prev;
151
+ }
152
+ // 글자 t 를 url 로 가는 링크로 감싼다. 폭 계산은 감싸기 전의 t 로 한다 (draw.mjs line).
153
+ export const osc8 = (url, t) => `\x1b]8;;${url}\x1b\\${t}\x1b]8;;\x1b\\`;
154
+
129
155
  // 하루 예산 경고. 주의(예상이 예산의 80% 이상)는 대기 색과 헷갈리지 않게 팀원 색을, 초과 예상은 경고 색을 쓴다.
130
156
  export const BUDGET_TOKEN = { caution: 'team', warn: 'alert' };
131
157
  export const BUDGET_COLOR = { caution: PALETTE[BUDGET_TOKEN.caution], warn: PALETTE[BUDGET_TOKEN.warn] };
package/src/ui.mjs CHANGED
@@ -26,7 +26,8 @@ export function animating(view) {
26
26
  // 터미널이 아닌 곳(파이프·파일)으로 내는 --once 용 (#292). render 결과에서 맨 아래 키 안내 줄과,
27
27
  // 화면 높이를 맞추려고 채운 빈 줄(끝의 빈 줄, 상세 상자 아래쪽의 테두리만 있는 줄)과 줄 끝 공백을 뺀다.
28
28
  // 테두리 글자는 지금 기호 세트(AITOP_AMBIGUOUS=wide 면 ASCII)에서 고른다.
29
- const ANSI = /\x1b\[[0-9;]*m/g;
29
+ // 색 코드와 OSC 8 링크 머리·꼬리 (#305).
30
+ const ANSI = /\x1b\[[0-9;]*m|\x1b\]8;[^\x07\x1b]*(?:\x07|\x1b\\)/g;
30
31
  const plain = (l) => l.replace(ANSI, '');
31
32
  // 줄 끝의 공백과 색 코드를 지운다. 색 코드가 있던 줄은 끝에 초기화(ESC[0m)를 붙여 색이 다음 줄로 번지지 않게 한다.
32
33
  const trimEnd = (l) => {