@muwi/herdr-app 0.0.0-stage → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1744 @@
1
+ // muwi 그래프 칸 (Herdr 앱 mod).
2
+ // AI가 적은 작업 계획과 진행 기록을 `muwi board`로 읽어 그린다. 기록도 세션도 바꾸지 않는다.
3
+ // 작업 목록: 급한 순서로 묶는다 (응답 대기가 위, 끝났는데 아직 안 본 작업은 "새 결과"). 계획 없이 일하는 세션도 같이 보여서 Herdr의 Agents 칸을 대신한다
4
+ // 그래프: 고른 작업의 계획. 카드와 선의 좌표는 `muwi board`가 ELK로 계산해서 준다. 기록이 바뀌면 전체를 다시 그린다
5
+ // 기록: 고른 노드의 기록 (맡은 세션, 걸린 시간, 읽은 skill, 문제 표시) 또는 작업의 기록 (계획이 바뀐 이유)
6
+ // 끌어서 옮기고, cmd/ctrl+스크롤로 확대한다. 지금 일어나는 곳(작업 중, 응답 대기)이 보이게 따라간다.
7
+ // 키보드가 있는 터미널이 바뀌면 그 터미널의 세션이 하는 작업으로 바꿔 보여 준다.
8
+ import { View, div, svg, image, PathBuilder } from "gpui-kit";
9
+ import { v_flex, h_flex } from "gpui-base";
10
+ import {
11
+ exec, home, theme, watchFolder, checking, shared, setShared, agents, panes, terminals, focused, updates, run, notify,
12
+ layout as shownLayout, props as blockProps, window as appWindow, settings,
13
+ } from "herdr";
14
+
15
+ const SELECTED = "muwi.selected";
16
+ /** 사람이(또는 따라가기가) 작업을 고른 때. 다른 칸이 계획 없는 세션의 빈 화면을 풀 때 본다 */
17
+ const PICKED = "muwi.picked";
18
+ /**
19
+ * 작업이나 노드를 눌러 그 작업을 한 대화의 터미널로 옮겨 간 때. 그 대화가 지금은 다른 작업에 붙어 있어도
20
+ * 키보드를 따라가는 그래프 칸들이 그 작업으로 바꾸지 않고 누른 작업을 그대로 보여 주게 한다 { terminal, at }
21
+ */
22
+ const JUMP = "muwi.jump";
23
+ const PLACE_NAME = { bottom: "아래", top: "위", right: "오른쪽" };
24
+ /** 오른쪽 기록 칸의 가장 좁은 너비 */
25
+ const DETAIL_MIN = 220;
26
+
27
+ /**
28
+ * Herdr 화면 배율(설정의 zoom). 칸 안에 놓는 길이(left·w 같은 것)는 이 배율이 곱해져 그려지는데,
29
+ * 크기 변화(on_size_change)와 마우스 위치는 화면에 보이는 픽셀로 온다. 보이는 픽셀을 이 배율로 나눠야 같은 단위가 된다.
30
+ * 나누지 않으면 배율이 0.9일 때 칸을 10% 좁게 알아서, 오른쪽·아래 끝에 걸친 노드를 칸 밖으로 보고 그리지 않는다
31
+ */
32
+ function uiZoom() {
33
+ try {
34
+ const z = Number(settings()?.zoom);
35
+ return Number.isFinite(z) && z > 0 ? z : 1;
36
+ } catch {
37
+ return 1;
38
+ }
39
+ }
40
+ /** 보이는 픽셀로 잰 크기를 칸 안에 놓는 길이의 단위로 바꾼다 */
41
+ const unzoom = (s) => {
42
+ const z = uiZoom();
43
+ return { width: s.width / z, height: s.height / z };
44
+ };
45
+ const SPIN = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
46
+ const STATE_NAME = { waiting: "응답 대기", blocked: "막힘", doing: "작업 중", stalled: "멈춤", done: "끝" };
47
+ /**
48
+ * 하는 노드가 없는 작업(앞 노드를 끝내고 다음 노드를 아직 시작하지 않음)은 그 작업의 세션이 하는 일로 보여 준다 (muwi의 between).
49
+ * 다음 노드를 준비하면 작업 중, 세션이 멈췄으면 응답 대기(사람이 말해야 움직인다), 맡은 세션이 없으면 멈춤
50
+ */
51
+ const BETWEEN_STATE = { working: "doing", asking: "waiting", stopped: "waiting", gone: "stalled", unknown: "doing" };
52
+ const BETWEEN_NAME = { working: "다음 노드 준비 중", asking: "세션이 입력을 기다림", stopped: "세션이 멈춤", gone: "맡은 세션이 없음" };
53
+ const STATUS_NAME = { todo: "아직", doing: "작업 중", waiting: "응답 대기", blocked: "막힘", done: "끝" };
54
+ const AGENT_NAME = { working: "세션 작업 중", blocked: "세션이 입력을 기다림", done: "세션이 멈춤", idle: "세션이 멈춤" };
55
+ /**
56
+ * 하는 중이라고 적힌 노드를 하던 세션이 일을 멈춘 모습 (muwi의 quiet).
57
+ * 노드의 상태는 AI가 적은 것이라, 세션이 멈추면(사용 한도, 권한 확인, 말을 끝냄) 적어 줄 쪽이 없어 계속 작업 중으로 남는다.
58
+ * 그래서 Herdr가 알려 주는 그 세션의 지금 상태로 다시 본다: 입력을 기다리면 asking, 멈춰서 다음 말을 기다리면 stopped.
59
+ * 둘 다 사람이 말해야 다시 움직이므로 응답 대기로 보여 준다. 도구가 무엇이든 Herdr가 아는 세션이면 된다
60
+ */
61
+ const quietOf = (status) => (!status || status === "working" ? null : status === "blocked" ? "asking" : "stopped");
62
+ const QUIET_NAME = { asking: "세션이 입력을 기다림", stopped: "세션이 멈춤" };
63
+ /** 세션(터미널)이 일을 멈춘 것을 처음 본 때. 멈춘 노드의 작업 시간을 거기서 세운다. 칸을 다시 그려도 남도록 칸 밖에 둔다 */
64
+ const QUIET_SINCE = new Map();
65
+ const RUN_NAME = { me: "직접", subagent: "서브에이전트", session: "새 세션" };
66
+ /** 세션 상태의 급한 정도 (Herdr의 Agents 칸과 같은 순서) */
67
+ const AGENT_RANK = { blocked: 3, working: 2, done: 1, idle: 0 };
68
+ /** 세션이 시작될 때 muwi 훅이 터미널에 붙이는 이름표 (그 터미널에서 지금 도는 세션) */
69
+ const LABEL_SESSION = "muwi.session";
70
+ /** Herdr가 직접 내는 레이아웃. muwi layout은 이걸 복제해서 바꾼다 */
71
+ const SHIPPED = ["main", "terminals", "win98"];
72
+
73
+ /** 에이전트가 제목 앞에 붙이는 상태 글자를 뗀다 (Herdr의 Agents 칸과 같은 규칙) */
74
+ const clean = (s) => (s ?? "").replace(/^[^\p{L}\p{N}\p{Ps}\p{Pi}]+/u, "").replace(/^\[ [!.] \] /, "").trim();
75
+
76
+ /** 프로그램 아이콘 (Herdr의 프로그램 표) */
77
+ function programIcon(p, size, color) {
78
+ if (!p?.icon) return null;
79
+ return p.tint ? svg(p.icon).size(size).flex_none().text_color(color) : image(p.icon).w(size).h(size).flex_none();
80
+ }
81
+
82
+ /**
83
+ * muwi 명령을 실행한다 (muwi setup이 ~/.local/bin에 넣은 것).
84
+ * Windows에서는 muwi.cmd를 cmd.exe로 실행한다. sh 스크립트는 Windows에서 바로 실행되지 않는다
85
+ */
86
+ function runMuwi(args, options) {
87
+ if (appWindow()?.platform === "windows") return exec("cmd.exe", ["/d", "/c", `${home()}\\.local\\bin\\muwi.cmd`, ...args], options);
88
+ return exec(`${home()}/.local/bin/muwi`, args, options);
89
+ }
90
+
91
+ /** 레이아웃 나무에서 id로 칸을 찾는다 */
92
+ function findNode(node, id) {
93
+ if (!node || typeof node !== "object") return null;
94
+ if (node.id === id) return node;
95
+ for (const child of node.children ?? []) {
96
+ const found = findNode(child, id);
97
+ if (found) return found;
98
+ }
99
+ return null;
100
+ }
101
+
102
+ /** 레이아웃 나무에 조건에 맞는 칸이 있는가 */
103
+ function anyNode(node, match) {
104
+ if (!node || typeof node !== "object") return false;
105
+ if (match(node)) return true;
106
+ return (node.children ?? []).some((child) => anyNode(child, match));
107
+ }
108
+
109
+ function ago(iso, now) {
110
+ if (!iso) return "";
111
+ const s = Math.max(0, Math.round((now - Date.parse(iso)) / 1000));
112
+ if (s < 60) return "방금";
113
+ if (s < 3600) return `${Math.round(s / 60)}분 전`;
114
+ if (s < 86400) return `${Math.round(s / 3600)}시간 전`;
115
+ return `${Math.round(s / 86400)}일 전`;
116
+ }
117
+
118
+ /** 걸린 시간: 1h 1m 1s. 진행 중인 노드는 초마다 늘어나므로 반올림하지 않고 버린다 */
119
+ function dur(ms) {
120
+ const s = Math.max(0, Math.floor(ms / 1000));
121
+ const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), sec = s % 60;
122
+ if (h > 0) return `${h}h ${m}m ${sec}s`;
123
+ if (m > 0) return `${m}m ${sec}s`;
124
+ return `${sec}s`;
125
+ }
126
+
127
+ function clock(iso) {
128
+ const d = new Date(iso);
129
+ const p = (n) => String(n).padStart(2, "0");
130
+ return `${p(d.getHours())}:${p(d.getMinutes())}`;
131
+ }
132
+
133
+ /** #rrggbb에 투명도(0~1)를 붙인다 */
134
+ function tint(c, a) {
135
+ if (typeof c !== "string" || c.length !== 7) return c;
136
+ return c + Math.round(a * 255).toString(16).padStart(2, "0");
137
+ }
138
+
139
+ /** 꺾이는 점들을 둥근 모서리로 잇는다 */
140
+ function roundPath(b, pts, r) {
141
+ b = b.move_to(pts[0][0], pts[0][1]);
142
+ for (let i = 1; i < pts.length - 1; i++) {
143
+ const [px, py] = pts[i - 1], [cx, cy] = pts[i], [nx, ny] = pts[i + 1];
144
+ const d1 = Math.hypot(cx - px, cy - py) || 1, d2 = Math.hypot(nx - cx, ny - cy) || 1;
145
+ const rr = Math.min(r, d1 / 2, d2 / 2);
146
+ b = b.line_to(cx + ((px - cx) / d1) * rr, cy + ((py - cy) / d1) * rr)
147
+ .curve_to(cx + ((nx - cx) / d2) * rr, cy + ((ny - cy) / d2) * rr, cx, cy);
148
+ }
149
+ const [lx, ly] = pts[pts.length - 1];
150
+ return b.line_to(lx, ly);
151
+ }
152
+
153
+ /** 이어 하기 버튼을 누른 뒤 이만큼은 다시 누르지 못하게 한다 (반응이 없어 보여 여러 번 눌러 탭이 여럿 뜨지 않게) */
154
+ const OPENING_MS = 3000;
155
+ /** Claude 세션 id 모양. 이 모양이면 claude --resume <id>로 그 대화를 다시 열 수 있다 */
156
+ const CLAUDE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
157
+ const SAMPLE_CLOSED = "0f0e0d0c-0b0a-4909-8807-060504030201";
158
+
159
+ /** herdr-app check가 그래프를 그리는 코드까지 확인할 수 있게 하는 작은 견본 */
160
+ const SAMPLE = (() => {
161
+ const node = (id, title, status, x, extra = {}) => ({
162
+ id, title, after: [], status, attempts: status === "todo" ? 0 : 1, spentMs: 65000, skills: [], flags: [], tries: [], spawns: [], seen: true, instant: false, ...extra,
163
+ });
164
+ // 견본은 화면의 모든 갈래를 한 번씩 지나가게 만든다 (herdr-app check가 이걸로 그려 본다):
165
+ // 다시 한 노드, 서브에이전트가 도운 회차, 훅이 보지 못한 회차, 한꺼번에 적은 회차, 새 세션에 맡긴 노드, 빠진 노드
166
+ const who = { kind: "me", session: "s1", agents: [{ id: "a1", kind: "Explore" }] };
167
+ const tries = [
168
+ { n: 1, startedAt: "2026-01-01T00:00:00.000Z", endedAt: "2026-01-01T00:01:00.000Z", spentMs: 60000, status: "done", note: "처음 결과", who: { kind: "me", session: "s1", agents: [] }, skills: [], seen: false, instant: false },
169
+ { n: 2, startedAt: "2026-01-01T00:02:00.000Z", endedAt: "2026-01-01T00:02:01.000Z", spentMs: 1000, status: "blocked", note: "막힘", who: { kind: "subagent", session: "s1", agents: [{ id: "a2", own: true }] }, skills: [], seen: true, instant: true },
170
+ { n: 3, startedAt: "2026-01-01T00:03:00.000Z", spentMs: 5000, status: "doing", who, seen: true, instant: false,
171
+ skills: [{ skill: "team-rules", state: "read", count: 2, via: "file", agent: true, guess: true }, { skill: "spec-reader", state: "loaded", count: 0, via: "tool" }] },
172
+ ];
173
+ const nodes = [
174
+ node("read", "티켓·기획 읽기", "done", 28, { note: "요구사항 2건", skills: [{ skill: "spec-reader", state: "read", count: 1, via: "tool" }] }),
175
+ node("impl", "구현", "doing", 308, { session: "s1", attempts: 3, who, tries, skills: tries[2].skills, run: "session", show: "pane", offPlan: true,
176
+ spawn: { at: "2026-01-01T00:00:00.000Z", terminal: "t9", task: "견본으로 맡긴 말" }, spawns: [{ at: "2026-01-01T00:00:00.000Z", terminal: "t9", task: "견본으로 맡긴 말" }] }),
177
+ node("pr", "PR 올리기", "waiting", 588, { note: "PR 올릴까요?", seen: false, closed: true, session: SAMPLE_CLOSED, flags: [{ at: "2026-01-01T00:00:00.000Z", text: "견본" }] }),
178
+ ];
179
+ const work = {
180
+ work: "sample", title: "견본 작업", request: "견본", state: "waiting", updatedAt: "2026-01-01T00:00:00.000Z",
181
+ counts: { total: 3, todo: 0, doing: 1, waiting: 1, blocked: 0, done: 1 },
182
+ };
183
+ return {
184
+ works: [
185
+ { ...work, past: false, active: [{ id: "pr", title: "PR 올리기", status: "waiting", note: "PR 올릴까요?" }] },
186
+ { ...work, work: "stalled", title: "멈춘 작업", state: "stalled", past: false, active: [{ id: "x", title: "하던 일", status: "doing", closed: true }] },
187
+ { ...work, work: "fresh", title: "새 결과 작업", state: "done", unread: true, past: false, active: [] },
188
+ { ...work, work: "between", title: "다음 노드를 준비하는 작업", state: "doing", between: "working", past: false, active: [] },
189
+ { ...work, work: "quiet", title: "세션이 멈춘 작업", state: "waiting", quiet: "stopped", past: false, active: [{ id: "y", title: "하던 일", status: "doing", quiet: "stopped" }] },
190
+ { ...work, work: "old", title: "지난 작업", state: "done", past: true, active: [] },
191
+ ],
192
+ errors: [],
193
+ sessions: [{ key: "s1", terminal: "t1", work: "sample", seenAt: "2026-01-01T00:00:00.000Z" }],
194
+ suggest: false,
195
+ selected: {
196
+ ...work, nodes, edges: [], outside: [], compacts: [], flags: [], lead: "s1", helpers: { sessions: 1, subagents: 2 },
197
+ gone: [{ at: "2026-01-01T00:00:00.000Z", id: "lint", title: "lint", status: "todo", why: "견본" }],
198
+ changes: [{ at: "2026-01-01T00:00:00.000Z", by: "human", why: "견본", first: false, added: ["pr"], removed: [], changed: [] }],
199
+ sessions: { s1: { label: "t1", tool: "claude", terminal: "t1" }, [SAMPLE_CLOSED]: { label: "t2", tool: "claude", terminal: "t2", cwd: "/tmp/sample repo" } },
200
+ resumable: [SAMPLE_CLOSED], exists: { "/tmp/sample repo": true },
201
+ layout: {
202
+ width: 840, height: 118,
203
+ nodes: nodes.map((n, i) => ({ id: n.id, x: 28 + i * 280, y: 28, w: 224, h: 62 })),
204
+ edges: [
205
+ { key: "read|impl", from: "read", to: "impl", points: [[252, 59], [308, 59]] },
206
+ { key: "impl|pr", from: "impl", to: "pr", points: [[532, 59], [588, 59]] },
207
+ ],
208
+ },
209
+ },
210
+ };
211
+ })();
212
+
213
+ /**
214
+ * 자리마다 다른 모양으로 쓴다 (레이아웃이나 pane의 props.variant)
215
+ * full (기본): 작업 목록 + 그래프 + 기록. muwi open으로 터미널 옆에 연 칸
216
+ * list: 작업 목록만 (사이드바의 Agents 자리. muwi layout이 넣는다)
217
+ * graph: 그래프와 기록만 (터미널 아래. 목록은 사이드바에서 고른다)
218
+ * 고른 작업은 shared 상태로 칸끼리 나눠 쓴다. props.work를 주면 그 작업에 고정한다.
219
+ */
220
+ export default class Muwi extends View {
221
+ init(_props, cx) {
222
+ this.data = null;
223
+ this.error = null;
224
+ this.selected = null;
225
+ this.node = null;
226
+ /** 기록 칸에서 보는 탭: work(시킨 말·계획이 바뀐 기록) 또는 node(고른 노드) */
227
+ this.tab = "work";
228
+ /** 좁은 칸(기록이 그래프 아래)에서 기록을 폈는가. 넓은 칸은 늘 펴 둔다 */
229
+ this.drawer = false;
230
+ /** 칸 전체 크기, 보이는 픽셀. 쓸 때는 배율을 뺀 size를 쓴다 */
231
+ this.sizePx = { width: 900, height: 400 };
232
+ this.loading = false;
233
+ this.again = false;
234
+ this.watching = false;
235
+ this.lastLoad = 0;
236
+ this.pan = { x: 0, y: 0 };
237
+ this.zoom = 1;
238
+ this.press = null;
239
+ /** 그래프를 그리는 곳의 크기, 보이는 픽셀. 쓸 때는 배율을 뺀 canvasSize를 쓴다 */
240
+ this.canvasPx = null;
241
+ this.focusKey = null;
242
+ this.stale = false;
243
+ this.showPast = false;
244
+ /** 접어 둔 묶음 (작업 목록의 "응답 대기" 같은 것) */
245
+ this.folded = new Set();
246
+ /** 키보드가 있는 터미널과 그 작업. 바뀔 때만 따라간다 (사람이 고른 것을 덮어쓰지 않게) */
247
+ this.followKey = null;
248
+ this.followTo = null;
249
+ /** 키보드가 있는 터미널의 세션이 계획 없이 일하는 중이다 */
250
+ this.planless = false;
251
+ /** 계획 없는 세션을 보게 된 때의 PICKED. 그 뒤 누가 작업을 고르면 빈 화면을 푼다 */
252
+ this.planlessSince = 0;
253
+ /** 화면 바꾸기 안내 */
254
+ this.applying = false;
255
+ this.bannerNote = null;
256
+ this.bannerClosed = false;
257
+ /** 그래프 칸의 자리를 바꾸는 중 */
258
+ this.moving = false;
259
+ /** 그래프를 위→아래로 그렸는가 (마지막으로 읽은 것) */
260
+ this.loadedDown = null;
261
+ /** 마지막으로 읽을 때 넘긴 그래프 칸 크기. 칸이 크게 바뀌면 그 크기에 맞춰 다시 배치한다 */
262
+ this.loadedFit = null;
263
+ /** 읽어 둔 작업의 그래프 (작업 → 마지막으로 읽은 것). 탭을 옮기면 이것을 바로 보여 주고 새로 읽는 것은 뒤에서 한다 */
264
+ this.views = new Map();
265
+ /** 본 것으로 적고 있는 작업 (새 결과). 못 적었으면 이 칸이 다시 켜질 때까지 다시 하지 않는다 */
266
+ this.viewing = new Set();
267
+ /** 오른쪽 기록 칸의 너비. 경계를 끌어서 바꾸고, 바꾼 너비를 기억한다 */
268
+ this.detailW = (() => {
269
+ try {
270
+ const w = Number(localStorage.getItem("detailW"));
271
+ return w >= DETAIL_MIN && w <= 900 ? w : 300;
272
+ } catch {
273
+ return 300;
274
+ }
275
+ })();
276
+ this.resizing = null;
277
+ if (checking()) {
278
+ this.data = SAMPLE;
279
+ this.node = "impl";
280
+ this.tab = "node";
281
+ return;
282
+ }
283
+ this.load(cx);
284
+ this.watch(cx);
285
+ // 다른 칸에서 작업을 바꿨으면 바로, 아니면 15초마다 다시 읽는다 (걸린 시간 갱신, 폴더 감시가 안 될 때 대비).
286
+ // 다시 읽을 때만 화면을 다시 그린다
287
+ cx.timer.every(1000, (cx) => {
288
+ if (this.stale || Date.now() - this.lastLoad > 15000) {
289
+ this.stale = false;
290
+ this.load(cx);
291
+ } else if (this.ticking() || (this.opening && Date.now() - this.opening.at < OPENING_MS + 1000)) {
292
+ cx.notify(); // 진행 중인 노드의 작업 시간을 초마다 늘리고, "여는 중…"을 제때 푼다
293
+ }
294
+ });
295
+ // 키보드가 다른 터미널로 옮겨 가면 곧바로 그 작업으로 바꾼다 (그리는 중에는 공유 상태를 바꾸지 않는다).
296
+ // 사이드바 목록과 그래프 칸은 따로 돈다. 다른 칸이 먼저 골랐어도 이 칸은 이 칸대로 바로 읽는다
297
+ cx.timer.every(50, (cx) => {
298
+ if (this.followTo) {
299
+ const work = this.followTo;
300
+ this.followTo = null;
301
+ if (work !== this.wanted()) this.select(work, cx);
302
+ else this.load(cx);
303
+ } else if (this.stale && !this.loading) {
304
+ this.stale = false;
305
+ this.load(cx);
306
+ }
307
+ });
308
+ }
309
+
310
+ variant() {
311
+ const v = (blockProps() ?? {}).variant;
312
+ return v === "list" || v === "graph" ? v : "full";
313
+ }
314
+
315
+ /** 칸 전체 크기. 칸 안에 놓는 길이와 같은 단위다 (Herdr 배율을 뺐다) */
316
+ get size() {
317
+ return unzoom(this.sizePx);
318
+ }
319
+
320
+ /** 그래프를 그리는 곳의 크기. 칸 안에 놓는 길이와 같은 단위다. 아직 모르면 null */
321
+ get canvasSize() {
322
+ return this.canvasPx ? unzoom(this.canvasPx) : null;
323
+ }
324
+
325
+ /** 그래프를 위→아래로 그릴까: 칸이 세로로 길 때. 크기를 모르면 그래프 칸이 터미널 오른쪽에 있는지로 짐작한다 */
326
+ wantsDown() {
327
+ const s = this.canvasSize;
328
+ if (s) return s.height > s.width * 1.15;
329
+ if (checking() || this.variant() === "list") return false;
330
+ return findNode(shownLayout(), "muwi-split")?.type === "row";
331
+ }
332
+
333
+ pinned() {
334
+ const w = (blockProps() ?? {}).work;
335
+ return typeof w === "string" && w ? w : null;
336
+ }
337
+
338
+ runsDir() {
339
+ return `${home()}/.muwi`;
340
+ }
341
+
342
+ /** 지금 고른 작업: 고정된 작업 → 칸끼리 나눠 쓰는 선택 → 이 칸의 선택 */
343
+ wanted() {
344
+ return this.pinned() ?? shared(SELECTED) ?? this.selected ?? null;
345
+ }
346
+
347
+ watch(cx) {
348
+ cx.spawn(async (cx) => {
349
+ try {
350
+ this.watching = true;
351
+ for (;;) {
352
+ await watchFolder(this.runsDir());
353
+ this.load(cx);
354
+ }
355
+ } catch {
356
+ this.watching = false;
357
+ }
358
+ });
359
+ }
360
+
361
+ load(cx) {
362
+ if (this.loading) {
363
+ this.again = true;
364
+ return;
365
+ }
366
+ this.loading = true;
367
+ this.stale = false; // 지금 고른 작업을 읽으므로 따로 다시 읽을 것이 없다
368
+ cx.spawn(async (cx) => {
369
+ try {
370
+ const want = this.wanted();
371
+ const args = want ? ["board", "--work", String(want)] : ["board"];
372
+ // 세로로 긴 칸이면 위→아래로 그린다
373
+ const down = this.wantsDown();
374
+ if (down) args.push("--down");
375
+ // 그래프 칸 크기를 넘긴다. 한 줄로는 너무 작아지는 긴 그래프를 칸 비율에 맞춰 여러 줄로 접고,
376
+ // 반대 방향이 칸에 훨씬 크게 들어가는 그래프(좁은 칸에 갈래가 많은 계획)는 반대 방향으로 그린다
377
+ const s = this.canvasSize;
378
+ const fit = s && this.variant() !== "list" ? { w: Math.round(s.width), h: Math.round(s.height) } : null;
379
+ if (fit) args.push("--fit", `${fit.w}x${fit.h}`);
380
+ const r = await runMuwi(args, { timeout: 20000 });
381
+ if (r.code !== 0) throw new Error(r.stderr.trim() || `muwi가 ${r.code}로 끝났어요`);
382
+ const data = JSON.parse(r.stdout);
383
+ // 고른 작업이 없어졌으면 맨 위 작업으로
384
+ if (want && !data.selected && data.works.length) {
385
+ this.selected = null;
386
+ if (!this.pinned()) setShared(SELECTED, null);
387
+ this.again = true;
388
+ }
389
+ this.data = data;
390
+ if (data.selected) {
391
+ this.views.delete(data.selected.work); // 최근 것을 뒤로 (오래된 것부터 버린다)
392
+ this.views.set(data.selected.work, data.selected);
393
+ if (this.views.size > 40) this.views.delete(this.views.keys().next().value);
394
+ }
395
+ this.error = null;
396
+ this.loadedDown = down;
397
+ this.loadedFit = fit;
398
+ // 칸 크기를 알기 전에 읽었으면(그래프 칸이 막 켜졌을 때) 크기를 안 지금 한 번 더 읽는다.
399
+ // 그러지 않으면 새 기록이 생길 때까지 칸 크기를 모르고 한 배치(긴 그래프를 접지 않은 한 줄)로 남는다
400
+ if (!fit && this.canvasSize && this.variant() !== "list") this.stale = true;
401
+ // 끝났는데 아직 안 본 작업을 사람이 골라 보고 있으면(목록에서 눌렀거나, 그 작업의 터미널로 와서 따라왔으면) 본 것으로 적는다.
402
+ // 아무도 고르지 않아 맨 위 작업을 보여 줄 때는 적지 않는다 (새 결과는 목록 위쪽에 오므로, 보지 않았는데 지워질 수 있다)
403
+ const sel = data.selected;
404
+ if (sel?.unread && want && sel.work === want && this.variant() !== "list" && !checking()) this.markViewed(sel.work, cx);
405
+ if (this.node && !data.selected?.nodes.some((n) => n.id === this.node)) {
406
+ this.node = null;
407
+ this.tab = "work";
408
+ }
409
+ } catch (e) {
410
+ this.error = String(e?.message ?? e);
411
+ } finally {
412
+ this.loading = false;
413
+ this.lastLoad = Date.now();
414
+ cx.notify();
415
+ if (this.again) {
416
+ this.again = false;
417
+ this.load(cx);
418
+ }
419
+ }
420
+ });
421
+ }
422
+
423
+ /** 작업 줄의 오른쪽 글 */
424
+ rowMeta(w, now) {
425
+ const ms = this.workSpent(w, now);
426
+ const time = ms > 0 ? dur(ms) : null;
427
+ if (w.state === "done") return [time, ago(w.updatedAt, now)].filter(Boolean).join(" · ");
428
+ return [`${w.counts.done}/${w.counts.total}`, time].filter(Boolean).join(" · ");
429
+ }
430
+
431
+ /** 시간이 흐르는 노드가 있는가: 지금 보는 작업이나 목록의 작업에 (하던 세션이 닫힌 노드는 멈춰 있다) */
432
+ ticking() {
433
+ const going = (n) => n.status === "doing" && !n.closed;
434
+ return (this.data?.selected?.nodes ?? []).some(going) || (this.data?.works ?? []).some((w) => (w.active ?? []).some(going));
435
+ }
436
+
437
+ /**
438
+ * 작업에 든 작업 시간: 노드들이 작업한 시간을 겹침 없이 더한 것 (muwi가 읽은 때까지).
439
+ * 지금 작업 중인 노드가 있으면 그 뒤로 흐른 시간을 더해 초마다 늘린다. 다 멈췄거나 기다리는 중이면 늘지 않는다
440
+ */
441
+ workSpent(w, now) {
442
+ const nodes = w.nodes ?? w.active ?? [];
443
+ const running = nodes.some((n) => n.status === "doing" && !n.closed && !this.quietIn(w.nodes ? this.terminalOf(w, n) : n.terminal, n.quiet));
444
+ return this.spent(w.spentMs ?? 0, running, now);
445
+ }
446
+
447
+ /**
448
+ * 작업 시간. muwi가 읽은 때까지의 시간이라, 진행 중이면 그 뒤로 흐른 시간을 더한다.
449
+ * running: 노드면 진행 중이고 세션이 열려 있을 때, 회차면 그 회차가 아직 열려 있을 때
450
+ */
451
+ spent(ms, running, now) {
452
+ return running ? ms + Math.max(0, now - (this.data?.now ?? now)) : ms;
453
+ }
454
+
455
+ /** 세션이 일을 멈춘 것을 처음 본 때를 적어 둔다. 다시 일하면 지운다 */
456
+ noteQuiet(live, now) {
457
+ const seen = new Set();
458
+ for (const a of live) {
459
+ seen.add(a.address);
460
+ if (!quietOf(a.status)) QUIET_SINCE.delete(a.address);
461
+ else if (!QUIET_SINCE.has(a.address)) QUIET_SINCE.set(a.address, now);
462
+ }
463
+ for (const k of [...QUIET_SINCE.keys()]) if (!seen.has(k)) QUIET_SINCE.delete(k);
464
+ }
465
+
466
+ /** 멈춘 노드의 작업 시간: 세션이 멈춘 것을 처음 본 때까지만 센다. 그 뒤로는 늘지 않는다 */
467
+ spentQuiet(ms, terminal) {
468
+ const at = QUIET_SINCE.get(terminal);
469
+ const read = this.data?.now;
470
+ return at === undefined || read === undefined ? ms : Math.max(0, ms + at - read);
471
+ }
472
+
473
+ /** 그 터미널의 세션이 지금 일을 멈췄는가. known: muwi가 읽은 때의 값 (Herdr가 그 터미널을 모를 때 쓴다) */
474
+ quietIn(terminal, known) {
475
+ const a = terminal && !checking() ? agents().find((x) => x.address === terminal) : null;
476
+ return a ? quietOf(a.status) : known ?? null;
477
+ }
478
+
479
+ /** 하는 중이라고 적힌 노드가 실제로는 멈춰 있는가 (세션이 닫힌 노드는 닫힌 것으로 따로 보여 준다) */
480
+ nodeQuiet(view, n) {
481
+ return n.status === "doing" && !n.closed ? this.quietIn(this.terminalOf(view, n), n.quiet) : null;
482
+ }
483
+
484
+ select(work, cx) {
485
+ this.selected = work;
486
+ // 사람이 작업을 골랐다 (또는 따라간 터미널에 작업이 있다). 계획 없는 세션의 빈 화면 대신 그 작업을 보여 준다
487
+ this.planless = false;
488
+ this.node = null;
489
+ this.tab = "work";
490
+ this.focusKey = null;
491
+ if (!this.pinned()) {
492
+ setShared(SELECTED, work);
493
+ setShared(PICKED, Date.now());
494
+ }
495
+ this.load(cx);
496
+ }
497
+
498
+ /**
499
+ * 터미널 → 그 터미널에서 지금 도는 세션이 붙어 있는 작업 (계획이 없으면 undefined).
500
+ * 세션이 시작될 때 터미널에 붙인 이름표가 있으면 그것을, 없으면 그 터미널에서 가장 최근에 본 세션을 쓴다
501
+ */
502
+ links() {
503
+ const sessions = this.data?.sessions ?? [];
504
+ const map = new Map();
505
+ for (const s of sessions) if (!map.has(s.terminal)) map.set(s.terminal, s.work); // 최근 것이 먼저 온다
506
+ if (checking()) return map;
507
+ for (const t of terminals() ?? []) {
508
+ const key = t.labels?.[LABEL_SESSION];
509
+ if (!key) continue;
510
+ map.set(t.address, sessions.find((x) => x.key === key)?.work);
511
+ }
512
+ return map;
513
+ }
514
+
515
+ /**
516
+ * 키보드가 있는 터미널이 바뀌었거나 그 터미널의 세션이 새 작업에 붙었으면 그 작업을 보여 준다.
517
+ * 같은 터미널에 머무는 동안에는 사람이 고른 작업을 덮어쓰지 않는다
518
+ */
519
+ follow(links) {
520
+ if (this.pinned() || !this.data || checking()) return;
521
+ const term = focused()?.terminal ?? null;
522
+ if (!term) return; // 그래프 칸 같은 mod 칸에 키보드가 있다
523
+ const work = links.get(term);
524
+ const known = Boolean(work) && (this.data.works ?? []).some((w) => w.work === work);
525
+ // 에이전트가 떴는지도 함께 본다. 새 탭은 셸로 시작해서 그 뒤에 claude가 뜨므로, 뜨는 순간 다시 따져야
526
+ // "그래프 없음"으로 바뀐다 (터미널이 바뀔 때만 따지면 전에 보던 작업이 그대로 남는다)
527
+ const agent = agents().some((a) => a.address === term);
528
+ const key = `${term}|${known ? work : ""}|${agent ? "agent" : ""}`;
529
+ if (key === this.followKey) return;
530
+ this.followKey = key;
531
+ // 작업이나 노드를 눌러 그 일을 한 대화로 옮겨 왔다: 누른 작업을 그대로 보여 준다
532
+ const jumped = shared(JUMP);
533
+ if (jumped?.terminal === term && Date.now() - (jumped.at ?? 0) < 5000) return;
534
+ this.planless = !known && agent;
535
+ this.planlessSince = shared(PICKED) ?? 0;
536
+ if (known) {
537
+ const showing = this.data?.selected?.work;
538
+ if (showing !== work) {
539
+ // 다른 작업으로 간다: 고른 노드는 그 작업의 것이 아니다 (같은 id의 노드가 있어도 다른 노드다)
540
+ this.node = null;
541
+ this.tab = "work";
542
+ // 전에 본 작업이면 기억해 둔 그래프를 바로 보여 준다. 새로 읽는 것은 타이머가 곧바로 한다
543
+ this.showCached(work);
544
+ }
545
+ // 같은 작업을 하는 다른 터미널로 옮겼을 뿐이면 다시 읽을 것이 없다
546
+ if (showing !== work || work !== this.wanted()) this.followTo = work;
547
+ }
548
+ }
549
+
550
+ /** 기억해 둔 그 작업의 그래프를 바로 보여 준다 (그리는 중에 불러도 된다: 이 칸의 상태만 바꾼다) */
551
+ showCached(work) {
552
+ const cached = this.views.get(work);
553
+ if (cached && this.data && this.data.selected?.work !== work) this.data = { ...this.data, selected: cached };
554
+ }
555
+
556
+ /** 그 터미널로 간다. pane에 있으면 그 pane으로, pane 없이 떠 있으면 그 자리에서 들여다본다 */
557
+ go(terminal) {
558
+ if (!terminal || checking()) return;
559
+ if (panes().some((p) => p.terminal === terminal)) run("pane.focus", { terminal });
560
+ else if (this.alive(terminal)) run("terminal.peek", { terminal });
561
+ // 누르는 사이에 터미널이 닫혔다. 앱의 오류(terminal.peek failed) 대신 무슨 일인지 알린다
562
+ else notify({ title: "그 세션의 터미널이 닫혔어요", body: "기록 칸의 \"이어서 하려면\"에서 이어 갈 수 있어요.", level: "info" });
563
+ }
564
+
565
+ /**
566
+ * 그 노드를 한 대화의 터미널로 갈 수 있는가. 누르면 그 일을 한 대화로 간다: 그 대화가 아직 그 터미널에 열려 있으면 간다.
567
+ * { go: 터미널 } 또는 { why: 갈 수 없는 이유, closed }. 아직 아무도 하지 않은 노드면 null
568
+ */
569
+ nodeTerminal(view, n) {
570
+ const terminal = this.terminalOf(view, n);
571
+ if (!terminal) return null;
572
+ if (!this.alive(terminal)) return { why: "터미널이 닫혔어요", closed: terminal };
573
+ // 띄우는 중인 새 세션은 아직 이름표가 붙기 전이다
574
+ if (n.status === "todo" && n.spawn?.terminal === terminal) return { go: terminal };
575
+ // 그 노드를 한 대화가 아직 그 터미널에 있으면 간다 (그 뒤에 다른 작업을 했어도 그 대화는 이 노드를 기억한다).
576
+ // 이름표가 없으면 옛 판에서 시작한 대화라 그 대화로 본다
577
+ const label = checking() ? null : (terminals() ?? []).find((x) => x.address === terminal)?.labels?.[LABEL_SESSION];
578
+ if (!label || label === n.session) return { go: terminal };
579
+ return { why: "그 터미널에서는 지금 다른 대화가 돌고 있어요" };
580
+ }
581
+
582
+ /** 그 노드를 한 세션의 터미널로 간다 (카드를 두 번 눌렀을 때). 갈 수 없으면 왜 안 가는지 알린다 */
583
+ goNode(view, n) {
584
+ const to = this.nodeTerminal(view, n);
585
+ if (!to) return;
586
+ if (to.go) return this.jump(to.go);
587
+ if (to.closed) return this.go(to.closed); // 닫혔으면 go가 알린다
588
+ notify({ title: "그 노드를 한 세션으로 옮겨 가지 않았어요", body: to.why, level: "info" });
589
+ }
590
+
591
+ /** 그 터미널이 아직 떠 있는가. 세션을 끝내거나 터미널을 닫으면 없어져서 그리로 갈 수 없다 */
592
+ alive(terminal) {
593
+ if (!terminal) return false;
594
+ if (checking()) return true; // herdr-app check는 견본으로 버튼까지 그려 본다
595
+ return panes().some((p) => p.terminal === terminal) || (terminals() ?? []).some((x) => x.address === terminal);
596
+ }
597
+
598
+ colors(t) {
599
+ // 응답 대기는 보라, 막힘은 빨강 (막힘이 더 나쁜 일이라 경고색을 쓴다). 테마에 보라(ansi5)가 없으면 둘 다 경고색
600
+ return { todo: t.input, doing: t.working, waiting: t.ansi5 ?? t.blocked, blocked: t.blocked, done: t.done, stalled: t.muted };
601
+ }
602
+
603
+ render(_cx) {
604
+ const t = theme();
605
+ const now = Date.now();
606
+ const variant = this.variant();
607
+ const links = this.links();
608
+ const live = checking() ? [] : agents();
609
+ this.noteQuiet(live, now);
610
+ // 하는 노드가 없는 작업은 그 작업의 세션이 지금 하는 일로, 하는 노드가 있어도 그 세션이 일을 멈췄으면 멈춘 것으로 보여 준다
611
+ const works = (this.data?.works ?? []).map((w) => this.shownView(w, links, live));
612
+ // 키보드가 다른 터미널로 옮겨 갔으면 그 터미널의 작업으로
613
+ this.follow(links);
614
+ // 다른 칸에서 작업을 바꿨으면 따라간다
615
+ const want = this.wanted();
616
+ let loaded = this.data?.selected ?? null;
617
+ // 다른 칸에서 작업을 바꿨다: 기억해 둔 그 작업의 그래프를 바로 보여 주고, 새로 읽는 것은 타이머가 곧바로 한다.
618
+ // 키보드를 따라 다른 작업으로 가는 중이면(followTo) 그 작업이 맞다. 공유 선택은 타이머가 곧 바꾼다
619
+ const target = this.followTo ?? want;
620
+ if (!checking() && target && loaded && loaded.work !== target && !this.loading) {
621
+ this.stale = true;
622
+ this.showCached(target);
623
+ loaded = this.data?.selected ?? null;
624
+ }
625
+ // 다른 칸(사이드바 목록)에서 작업을 골랐으면 빈 화면을 풀고 그 작업을 보여 준다
626
+ if (this.planless && (shared(PICKED) ?? 0) !== this.planlessSince) this.planless = false;
627
+ // 키보드가 있는 세션이 계획 없이 일한다: 다른 작업의 그래프를 띄우면 그 세션이 그 일을 하는 것처럼 보이므로 비워서 보여 준다.
628
+ // 목록에서 작업을 고르면 다시 그 작업을 보여 준다
629
+ const view = this.planless || !loaded ? null : this.shownView(loaded, links, live);
630
+ const root = v_flex().id("root").size_full().min_h(0).text_color(t.foreground).text_size(12)
631
+ .on_size_change((size, cx) => {
632
+ if (Math.abs(size.width - this.sizePx.width) > 1 || Math.abs(size.height - this.sizePx.height) > 1) {
633
+ this.sizePx = { width: size.width, height: size.height };
634
+ cx.notify();
635
+ }
636
+ })
637
+ // 오른쪽 기록 칸의 경계를 끄는 중이면 너비를 바꾼다. 그래프 칸이 너무 좁아지지 않게 막는다
638
+ .on_mouse_move((e, cx) => {
639
+ if (!this.resizing) return;
640
+ const max = Math.max(DETAIL_MIN, Math.min(900, this.size.width - 360));
641
+ const w = Math.round(Math.max(DETAIL_MIN, Math.min(max, this.resizing.w + (this.resizing.x - e.position.x) / uiZoom())));
642
+ if (w !== this.detailW) {
643
+ this.detailW = w;
644
+ cx.notify();
645
+ }
646
+ })
647
+ .on_mouse_up("left", () => this.endResize())
648
+ .on_hover((hovered) => { if (!hovered) this.endResize(); });
649
+
650
+ // 그래프만 그리는 칸은 목록이 필요 없다
651
+ const groups = this.data && variant !== "graph" ? this.groups(t, works, links) : [];
652
+ const listed = groups.length > 0 || works.length > 0;
653
+
654
+ if (variant === "list") {
655
+ // 사이드바를 좁혀 아이콘만 보이게 했을 때 (Herdr의 Agents 칸과 같은 기준)
656
+ const compact = this.size.width < 160;
657
+ return root.bg(t.chrome).border_t(1).border_color(t.border)
658
+ .when(!compact, (el) => el.child(this.listHead(t, works, true)))
659
+ .when(Boolean(this.error), (el) => el.child(this.problem(t)))
660
+ .when(!this.error && this.data !== null && !listed, (el) => el.child(this.empty(t)))
661
+ .when(listed, (el) => el.child(this.list(t, works, groups, view?.work, now, true, compact)));
662
+ }
663
+
664
+ // 기록 칸 자리: 칸이 넓거나 가로로 길면 그래프 오른쪽, 좁고 세로로 길면(그래프 칸을 오른쪽에 뒀을 때) 그래프 아래
665
+ const wide = this.size.width >= 1040 || (this.size.width >= 640 && this.size.width >= this.size.height * 1.3);
666
+ // 그래프가 너무 좁아지지 않게 칸 크기에 맞춰 줄여 그린다 (기억한 너비는 그대로)
667
+ const detailW = Math.max(DETAIL_MIN, Math.min(this.detailW, this.size.width - 360));
668
+ const drawerH = Math.round(Math.min(240, Math.max(140, this.size.height * 0.3)));
669
+ const showList = variant === "full" && this.size.width >= 720 && !this.pinned();
670
+ const body = h_flex().flex_1().min_h(0)
671
+ .when(showList, (el) => el.child(
672
+ v_flex().w(236).flex_none().h_full().min_h(0).bg(t.chrome).border_r(1).border_color(t.border)
673
+ .child(this.listHead(t, works, false))
674
+ .child(this.list(t, works, groups, view?.work, now, true, false))))
675
+ .child(v_flex().flex_1().min_w(0).h_full().min_h(0)
676
+ .when(!showList && variant === "full" && works.length > 1 && !this.pinned(), (el) => el.child(this.chips(t, works, view?.work, links)))
677
+ .child(view ? this.canvas(t, view, now) : this.planless && works.length > 0 ? this.planlessNote(t) : div().flex_1())
678
+ .when(Boolean(view) && !wide, (el) => el.child(
679
+ div().flex_none().h(this.drawer ? 36 + drawerH : 36).border_t(1).border_color(t.border).bg(t.surface)
680
+ .child(this.detailPane(t, view, now, true)))))
681
+ .when(Boolean(view) && wide, (el) => el
682
+ // 경계: 끌어서 오른쪽 기록 칸의 너비를 바꾼다
683
+ .child(div().id("detail-edge").w(6).ml(-3).mr(-3).flex_none().h_full().cursor_col_resize()
684
+ .when(Boolean(this.resizing), (el2) => el2.bg(t.accent))
685
+ .when(!this.resizing, (el2) => el2.hover((s) => s.bg(t.border)))
686
+ .on_mouse_down("left", (e, cx) => {
687
+ cx.stop_propagation();
688
+ this.resizing = { x: e.position.x, w: detailW };
689
+ cx.notify();
690
+ }))
691
+ .child(div().w(detailW).flex_none().h_full().min_h(0).border_l(1).border_color(t.border).bg(t.surface).child(this.detailPane(t, view, now, false))));
692
+
693
+ const banner = this.banner(t, variant);
694
+ return root.bg(t.canvas)
695
+ .child(this.head(t, view, works, now))
696
+ .when(Boolean(banner), (el) => el.child(banner))
697
+ .when(Boolean(this.error), (el) => el.child(this.problem(t)))
698
+ .when(!this.error && this.data !== null && works.length === 0, (el) => el.child(this.empty(t)))
699
+ .when(!this.error && this.data === null, (el) => el.child(div().p(16).text_color(t.dim).child("불러오는 중…")))
700
+ .when(works.length > 0, (el) => el.child(body));
701
+ }
702
+
703
+ pill(t, text, color) {
704
+ return h_flex().h(18).px(7).flex_none().items_center().rounded(9).bg(tint(color, 0.16)).border_1().border_color(tint(color, 0.55))
705
+ .text_size(10.5).font_medium().text_color(color).child(text);
706
+ }
707
+
708
+ head(t, view, works, now) {
709
+ const c = this.colors(t);
710
+ // 이 작업을 한 대화가 열려 있는가. 열려 있으면 목록에서 누를 때 그리로 가고, 닫혔으면 새 대화로 이어 갈 수 있다
711
+ const talk = view ? this.talkOf(view, this.links()) : null;
712
+ const continuable = view && !talk && !checking() && this.folderOk(view, view.cwd);
713
+ const place = this.placeControl(t);
714
+ const legend = (text, color) => h_flex().gap(5).items_center()
715
+ .child(div().size(8).rounded_full().bg(color))
716
+ .child(div().text_size(10.5).text_color(t.dim).child(text));
717
+ return h_flex().id("head").flex_none().h(44).px(16).gap(10).items_center().border_b(1).border_color(t.border).bg(t.chrome)
718
+ .child(v_flex().flex_1().min_w(0).gap(1)
719
+ .child(h_flex().gap(8).items_center()
720
+ .child(div().min_w(0).truncate().text_size(13).font_semibold().child(view ? (view.title ?? view.work) : this.planless ? "계획 없는 세션" : "작업 그래프"))
721
+ .when(Boolean(view), (el) => el.child(this.pill(t, STATE_NAME[view.state] ?? view.state, c[view.state] ?? t.muted))))
722
+ .child(h_flex().min_w(0).gap(6).items_center().text_size(10.5)
723
+ .child(div().min_w(0).truncate().text_color(t.dim).child(
724
+ // 지금 보는 터미널의 세션은 계획 없이 일한다
725
+ !view && this.planless ? "지금 칸의 세션은 계획 없이 진행 중이에요"
726
+ : view ? [`${view.work} · ${view.counts.done}/${view.counts.total} 끝`,
727
+ // 작업 시간: 노드들이 작업한 시간의 합. 끝난 작업은 끝난 때도 같이
728
+ this.workSpent(view, now) > 0 ? `작업 ${dur(this.workSpent(view, now))}` : null,
729
+ view.state === "done" ? ago(view.updatedAt, now) : null,
730
+ view.helpers?.sessions ? `새 세션 ${view.helpers.sessions}` : null,
731
+ view.helpers?.subagents ? `서브에이전트 ${view.helpers.subagents}` : null,
732
+ talk ? `대화: ${talk.name} · 열려 있음` : "대화: 닫힘"].filter(Boolean).join(" · ") : `${works.length}개 작업`))
733
+ // 대화가 닫혔으면 새 대화가 muwi 기록을 읽고 이어 가게 연다 (그 작업을 하던 폴더에서)
734
+ .when(Boolean(continuable), (el) => el.child(div().id("head-continue").flex_none().text_color(t.accent).cursor_pointer()
735
+ .hover((s) => s.text_color(t.foreground))
736
+ .on_click((_e, cx) => { this.openTerminal("head-continue", this.launchWith(view.launcher, `${view.work} 작업 이어서 해줘`), view.cwd, view.work); cx.notify(); })
737
+ .child("새 대화로 이어 가기 ›")))))
738
+ .when(Boolean(view) && this.size.width >= 860, (el) => el.child(h_flex().flex_none().gap(12)
739
+ .child(legend("작업 중", c.doing)).child(legend("응답 대기", c.waiting)).child(legend("막힘", c.blocked)).child(legend("끝", c.done))))
740
+ .when(Boolean(place), (el) => el.child(place));
741
+ }
742
+
743
+ /** 지금 그래프 칸의 자리. muwi layout이 만든 화면의 그래프 칸이 아니면 null (옮길 수 없다) */
744
+ graphAtNow() {
745
+ if (checking() || this.variant() !== "graph") return null;
746
+ const split = findNode(shownLayout(), "muwi-split");
747
+ if (!split) return null;
748
+ return split.type === "row" ? "right" : split.children?.[0]?.id === "muwi-graph" ? "top" : "bottom";
749
+ }
750
+
751
+ /**
752
+ * 그래프 칸의 자리 고르기: 위 · 아래 · 오른쪽. muwi layout이 만든 화면의 그래프 칸에만 둔다.
753
+ * 누르면 지금 레이아웃에서 그래프 칸만 그 자리로 옮긴다 (muwi layout --graph, 레이아웃은 그대로라 번쩍이지 않는다)
754
+ */
755
+ placeControl(t) {
756
+ const now = this.graphAtNow();
757
+ if (!now) return null;
758
+ const opt = (where) => {
759
+ const on = now === where;
760
+ return div().id(`at-${where}`).h(20).px(7).flex().items_center().rounded(5).text_size(10.5)
761
+ .bg(on ? t.selected : t.chrome).text_color(on ? t.foreground : t.dim)
762
+ .when(!on && !this.moving, (el) => el.cursor_pointer().hover((s) => s.bg(t.hover).text_color(t.foreground))
763
+ .on_click((_e, cx) => this.moveGraph(where, cx)))
764
+ .child(PLACE_NAME[where]);
765
+ };
766
+ return h_flex().id("place").flex_none().gap(2).p(2).items_center().rounded(7).border_1().border_color(t.border).bg(t.chrome)
767
+ .when(this.moving, (el) => el.child(div().px(5).text_size(10.5).text_color(t.dim).child("옮기는 중…")))
768
+ .child(opt("top")).child(opt("bottom")).child(opt("right"));
769
+ }
770
+
771
+ /** 경계 끌기를 끝내고 너비를 기억한다 */
772
+ endResize() {
773
+ if (!this.resizing) return;
774
+ this.resizing = null;
775
+ try {
776
+ localStorage.setItem("detailW", String(this.detailW));
777
+ } catch {
778
+ // 기억하지 못해도 이번에는 그 너비로 그린다
779
+ }
780
+ }
781
+
782
+ /** 그래프 칸을 다른 자리로 옮긴다. 레이아웃을 다시 만들면 이 칸은 새로 뜬다 */
783
+ moveGraph(where, cx) {
784
+ if (this.moving) return;
785
+ this.moving = true;
786
+ cx.notify();
787
+ cx.spawn(async (cx) => {
788
+ try {
789
+ const r = await runMuwi(["layout", "--graph", where], { timeout: 60000 });
790
+ if (r.code !== 0) throw new Error((r.stderr || r.stdout).trim() || `muwi layout이 ${r.code}로 끝났어요`);
791
+ } catch (e) {
792
+ notify({ title: "그래프 자리를 바꾸지 못했어요", body: String(e?.message ?? e), level: "error" });
793
+ } finally {
794
+ this.moving = false;
795
+ cx.notify();
796
+ }
797
+ });
798
+ }
799
+
800
+ listHead(t, works, sidebar) {
801
+ const waiting = works.filter((w) => w.state === "waiting").length;
802
+ const running = works.filter((w) => w.state === "doing").length;
803
+ // 사이드바에서는 Herdr의 Agents 칸 머리와 같은 자리에 맞춘다
804
+ return h_flex().px(sidebar ? 16 : 14).h(sidebar ? 41 : 36).when(sidebar, (el) => el.pt(14).pb(5)).flex_none().items_center().gap(6)
805
+ .child(div().flex_1().text_size(11.5).font_medium().text_color(t.dim).child("작업"))
806
+ .when(running > 0, (el) => el.child(h_flex().gap(3).items_center().text_size(10.5).text_color(t.working)
807
+ .child(div().frames(SPIN, 90)).child(String(running))))
808
+ .when(waiting > 0, (el) => el.child(
809
+ h_flex().h(18).px(6).flex_none().items_center().rounded(5).bg(this.colors(t).waiting).text_size(10.5).font_semibold()
810
+ .text_color(t.background).child(`⏸ ${waiting}`)));
811
+ }
812
+
813
+ problem(t) {
814
+ return v_flex().p(14).gap(6).text_size(12)
815
+ .child(div().text_color(t.blocked).font_semibold().child("기록을 읽지 못했어요"))
816
+ .child(div().text_color(t.muted).child(this.error ?? ""))
817
+ .child(div().text_color(t.dim).child("터미널에서 muwi setup을 실행하세요. 이 칸이 쓰는 ~/.local/bin/muwi(Windows는 muwi.cmd)를 넣고, 화면의 자리를 다시 적어 둡니다."));
818
+ }
819
+
820
+ /**
821
+ * 하던 세션의 터미널이 닫힌 노드를 이어서 하는 버튼. 누르면 그 세션이 일하던 폴더에서 새 탭으로 열린다:
822
+ * 하던 대화 다시 열기: 그 도구의 이어 가기 명령 (Claude Code면 claude --resume <세션 id>). 하던 대화 내용이 그대로 남아 있다
823
+ * 새 대화로 이어 가기: "<작업> 작업의 <노드> 노드 이어서 해줘"로 새 대화를 연다. muwi 기록(계획·결과)을 읽고 이어 간다
824
+ * 맡긴 세션이 기록을 남기기 전에 닫혔으면 세션 정보가 없으니 그 세션을 띄운 폴더(worktree일 수 있다)에서 새 대화로 연다
825
+ */
826
+ resumeHints(t, view, n) {
827
+ const key = n.session ?? null;
828
+ const s = key ? view.sessions?.[key] : null;
829
+ const unstarted = !key && Boolean(n.spawn);
830
+ // 그 세션이 일하던 폴더. 없어졌으면(worktree를 지웠다) 작업 폴더에서 연다. 없는 폴더에서는 터미널이 뜨지 않는다
831
+ const want = s?.cwd ?? (unstarted ? n.spawn.cwd : null) ?? null;
832
+ const folder = [want, view.cwd].find((p) => this.folderOk(view, p)) ?? null;
833
+ const moved = want && !this.folderOk(view, want) ? want : null;
834
+ // 띄우는 명령과 다시 여는 명령은 muwi가 그 세션의 도구에 맞게 알려 준다 (Claude Code, Codex …)
835
+ const tool = (key && view.launch?.[key]) || view.launcher || ["claude", "{prompt}"];
836
+ const again = key ? view.resume?.[key] : null;
837
+ const buttons = [];
838
+ // 대화가 남아 있고 그 폴더가 그대로일 때만 다시 열 수 있다 (아니면 "No conversation found" 같은 말로 끝난다)
839
+ if (again && !moved) {
840
+ buttons.push(this.openRow(t, `resume-${n.id}`, "하던 대화 다시 열기", "전에 하던 대화 내용이 그대로 남아 있어요", again, folder, n.id));
841
+ }
842
+ if (n.status !== "done") {
843
+ buttons.push(this.openRow(t, `continue-${n.id}`, "새 대화로 이어 가기", unstarted ? "muwi 기록(계획·맡긴 말)을 읽고 이어 가요" : "muwi 기록(계획·결과)을 읽고 이어 가요",
844
+ this.launchWith(tool, `${view.work} 작업의 ${n.id} 노드 이어서 해줘`), folder, n.id));
845
+ }
846
+ if (!buttons.length) return { rows: [], choices: 0 };
847
+ const note = (text) => div().text_size(10.5).text_color(t.dim).child(text);
848
+ const rows = [
849
+ ...(unstarted ? [note("맡긴 세션이 일을 시작하기 전에 닫혔어요")] : []),
850
+ ...buttons,
851
+ ...(moved ? [note(`원래 폴더(${this.shortPath(moved)})가 없어져서 ${folder ? `${this.shortPath(folder)}에서` : "기본 폴더에서"} 새 탭으로 열려요`)]
852
+ : folder ? [note(`누르면 ${this.shortPath(folder)}에서 새 탭으로 열려요`)] : []),
853
+ ];
854
+ return { rows, choices: buttons.length };
855
+ }
856
+
857
+ /** 그 폴더가 아직 있는가. muwi board가 알려 준 것을 쓰고, 모르면 있다고 본다 */
858
+ folderOk(view, p) {
859
+ return Boolean(p) && view.exists?.[p] !== false;
860
+ }
861
+
862
+ /** 누르면 그 폴더에서 새 탭으로 여는 버튼과, 그 아래 무엇이 열리는지 한 줄 */
863
+ openRow(t, id, text, about, argv, folder, name) {
864
+ const busy = this.opening?.id === id && Date.now() - this.opening.at < OPENING_MS;
865
+ return v_flex().gap(3)
866
+ .child(h_flex().child(h_flex().id(`open-${id}`).h(26).px(10).flex_none().items_center().rounded(6).bg(t.raised).border_1().border_color(t.border)
867
+ .text_size(11.5).text_color(busy ? t.dim : t.foreground)
868
+ .when(!busy, (el) => el.cursor_pointer().hover((st) => st.bg(t.hover)))
869
+ .on_click((_e, cx) => { this.openTerminal(id, argv, folder, name); cx.notify(); })
870
+ .child(busy ? "여는 중…" : text)))
871
+ .child(div().text_size(10.5).text_color(t.dim).child(about));
872
+ }
873
+
874
+ /** 첫 말과 함께 새 대화를 띄우는 명령. muwi가 그 도구의 모양으로 알려 준 것에 첫 말을 넣는다 (첫 말을 못 받는 도구는 명령만) */
875
+ launchWith(template, prompt) {
876
+ const list = Array.isArray(template) && template.length ? template : ["claude", "{prompt}"];
877
+ return list.map((part) => (part === "{prompt}" ? prompt : part));
878
+ }
879
+
880
+ /** 새 탭에서 명령을 연다 (그 세션이 일하던 폴더에서). 연달아 눌러도 한 번만 연다 */
881
+ openTerminal(id, argv, folder, name) {
882
+ if (checking()) return;
883
+ if (this.opening?.id === id && Date.now() - this.opening.at < OPENING_MS) return;
884
+ this.opening = { id, at: Date.now() };
885
+ run("terminal.open", { argv, ...(folder ? { folder } : {}), ...(name ? { name } : {}) });
886
+ }
887
+
888
+ /** 홈 폴더는 ~로 줄여 보여 준다 */
889
+ shortPath(p) {
890
+ const h = checking() ? "" : home();
891
+ return h && p.startsWith(h) ? `~${p.slice(h.length)}` : p;
892
+ }
893
+
894
+ /** 키보드가 있는 세션이 계획 없이 일할 때 그래프 자리 */
895
+ planlessNote(t) {
896
+ return v_flex().flex_1().min_h(0).items_center().justify_center().gap(6).p(16)
897
+ .child(div().text_size(13).text_color(t.muted).child("그래프 없음"))
898
+ .child(div().text_size(11).text_color(t.dim).child("지금 칸의 세션은 계획 없이 일하고 있어요. 질문에 답하거나 한 번에 끝나는 일이에요."))
899
+ .child(div().text_size(11).text_color(t.dim).child("여러 단계로 하는 일을 시키면 계획이 여기에 그려져요. 다른 작업은 목록에서 고르세요."));
900
+ }
901
+
902
+ empty(t) {
903
+ return v_flex().p(16).gap(6)
904
+ .child(div().text_color(t.muted).child("기록된 작업이 없어요."))
905
+ .child(div().text_color(t.dim).text_size(11).child("에이전트에게 일을 시키면, 에이전트가 짠 계획이 여기에 그려져요."));
906
+ }
907
+
908
+ /**
909
+ * 하는 노드가 없는 작업(between)을 그 작업에 지금 붙어 있는 세션이 하는 일로 다시 본다.
910
+ * muwi가 읽어 올 때도 나눠 오지만, 세션 상태는 그 사이에도 바뀌므로 Herdr가 알려 주는 지금 상태를 쓴다.
911
+ * 세션이 무얼 하는지 모르던 작업(Herdr 밖)은 그대로 둔다
912
+ */
913
+ shownView(w, links, live) {
914
+ if (!w) return w;
915
+ if (!w.between) return this.shownQuiet(w);
916
+ const mine = live.filter((a) => links.get(a.address) === w.work);
917
+ const between = mine.some((a) => a.status === "working") ? "working"
918
+ : mine.some((a) => a.status === "blocked") ? "asking"
919
+ : mine.length ? "stopped"
920
+ : w.between === "unknown" ? "unknown" : "gone";
921
+ const state = BETWEEN_STATE[between];
922
+ return between === w.between && state === w.state ? w : { ...w, between, state };
923
+ }
924
+
925
+ /**
926
+ * 하는 노드를 하던 세션이 모두 일을 멈췄으면 응답 대기로, 다시 일하면 작업 중으로 (muwi가 읽은 뒤에 바뀐 것을 따라간다).
927
+ * 하나라도 일하고 있거나 알 수 없으면 작업 중이다. AI가 적은 응답 대기·막힘은 그대로 둔다
928
+ */
929
+ shownQuiet(w) {
930
+ if (w.state !== "doing" && !w.quiet) return w;
931
+ const doing = (w.nodes ?? w.active ?? []).filter((n) => n.status === "doing" && !n.closed);
932
+ const each = doing.map((n) => this.quietIn(w.nodes ? this.terminalOf(w, n) : n.terminal, n.quiet));
933
+ const quiet = !each.length || each.some((q) => !q) ? undefined : each.includes("asking") ? "asking" : "stopped";
934
+ const state = quiet ? "waiting" : "doing";
935
+ return state === w.state && quiet === w.quiet ? w : { ...w, state, quiet };
936
+ }
937
+
938
+ workMark(t, w, c, ask = false) {
939
+ // 그 작업을 하는 세션이 입력을 기다린다 (권한 확인 같은 것). 사람이 가 봐야 한다
940
+ if (ask) return div().w(14).flex_none().text_color(c.waiting).font_semibold().child("!");
941
+ if (w.state === "doing") return div().w(14).flex_none().text_color(c.doing).frames(SPIN, 90);
942
+ // 새 결과: 끝났는데 아직 안 봤다 (읽지 않은 메시지처럼 점으로)
943
+ if (w.unread) return div().w(14).flex_none().text_color(t.accent).child("●");
944
+ const mark = { waiting: "⏸", blocked: "✗", stalled: "◌", done: "✓" }[w.state] ?? "•";
945
+ return div().w(14).flex_none().text_color(c[w.state] ?? t.muted).child(mark);
946
+ }
947
+
948
+ /**
949
+ * 작업 목록의 묶음. 급한 순서: 응답 대기 → 막힘 → 새 결과 → 작업 중 → 멈춤 → 계획 없는 세션 → 끝.
950
+ * 하는 노드가 없는 작업은 그 작업의 세션이 하는 일로 묶는다 (shownView).
951
+ * 새 결과: 모두 끝났는데 사람이 아직 보지 않은 작업. 그 작업을 골라 그래프로 보면 "끝"으로 내려간다.
952
+ * 계획 없이 일하는 세션(작업에 붙지 않은 에이전트)도 넣는다. 그래서 Herdr의 Agents 칸이 없어도 모든 세션이 보인다.
953
+ * 세션이 입력을 기다리면(권한 확인 같은 것) 그 작업이나 세션을 "응답 대기"로 올린다
954
+ */
955
+ groups(t, works, links) {
956
+ const c = this.colors(t);
957
+ const current = works.filter((w) => !w.past);
958
+ const open = new Set(current.filter((w) => w.state !== "done").map((w) => w.work));
959
+ const byWork = new Map();
960
+ const free = [];
961
+ for (const a of checking() ? [] : agents()) {
962
+ const work = links.get(a.address);
963
+ // 끝나지 않은 작업을 하는 세션은 그 작업 줄에 들어간다. 나머지 열린 대화(작업을 끝냈거나 계획 없이 일하는 것)는 "열린 대화"에
964
+ if (work && open.has(work)) byWork.set(work, [...(byWork.get(work) ?? []), a]);
965
+ else free.push(a);
966
+ }
967
+ const bucket = { need: [], blocked: [], fresh: [], doing: [], stalled: [], free: [], done: [] };
968
+ for (const w of current) {
969
+ const mine = byWork.get(w.work) ?? [];
970
+ const item = { kind: "work", w, agents: mine, ask: mine.some((a) => a.status === "blocked") };
971
+ if (w.state === "waiting" || item.ask) bucket.need.push(item);
972
+ else if (w.unread) bucket.fresh.push(item);
973
+ else (bucket[w.state] ?? bucket.doing).push(item);
974
+ }
975
+ const rank = (a) => AGENT_RANK[a.status] ?? 0;
976
+ for (const a of free.sort((x, y) => rank(y) - rank(x) || (y.seq ?? 0) - (x.seq ?? 0))) {
977
+ (a.status === "blocked" ? bucket.need : bucket.free).push({ kind: "agent", a });
978
+ }
979
+ return [
980
+ { id: "need", label: STATE_NAME.waiting, color: c.waiting, items: bucket.need },
981
+ { id: "blocked", label: STATE_NAME.blocked, color: c.blocked, items: bucket.blocked },
982
+ { id: "fresh", label: "새 결과", color: t.accent, items: bucket.fresh },
983
+ { id: "doing", label: STATE_NAME.doing, color: c.doing, items: bucket.doing },
984
+ { id: "stalled", label: STATE_NAME.stalled, color: t.muted, items: bucket.stalled },
985
+ { id: "free", label: "열린 대화", color: t.dim, items: bucket.free },
986
+ { id: "done", label: STATE_NAME.done, color: c.done, items: bucket.done },
987
+ ].filter((g) => g.items.length > 0);
988
+ }
989
+
990
+ /**
991
+ * 작업 목록: 묶음 머리와 줄들. 끝났거나 멈춘 채로 오래된 작업(past)은 맨 아래에 "지난 작업 N개"로 접어 둔다. 지우지는 않는다.
992
+ * compact: 사이드바를 좁혀 아이콘만 보일 때
993
+ */
994
+ list(t, works, groups, selected, now, fill, compact) {
995
+ const c = this.colors(t);
996
+ const box = fill ? v_flex().flex_1().min_h(0) : v_flex().flex_none();
997
+ const row = (item) => (item.kind === "work" ? this.workRow(t, c, item, selected, now, compact) : this.agentRow(t, item.a, compact));
998
+ const past = works.filter((w) => w.past);
999
+ // 접어 둔 작업을 보고 있으면 펼쳐 둔다
1000
+ const open = this.showPast || past.some((w) => w.work === selected);
1001
+ return box.id("works").overflow_y_scrollbar().px(compact ? 4 : 8).pb(8).gap(1)
1002
+ .children(groups.flatMap((g) => [
1003
+ ...(compact ? [] : [this.groupHead(t, g)]),
1004
+ ...(this.folded.has(g.id) && !compact ? [] : g.items.map(row)),
1005
+ ]))
1006
+ .when(past.length > 0 && !compact, (el) => el
1007
+ .child(h_flex().id("past-toggle").px(8).py(6).mt(4).gap(8).items_center().rounded(7).cursor_pointer()
1008
+ .hover((s) => s.bg(t.hover))
1009
+ .on_click((_e, cx) => { this.showPast = !open; cx.notify(); })
1010
+ .child(div().w(14).flex_none().text_size(10).text_color(t.dim).child(open ? "▾" : "▸"))
1011
+ .child(div().flex_1().text_size(11).text_color(t.dim).child(`지난 작업 ${past.length}개`)))
1012
+ .when(open, (el2) => el2.children(past.map((w) => row({ kind: "work", w, agents: [], ask: false })))));
1013
+ }
1014
+
1015
+ /** 묶음 머리. 누르면 접는다 */
1016
+ groupHead(t, g) {
1017
+ const open = !this.folded.has(g.id);
1018
+ return h_flex().id(`sec-${g.id}`).px(8).pt(8).h(28).flex_none().gap(6).items_center().text_size(11).font_medium().cursor_pointer()
1019
+ .hover((s) => s.text_color(t.foreground))
1020
+ .on_click((_e, cx) => { open ? this.folded.add(g.id) : this.folded.delete(g.id); cx.notify(); })
1021
+ .child(div().truncate().text_color(g.color).child(g.label))
1022
+ .child(div().text_color(t.dim).child(String(g.items.length)))
1023
+ .child(div().flex_1())
1024
+ .when(!open, (el) => el.child(div().text_size(10).text_color(t.dim).child("▸")));
1025
+ }
1026
+
1027
+ /**
1028
+ * 작업을 고른다 (목록의 줄, 좁은 칸의 칩). 누르면 그 작업을 한 대화로 간다. 닫혔으면 그래프만:
1029
+ * 그 작업의 그래프를 보여 주고, 그 작업을 한 대화가 아직 열려 있으면 그 터미널로 간다 (끝난 작업이어도,
1030
+ * 그 대화가 그 뒤에 다른 작업을 했어도. 그 대화는 이 작업을 기억한다). 그래프는 누른 작업 그대로 둔다
1031
+ */
1032
+ openWork(w, cx) {
1033
+ this.select(w.work, cx);
1034
+ const talk = this.talkOf(w, this.links());
1035
+ if (talk) this.jump(talk.terminal);
1036
+ }
1037
+
1038
+ /** 그 터미널로 간다. 키보드를 따라가는 그래프 칸들이 그 대화의 다른 작업으로 바꾸지 않게 알린다 */
1039
+ jump(terminal) {
1040
+ if (!terminal) return;
1041
+ if (!checking()) setShared(JUMP, { terminal, at: Date.now() });
1042
+ this.go(terminal);
1043
+ }
1044
+
1045
+ /**
1046
+ * 그 작업을 한 대화가 지금 열려 있는 터미널. 그 작업에 지금 붙어 있는 대화 → 계획을 낸 대화 → 나머지 순.
1047
+ * 열려 있다 = 그 터미널에 그 대화(세션)의 이름표가 그대로 붙어 있고 에이전트가 돌고 있다 (/clear나 새로 띄운 대화는 다른 이름표다)
1048
+ */
1049
+ talkOf(w, links) {
1050
+ if (!w || checking()) return null;
1051
+ const keys = [...new Set(w.talks ?? [w.lead, ...Object.keys(w.sessions ?? {})].filter(Boolean))];
1052
+ if (!keys.length) return null;
1053
+ const running = agents();
1054
+ const live = new Set(running.map((a) => a.address));
1055
+ const open = (terminals() ?? []).filter((x) => live.has(x.address) && keys.includes(x.labels?.[LABEL_SESSION]));
1056
+ if (!open.length) return null;
1057
+ const rank = (x) => (links.get(x.address) === w.work ? 0 : 1000) + keys.indexOf(x.labels[LABEL_SESSION]);
1058
+ const best = open.sort((a, b) => rank(a) - rank(b))[0];
1059
+ const a = running.find((y) => y.address === best.address);
1060
+ return { terminal: best.address, name: a?.space_name || a?.tab_name || best.address };
1061
+ }
1062
+
1063
+ /**
1064
+ * 작업 한 줄: 제목 / 지금 눈여겨볼 노드.
1065
+ * 누르면 그 작업의 그래프를 보여 주고, 그 작업을 한 대화가 열려 있으면 그 터미널로 간다 (그래프 위 머리줄에 대화가 열렸는지 나온다)
1066
+ */
1067
+ workRow(t, c, item, selected, now, compact) {
1068
+ const w = item.w;
1069
+ const on = w.work === selected;
1070
+ const click = (_e, cx) => this.openWork(w, cx);
1071
+ if (compact) {
1072
+ return h_flex().id(`work-${w.work}`).h(26).flex_none().items_center().justify_center().rounded(6)
1073
+ .bg(on ? t.selected : t.chrome).hover((s) => s.bg(on ? t.selected : t.hover)).cursor_pointer()
1074
+ .on_click(click)
1075
+ .child(this.workMark(t, w, c, item.ask));
1076
+ }
1077
+ const first = w.active.find((n) => n.status === "waiting" && !n.closed) ?? w.active.find((n) => n.status === "blocked" && !n.closed) ?? w.active[0];
1078
+ const line = item.ask ? "세션이 입력을 기다림" : w.state === "done" ? "모든 노드가 끝났어요"
1079
+ // 하는 노드가 여럿이면(나란히 맡긴 점검들) 첫 노드와 나머지 수
1080
+ : first ? `${first.title}${w.active.length > 1 ? ` 외 ${w.active.length - 1}` : ""}${first.closed ? " · 세션이 닫힘" : w.quiet ? ` · ${QUIET_NAME[w.quiet]}` : first.note ? ` · ${first.note}` : ""}`
1081
+ // 하는 노드가 없다 (몇 단계째인지는 오른쪽에 나온다)
1082
+ : (w.between && BETWEEN_NAME[w.between]) || "다음 노드 전";
1083
+ return h_flex().id(`work-${w.work}`).px(8).py(6).gap(8).items_center().rounded(7)
1084
+ .bg(on ? t.selected : t.chrome).hover((s) => s.bg(on ? t.selected : t.hover)).cursor_pointer()
1085
+ .on_click(click)
1086
+ .child(this.workMark(t, w, c, item.ask))
1087
+ .child(v_flex().flex_1().min_w(0).gap(1)
1088
+ .child(div().truncate().text_size(12).text_color(on || w.unread ? t.foreground : t.muted).when(on || w.unread, (el) => el.font_medium()).child(w.title ?? w.work))
1089
+ .child(h_flex().gap(6).text_size(10.5)
1090
+ .child(div().flex_1().min_w(0).truncate().text_color(item.ask ? c.waiting : c[w.state] ?? t.dim).child(line))
1091
+ // 끝나지 않은 작업은 몇 단계째인지: 끝난 노드 / 전체
1092
+ // 오른쪽: 몇 단계째인지와 작업 시간 (노드들이 작업한 시간의 합. 작업 중이면 초마다 늘어난다). 끝난 작업은 작업 시간과 끝난 때
1093
+ .child(div().flex_none().text_color(t.dim).child(this.rowMeta(w, now)))));
1094
+ }
1095
+
1096
+ /** 계획 없이 일하는 세션 한 줄 (Herdr의 Agents 칸과 같은 모양). 누르면 그 터미널로 간다 */
1097
+ agentRow(t, a, compact) {
1098
+ const click = () => run("pane.focus", { pane: a.pane });
1099
+ if (compact) {
1100
+ return h_flex().id(`ag-${a.address}`).h(26).flex_none().items_center().justify_center().rounded(6)
1101
+ .bg(a.focused ? t.selected : t.chrome).hover((s) => s.bg(a.focused ? t.selected : t.hover)).cursor_pointer()
1102
+ .on_click(click)
1103
+ .child(this.agentStatus(t, a));
1104
+ }
1105
+ const pic = programIcon(a.program, 14, t.foreground);
1106
+ const name = a.space_name || a.tab_name || a.address;
1107
+ const title = clean(a.title);
1108
+ const more = title && title !== name && title !== a.program?.name ? title : null;
1109
+ const quiet = a.status === "idle" && !a.focused;
1110
+ return h_flex().id(`ag-${a.address}`).px(8).h(30).flex_none().gap(8).items_center().rounded(7)
1111
+ .bg(a.focused ? t.selected : t.chrome).hover((s) => s.bg(a.focused ? t.selected : t.hover)).cursor_pointer()
1112
+ .on_click(click)
1113
+ .child(h_flex().w(14).flex_none().items_center().justify_center().when(Boolean(pic), (el) => el.child(pic)))
1114
+ .child(h_flex().flex_1().min_w(0).gap(5).items_center().text_size(12)
1115
+ .child(div().min_w(0).max_w(more ? 110 : 220).truncate().text_color(quiet ? t.muted : t.foreground).child(name))
1116
+ .when(Boolean(more), (el) => el.child(div().flex_1().min_w(0).truncate().text_color(t.dim).child(`· ${more}`))))
1117
+ .child(this.sessionMark(t, a, `ag-ses-${a.address}`));
1118
+ }
1119
+
1120
+ /** 줄 오른쪽의 세션 표시. 마우스를 올리면 뜻을 알려 준다 (표시 모양은 Herdr의 Agents 칸과 같다) */
1121
+ sessionMark(t, a, id) {
1122
+ const what = { working: "세션 작업 중", blocked: "세션이 입력을 기다림", done: "세션 쉬는 중 (다음 말을 기다림)", idle: "세션 쉬는 중 (다음 말을 기다림)" }[a.status] ?? "세션 있음";
1123
+ return h_flex().id(id).flex_none().items_center().tooltip(`${what} · 누르면 그 터미널로 가요`).child(this.agentStatus(t, a));
1124
+ }
1125
+
1126
+ /** 세션 상태 표시 (Herdr의 Agents 칸과 같은 모양): 일하는 중은 도는 원, 입력을 기다리면 !, 쉬는 중은 빈 원 */
1127
+ agentStatus(t, a) {
1128
+ if (a.status === "working") return svg("mods/workspace-chrome/spinner.svg").size(12).mx(1).flex_none().text_color(t.working).spin(900);
1129
+ if (a.status === "blocked") {
1130
+ // 입력을 기다리는 세션은 응답 대기와 같은 색
1131
+ const ask = this.colors(t).waiting;
1132
+ return div().size(14).flex_none().rounded(4).bg(tint(ask, 0.15)).text_size(10.5).font_bold().text_color(ask)
1133
+ .flex().items_center().justify_center().child("!");
1134
+ }
1135
+ if (a.status === "idle") return div().size(7).mx(3).flex_none().rounded(4).border(1.5).border_color(t.idle ?? t.dim);
1136
+ return div().size(7).mx(3).flex_none().rounded(4).bg(a.status === "done" ? t.done ?? t.dim : t.dim);
1137
+ }
1138
+
1139
+ /**
1140
+ * 그래프 칸 위쪽의 한 줄 안내.
1141
+ * 터미널 옆에 따로 연 칸(full)인데 화면에 muwi 칸이 없으면: 사이드바와 터미널 아래에 고정하자고 (muwi config layout off면 묻지 않는다)
1142
+ * muwi layout으로 만든 화면인데 Herdr가 업데이트됐으면: 새 모양에 맞추자고
1143
+ */
1144
+ banner(t, variant) {
1145
+ if (checking() || !this.data || this.bannerClosed) return null;
1146
+ const tree = shownLayout();
1147
+ const has = anyNode(tree, (n) => n?.content?.mod === "muwi");
1148
+ let text = null, act = null, later = null;
1149
+ if (!has && variant === "full" && this.data.suggest) {
1150
+ text = "사이드바의 Agents 자리에 작업 목록을 두고, 그래프를 터미널 아래에 고정할 수 있어요. 지금 레이아웃은 그대로 남아요.";
1151
+ act = { label: "바꾸기", run: (cx) => this.applyLayout(cx, true) };
1152
+ later = { label: "묻지 않기", run: (cx) => this.stopAsking(cx) };
1153
+ } else if (has && /^muwi(-\d+)?$/.test(String(shared("layout") ?? ""))) {
1154
+ // muwi layout으로 만든 화면이다. 다시 맞출 일이 있는지 본다
1155
+ const was = tree?.cloned_from?.version;
1156
+ const now = updates()?.app?.version;
1157
+ const later0 = { label: "나중에", run: (cx) => { this.bannerClosed = true; cx.notify(); } };
1158
+ if (SHIPPED.includes(tree?.cloned_from?.name) && was && now && was !== now) {
1159
+ text = `Herdr가 업데이트됐어요 (${was} → ${now}). muwi 화면을 새 모양에 맞출 수 있어요.`;
1160
+ act = { label: "맞추기", run: (cx) => this.applyLayout(cx, false) };
1161
+ later = later0;
1162
+ } else if (anyNode(tree, (n) => n?.id === "muwi-graph") && !anyNode(tree, (n) => n?.id === "muwi-split")) {
1163
+ // 옛 배치: 그래프 칸 높이를 바꿀 수 없다
1164
+ text = "muwi 화면 배치가 나아졌어요. 다시 맞추면 터미널과 그래프 사이 경계를 끌어서 그래프 높이를 바꿀 수 있어요.";
1165
+ act = { label: "맞추기", run: (cx) => this.applyLayout(cx, false) };
1166
+ later = later0;
1167
+ }
1168
+ }
1169
+ if (!text) return null;
1170
+ const button = (id, b, primary) => h_flex().id(id).h(24).px(10).flex_none().items_center().rounded(6)
1171
+ .bg(primary ? t.accent : t.raised).border_1().border_color(primary ? t.accent : t.border)
1172
+ .text_size(11).font_medium().text_color(primary ? t.background : t.muted).cursor_pointer()
1173
+ .when(!primary, (el) => el.hover((s) => s.bg(t.hover).text_color(t.foreground)))
1174
+ .on_click((_e, cx) => b.run(cx))
1175
+ .child(b.label);
1176
+ return h_flex().flex_none().px(14).py(7).gap(10).items_center().bg(t.surface).border_b(1).border_color(t.border)
1177
+ .child(div().flex_1().min_w(0).text_size(11.5).text_color(this.bannerNote && !this.applying ? t.blocked : t.foreground).child(this.bannerNote ?? text))
1178
+ .when(!this.applying, (el) => el.child(button("banner-act", act, true)).child(button("banner-later", later, false)));
1179
+ }
1180
+
1181
+ /** muwi layout을 실행한다. 터미널 옆에 따로 연 칸이면 바꾼 뒤 그 칸을 닫는다 (같은 그래프가 두 번 보이지 않게) */
1182
+ applyLayout(cx, closeMe) {
1183
+ if (this.applying) return;
1184
+ this.applying = true;
1185
+ this.bannerNote = "바꾸는 중…";
1186
+ const me = closeMe ? panes().find((p) => p.mod === "muwi" && p.focused)?.pane ?? null : null;
1187
+ cx.notify();
1188
+ cx.spawn(async (cx) => {
1189
+ try {
1190
+ const r = await runMuwi(["layout"], { timeout: 60000 });
1191
+ if (r.code !== 0) throw new Error((r.stderr || r.stdout).trim() || `muwi layout이 ${r.code}로 끝났어요`);
1192
+ this.applying = false;
1193
+ this.bannerNote = null;
1194
+ this.bannerClosed = true;
1195
+ cx.notify();
1196
+ if (me) run("pane.close", { pane: me });
1197
+ } catch (e) {
1198
+ this.applying = false;
1199
+ this.bannerNote = String(e?.message ?? e);
1200
+ cx.notify();
1201
+ }
1202
+ });
1203
+ }
1204
+
1205
+ /** 다시 묻지 않는다 (muwi config layout off) */
1206
+ stopAsking(cx) {
1207
+ this.bannerClosed = true;
1208
+ if (this.data) this.data.suggest = false;
1209
+ cx.notify();
1210
+ cx.spawn(async () => {
1211
+ try {
1212
+ await runMuwi(["config", "layout", "off"], { timeout: 20000 });
1213
+ } catch {
1214
+ // 적지 못해도 이 칸에서는 다시 묻지 않는다
1215
+ }
1216
+ });
1217
+ }
1218
+
1219
+ /** 좁을 때는 목록 대신 한 줄로 */
1220
+ chips(t, works, selected, links) {
1221
+ const c = this.colors(t);
1222
+ return h_flex().id("chips").flex_none().h(34).px(10).gap(6).items_center().overflow_x_hidden().border_b(1).border_color(t.border)
1223
+ .children([...works.filter((w) => !w.past), ...works.filter((w) => w.past)].slice(0, 8).map((w) => {
1224
+ const on = w.work === selected;
1225
+ return h_flex().id(`chip-${w.work}`).h(22).px(8).gap(5).flex_none().items_center().rounded(11)
1226
+ .bg(on ? t.selected : t.surface).border_1().border_color(on ? t.accent : t.border).cursor_pointer()
1227
+ .hover((s) => s.bg(t.hover))
1228
+ // 목록의 줄과 같다: 그 작업에 붙어 있는 세션이 있으면 그 터미널로 같이 간다
1229
+ .on_click((_e, cx) => this.openWork(w, cx))
1230
+ .child(div().size(7).rounded_full().bg(c[w.state] ?? t.muted))
1231
+ .child(div().text_size(11).text_color(on ? t.foreground : t.muted).child(w.work));
1232
+ }));
1233
+ }
1234
+
1235
+ /** 노드를 맡은 세션의 지금 상태 (Herdr가 아는 것). 터미널을 모르면 null */
1236
+ /** 이 노드를 하는 세션의 Herdr 터미널 주소. 맡긴 세션이 아직 뜨는 중이면 띄운 터미널 */
1237
+ terminalOf(view, n) {
1238
+ return (n.session ? view.sessions?.[n.session]?.terminal : null) ?? (n.status === "todo" ? n.spawn?.terminal : null) ?? null;
1239
+ }
1240
+
1241
+ /**
1242
+ * 카드 오른쪽 위의 표시: 누가 하는가. 대화가 직접 하면 비워 둔다.
1243
+ * planned: 아직 시작 전이고 계획에 그렇게 적혀 있다 (흐리게 그린다)
1244
+ */
1245
+ tagOf(n) {
1246
+ if (n.who) {
1247
+ if (n.who.kind === "session") return { text: "세션", planned: false };
1248
+ const subs = n.who.agents.length;
1249
+ if (n.who.kind === "subagent") return { text: subs > 1 ? `서브 ×${subs}` : "서브", planned: false };
1250
+ // 세션이 직접 했고, 그동안 뜬 서브에이전트가 도왔다
1251
+ if (subs > 0) return { text: subs > 1 ? `+서브 ×${subs}` : "+서브", planned: false };
1252
+ return null;
1253
+ }
1254
+ if (n.status !== "todo") return null;
1255
+ if (n.spawn || n.run === "session") return { text: "세션", planned: true };
1256
+ if (n.run === "subagent") return { text: "서브", planned: true };
1257
+ return null;
1258
+ }
1259
+
1260
+ agentOf(view, n) {
1261
+ const terminal = this.terminalOf(view, n);
1262
+ if (!terminal) return null;
1263
+ return agents().find((a) => a.address === terminal) ?? null;
1264
+ }
1265
+
1266
+ statusIcon(t, n, color, size, quiet = null) {
1267
+ const circle = () => div().size(size).flex_none().rounded_full().flex().items_center().justify_center();
1268
+ // 하던 세션이 닫혔다: 돌지 않는 빈 원으로. 끝난 것도 하는 중도 아니다
1269
+ if (n.closed) return circle().border(1.5).border_color(t.muted).text_size(size * 0.62).font_semibold().text_color(t.muted).child("–");
1270
+ // 하던 세션이 일을 멈췄다: 돌지 않는다. 입력을 기다리면 응답 대기와 같은 "!", 멈췄으면 멈춤 표시(막대 둘)
1271
+ if (n.status === "doing" && quiet === "asking") return circle().bg(color).text_size(size * 0.62).font_semibold().text_color(t.background).child("!");
1272
+ if (n.status === "doing" && quiet) {
1273
+ const bar = () => div().w(size * 0.13).h(size * 0.4).rounded(1).bg(color);
1274
+ return circle().border(1.5).border_color(color).gap(size * 0.13).child(bar()).child(bar());
1275
+ }
1276
+ if (n.status === "doing") {
1277
+ return div().size(size).flex_none().relative()
1278
+ .child(div().absolute().left(0).top(0).size(size).rounded_full().border(2).border_color(tint(color, 0.28)))
1279
+ .child(svg("mods/muwi/arc.svg").absolute().left(0).top(0).size(size).text_color(color).spin(900));
1280
+ }
1281
+ if (n.status === "waiting") return circle().bg(color).text_size(size * 0.62).font_semibold().text_color(t.background).child("!");
1282
+ if (n.status === "blocked") return circle().bg(color).text_size(size * 0.62).font_semibold().text_color(t.background).child("×");
1283
+ if (n.status === "done") return circle().bg(color).text_size(size * 0.62).font_semibold().text_color(t.background).child("✓");
1284
+ return circle().border(1.5).border_color(t.input);
1285
+ }
1286
+
1287
+ /** 카드 둘째 줄: 상태에 따라 가장 궁금한 것 하나 */
1288
+ metaOf(view, n, now) {
1289
+ const stopped = this.nodeQuiet(view, n);
1290
+ const ms = stopped ? this.spentQuiet(n.spentMs, this.terminalOf(view, n)) : this.spent(n.spentMs, n.status === "doing" && !n.closed, now);
1291
+ const times = n.spentMs > 0 ? dur(ms) : null;
1292
+ if (n.closed) return ["세션이 닫힘", times, n.status !== "doing" ? n.note : null].filter(Boolean).join(" · ");
1293
+ if (n.status === "waiting" || n.status === "blocked") return n.note ?? STATUS_NAME[n.status];
1294
+ if (n.status === "doing") {
1295
+ return [n.who?.kind === "subagent" ? "서브에이전트" : null, times, stopped ? QUIET_NAME[stopped] : null].filter(Boolean).join(" · ") || "작업 중";
1296
+ }
1297
+ if (n.status === "done") return [times, n.note].filter(Boolean).join(" · ");
1298
+ // 시작했다가 앞에 먼저 할 노드가 끼어들어 잠시 멈췄다
1299
+ if (n.paused) return ["잠시 멈춤", times].filter(Boolean).join(" · ");
1300
+ if (n.spawn) {
1301
+ // 맡긴 세션이 일을 시작하기 전에 터미널이 닫혔다. 더 기다려도 뜨지 않는다
1302
+ if (!this.alive(n.spawn.terminal)) return "맡긴 세션이 닫힘";
1303
+ // 폴더 신뢰 확인이나 권한 확인에서 멈춰 있으면 그렇게 보여 준다. 사람이 그 칸에서 답해야 한다
1304
+ const agent = this.agentOf(view, n);
1305
+ return agent?.status === "blocked" ? AGENT_NAME.blocked : "새 세션이 뜨는 중";
1306
+ }
1307
+ return "";
1308
+ }
1309
+
1310
+ /** 새 결과를 본 것으로 적는다. 적고 나면 다시 읽어 목록에서 "끝"으로 내린다 */
1311
+ markViewed(work, cx) {
1312
+ if (this.viewing.has(work)) return;
1313
+ this.viewing.add(work);
1314
+ cx.spawn(async (cx) => {
1315
+ const r = await runMuwi(["viewed", "--work", work], { timeout: 10000 }).catch(() => null);
1316
+ if (r?.code !== 0) return; // 못 적었으면(옛 muwi 명령 등) 다시 시도하지 않는다
1317
+ this.viewing.delete(work);
1318
+ this.stale = true;
1319
+ cx.notify();
1320
+ });
1321
+ }
1322
+
1323
+ centerOn(view) {
1324
+ const s = this.canvasSize;
1325
+ const L = view.layout;
1326
+ if (!s || !L.width) return;
1327
+ // 그래프가 칸에 다 들어오면 가운데에. 터미널 아래처럼 낮은 칸은 글자가 읽히는 만큼(0.7배)까지 줄여서 담는다
1328
+ const floor = this.variant() === "graph" ? 0.7 : 0.9;
1329
+ const fit = Math.min(1, s.width / L.width, s.height / L.height);
1330
+ if (fit >= floor) {
1331
+ this.zoom = fit;
1332
+ this.pan = { x: (s.width - L.width * fit) / 2, y: Math.max(0, (s.height - L.height * fit) / 2) };
1333
+ return;
1334
+ }
1335
+ // 다 담기지 않으면 높이를 읽히는 만큼만 줄이고, 볼 노드를 가운데에 둔다
1336
+ const z = Math.max(floor, Math.min(1, s.height / L.height));
1337
+ this.zoom = z;
1338
+ const ids = this.focusIds(view);
1339
+ const boxes = L.nodes.filter((p) => ids.includes(p.id));
1340
+ if (!boxes.length) return;
1341
+ const x1 = Math.min(...boxes.map((p) => p.x)), x2 = Math.max(...boxes.map((p) => p.x + p.w));
1342
+ const y1 = Math.min(...boxes.map((p) => p.y)), y2 = Math.max(...boxes.map((p) => p.y + p.h));
1343
+ const clamp = (v, size, full) => (full <= size ? (size - full) / 2 : Math.min(0, Math.max(size - full, v)));
1344
+ this.pan = {
1345
+ x: clamp(s.width / 2 - ((x1 + x2) / 2) * z, s.width, L.width * z),
1346
+ y: clamp(s.height / 2 - ((y1 + y2) / 2) * z, s.height, L.height * z),
1347
+ };
1348
+ }
1349
+
1350
+ /**
1351
+ * 그래프가 칸에 다 담기지 않을 때 보여 줄 노드:
1352
+ * 지금 일어나는 노드 → (시작 전이면) 처음 노드 → (다 끝났으면) 흐름의 끝 노드 → 다음에 할 노드
1353
+ */
1354
+ focusIds(view) {
1355
+ const live = view.nodes.filter((n) => n.status === "doing" || n.status === "waiting" || n.status === "blocked").map((n) => n.id);
1356
+ if (live.length) return live;
1357
+ const done = new Set(view.nodes.filter((n) => n.status === "done").map((n) => n.id));
1358
+ if (done.size === 0) return view.nodes.filter((n) => !(n.after ?? []).length).map((n) => n.id);
1359
+ if (done.size === view.nodes.length) {
1360
+ const before = new Set(view.nodes.flatMap((n) => n.after ?? []));
1361
+ return view.nodes.filter((n) => !before.has(n.id)).map((n) => n.id);
1362
+ }
1363
+ // 하는 노드가 없다: 앞 노드가 다 끝났는데 아직 시작하지 않은 노드
1364
+ const next = view.nodes.filter((n) => n.status === "todo" && (n.after ?? []).every((a) => done.has(a))).map((n) => n.id);
1365
+ return next.length ? next : view.nodes.map((n) => n.id);
1366
+ }
1367
+
1368
+ fit(view) {
1369
+ const s = this.canvasSize;
1370
+ const L = view.layout;
1371
+ if (!s || !L.width) return;
1372
+ this.zoom = Math.max(0.3, Math.min(1.2, s.width / L.width, s.height / L.height));
1373
+ this.pan = { x: (s.width - L.width * this.zoom) / 2, y: Math.max(0, (s.height - L.height * this.zoom) / 2) };
1374
+ }
1375
+
1376
+ zoomBy(f, point, L) {
1377
+ const next = Math.max(0.3, Math.min(1.6, this.zoom * f));
1378
+ const wx = (point.x - this.pan.x) / this.zoom, wy = (point.y - this.pan.y) / this.zoom;
1379
+ this.zoom = next;
1380
+ this.pan = { x: point.x - wx * next, y: point.y - wy * next };
1381
+ this.clampPan(L);
1382
+ }
1383
+
1384
+ /**
1385
+ * 그래프가 칸 밖으로 밀려나지 않게, 옮길 수 있는 범위를 그래프 크기로 막는다.
1386
+ * 그래프가 칸보다 작은 쪽은 칸 안에서 옮기고 가장자리에 닿으면 멈춘다(끌면 움직인다).
1387
+ * 큰 쪽은 그래프 끝이 칸 끝에 닿을 때까지만 옮긴다. 처음 보여 줄 때 가운데에 두는 것은 centerOn이 한다
1388
+ */
1389
+ clampPan(L) {
1390
+ const s = this.canvasSize;
1391
+ if (!s || !L?.width) return;
1392
+ const z = this.zoom;
1393
+ const edge = 12;
1394
+ // a: 그래프 왼쪽(위쪽) 끝이 칸 가장자리에 닿는 곳, b: 오른쪽(아래쪽) 끝이 닿는 곳. 작은 그래프는 a < b, 큰 그래프는 b < a
1395
+ const axis = (v, size, full) => {
1396
+ const a = edge, b = size - full - edge;
1397
+ return Math.min(Math.max(a, b), Math.max(Math.min(a, b), v));
1398
+ };
1399
+ this.pan = { x: axis(this.pan.x, s.width, L.width * z), y: axis(this.pan.y, s.height, L.height * z) };
1400
+ }
1401
+
1402
+ canvas(t, view, now) {
1403
+ const L = view.layout;
1404
+ const c = this.colors(t);
1405
+ const byId = Object.fromEntries(view.nodes.map((n) => [n.id, n]));
1406
+
1407
+ // 작업이 바뀌거나, 지금 일어나는 곳이 바뀌거나, 계획의 모양이 바뀌면 다시 맞춘다
1408
+ const live = view.nodes.filter((n) => n.status === "doing" || n.status === "waiting" || n.status === "blocked").map((n) => n.id).join(",");
1409
+ // Herdr 배율을 바꿔도 다시 맞춘다 (칸 크기를 재는 단위가 바뀐다)
1410
+ const focus = `${view.work}|${live}|${L.width}x${L.height}|${L.nodes.length}|${uiZoom()}`;
1411
+ if (this.canvasSize && this.focusKey !== focus) {
1412
+ this.focusKey = focus;
1413
+ this.centerOn(view);
1414
+ }
1415
+ const z = this.zoom;
1416
+ const X = (x) => this.pan.x + x * z, Y = (y) => this.pan.y + y * z;
1417
+ const cw = this.canvasSize?.width ?? 900, ch = this.canvasSize?.height ?? 300;
1418
+
1419
+ // 선: 끝난 노드에서 나가는 선은 진하게, 나머지는 옅게. 끝에 화살촉
1420
+ const paths = [], dots = [];
1421
+ for (const e of L.edges) {
1422
+ const passed = byId[e.from]?.status === "done";
1423
+ const color = passed ? tint(c.done, 0.8) : t.input;
1424
+ const pts = e.points.map(([x, y]) => [X(x), Y(y)]);
1425
+ const [ex, ey] = pts[pts.length - 1], [qx, qy] = pts[pts.length - 2];
1426
+ const len = Math.hypot(ex - qx, ey - qy) || 1;
1427
+ const ux = (ex - qx) / len, uy = (ey - qy) / len;
1428
+ const ah = 6.5 * z, aw = 3.6 * z;
1429
+ const body = [...pts.slice(0, -1), [ex - ux * ah * 0.7, ey - uy * ah * 0.7]];
1430
+ paths.push({ path: roundPath(PathBuilder.stroke((passed ? 1.8 : 1.3) * Math.max(0.8, z)), body, 8 * z).build(), color });
1431
+ paths.push({
1432
+ path: PathBuilder.fill().add_polygon([[ex - ux * ah - uy * aw, ey - uy * ah + ux * aw], [ex, ey], [ex - ux * ah + uy * aw, ey - uy * ah - ux * aw]], true).build(),
1433
+ color,
1434
+ });
1435
+ dots.push({ x: pts[0][0], y: pts[0][1], color: passed ? color : t.muted });
1436
+ }
1437
+
1438
+ // 이 작업에 나온 도구가 둘 이상이면 카드마다 그 노드를 한 도구를 적는다
1439
+ const toolsUsed = new Set(Object.values(view.sessions ?? {}).map((x) => x.tool).filter((x) => x && x !== "unknown"));
1440
+ const madeBy = (n) => {
1441
+ const tool = toolsUsed.size > 1 && n.session ? view.sessions?.[n.session]?.tool : null;
1442
+ return tool && tool !== "unknown" ? String(view.toolNames?.[tool] ?? tool).split(" ")[0] : null;
1443
+ };
1444
+ const glows = [], cards = [];
1445
+ for (const p of L.nodes) {
1446
+ const n = byId[p.id];
1447
+ if (!n) continue;
1448
+ const x = X(p.x), y = Y(p.y), w = p.w * z, h = p.h * z;
1449
+ if (x > cw || y > ch || x + w < 0 || y + h < 0) continue; // 화면 밖은 그리지 않는다
1450
+ // 하던 세션이 닫힌 노드는 눈에 띄게 그리지 않는다. 지금 일어나는 일이 아니다
1451
+ // 하는 중이라고 적혀 있어도 그 세션이 일을 멈췄으면 응답 대기처럼 그린다 (돌지 않고, 색도 응답 대기 색)
1452
+ const quiet = this.nodeQuiet(view, n);
1453
+ const color = n.closed ? t.muted : quiet ? c.waiting : c[n.status];
1454
+ const active = !n.closed && (n.status === "doing" || n.status === "waiting" || n.status === "blocked");
1455
+ const picked = this.node === n.id;
1456
+ if (active) {
1457
+ const moving = n.status === "doing" && !quiet;
1458
+ glows.push(div().absolute().left(x - 6 * z).top(y - 6 * z).w(w + 12 * z).h(h + 12 * z).rounded(12 * z).bg(color)
1459
+ .loop("opacity", { from: 0.05, to: moving ? 0.2 : 0.28, period: moving ? 1200 : 1800 }));
1460
+ }
1461
+ const read = n.skills.filter((s) => s.state === "read").length;
1462
+ const meta = this.metaOf(view, n, now);
1463
+ const tag = this.tagOf(n);
1464
+ const chip = (text, tone, faint) => div().flex_none().px(4.5 * z).rounded(4 * z).border(1).border_color(tint(tone, faint ? 0.3 : 0.6))
1465
+ .text_size(9.5 * z).text_color(faint ? tint(tone, 0.7) : tone).child(text);
1466
+ cards.push(h_flex().id(`node-${n.id}`).absolute().left(x).top(y).w(w).h(h).px(11 * z).gap(9 * z).items_center().rounded(8 * z)
1467
+ .bg(active ? tint(color, 0.12) : t.raised)
1468
+ .border(active || picked ? 1.5 : 1)
1469
+ .border_color(picked ? t.accent : active ? tint(color, 0.9) : n.status === "done" ? t.input : t.border)
1470
+ .cursor_pointer()
1471
+ .on_mouse_down("left", (_e, cx) => cx.stop_propagation())
1472
+ // 누르면 그 노드의 기록을 본다. 두 번 누르면 그 노드를 하는 세션의 터미널로 간다.
1473
+ // 작업의 기록은 위의 "작업" 탭이나 그래프의 빈 곳을 눌러서 본다 (다시 눌러 고르기를 풀지 않는다: 두 번 누르기와 겹친다)
1474
+ .on_click((e, cx) => {
1475
+ this.node = n.id;
1476
+ this.tab = "node";
1477
+ this.drawer = true;
1478
+ if ((e?.click_count ?? 1) >= 2) this.goNode(view, n);
1479
+ cx.notify();
1480
+ })
1481
+ .child(this.statusIcon(t, n, color, 17 * z, quiet))
1482
+ .child(v_flex().flex_1().min_w(0).gap(2 * z)
1483
+ .child(h_flex().gap(5 * z).items_center()
1484
+ .child(div().flex_1().min_w(0).truncate().text_size(12.5 * z).text_color(n.status === "todo" ? t.muted : t.foreground)
1485
+ .when(active, (el) => el.font_semibold()).child(n.title))
1486
+ // 다시 한 노드는 눈에 띄게: 여기서 뭔가 걸렸다는 신호다
1487
+ .when(n.attempts > 1, (el) => el.child(chip(`${n.attempts}회차`, t.accent, false)))
1488
+ .when(Boolean(tag), (el) => el.child(chip(tag.text, t.muted, tag.planned)))
1489
+ // 여러 도구가 같이 한 작업이면 이 노드를 어느 도구가 했는지 (리뷰는 Codex, 구현은 Claude처럼)
1490
+ .when(Boolean(madeBy(n)), (el) => el.child(chip(madeBy(n), t.accent, true)))
1491
+ .when(Boolean(n.offPlan), (el) => el.child(chip("≠계획", t.blocked, false)))
1492
+ // 앞 노드가 끝나기 전에 시작했다: 그래프 흐름과 다르게 진행 중이라는 표시
1493
+ .when(Boolean(n.early), (el) => el.child(chip("순서 앞당김", t.muted, false))))
1494
+ .child(h_flex().gap(6 * z).items_center().text_size(10.5 * z)
1495
+ .child(div().flex_1().min_w(0).truncate().text_color(active ? color : t.dim).child(meta || " "))
1496
+ .when(n.flags.length > 0, (el) => el.child(div().flex_none().text_color(t.blocked).child("⚑")))
1497
+ .when(read > 0, (el) => el.child(div().flex_none().text_color(t.dim).child(`skill ${read}`))))));
1498
+ }
1499
+ const ports = dots.map((d) => div().absolute().left(d.x - 3 * z).top(d.y - 3 * z).size(6 * z)
1500
+ .rounded_full().bg(d.color).border(1.5).border_color(t.canvas));
1501
+
1502
+ const button = (id, label, act) => h_flex().id(id).h(26).px(9).items_center().rounded(6).bg(t.surface).border_1().border_color(t.border)
1503
+ .text_size(11).text_color(t.muted).hover((s) => s.bg(t.hover).text_color(t.foreground)).cursor_pointer()
1504
+ .on_mouse_down("left", (_e, cx) => cx.stop_propagation())
1505
+ .on_click((_e, cx) => { act(); cx.notify(); })
1506
+ .child(label);
1507
+ const controls = h_flex().absolute().right(12).bottom(12).gap(6)
1508
+ .child(button("c-now", "◎ 지금", () => { this.centerOn(view); }))
1509
+ .child(button("c-fit", "⤢ 전체", () => { this.fit(view); }))
1510
+ .child(button("c-out", "−", () => { this.zoomBy(1 / 1.2, { x: cw / 2, y: ch / 2 }, L); }))
1511
+ .child(button("c-in", "+", () => { this.zoomBy(1.2, { x: cw / 2, y: ch / 2 }, L); }));
1512
+
1513
+ const layer = paths.map((q) => window.paint_path(q.path, q.color).absolute().left(0).top(0).w(cw).h(ch));
1514
+ return div().id("canvas").relative().flex_1().min_h(0).overflow_hidden().bg(t.canvas)
1515
+ .on_size_change((size, cx) => {
1516
+ const old = this.canvasPx;
1517
+ if (!old || Math.abs(old.width - size.width) > 1 || Math.abs(old.height - size.height) > 1) {
1518
+ this.canvasPx = { width: size.width, height: size.height };
1519
+ this.focusKey = null; // 크기가 바뀌면 다시 맞춘다
1520
+ // 칸이 가로로 길다가 세로로 길어졌으면(또는 반대) 흐름 방향을 바꿔 다시 읽는다
1521
+ if (this.loadedDown !== null && this.wantsDown() !== this.loadedDown) this.stale = true;
1522
+ // 칸 크기를 모른 채 읽었거나 크기가 크게 바뀌었으면, 그 크기에 맞춰 다시 배치한다 (긴 그래프를 접는 줄 수가 달라진다)
1523
+ const f = this.loadedFit, s = this.canvasSize;
1524
+ if (this.data?.selected && (!f || Math.abs(s.width - f.w) > f.w * 0.15 || Math.abs(s.height - f.h) > f.h * 0.15)) this.stale = true;
1525
+ cx.notify();
1526
+ }
1527
+ })
1528
+ .when(Boolean(this.press), (el) => el.cursor_grabbing())
1529
+ .when(!this.press, (el) => el.cursor_grab())
1530
+ .on_mouse_down("left", (e, cx) => { this.press = { x: e.position.x, y: e.position.y, px: this.pan.x, py: this.pan.y, moved: false }; cx.notify(); })
1531
+ .on_mouse_move((e, cx) => {
1532
+ if (!this.press) return;
1533
+ if (Math.abs(e.position.x - this.press.x) + Math.abs(e.position.y - this.press.y) > 3) this.press.moved = true;
1534
+ // 마우스는 보이는 픽셀로 온다. 배율로 나눠야 그래프가 커서를 그대로 따라온다
1535
+ const k = uiZoom();
1536
+ this.pan = { x: this.press.px + (e.position.x - this.press.x) / k, y: this.press.py + (e.position.y - this.press.y) / k };
1537
+ this.clampPan(L);
1538
+ cx.notify();
1539
+ })
1540
+ .on_mouse_up("left", (_e, cx) => {
1541
+ // 끌지 않고 빈 곳을 눌렀다: 고른 노드를 풀고 작업 기록을 보여 준다
1542
+ if (this.press && !this.press.moved && (this.node || this.tab !== "work")) {
1543
+ this.node = null;
1544
+ this.tab = "work";
1545
+ }
1546
+ this.press = null;
1547
+ cx.notify();
1548
+ })
1549
+ .on_hover((hovered, cx) => { if (!hovered && this.press) { this.press = null; cx.notify(); } })
1550
+ .on_scroll_wheel((e, cx) => {
1551
+ if (e.modifiers.platform || e.modifiers.control) {
1552
+ const k = uiZoom();
1553
+ const local = e.local_position ? { x: e.local_position.x / k, y: e.local_position.y / k } : { x: cw / 2, y: ch / 2 };
1554
+ // 휠을 위로 굴리면 확대, 아래로 굴리면 축소 (브라우저·지도와 같은 방향)
1555
+ this.zoomBy(Math.exp(Math.max(-60, Math.min(60, e.delta.y)) * 0.004), local, L);
1556
+ } else {
1557
+ const k = uiZoom();
1558
+ this.pan = { x: this.pan.x + e.delta.x / k, y: this.pan.y + e.delta.y / k };
1559
+ this.clampPan(L);
1560
+ }
1561
+ cx.notify();
1562
+ })
1563
+ .children([...layer, ...glows, ...cards, ...ports, controls]);
1564
+ }
1565
+
1566
+ /**
1567
+ * 기록 칸: 위에 "작업 · 노드" 탭, 그 아래에 고른 탭의 기록.
1568
+ * 넓은 칸은 그래프 오른쪽에 늘 펴 두고, 좁은 칸(그래프 칸을 오른쪽에 뒀을 때)은 그래프 아래에 탭만 두었다가 누르면 편다
1569
+ */
1570
+ detailPane(t, view, now, foldable) {
1571
+ const open = !foldable || this.drawer;
1572
+ const tab = (id, text) => {
1573
+ const on = open && this.tab === id;
1574
+ return div().id(`tab-${id}`).h(22).px(10).flex().items_center().rounded(5).text_size(11)
1575
+ .bg(on ? t.selected : t.chrome).text_color(on ? t.foreground : t.dim)
1576
+ .cursor_pointer().hover((s) => s.bg(on ? t.selected : t.hover).text_color(t.foreground))
1577
+ .on_click((_e, cx) => {
1578
+ // 좁은 칸에서 보고 있는 탭을 다시 누르면 접는다
1579
+ if (foldable && on) this.drawer = false;
1580
+ else {
1581
+ this.tab = id;
1582
+ this.drawer = true;
1583
+ }
1584
+ cx.notify();
1585
+ })
1586
+ .child(text);
1587
+ };
1588
+ const strip = h_flex().id("detail-tabs").flex_none().h(36).px(10).gap(8).items_center()
1589
+ .when(open, (el) => el.border_b(1).border_color(t.border))
1590
+ .child(h_flex().flex_none().gap(2).p(2).items_center().rounded(7).border_1().border_color(t.border).bg(t.chrome)
1591
+ .child(tab("work", "작업"))
1592
+ .child(tab("node", "노드")))
1593
+ .child(div().flex_1())
1594
+ .when(foldable, (el) => el.child(div().id("detail-fold").h(22).px(8).flex().items_center().rounded(5)
1595
+ .text_size(10.5).text_color(t.dim).cursor_pointer().hover((s) => s.bg(t.hover).text_color(t.foreground))
1596
+ .on_click((_e, cx) => { this.drawer = !open; cx.notify(); })
1597
+ .child(open ? "접기 ▾" : "펴기 ▴")));
1598
+ return v_flex().size_full().min_h(0)
1599
+ .child(strip)
1600
+ .when(open, (el) => el.child(div().flex_1().min_h(0).child(this.detail(t, view, now))));
1601
+ }
1602
+
1603
+ /** 기록: 작업 탭이면 시킨 말과 계획이 바뀐 기록, 노드 탭이면 고른 노드 */
1604
+ detail(t, view, now) {
1605
+ const c = this.colors(t);
1606
+ const n = this.tab === "node" && this.node ? view.nodes.find((x) => x.id === this.node) : null;
1607
+ const label = (text) => div().text_size(10).font_semibold().text_color(t.dim).child(text);
1608
+ const line = (text, color) => div().text_size(11.5).text_color(color ?? t.muted).child(text);
1609
+ const box = v_flex().id("detail").size_full().min_h(0).overflow_y_scrollbar().p(14).gap(10);
1610
+
1611
+ if (this.tab === "node" && !n) return box.child(line("그래프에서 노드를 누르면 그 노드의 기록이 보여요", t.dim));
1612
+ if (!n) {
1613
+ const changes = view.changes.filter((ch) => !ch.first).slice(-6).reverse();
1614
+ const loose = view.flags.filter((f) => !f.node);
1615
+ return box
1616
+ .when(Boolean(view.request), (el) => el.child(v_flex().gap(3).child(label("시킨 말")).child(line(view.request, t.foreground))))
1617
+ .child(v_flex().gap(4).child(label("계획이 바뀐 기록"))
1618
+ .when(changes.length === 0, (el) => el.child(line("처음 계획 그대로예요", t.dim)))
1619
+ .children(changes.map((ch) => v_flex().gap(1)
1620
+ .child(h_flex().gap(6).text_size(10.5)
1621
+ .child(div().text_color(t.dim).child(clock(ch.at)))
1622
+ .child(div().text_color(ch.by === "human" ? t.accent : t.dim).child(ch.by === "human" ? "사람" : "AI"))
1623
+ .child(div().flex_1().min_w(0).truncate().text_color(t.muted)
1624
+ .child([...ch.added.map((id) => `+${id}`), ...ch.removed.map((id) => `−${id}`), ...ch.changed.map((id) => `~${id}`)].join(" "))))
1625
+ .child(line(ch.why ?? "(이유 없음)")))))
1626
+ .when((view.gone ?? []).length > 0, (el) => el.child(v_flex().gap(3).child(label("빠진 노드"))
1627
+ .children(view.gone.map((g) => line(`${g.title} (${STATUS_NAME[g.status] ?? g.status}) · ${g.why ?? "이유 없음"}`)))))
1628
+ .when(view.outside.length > 0, (el) => el.child(v_flex().gap(3).child(label("노드 밖에서 읽은 skill"))
1629
+ .child(line([...new Set(view.outside.map((s) => s.skill))].join(", ")))))
1630
+ .when(loose.length > 0, (el) => el.child(v_flex().gap(3).child(label("문제 표시"))
1631
+ .children(loose.map((f) => line(`⚑ ${f.text}`, t.blocked)))))
1632
+ .when(view.state === "stalled", (el) => el.child(v_flex().gap(8).child(label("이어서 하려면"))
1633
+ .child(div().text_size(10.5).text_color(t.dim).child(view.between === "gone" ? "이 작업을 맡은 세션이 없어요" : "하던 세션이 모두 닫혔어요"))
1634
+ .child(this.openRow(t, "continue-work", "새 대화로 이어 가기", "muwi 기록(계획·결과)을 읽고 멈춘 노드부터 이어 가요", this.launchWith(view.launcher, `${view.work} 작업 이어서 해줘`),
1635
+ this.folderOk(view, view.cwd) ? view.cwd : null, view.work))
1636
+ .when(Boolean(view.cwd), (el2) => el2.child(div().text_size(10.5).text_color(t.dim).child(this.folderOk(view, view.cwd)
1637
+ ? `누르면 ${this.shortPath(view.cwd)}에서 새 탭으로 열려요` : `작업 폴더(${this.shortPath(view.cwd)})가 없어져서 기본 폴더에서 새 탭으로 열려요`)))));
1638
+ }
1639
+
1640
+ const quiet = this.nodeQuiet(view, n);
1641
+ const color = n.closed ? t.muted : quiet ? c.waiting : c[n.status];
1642
+ const agent = this.agentOf(view, n);
1643
+ const terminal = this.terminalOf(view, n);
1644
+ const to = this.nodeTerminal(view, n);
1645
+ const sessionName = (key, model) => {
1646
+ const i = key ? view.sessions?.[key] : null;
1647
+ // 어느 도구의 어떤 모델인지 (모델은 그 도구의 훅이 알려 줄 때만)
1648
+ const made = [i?.tool && i.tool !== "unknown" ? (view.toolNames?.[i.tool] ?? i.tool) : null, model ?? i?.model].filter(Boolean).join(" · ");
1649
+ return `${i?.label ?? ""}${made ? ` (${made})` : ""}`;
1650
+ };
1651
+ /** 회차를 누가 했는지 한 줄 */
1652
+ const whoOf = (who) => {
1653
+ const count = (list) => {
1654
+ const kinds = [...new Set(list.map((a) => a.kind).filter(Boolean))].join(", ");
1655
+ return `서브에이전트 ${list.length}개${kinds ? ` (${kinds})` : ""}`;
1656
+ };
1657
+ const own = who.agents.filter((a) => a.own);
1658
+ const helped = who.agents.filter((a) => !a.own);
1659
+ if (who.kind === "subagent") return own.length ? count(own) : `${count(helped)} · 세션 ${view.sessions?.[who.session]?.label ?? ""}이 시작함`;
1660
+ // 이 회차를 시작할 때의 모델 (노드마다 적힌 것). 없으면 그 세션의 지금 모델
1661
+ const base = who.kind === "session" ? `새 세션 ${sessionName(who.session, who.model)}` : `세션 ${sessionName(who.session, who.model)}`;
1662
+ return [base, own.length ? count(own) : null, helped.length ? `${count(helped)}가 도움` : null].filter(Boolean).join(" + ");
1663
+ };
1664
+ // 실제로 한 쪽. 시작 전이면 뜨는 중인 세션
1665
+ const whoText = n.who ? whoOf(n.who) : n.spawn ? `새 세션 ${n.spawn.terminal} · ${this.alive(n.spawn.terminal) ? "뜨는 중" : "일을 시작하기 전에 닫힘"}` : null;
1666
+ const plannedText = n.run ? `계획: ${RUN_NAME[n.run] ?? n.run}${n.show ? `, ${n.show}` : ""}` : null;
1667
+ /**
1668
+ * 한 회차(또는 한 번만 한 노드)의 읽은 skill.
1669
+ * "읽은 skill이 없어요"는 훅이 보고 있었는데 읽지 않았을 때만 쓴다. 보지 못했으면 그렇게 적는다.
1670
+ */
1671
+ const skillRows = (x) => {
1672
+ const read = x.skills.filter((s) => s.state === "read");
1673
+ const loaded = x.skills.filter((s) => s.state === "loaded");
1674
+ const rows = [];
1675
+ if (x.seen === false) rows.push(line("읽은 skill을 볼 수 없었어요 (이 세션에서 훅이 돌지 않았어요)", t.blocked));
1676
+ else if (read.length === 0) rows.push(line(x.instant ? "시작과 끝을 한꺼번에 적어서 하는 동안의 기록이 없어요" : "하는 동안 읽은 skill이 없어요", t.dim));
1677
+ for (const s of read) {
1678
+ rows.push(h_flex().gap(6).items_start()
1679
+ .child(div().size(6).mt(5).flex_none().rounded_full().bg(t.done))
1680
+ .child(line(`${s.skill}${s.count > 1 ? ` ×${s.count}` : ""}${s.via === "file" ? " (파일을 직접 읽음)" : ""}${s.agent ? " · 서브에이전트가 읽음" : ""}${s.guess ? " · 확실하지 않음" : ""}`, t.foreground).flex_1().min_w(0)));
1681
+ }
1682
+ if (loaded.length > 0) {
1683
+ rows.push(div().pt(2).text_size(10).text_color(t.dim).child("이미 읽은 상태 (같은 세션이 앞에서 읽음)"));
1684
+ for (const s of loaded) {
1685
+ rows.push(h_flex().gap(6).items_start()
1686
+ .child(div().size(6).mt(5).flex_none().rounded_full().border(1).border_color(t.muted))
1687
+ .child(line(s.skill).flex_1().min_w(0)));
1688
+ }
1689
+ }
1690
+ return rows;
1691
+ };
1692
+ const tries = n.tries ?? [];
1693
+ const running = n.status === "doing" && !n.closed && !quiet;
1694
+ // 하던 세션의 터미널이 닫혔으면 그 세션에 맞춰 이어 하는 방법을 보여 준다
1695
+ const resume = n.closed || (terminal && !this.alive(terminal)) ? this.resumeHints(t, view, n) : { rows: [], choices: 0 };
1696
+ const times = [
1697
+ n.startedAt ? `${clock(n.startedAt)} 시작` : null,
1698
+ n.spentMs > 0 ? `${dur(quiet ? this.spentQuiet(n.spentMs, terminal) : this.spent(n.spentMs, running, now))} 작업` : null,
1699
+ n.attempts > 1 ? `${n.attempts}회차` : null,
1700
+ ].filter(Boolean).join(" · ");
1701
+ return box
1702
+ .child(v_flex().gap(4)
1703
+ .child(div().text_size(13).font_semibold().child(n.title))
1704
+ .child(h_flex().gap(6).items_center()
1705
+ .child(this.pill(t, n.closed ? `멈춤 · ${STATUS_NAME[n.status]}이던 중` : quiet ? `${QUIET_NAME[quiet]} · ${STATUS_NAME[n.status]}이던 중` : STATUS_NAME[n.status], n.status === "todo" ? t.muted : color))
1706
+ .child(div().min_w(0).truncate().text_size(10.5).text_color(t.dim).child(n.id))))
1707
+ .when(Boolean(n.closed), (el) => el.child(v_flex().gap(3).child(label("세션이 닫힘"))
1708
+ .child(line("이 노드를 하던 세션이 닫혔어요. 일이 끝났는지는 알 수 없어요. 이어서 하는 방법은 아래에 있어요."))))
1709
+ .when(Boolean(n.note), (el) => el.child(v_flex().gap(3)
1710
+ .child(label({ waiting: "기다리는 것", blocked: "막힌 이유", done: "결과" }[n.status] ?? "메모"))
1711
+ .child(line(n.note, n.status === "done" ? t.foreground : color))))
1712
+ .when(Boolean(times), (el) => el.child(v_flex().gap(3).child(label("시간")).child(line(times))))
1713
+ .when(Boolean(whoText || plannedText), (el) => el.child(v_flex().gap(4).child(label("누가"))
1714
+ // 글이 길면 줄을 바꾸고, 버튼은 그 아래에 둔다 (칸이 좁아도 잘리지 않게)
1715
+ .when(Boolean(whoText), (el) => el.child(line(`${whoText}${agent ? ` · ${AGENT_NAME[agent.status] ?? agent.status}` : ""}`, t.foreground)))
1716
+ // 그 세션이 아직 이 작업에 붙어 있을 때만 갈 수 있다 (그래프와 터미널은 늘 같은 작업을 가리킨다). 못 가면 버튼 대신 이유를 적는다
1717
+ .when(Boolean(whoText && to?.go), (el) => el.child(h_flex().child(
1718
+ h_flex().id(`go-${n.id}`).h(20).px(7).flex_none().items_center().rounded(5).bg(t.raised).border_1().border_color(t.border)
1719
+ .text_size(10.5).text_color(t.muted).cursor_pointer().hover((s) => s.bg(t.hover).text_color(t.foreground))
1720
+ // pane이 있으면 그 pane으로 가고, pane 없이 떠 있는 세션이면 그 자리에서 들여다본다
1721
+ .on_click(() => this.jump(to.go))
1722
+ .child("터미널로 가기"))))
1723
+ .when(Boolean(whoText && to?.why), (el) => el.child(line(to.why, t.dim)))
1724
+ .when(Boolean(plannedText), (el) => el.child(line(
1725
+ n.offPlan ? `${plannedText} · 계획과 다르게 했어요`
1726
+ : n.runUnknown ? `${plannedText} · 이 세션에서 훅이 돌지 않아 계획대로 했는지 확인하지 못했어요` : plannedText,
1727
+ n.offPlan ? t.blocked : t.dim)))))
1728
+ .when(resume.choices > 0, (el) => el.child(v_flex().gap(8).child(label(n.status === "done" ? "그 대화를 다시 열려면" : resume.choices > 1 ? "이어서 하려면 (둘 중 하나)" : "이어서 하려면")).children(resume.rows)))
1729
+ .child(v_flex().gap(4).child(label(tries.length > 1 ? "회차별 기록" : "읽은 skill"))
1730
+ .when(n.attempts === 0, (el) => el.child(line("아직 시작하지 않았어요", t.dim)))
1731
+ .children(tries.length > 1
1732
+ ? tries.map((x) => v_flex().gap(3).pt(2)
1733
+ .child(h_flex().gap(6).items_center()
1734
+ .child(div().flex_none().px(5).rounded(4).border(1).border_color(tint(t.accent, 0.6)).text_size(10).text_color(t.accent).child(`${x.n}회차`))
1735
+ .child(div().flex_1().min_w(0).truncate().text_size(10.5).text_color(t.dim)
1736
+ .child([x.startedAt ? clock(x.startedAt) : null, x.spentMs > 0 ? dur(this.spent(x.spentMs, running && x === tries[tries.length - 1], now)) : null, x.who ? whoOf(x.who) : null].filter(Boolean).join(" · "))))
1737
+ .children(skillRows(x))
1738
+ .when(Boolean(x.note), (el) => el.child(line(`${{ waiting: "기다린 것", blocked: "막힌 이유", done: "결과" }[x.status] ?? "메모"}: ${x.note}`))))
1739
+ : n.attempts > 0 ? skillRows(n) : []))
1740
+ .when(Boolean(n.spawn?.task), (el) => el.child(v_flex().gap(3).child(label("맡긴 말")).child(line(n.spawn.task))))
1741
+ .when(n.flags.length > 0, (el) => el.child(v_flex().gap(3).child(label("문제 표시"))
1742
+ .children(n.flags.map((f) => line(`⚑ ${f.text} (${ago(f.at, now)})`, t.blocked)))));
1743
+ }
1744
+ }