opencode-subagent-magazine 1.5.1 → 1.6.0-beta.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.
Files changed (60) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +192 -192
  3. package/dist/_version.d.ts +1 -1
  4. package/dist/_version.js +1 -1
  5. package/dist/core/color.d.ts +20 -0
  6. package/dist/core/color.js +68 -0
  7. package/dist/core/format.d.ts +5 -0
  8. package/dist/core/format.js +68 -0
  9. package/dist/core/index.d.ts +6 -0
  10. package/dist/core/index.js +6 -0
  11. package/dist/core/kv.d.ts +20 -0
  12. package/dist/core/kv.js +30 -0
  13. package/dist/core/state-machine.d.ts +17 -0
  14. package/dist/core/state-machine.js +27 -0
  15. package/dist/core/types.d.ts +51 -0
  16. package/dist/core/types.js +2 -0
  17. package/dist/core/usage.d.ts +15 -0
  18. package/dist/core/usage.js +1 -0
  19. package/dist/index.js +148 -1480
  20. package/dist/panel/SubAgentPanel.d.ts +13 -0
  21. package/dist/panel/SubAgentPanel.js +1232 -0
  22. package/dist/panel/panel-api.d.ts +67 -0
  23. package/dist/panel/panel-api.js +1 -0
  24. package/dist/panel/store.d.ts +5 -0
  25. package/dist/panel/store.js +5 -0
  26. package/dist/tui.js +383 -290
  27. package/dist/v2/commands.d.ts +7 -0
  28. package/dist/v2/commands.js +263 -0
  29. package/dist/v2/index.d.ts +8 -0
  30. package/dist/v2/index.js +62 -0
  31. package/dist/v2/theme.d.ts +3 -0
  32. package/dist/v2/theme.js +12 -0
  33. package/dist/v2/types.d.ts +231 -0
  34. package/dist/v2/types.js +6 -0
  35. package/dist/v2/v2-panel-api.d.ts +12 -0
  36. package/dist/v2/v2-panel-api.js +345 -0
  37. package/dist/v2.js +3003 -0
  38. package/install.mjs +103 -103
  39. package/package.json +64 -63
  40. package/src/_version.ts +1 -1
  41. package/src/clipboard.ts +134 -134
  42. package/src/core/color.ts +70 -0
  43. package/src/core/format.ts +61 -0
  44. package/src/core/index.ts +6 -0
  45. package/src/core/kv.ts +36 -0
  46. package/src/core/state-machine.ts +46 -0
  47. package/src/core/types.ts +58 -0
  48. package/src/core/usage.ts +16 -0
  49. package/src/i18n.ts +261 -261
  50. package/src/index.tsx +124 -1745
  51. package/src/panel/SubAgentPanel.tsx +1460 -0
  52. package/src/panel/panel-api.ts +72 -0
  53. package/src/panel/store.ts +8 -0
  54. package/src/server.ts +10 -10
  55. package/src/v2/commands.ts +251 -0
  56. package/src/v2/index.tsx +98 -0
  57. package/src/v2/theme.ts +14 -0
  58. package/src/v2/types.ts +165 -0
  59. package/src/v2/v2-panel-api.ts +301 -0
  60. package/tui/index.js +11 -0
package/dist/index.js CHANGED
@@ -1,1511 +1,179 @@
1
- import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "@opentui/solid/jsx-runtime";
2
- import { createMemo, createSignal, createEffect, onMount, onCleanup, untrack, Show, For, } from "solid-js";
1
+ import { jsx as _jsx } from "@opentui/solid/jsx-runtime";
2
+ import { createSignal } from "solid-js";
3
3
  import { PLUGIN_VERSION } from "./_version";
4
- import { copyText } from "./clipboard";
5
4
  import { LANG_META, createT, detectLang } from "./i18n";
6
- /** OpenCode built-in tool names that spawn sub-agents or delegate tasks. */
7
- const SUBAGENT_TOOLS = new Set(["task", "delegate", "call_omo_agent"]);
5
+ import { KV_PREFIX } from "./core/kv";
6
+ import { SubAgentPanel } from "./panel/SubAgentPanel";
7
+ import { globalEntryCache, setClearTick } from "./panel/store";
8
+ // Plugin entry
8
9
  // ===================================================================
9
- // Helpers visual width
10
- // ===================================================================
11
- function charColumns(c) {
12
- const code = c.codePointAt(0) ?? 0;
13
- if (code < 0x20)
14
- return 0;
15
- if (code < 0x7f)
16
- return 1;
17
- if (code < 0xa0)
18
- return 0;
19
- if ((code >= 0x1100 && code <= 0x115f) ||
20
- (code >= 0x2e80 && code <= 0xa4cf) ||
21
- (code >= 0xac00 && code <= 0xd7a3) ||
22
- (code >= 0xf900 && code <= 0xfaff) ||
23
- (code >= 0xfe10 && code <= 0xfe6f) ||
24
- (code >= 0xff01 && code <= 0xff60) ||
25
- (code >= 0xffe0 && code <= 0xffe6) ||
26
- (code >= 0x1f300 && code <= 0x1f64f) ||
27
- (code >= 0x20000 && code <= 0x3fffd))
28
- return 2;
29
- return 1;
30
- }
31
- function visualWidth(s) {
32
- let w = 0;
33
- for (const c of s)
34
- w += charColumns(c);
35
- return w;
36
- }
37
- function truncate(text, maxCols) {
38
- if (visualWidth(text) <= maxCols)
39
- return text;
40
- let cols = 0;
41
- let i = 0;
42
- for (const c of text) {
43
- const w = charColumns(c);
44
- if (cols + w > maxCols - 1)
45
- break;
46
- cols += w;
47
- i += c.length;
48
- }
49
- return text.slice(0, i) + "\u2026";
50
- }
51
- function fmtDurationShort(ms, running) {
52
- if (running && ms < 2000)
53
- return "";
54
- if (ms < 1000)
55
- return (ms / 1000).toFixed(2) + "s";
56
- if (ms < 60000)
57
- return (ms / 1000).toFixed(2) + "s";
58
- const m = Math.floor(ms / 60000);
59
- const s = Math.round((ms % 60000) / 1000);
60
- return `${m}m${s}s`;
61
- }
62
- function fmtTokens(n) {
63
- if (n < 1000)
64
- return `${n}`;
65
- if (n < 1000000)
66
- return `${(n / 1000).toFixed(1)}k`;
67
- return `${(n / 1000000).toFixed(1)}M`;
68
- }
69
- // ===================================================================
70
- // Color helpers — Morandi palette
71
- // ===================================================================
72
- function rgb(raw) {
73
- if (typeof raw === "string" && raw.startsWith("#")) {
74
- const h = raw.slice(1);
75
- return {
76
- r: parseInt(h.slice(0, 2), 16),
77
- g: parseInt(h.slice(2, 4), 16),
78
- b: parseInt(h.slice(4, 6), 16),
79
- };
80
- }
81
- if (raw && typeof raw === "object") {
82
- const o = raw;
83
- if (typeof o.r === "number" && typeof o.g === "number" && typeof o.b === "number") {
84
- const scale = o.r > 1 || o.g > 1 || o.b > 1 ? 1 : 255;
85
- return { r: Math.round(o.r * scale), g: Math.round(o.g * scale), b: Math.round(o.b * scale) };
86
- }
87
- }
88
- return null;
89
- }
90
- function saturation(r, g, b) {
91
- const max = Math.max(r, g, b) / 255;
92
- const min = Math.min(r, g, b) / 255;
93
- const delta = max - min;
94
- if (delta === 0)
95
- return 0;
96
- const L = (max + min) / 2;
97
- return L <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
98
- }
99
- function desaturateTo(raw, maxSat, fallback) {
100
- const c = rgb(raw);
101
- if (!c)
102
- return fallback;
103
- const sat = saturation(c.r, c.g, c.b);
104
- if (sat <= maxSat) {
105
- return "#" + [c.r, c.g, c.b].map((v) => v.toString(16).padStart(2, "0")).join("");
106
- }
107
- const luma = c.r * 0.299 + c.g * 0.587 + c.b * 0.114;
108
- let lo = 0, hi = 1;
109
- for (let i = 0; i < 12; i++) {
110
- const mid = (lo + hi) / 2;
111
- const nr = Math.round(c.r + (luma - c.r) * mid);
112
- const ng = Math.round(c.g + (luma - c.g) * mid);
113
- const nb = Math.round(c.b + (luma - c.b) * mid);
114
- if (saturation(nr, ng, nb) > maxSat)
115
- lo = mid;
116
- else
117
- hi = mid;
118
- }
119
- const nr = Math.round(c.r + (luma - c.r) * hi);
120
- const ng = Math.round(c.g + (luma - c.g) * hi);
121
- const nb = Math.round(c.b + (luma - c.b) * hi);
122
- return "#" + [nr, ng, nb].map((v) => Math.max(0, Math.min(255, v)).toString(16).padStart(2, "0")).join("");
123
- }
124
- function dimColor(hex, factor = 0.5) {
125
- const c = rgb(hex);
126
- if (!c)
127
- return hex;
128
- const r = Math.round(c.r * factor);
129
- const g = Math.round(c.g * factor);
130
- const b = Math.round(c.b * factor);
131
- return "#" + [r, g, b].map((v) => Math.max(0, Math.min(255, v)).toString(16).padStart(2, "0")).join("");
132
- }
133
- const FALLBACK = {
134
- primary: "#8B9DAF", text: "#C5C5BB", muted: "#7A7A72",
135
- success: "#9CAF8B", warning: "#C5B88D", error: "#B08A8A", border: "#6B6B63",
136
- };
137
- const MAX_SAT = 0.28;
138
- /** Entry line left prefix: icon + space + status dot + space */
139
- const LEFT_PAD = 4;
140
- /** Detail row indent: two spaces */
141
- const INDENT = 2;
142
- function safeErrorMsg(err) {
143
- if (!err)
144
- return "";
145
- if (typeof err === "string")
146
- return err;
147
- if (typeof err === "object")
148
- return String(err.message || err.code || "");
149
- return "";
150
- }
151
- // ===================================================================
152
- // Sidebar component
153
- // ===================================================================
154
- // 模块级缓存:各 session 的 entry 状态独立存储,不随当前视图切换而清除。
155
- const globalEntryCache = new Map();
156
- // 模块级刷新信号:外部(如斜杠命令)触发清除后 +1,组件 scan 依赖它以重扫。
157
- const [clearTick, setClearTick] = createSignal(0);
158
- function SubAgentPanel(props) {
159
- const t = createT(() => props.lang());
160
- // ── session data (single-key, true deletion on cleanup) ──
161
- const SESSION_DATA_KEY = `${KV_PREFIX}.session_data`;
162
- const ttlDaysRaw = parseInt(String(props.api.kv.get(`${KV_PREFIX}.ttl_days`, "3")), 10);
163
- const ttlDays = Number.isNaN(ttlDaysRaw) ? 3 : ttlDaysRaw;
164
- const TTL_MS = ttlDays * 24 * 60 * 60 * 1000;
165
- const loadSessionData = () => {
166
- try {
167
- const raw = props.api.kv.get(SESSION_DATA_KEY, "{}");
168
- return JSON.parse(String(raw));
169
- }
170
- catch {
171
- return {};
172
- }
173
- };
174
- const saveSessionData = (data) => {
175
- try {
176
- props.api.kv.set(SESSION_DATA_KEY, JSON.stringify(data));
177
- }
178
- catch { }
179
- };
180
- /** 将任意 session ID 解析为父会话 ID + 是否子会话。
181
- * 通过 SDK session.get(sid).parentID 判断,无 parentID 即为主会话。 */
182
- const resolveParent = (sid) => {
183
- try {
184
- const session = props.api.state.session.get(sid);
185
- const parentID = session?.parentID;
186
- if (parentID)
187
- return { parentSid: parentID, isChild: true };
188
- }
189
- catch { }
190
- return { parentSid: sid, isChild: false };
191
- };
192
- const loadEntries = (sid) => {
193
- const m = new Map();
194
- try {
195
- const { parentSid, isChild } = resolveParent(sid);
196
- const rec = loadSessionData()[parentSid];
197
- if (rec) {
198
- const source = isChild ? rec.children?.[sid]?.entries : rec.entries;
199
- if (source) {
200
- for (const e of source)
201
- m.set(e.id, e);
202
- }
203
- }
204
- }
205
- catch { }
206
- return m;
207
- };
208
- let persistTimer;
209
- const persistEntries = (sid, entries) => {
210
- clearTimeout(persistTimer);
211
- persistTimer = setTimeout(() => {
212
- try {
213
- const data = loadSessionData();
214
- const { parentSid, isChild } = resolveParent(sid);
215
- if (isChild) {
216
- if (!data[parentSid])
217
- data[parentSid] = { ts: Date.now(), entries: [], scroll: 0, expanded: "", children: {} };
218
- if (!data[parentSid].children)
219
- data[parentSid].children = {};
220
- if (!data[parentSid].children[sid])
221
- data[parentSid].children[sid] = { scroll: 0, expanded: "", entries: [] };
222
- data[parentSid].children[sid] = { ...data[parentSid].children[sid], entries: [...entries.values()] };
223
- }
224
- else {
225
- data[sid] = { ...data[sid], ts: Date.now(), entries: [...entries.values()], children: data[sid]?.children ?? {} };
226
- }
227
- saveSessionData(data);
228
- }
229
- catch { }
230
- }, 200);
231
- };
232
- const persistScroll = (sid, scroll) => {
233
- try {
234
- const data = loadSessionData();
235
- const { parentSid, isChild } = resolveParent(sid);
236
- if (isChild) {
237
- if (!data[parentSid])
238
- data[parentSid] = { ts: Date.now(), entries: [], scroll: 0, expanded: "", children: {} };
239
- if (!data[parentSid].children)
240
- data[parentSid].children = {};
241
- if (!data[parentSid].children[sid])
242
- data[parentSid].children[sid] = { scroll: 0, expanded: "", entries: [] };
243
- data[parentSid].children[sid] = { ...data[parentSid].children[sid], scroll };
244
- }
245
- else {
246
- data[sid] = { ...data[sid], ts: Date.now(), scroll, children: data[sid]?.children ?? {} };
247
- }
248
- saveSessionData(data);
249
- }
250
- catch { }
251
- };
252
- const persistExpanded = (sid, expanded) => {
253
- try {
254
- const data = loadSessionData();
255
- const { parentSid, isChild } = resolveParent(sid);
256
- if (isChild) {
257
- if (!data[parentSid])
258
- data[parentSid] = { ts: Date.now(), entries: [], scroll: 0, expanded: "", children: {} };
259
- if (!data[parentSid].children)
260
- data[parentSid].children = {};
261
- if (!data[parentSid].children[sid])
262
- data[parentSid].children[sid] = { scroll: 0, expanded: "", entries: [] };
263
- data[parentSid].children[sid] = { ...data[parentSid].children[sid], expanded };
264
- }
265
- else {
266
- data[sid] = { ...data[sid], ts: Date.now(), expanded, children: data[sid]?.children ?? {} };
267
- }
268
- saveSessionData(data);
269
- }
270
- catch { }
10
+ function createSidebarSlot(api, panelApi, sig) {
11
+ return {
12
+ order: 60,
13
+ slots: {
14
+ sidebar_content(ctx, input) {
15
+ sig.sessionId = input.session_id;
16
+ return (_jsx(SubAgentPanel, { api: panelApi, theme: ctx.theme.current, lang: sig.lang, maxEntries: sig.maxEntries, sortOrder: sig.sortOrder, scrollMode: sig.scrollMode, sessionId: input.session_id }));
17
+ },
18
+ },
271
19
  };
272
- const cleanupOldSessions = () => {
273
- if (ttlDays <= 0)
274
- return; // 无期限,跳过清理
275
- try {
276
- const data = loadSessionData();
277
- const cutoff = Date.now() - TTL_MS;
278
- let changed = false;
279
- for (const sid of Object.keys(data)) {
280
- if (data[sid].ts < cutoff) {
281
- delete data[sid];
282
- changed = true;
20
+ }
21
+ const tui = async (api) => {
22
+ // ── language ──
23
+ const stored = String(api.kv.get(`${KV_PREFIX}.lang`, ""));
24
+ const initialLang = LANG_META.some((m) => m.code === stored) ? stored : detectLang();
25
+ const [lang, setLang] = createSignal(initialLang);
26
+ const [maxEntries, setMaxEntries] = createSignal(parseInt(String(api.kv.get(`${KV_PREFIX}.max_entries`, "10")), 10) || 10);
27
+ const [sortOrder, setSortOrder] = createSignal(String(api.kv.get(`${KV_PREFIX}.order`, "desc")) === "asc" ? "asc" : "desc");
28
+ const [scrollMode, setScrollMode] = createSignal(String(api.kv.get(`${KV_PREFIX}.scroll_mode`, "wheel")) === "click" ? "click" : "wheel");
29
+ const signals = { lang, setLang, maxEntries, setMaxEntries, sortOrder, setSortOrder, scrollMode, setScrollMode, sessionId: "" };
30
+ // ── V1 PanelApi adapter: wraps the V1 host API into the shared panel contract ──
31
+ const v1Api = {
32
+ kv: api.kv,
33
+ usage: {
34
+ readSessionTokens: (sid) => {
35
+ if (!sid)
36
+ return undefined;
37
+ try {
38
+ const msgs = api.state.session.messages(sid);
39
+ if (msgs) {
40
+ for (let i = msgs.length - 1; i >= 0; i--) {
41
+ const m = msgs[i];
42
+ if (m.role !== "assistant")
43
+ continue;
44
+ const t = m.tokens;
45
+ if (!t || !(Number(t.output) > 0))
46
+ continue;
47
+ const ctx = (Number(t.input) || 0) +
48
+ (Number(t.output) || 0) +
49
+ (Number(t.reasoning) || 0) +
50
+ (Number(t.cache?.read) || 0) +
51
+ (Number(t.cache?.write) || 0);
52
+ if (ctx > 0)
53
+ return ctx;
54
+ }
55
+ }
56
+ return undefined;
283
57
  }
284
- }
285
- if (changed)
286
- saveSessionData(data);
287
- }
288
- catch { }
289
- };
290
- cleanupOldSessions();
291
- const [entryMap, setEntryMapRaw] = createSignal(loadEntries(props.sessionId));
292
- // Wrapped setter — also persists to kv on every mutation
293
- const setEntryMap = (arg) => {
294
- setEntryMapRaw((prev) => {
295
- const next = typeof arg === "function" ? arg(prev) : arg;
296
- // entry 状态落定(done/error)时立即持久化到 KV,跳过常规 debounce,
297
- // 确保跨视图的状态一致性。
298
- let needsImmediateFlush = false;
299
- for (const [id, entry] of next) {
300
- const prevEntry = prev.get(id);
301
- if (prevEntry?.status === "running" && (entry.status === "done" || entry.status === "error" || entry.status === "cancelled")) {
302
- needsImmediateFlush = true;
303
- break;
58
+ catch {
59
+ return undefined;
304
60
  }
305
- }
306
- if (needsImmediateFlush) {
307
- clearTimeout(persistTimer);
61
+ },
62
+ readSessionCost: (sid) => {
63
+ if (!sid)
64
+ return undefined;
308
65
  try {
309
- const data = loadSessionData();
310
- const { parentSid, isChild } = resolveParent(props.sessionId);
311
- if (isChild) {
312
- if (!data[parentSid])
313
- data[parentSid] = { ts: Date.now(), entries: [], scroll: 0, expanded: "", children: {} };
314
- if (!data[parentSid].children)
315
- data[parentSid].children = {};
316
- if (!data[parentSid].children[props.sessionId])
317
- data[parentSid].children[props.sessionId] = { scroll: 0, expanded: "", entries: [] };
318
- data[parentSid].children[props.sessionId] = { ...data[parentSid].children[props.sessionId], entries: [...next.values()] };
319
- }
320
- else {
321
- data[props.sessionId] = { ...data[props.sessionId], ts: Date.now(), entries: [...next.values()], children: data[props.sessionId]?.children ?? {} };
66
+ const session = api.state.session.get(sid);
67
+ if (session?.cost != null && session.cost > 0)
68
+ return session.cost;
69
+ const msgs = api.state.session.messages(sid);
70
+ if (!msgs)
71
+ return undefined;
72
+ let total = 0;
73
+ for (const m of msgs) {
74
+ if (m.role === "assistant" && typeof m.cost === "number")
75
+ total += m.cost;
322
76
  }
323
- saveSessionData(data);
77
+ return total > 0 ? total : undefined;
324
78
  }
325
- catch { }
326
- }
327
- else {
328
- persistEntries(props.sessionId, next);
329
- }
330
- // 同步到模块级缓存,供其他视图读取当前 session 的最新状态
331
- globalEntryCache.set(props.sessionId, new Map(next));
332
- return next;
333
- });
334
- };
335
- const [panelWidth, setPanelWidth] = createSignal(28);
336
- const [open, setOpen] = createSignal((() => { try {
337
- return props.api.kv.get(`${KV_PREFIX}.open`, true);
338
- }
339
- catch {
340
- return true;
341
- } })());
342
- const [expanded, setExpanded] = createSignal((() => {
343
- try {
344
- const { parentSid, isChild } = resolveParent(props.sessionId);
345
- const rec = loadSessionData()[parentSid];
346
- if (rec)
347
- return isChild ? rec.children?.[props.sessionId]?.expanded || undefined : rec.expanded || undefined;
348
- }
349
- catch { }
350
- return undefined;
351
- })());
352
- const [hoveredOpen, setHoveredOpen] = createSignal(undefined);
353
- const [hoveredDismiss, setHoveredDismiss] = createSignal(undefined);
354
- const [hoveredCancel, setHoveredCancel] = createSignal(undefined);
355
- const [hoveredTop, setHoveredTop] = createSignal(false);
356
- const [hoveredMoreAbove, setHoveredMoreAbove] = createSignal(false);
357
- const [hoveredMoreBelow, setHoveredMoreBelow] = createSignal(false);
358
- const [scrollOffset, setScrollOffset] = createSignal((() => {
359
- try {
360
- const { parentSid, isChild } = resolveParent(props.sessionId);
361
- const rec = loadSessionData()[parentSid];
362
- return isChild ? rec?.children?.[props.sessionId]?.scroll ?? 0 : rec?.scroll ?? 0;
363
- }
364
- catch {
365
- return 0;
366
- }
367
- })());
368
- const [now, setNow] = createSignal(Date.now());
369
- const [renderTick, setRenderTick] = createSignal(0);
370
- let boxEl;
371
- let disposed = false;
372
- /** Total context tokens for a sub-agent session.
373
- * Matches opencode-visual-cache's "总计": last assistant message's input + cache.read. */
374
- const readSessionTokens = (sid) => {
375
- if (!sid)
376
- return undefined;
377
- try {
378
- const msgs = props.api.state.session.messages(sid);
379
- if (msgs) {
380
- for (let i = msgs.length - 1; i >= 0; i--) {
381
- const m = msgs[i];
382
- if (m.role !== "assistant")
383
- continue;
384
- const t = m.tokens;
385
- if (!t)
386
- continue;
387
- const cache = t.cache;
388
- const ctx = (Number(t.input) || 0) + (cache?.read ?? 0);
389
- if (ctx > 0)
390
- return ctx;
391
- }
392
- }
393
- return undefined;
394
- }
395
- catch {
396
- return undefined;
397
- }
398
- };
399
- /** Sum USD cost from a session's messages.
400
- * Prefers the database-level aggregate (`session.cost`) which is not affected
401
- * by the sync layer's `limit: 100` message window. Falls back to message
402
- * traversal when the aggregate is unavailable (older SDK versions). */
403
- const readSessionCost = (sid) => {
404
- if (!sid)
405
- return undefined;
406
- try {
407
- const session = props.api.state.session.get(sid);
408
- if (session?.cost != null && session.cost > 0)
409
- return session.cost;
410
- const msgs = props.api.state.session.messages(sid);
411
- if (!msgs)
412
- return undefined;
413
- let total = 0;
414
- for (const m of msgs) {
415
- if (m.role === "assistant" && typeof m.cost === "number")
416
- total += m.cost;
417
- }
418
- return total > 0 ? total : undefined;
419
- }
420
- catch {
421
- return undefined;
422
- }
423
- };
424
- /** Last assistant message's modelID for a sub-agent session. */
425
- const readSessionModel = (sid) => {
426
- if (!sid)
427
- return undefined;
428
- try {
429
- const msgs = props.api.state.session.messages(sid);
430
- if (msgs) {
431
- for (let i = msgs.length - 1; i >= 0; i--) {
432
- const m = msgs[i];
433
- if (m.role === "assistant" && m.modelID)
434
- return String(m.modelID);
79
+ catch {
80
+ return undefined;
435
81
  }
436
- }
437
- return undefined;
438
- }
439
- catch {
440
- return undefined;
441
- }
442
- };
443
- /** Todo completion stats for a sub-agent session.
444
- * `done` counts completed + cancelled items. */
445
- const readSessionTodo = (sid) => {
446
- if (!sid)
447
- return undefined;
448
- try {
449
- const todos = props.api.state.session.todo(sid);
450
- if (!todos || todos.length === 0)
451
- return undefined;
452
- let done = 0;
453
- for (const t of todos) {
454
- if (t.status === "completed" || t.status === "cancelled")
455
- done++;
456
- }
457
- return { total: todos.length, done };
458
- }
459
- catch {
460
- return undefined;
461
- }
462
- };
463
- // ── upsert ──
464
- const upsertEntry = (partial) => {
465
- setEntryMap((prev) => {
466
- const existing = prev.get(partial.id);
467
- const next = new Map(prev);
468
- const nowTs = Date.now();
469
- const e = partial.status;
470
- const ended = e === "done" || e === "error" || e === "cancelled";
471
- next.set(partial.id, {
472
- ...(existing ?? { startedAt: nowTs }),
473
- ...partial,
474
- startedAt: existing?.startedAt || partial.startedAt || nowTs,
475
- endedAt: ended ? (existing?.endedAt || nowTs) : undefined,
476
- });
477
- return next;
478
- });
479
- };
480
- // ── cancel helpers ──
481
- const isDescendantOf = (childId, rootId) => {
482
- const visited = new Set();
483
- try {
484
- let current = props.api.state.session.get(childId);
485
- while (current?.parentID) {
486
- if (visited.has(current.id))
487
- return false;
488
- visited.add(current.id);
489
- if (current.parentID === rootId)
490
- return true;
491
- current = props.api.state.session.get(current.parentID);
492
- }
493
- }
494
- catch { }
495
- return false;
496
- };
497
- const settleOnIdle = (entry) => {
498
- if (entry.status === "cancel_requested" && entry.abortAccepted)
499
- return "cancelled";
500
- return "done";
501
- };
502
- const cancelEntry = async (entry) => {
503
- const childId = entry.sessionId;
504
- if (!childId) {
505
- props.api.ui.toast({
506
- title: entry.title || entry.agent,
507
- message: t("cancel.label") + ": " + t("cancel.no_session"),
508
- });
509
- return;
510
- }
511
- try {
512
- const child = props.api.state.session.get(childId);
513
- if (!child?.parentID) {
514
- props.api.ui.toast({
515
- title: entry.title || entry.agent,
516
- message: t("cancel.label") + ": " + t("cancel.not_child"),
517
- });
518
- return;
519
- }
520
- }
521
- catch {
522
- props.api.ui.toast({
523
- title: entry.title || entry.agent,
524
- message: t("cancel.label") + ": " + t("cancel.read_error"),
525
- });
526
- return;
527
- }
528
- if (!isDescendantOf(childId, props.sessionId)) {
529
- props.api.ui.toast({
530
- title: entry.title || entry.agent,
531
- message: t("cancel.label") + ": " + t("cancel.outside_tree"),
532
- });
533
- return;
534
- }
535
- try {
536
- const st = props.api.state.session.status(childId);
537
- if (st?.type !== "busy") {
538
- const tokens = readSessionTokens(childId);
539
- const cost = readSessionCost(childId);
540
- upsertEntry({
541
- id: entry.id, title: entry.title, agent: entry.agent, prompt: entry.prompt,
542
- status: "done", sessionId: entry.sessionId,
543
- tokens, cost,
544
- });
545
- return;
546
- }
547
- }
548
- catch {
549
- props.api.ui.toast({
550
- title: entry.title || entry.agent,
551
- message: t("cancel.label") + ": " + t("cancel.status_error"),
552
- });
553
- return;
554
- }
555
- upsertEntry({
556
- id: entry.id, title: entry.title, agent: entry.agent, prompt: entry.prompt,
557
- status: "cancel_requested", sessionId: entry.sessionId,
558
- cancelRequestedAt: Date.now(), abortAccepted: false, cancelReason: "manual",
559
- });
560
- try {
561
- await props.api.client.session.abort({ sessionID: childId });
562
- upsertEntry({
563
- id: entry.id, title: entry.title, agent: entry.agent, prompt: entry.prompt,
564
- status: "cancel_requested", sessionId: entry.sessionId,
565
- abortAccepted: true,
566
- });
567
- props.api.ui.toast({ message: t("cancel.label") + ": " + t("cancel.sent") });
568
- }
569
- catch (err) {
570
- upsertEntry({
571
- id: entry.id, title: entry.title, agent: entry.agent, prompt: entry.prompt,
572
- status: "error", sessionId: entry.sessionId,
573
- error: String(err),
574
- });
575
- props.api.ui.toast({
576
- title: entry.title || entry.agent,
577
- message: t("cancel.label") + ": " + t("cancel.failed"),
578
- });
579
- }
580
- };
581
- // ── event handlers ──
582
- const handlePartUpdated = (event) => {
583
- const e = event;
584
- const props_ = e.properties;
585
- const part = props_?.part;
586
- if (!part)
587
- return;
588
- // SubtaskPart
589
- if (part.type === "subtask") {
590
- const agent = String(part.agent ?? "?");
591
- const prompt = String(part.prompt ?? "");
592
- const desc = String(part.description ?? "");
593
- const title = desc || truncate(prompt.replace(/\n/g, " ").replace(/\s+/g, " ").trim(), 40);
594
- const id = `sub:${String(part.id ?? crypto.randomUUID())}`;
595
- const subSid = part.sessionID !== undefined ? String(part.sessionID) : undefined;
596
- const partModel = part.model;
597
- const modelId = partModel?.modelID ? String(partModel.modelID) : undefined;
598
- upsertEntry({ id, title, agent, prompt, sessionId: subSid, status: "running", model: modelId });
599
- }
600
- // ToolPart
601
- if (part.type === "tool") {
602
- const tool = String(part.tool ?? "");
603
- if (!SUBAGENT_TOOLS.has(tool))
604
- return;
605
- const st = part.state;
606
- const rawStatus = String(st?.status ?? "");
607
- // Only create entries for tool calls that actually entered execution.
608
- // "pending" / empty → state unknown yet, wait for next event
609
- if (rawStatus === "pending" || rawStatus === "")
610
- return;
611
- // "error" → tool call failed, sub-agent never spawned.
612
- // Only update an existing entry (e.g. previously running → now error),
613
- // never create a new one.
614
- if (rawStatus === "error") {
615
- const id = `tool:${String(part.id ?? "")}`;
616
- if (!part.id)
617
- return;
618
- const existing = entryMap().get(id);
619
- if (existing) {
620
- upsertEntry({ id, title: existing.title, agent: existing.agent, prompt: existing.prompt, status: "error" });
621
- }
622
- return;
623
- }
624
- // rawStatus is "running" or "completed" — tool entered execution, track it.
625
- const input = st?.input;
626
- let status = "running";
627
- if (rawStatus === "completed")
628
- status = "done";
629
- // Background tasks: tool completion ≠ agent completion — keep running until session.idle
630
- // Only keep running if state metadata confirms a child session was spawned;
631
- // otherwise (failed spawn, invalid agent) mark as done so the entry isn't stuck forever.
632
- if ((input?.run_in_background === true || input?.background === true) && status === "done") {
633
- const stMetaCheck = st?.metadata;
634
- const hasChild = stMetaCheck?.session_id !== undefined || stMetaCheck?.sessionId !== undefined;
635
- if (hasChild)
636
- status = "running";
637
- }
638
- const agent = String(part.subagent_type ?? input?.subagent_type ?? input?.category ?? tool);
639
- const prompt = String(input?.prompt ?? part.description ?? "");
640
- const desc = input?.description !== undefined ? String(input.description) : "";
641
- const title = desc || truncate(prompt.replace(/\n/g, " ").replace(/\s+/g, " ").trim(), 40);
642
- const id = `tool:${String(part.id ?? crypto.randomUUID())}`;
643
- // Child session ID lives in state-level metadata (ToolStateCompleted.metadata),
644
- // injected by the tool executor. ToolPart.sessionID is the parent session.
645
- const stMeta = st?.metadata;
646
- const subSid = stMeta?.session_id !== undefined ? String(stMeta.session_id)
647
- : stMeta?.sessionId !== undefined ? String(stMeta.sessionId)
648
- : undefined;
649
- upsertEntry({ id, title, agent, prompt, sessionId: subSid, status });
650
- }
651
- };
652
- const handleSessionEnd = (event, status) => {
653
- const e = event;
654
- const props_ = e.properties;
655
- const sid = String(props_?.sessionID ?? "");
656
- if (!sid)
657
- return;
658
- const sessionTokens = readSessionTokens(sid);
659
- const sessionCost = readSessionCost(sid);
660
- const sessionModel = readSessionModel(sid);
661
- const sessionTodo = readSessionTodo(sid);
662
- let sessionAgent;
663
- let errorMsg;
664
- try {
665
- const s = props.api.state.session.get(sid);
666
- sessionAgent = s?.agent;
667
- if (status === "error") {
668
- const evtErr = props_?.error;
669
- errorMsg = safeErrorMsg(evtErr) || safeErrorMsg(props_?.message);
670
- if (!errorMsg) {
671
- const msgs = props.api.state.session.messages(sid);
82
+ },
83
+ readSessionModel: (sid) => {
84
+ if (!sid)
85
+ return undefined;
86
+ try {
87
+ const msgs = api.state.session.messages(sid);
672
88
  if (msgs) {
673
89
  for (let i = msgs.length - 1; i >= 0; i--) {
674
90
  const m = msgs[i];
675
- if (m.role === "assistant" && m.error) {
676
- errorMsg = safeErrorMsg(m.error);
677
- break;
678
- }
91
+ if (m.role === "assistant" && m.modelID)
92
+ return String(m.modelID);
679
93
  }
680
94
  }
95
+ return undefined;
681
96
  }
682
- }
683
- }
684
- catch { }
685
- // 在给定的 entries Map 中查找并更新匹配的子代理 entry。
686
- // 返回 true 表示找到并更新了,false 表示未找到。
687
- const tryMatchAndUpdate = (entriesMap, targetSid, targetStatus, nowTs) => {
688
- // 精确匹配:sessionId 对得上 + 状态为 running / cancel_requested
689
- for (const [, entry] of entriesMap) {
690
- if (entry.sessionId === targetSid && (entry.status === "running" || entry.status === "cancel_requested")) {
691
- const finalStatus = targetStatus === "error" ? "error" : settleOnIdle(entry);
692
- entry.status = finalStatus;
693
- entry.endedAt = nowTs;
694
- entry.tokens = entry.tokens ?? sessionTokens;
695
- entry.cost = entry.cost ?? sessionCost;
696
- entry.model = entry.model ?? sessionModel;
697
- entry.todoTotal = entry.todoTotal ?? sessionTodo?.total;
698
- entry.todoDone = entry.todoDone ?? sessionTodo?.done;
699
- entry.error = errorMsg || entry.error;
700
- return true;
97
+ catch {
98
+ return undefined;
701
99
  }
702
- }
703
- // 回退:sessionId 未关联但 agent 名匹配 + 状态为 running / cancel_requested
704
- if (sessionAgent) {
705
- const normalize = (s) => s.toLowerCase().replace(/[^a-z0-9-]/g, "");
706
- const saNorm = normalize(sessionAgent);
707
- let best = null;
708
- for (const [, entry] of entriesMap) {
709
- if (entry.status !== "running" && entry.status !== "cancel_requested")
710
- continue;
711
- const eaNorm = normalize(entry.agent);
712
- if (!eaNorm || !saNorm)
713
- continue;
714
- if (!eaNorm.includes(saNorm) && !saNorm.includes(eaNorm))
715
- continue;
716
- const gap = nowTs - (entry.startedAt || 0);
717
- if (!best || gap > best.gap)
718
- best = { entry, gap };
719
- }
720
- if (!best) {
721
- for (const [, entry] of entriesMap) {
722
- if (entry.status !== "running" && entry.status !== "cancel_requested")
723
- continue;
724
- if (entry.sessionId)
725
- continue;
726
- const gap = nowTs - (entry.startedAt || 0);
727
- if (!best || gap > best.gap)
728
- best = { entry, gap };
100
+ },
101
+ readSessionTodo: (sid) => {
102
+ if (!sid)
103
+ return undefined;
104
+ try {
105
+ const todos = api.state.session.todo(sid);
106
+ if (!todos || todos.length === 0)
107
+ return undefined;
108
+ let done = 0;
109
+ for (const t of todos) {
110
+ if (t.status === "completed" || t.status === "cancelled")
111
+ done++;
729
112
  }
113
+ return { total: todos.length, done };
730
114
  }
731
- if (best) {
732
- const finalStatus = targetStatus === "error" ? "error" : settleOnIdle(best.entry);
733
- best.entry.status = finalStatus;
734
- best.entry.endedAt = nowTs;
735
- best.entry.tokens = best.entry.tokens ?? sessionTokens;
736
- best.entry.cost = best.entry.cost ?? sessionCost;
737
- best.entry.model = best.entry.model ?? sessionModel;
738
- best.entry.todoTotal = best.entry.todoTotal ?? sessionTodo?.total;
739
- best.entry.todoDone = best.entry.todoDone ?? sessionTodo?.done;
740
- best.entry.sessionId = targetSid;
741
- best.entry.error = errorMsg || best.entry.error;
742
- return true;
115
+ catch {
116
+ return undefined;
743
117
  }
118
+ },
119
+ },
120
+ session: {
121
+ get: (sid) => { try {
122
+ return api.state.session.get(sid);
744
123
  }
745
- return false;
746
- };
747
- setEntryMap((prev) => {
748
- let changed = false;
749
- const next = new Map(prev);
750
- for (const [id, entry] of next) {
751
- if (entry.sessionId !== sid)
752
- continue;
753
- if (entry.status !== "running" && entry.status !== "done" && entry.status !== "cancel_requested")
754
- continue;
755
- // Skip parent session idle — subagent entries belong to child sessions only
756
- if (sid === props.sessionId)
757
- continue;
758
- // For "done" entries (sync tasks completed before session.idle), only backfill tokens/cost
759
- const alreadySettled = entry.status !== "running" && entry.status !== "cancel_requested";
760
- const finalStatus = status === "error" ? "error" : settleOnIdle(entry);
761
- next.set(id, {
762
- ...entry,
763
- ...(alreadySettled ? {} : { status: finalStatus, endedAt: Date.now() }),
764
- tokens: entry.tokens ?? sessionTokens,
765
- cost: entry.cost ?? sessionCost,
766
- model: entry.model ?? sessionModel,
767
- todoTotal: entry.todoTotal ?? sessionTodo?.total,
768
- todoDone: entry.todoDone ?? sessionTodo?.done,
769
- error: errorMsg || entry.error,
770
- });
771
- changed = true;
772
- }
773
- if (!changed && sessionAgent) {
774
- const nowTs = Date.now();
775
- const normalize = (s) => s.toLowerCase().replace(/[^a-z0-9-]/g, "");
776
- const saNorm = normalize(sessionAgent);
777
- let best = null;
778
- // Phase 1: try matching by agent name(agent 名有交集)
779
- for (const [id, entry] of next) {
780
- if (entry.status !== "running" && entry.status !== "cancel_requested")
781
- continue;
782
- const eaNorm = normalize(entry.agent);
783
- if (!eaNorm || !saNorm)
784
- continue;
785
- if (!eaNorm.includes(saNorm) && !saNorm.includes(eaNorm))
786
- continue;
787
- const gap = nowTs - (entry.startedAt || 0);
788
- if (!best || gap > best.gap)
789
- best = { id, gap };
790
- }
791
- // Phase 2: if agent name has no overlap (e.g. category calls: agent="deep" vs sessionAgent="Sisyphus-Junior"),
792
- // fall back to time proximity for entries that have no sessionId yet
793
- if (!best) {
794
- for (const [id, entry] of next) {
795
- if (entry.status !== "running" && entry.status !== "cancel_requested")
796
- continue;
797
- if (entry.sessionId)
798
- continue;
799
- const gap = nowTs - (entry.startedAt || 0);
800
- if (!best || gap > best.gap)
801
- best = { id, gap };
802
- }
803
- }
804
- if (best) {
805
- const entry = next.get(best.id);
806
- const finalStatus = status === "error" ? "error" : settleOnIdle(entry);
807
- next.set(best.id, {
808
- ...entry, status: finalStatus, endedAt: nowTs,
809
- tokens: sessionTokens || entry.tokens,
810
- cost: sessionCost || entry.cost,
811
- sessionId: sid,
812
- error: errorMsg || entry.error,
813
- });
814
- changed = true;
815
- }
124
+ catch {
125
+ return undefined;
126
+ } },
127
+ status: (sid) => { try {
128
+ return api.state.session.status(sid);
816
129
  }
817
- return changed ? next : prev;
818
- });
819
- // 当子代理所属的父 session 与当前视图不同时,通过模块级缓存定位
820
- // 并更新父 session entry 状态,随后写回 KV。
821
- try {
822
- const sessionObj = props.api.state.session.get(sid);
823
- const parentSid = sessionObj?.parentID;
824
- if (parentSid && parentSid !== props.sessionId) {
825
- // 优先从模块级缓存获取父 session 的 entries,不受当前视图切换影响
826
- const parentCache = globalEntryCache.get(parentSid);
827
- const nowTs = Date.now();
828
- let found = false;
829
- if (parentCache) {
830
- found = tryMatchAndUpdate(parentCache, sid, status, nowTs);
831
- }
832
- // 缓存未命中时回退到 KV 读取
833
- if (!found) {
834
- const data = loadSessionData();
835
- const rec = data[parentSid];
836
- if (rec?.entries) {
837
- const fallbackMap = new Map(rec.entries.map((e) => [e.id, e]));
838
- found = tryMatchAndUpdate(fallbackMap, sid, status, nowTs);
839
- if (found) {
840
- // 回退命中后写入 KV 并回填缓存
841
- data[parentSid] = { ...rec, ts: nowTs, entries: [...fallbackMap.values()] };
842
- saveSessionData(data);
843
- globalEntryCache.set(parentSid, fallbackMap);
844
- }
845
- }
846
- }
847
- // 将模块级缓存中的最新状态同步到 KV
848
- if (found && parentCache) {
849
- const data = loadSessionData();
850
- data[parentSid] = { ...data[parentSid], ts: nowTs, entries: [...parentCache.values()] };
851
- saveSessionData(data);
852
- }
130
+ catch {
131
+ return undefined;
132
+ } },
133
+ messages: (sid) => { try {
134
+ return api.state.session.messages(sid);
853
135
  }
854
- }
855
- catch { }
856
- // Delayed backfill: re-read data after state sync catches up, to capture the final
857
- // token/cost values that may not have been available when session.idle fired.
858
- setTimeout(() => {
859
- if (disposed)
860
- return;
861
- const finalTokens = readSessionTokens(sid);
862
- const finalCost = readSessionCost(sid);
863
- const finalModel = readSessionModel(sid);
864
- const finalTodo = readSessionTodo(sid);
865
- setEntryMap((prev) => {
866
- let changed = false;
867
- const next = new Map(prev);
868
- for (const [id, entry] of next) {
869
- if (entry.sessionId !== sid)
870
- continue;
871
- const t = finalTokens ?? entry.tokens;
872
- const c = finalCost ?? entry.cost;
873
- const m = finalModel ?? entry.model;
874
- const tt = finalTodo?.total ?? entry.todoTotal;
875
- const td = finalTodo?.done ?? entry.todoDone;
876
- if (t !== entry.tokens || c !== entry.cost || m !== entry.model ||
877
- tt !== entry.todoTotal || td !== entry.todoDone) {
878
- next.set(id, { ...entry, tokens: t, cost: c, model: m, todoTotal: tt, todoDone: td });
879
- changed = true;
880
- }
881
- }
882
- return changed ? next : prev;
883
- });
884
- bump();
885
- }, 150);
886
- };
887
- // ── bumpRenderTick: force re-render (visual-cache pattern) ──
888
- const bump = () => setRenderTick((v) => v + 1);
889
- onMount(() => {
890
- // Fast clock for smooth time display, separate from token polling
891
- const clock = setInterval(() => { setNow(Date.now()); bump(); }, 100);
892
- // Token poll — runs every 500ms for running entries
893
- const tokenTimer = setInterval(() => {
894
- untrack(() => {
895
- setEntryMapRaw((prev) => {
896
- let changed = false;
897
- const next = new Map(prev);
898
- for (const [id, entry] of next) {
899
- if (entry.status === "running" && entry.sessionId) {
900
- // Only read from child sessions, never the parent
901
- let isChild = false;
902
- try {
903
- const s = props.api.state.session.get(entry.sessionId);
904
- isChild = s?.parentID === props.sessionId;
905
- }
906
- catch { }
907
- if (!isChild)
908
- continue;
909
- const total = readSessionTokens(entry.sessionId);
910
- const todo = readSessionTodo(entry.sessionId);
911
- const model = entry.model ?? readSessionModel(entry.sessionId);
912
- const nextEntry = { ...entry };
913
- if (total !== undefined && total !== entry.tokens) {
914
- nextEntry.tokens = total;
915
- changed = true;
916
- }
917
- if (todo !== undefined) {
918
- if (todo.total !== entry.todoTotal || todo.done !== entry.todoDone) {
919
- nextEntry.todoTotal = todo.total;
920
- nextEntry.todoDone = todo.done;
921
- changed = true;
922
- }
923
- }
924
- if (model && !entry.model) {
925
- nextEntry.model = model;
926
- changed = true;
927
- }
928
- if (changed)
929
- next.set(id, nextEntry);
930
- }
931
- }
932
- return changed ? next : prev;
933
- });
934
- });
935
- bump();
936
- }, 500);
937
- bump();
938
- const unsubPart = props.api.event.on("message.part.updated", (e) => {
939
- handlePartUpdated(e);
940
- bump();
941
- });
942
- const unsubMsg = props.api.event.on("message.updated", () => bump());
943
- const unsubIdle = props.api.event.on("session.idle", (e) => {
944
- handleSessionEnd(e, "done");
945
- bump();
946
- });
947
- const unsubError = props.api.event.on("session.error", (e) => {
948
- handleSessionEnd(e, "error");
949
- bump();
950
- });
951
- onCleanup(() => {
952
- disposed = true;
953
- clearInterval(clock);
954
- clearInterval(tokenTimer);
955
- unsubPart();
956
- unsubMsg();
957
- unsubIdle();
958
- unsubError();
959
- });
960
- });
961
- // ── session‑switch & initial‑load scan ──
962
- // On session change: load from kv (entries survive component unmount), then scan+merge.
963
- // On same session: only scan+merge (keep event‑driven running entries).
964
- let lastSid = props.sessionId;
965
- let lastTick = 0;
966
- createEffect(() => {
967
- const sid = props.sessionId;
968
- const switched = sid !== lastSid;
969
- lastSid = sid;
970
- const tick = clearTick(); // 外部触发清除时 +1,effect 重跑
971
- const forceReload = tick !== lastTick && !switched;
972
- lastTick = tick;
973
- const t = setTimeout(() => {
974
- untrack(() => {
975
- if (switched) {
976
- const { parentSid, isChild } = resolveParent(sid);
977
- const data = loadSessionData();
978
- const saved = isChild
979
- ? data[parentSid]?.children?.[sid]?.scroll ?? 0
980
- : data[sid]?.scroll ?? 0;
981
- setScrollOffset(saved);
982
- // 刷新父会话的访问时间 TTL,防止活跃会话的数据过期
983
- if (!isChild && data[sid]?.entries?.length) {
984
- data[sid].ts = Date.now();
985
- saveSessionData(data);
986
- }
987
- }
988
- // scan uses setEntryMapRaw — ephemeral data, not persisted to kv.
989
- // Only event-driven changes (handlePartUpdated, handleSessionEnd) persist.
990
- setEntryMapRaw((prev) => {
991
- // 优先从模块级缓存加载,KV 仅作缓存未命中时的回退
992
- const next = (switched || forceReload)
993
- ? new Map(globalEntryCache.get(sid) ?? loadEntries(sid))
994
- : new Map(prev);
995
- // 从 KV 加载当前会话的清除名单,扫描时跳过被手动清除的历史条目
996
- const { parentSid: scanPSid, isChild: scanChild } = resolveParent(sid);
997
- const scanRec = loadSessionData()[scanPSid];
998
- const clearedIds = new Set(scanChild ? scanRec?.children?.[sid]?.clearedIds : scanRec?.clearedIds);
999
- try {
1000
- const msgs = props.api.state.session.messages(sid);
1001
- if (msgs && msgs.length) {
1002
- for (const msg of msgs) {
1003
- const parts = props.api.state.part(msg.id) ?? [];
1004
- for (const partRaw of parts) {
1005
- const part = partRaw;
1006
- // Subtask entries are purely event-driven — never created by scan.
1007
- // (SubtaskPart exists from spawn, not completion, so we cannot infer status.)
1008
- if (part.type === "tool") {
1009
- const tool = String(part.tool ?? "");
1010
- if (!SUBAGENT_TOOLS.has(tool))
1011
- continue;
1012
- const id = `tool:${String(part.id ?? "")}`;
1013
- if (!part.id)
1014
- continue;
1015
- const st = part.state;
1016
- const rawStatus = String(st?.status ?? "");
1017
- const exists = next.get(id);
1018
- // 已手动清除的条目:scan 发现但不在内存 → 跳过重建
1019
- if (!exists && clearedIds.has(id))
1020
- continue;
1021
- // Only create entries for tool calls that entered execution.
1022
- // "pending" / empty: skip new entries; allow heuristics for existing ones below.
1023
- if ((rawStatus === "pending" || rawStatus === "") && !exists)
1024
- continue;
1025
- // "error": only update existing, never create a new entry
1026
- if (rawStatus === "error") {
1027
- if (exists && exists.status === "running") {
1028
- next.set(id, { ...exists, status: "error", endedAt: Date.now() });
1029
- }
1030
- continue;
1031
- }
1032
- let status = "running";
1033
- if (rawStatus === "completed")
1034
- status = "done";
1035
- // Background tasks: tool completion ≠ agent completion — keep running until session.idle
1036
- // Only keep running if state metadata confirms a child session was spawned.
1037
- if ((st?.input?.run_in_background === true || st?.input?.background === true) && status === "done") {
1038
- const scanStMeta = st?.metadata;
1039
- const scanHasChild = scanStMeta?.session_id !== undefined || scanStMeta?.sessionId !== undefined;
1040
- if (scanHasChild)
1041
- status = "running";
1042
- }
1043
- // Already settled → skip
1044
- if (exists && exists.status !== "running" && exists.status !== "cancel_requested")
1045
- continue;
1046
- // Running entry with no explicit status improvement from part:
1047
- // try message-level heuristics first, then time-based fallback.
1048
- if (exists && status === "running") {
1049
- if (!rawStatus) {
1050
- const msgTokens = msg?.tokens;
1051
- if (msgTokens && (Number(msgTokens.input) > 0 || Number(msgTokens.output) > 0)) {
1052
- status = "done"; // LLM returned tokens → agent completed
1053
- }
1054
- else if (Date.now() - exists.startedAt > 30 * 60 * 1000) {
1055
- status = "done"; // >30 min idle → assume completed
1056
- }
1057
- else {
1058
- continue;
1059
- }
1060
- }
1061
- else {
1062
- continue;
1063
- }
1064
- }
1065
- // If already tracked as running but tool state says completed/error → update
1066
- // If not tracked → add fresh
1067
- const input = st?.input;
1068
- const agent = String(part.subagent_type ?? input?.subagent_type ?? tool);
1069
- const prompt = String(input?.prompt ?? part.description ?? "");
1070
- const desc = input?.description !== undefined ? String(input.description) : "";
1071
- const title = desc || truncate(prompt.replace(/\n/g, " ").trim(), 40);
1072
- let tokens;
1073
- const scanStMeta2 = st?.metadata;
1074
- const scanSubSid = scanStMeta2?.session_id !== undefined ? String(scanStMeta2.session_id)
1075
- : scanStMeta2?.sessionId !== undefined ? String(scanStMeta2.sessionId)
1076
- : undefined;
1077
- if (scanSubSid)
1078
- tokens = readSessionTokens(scanSubSid);
1079
- const ended = status === "done"; // "error" handled above, never reaches here
1080
- next.set(id, {
1081
- id, title, agent, prompt,
1082
- // Preserve existing values (from handleSessionEnd / KV) — scan must not overwrite
1083
- tokens: exists?.tokens ?? tokens,
1084
- sessionId: exists?.sessionId ?? scanSubSid,
1085
- status,
1086
- startedAt: exists?.startedAt || Date.now(),
1087
- endedAt: ended ? (exists?.endedAt || Date.now()) : undefined,
1088
- });
1089
- }
1090
- }
1091
- }
1092
- }
1093
- }
1094
- catch { }
1095
- return next;
1096
- });
1097
- // Reconcile: check running entries against live child session status.
1098
- // Covers session.idle events missed while user was inside a child session.
1099
- setEntryMapRaw((prev) => {
1100
- let changed = false;
1101
- const next = new Map(prev);
1102
- for (const [id, entry] of next) {
1103
- if ((entry.status !== "running" && entry.status !== "cancel_requested") || !entry.sessionId)
1104
- continue;
1105
- try {
1106
- const st = props.api.state.session.status(entry.sessionId);
1107
- if (!st || st.type !== "idle")
1108
- continue;
1109
- const tokens = readSessionTokens(entry.sessionId);
1110
- const cost = readSessionCost(entry.sessionId);
1111
- const finalStatus = entry.status === "cancel_requested" && entry.abortAccepted
1112
- ? "cancelled"
1113
- : "done";
1114
- next.set(id, {
1115
- ...entry, status: finalStatus, endedAt: Date.now(),
1116
- tokens: tokens ?? entry.tokens,
1117
- cost: cost ?? entry.cost,
1118
- });
1119
- changed = true;
1120
- }
1121
- catch { }
1122
- }
1123
- return changed ? next : prev;
1124
- });
1125
- bump();
1126
- });
1127
- }, 150);
1128
- onCleanup(() => clearTimeout(t));
1129
- });
1130
- // ── palette ──
1131
- const pal = createMemo(() => {
1132
- const th = props.theme;
1133
- const sat = (k, fb) => desaturateTo(th[k], MAX_SAT, fb);
1134
- return {
1135
- primary: sat("primary", FALLBACK.primary),
1136
- text: sat("text", FALLBACK.text),
1137
- muted: sat("textMuted", FALLBACK.muted),
1138
- success: sat("success", FALLBACK.success),
1139
- warning: sat("warning", FALLBACK.warning),
1140
- error: sat("error", FALLBACK.error),
1141
- border: sat("border", FALLBACK.border),
1142
- };
1143
- });
1144
- // ── derived signals ──
1145
- // Stable list — only changes when entryMap changes
1146
- const entryList = createMemo(() => {
1147
- const entries = [...entryMap().values()];
1148
- if (props.sortOrder() === "desc") {
1149
- return entries.sort((a, b) => b.startedAt - a.startedAt);
1150
- }
1151
- return entries.sort((a, b) => a.startedAt - b.startedAt);
1152
- });
1153
- const max = props.maxEntries;
1154
- const clampedOffset = createMemo(() => {
1155
- const total = entryList().length;
1156
- const m = max();
1157
- if (total <= m)
1158
- return 0;
1159
- return Math.min(scrollOffset(), total - m);
1160
- });
1161
- const visibleList = createMemo(() => entryList().slice(clampedOffset(), clampedOffset() + max()));
1162
- const hiddenAbove = createMemo(() => clampedOffset());
1163
- const hiddenBelow = createMemo(() => Math.max(0, entryList().length - clampedOffset() - max()));
1164
- // Drop hover state when ↑ more disappears (hiddenAbove hits zero)
1165
- createEffect(() => {
1166
- if (hiddenAbove() === 0)
1167
- setHoveredMoreAbove(false);
1168
- });
1169
- // Reset scroll on sort order change: jump to newest in view
1170
- let sortInitialized = false;
1171
- createEffect(() => {
1172
- props.sortOrder();
1173
- if (!sortInitialized) {
1174
- sortInitialized = true;
1175
- return;
1176
- }
1177
- const total = untrack(() => entryList().length);
1178
- const m = untrack(() => max());
1179
- const target = props.sortOrder() === "desc" ? 0 : Math.max(0, total - m);
1180
- setScrollOffset(target);
1181
- setTimeout(() => {
1182
- try {
1183
- persistScroll(props.sessionId, target);
136
+ catch {
137
+ return undefined;
138
+ } },
139
+ part: (messageID) => { try {
140
+ return api.state.part(messageID);
1184
141
  }
1185
- catch { }
1186
- }, 0);
1187
- });
1188
- // When new entries arrive while viewing the newest end, keep the view at newest
1189
- let prevEntryCount = 0;
1190
- createEffect(() => {
1191
- const total = entryList().length;
1192
- if (prevEntryCount === 0) {
1193
- prevEntryCount = total;
1194
- return;
1195
- }
1196
- if (total === prevEntryCount)
1197
- return;
1198
- const m = max();
1199
- const wasAtNewest = props.sortOrder() === "desc"
1200
- ? untrack(() => scrollOffset() === 0)
1201
- : untrack(() => scrollOffset() >= prevEntryCount - m);
1202
- prevEntryCount = total;
1203
- if (wasAtNewest) {
1204
- const target = props.sortOrder() === "desc" ? 0 : Math.max(0, total - m);
1205
- setScrollOffset(target);
1206
- setTimeout(() => {
1207
- try {
1208
- persistScroll(props.sessionId, target);
142
+ catch {
143
+ return undefined;
144
+ } },
145
+ },
146
+ event: {
147
+ on: (type, cb) => {
148
+ switch (type) {
149
+ case "part.updated":
150
+ return api.event.on("message.part.updated", (e) => cb({ type, payload: { part: e.properties?.part } }));
151
+ case "message.updated":
152
+ return api.event.on("message.updated", () => cb({ type }));
153
+ case "session.idle":
154
+ return api.event.on("session.idle", (e) => cb({ type, payload: e.properties }));
155
+ case "session.error":
156
+ return api.event.on("session.error", (e) => cb({ type, payload: e.properties }));
1209
157
  }
1210
- catch { }
1211
- }, 0);
1212
- }
1213
- });
1214
- const entries = createMemo(() => {
1215
- const nowVal = now();
1216
- return entryList().map((e) => ({
1217
- ...e,
1218
- elapsed: (e.endedAt ?? nowVal) - e.startedAt,
1219
- }));
1220
- });
1221
- const doneCount = createMemo(() => entryList().filter((e) => e.status === "done" || e.status === "cancelled").length);
1222
- const runningCount = createMemo(() => entryList().filter((e) => e.status === "running" || e.status === "cancel_requested").length);
1223
- const errCount = createMemo(() => entryList().filter((e) => e.status === "error").length);
1224
- const anyEntry = () => entryList().length > 0;
1225
- const totalTokens = createMemo(() => {
1226
- let sum = 0;
1227
- for (const e of entryList()) {
1228
- if (e.tokens)
1229
- sum += e.tokens;
1230
- }
1231
- return sum;
1232
- });
1233
- const totalCost = createMemo(() => {
1234
- let sum = 0;
1235
- for (const e of entryList()) {
1236
- if (e.cost)
1237
- sum += e.cost;
1238
- }
1239
- return sum;
1240
- });
1241
- const toggleExpand = (id) => {
1242
- setExpanded((prev) => {
1243
- const next = prev === id ? undefined : id;
1244
- try {
1245
- persistExpanded(props.sessionId, next ?? "");
1246
- }
1247
- catch { }
1248
- return next;
1249
- });
1250
- };
1251
- const sep = () => "\u2500".repeat(Math.max(1, panelWidth()));
1252
- // ── expanded detail right-align ──
1253
- const expandedMaxLabelW = createMemo(() => {
1254
- const labels = [
1255
- t("agent.label"), t("status.label"), t("time.label"), t("tokens.label"),
1256
- t("error.label"), t("cost.label"), t("model.label"), t("todo.label"), t("session.label"),
1257
- ];
1258
- return Math.max(...labels.map(l => visualWidth(l + ": ")));
1259
- });
1260
- const expandedPad = (label) => Math.max(0, expandedMaxLabelW() - visualWidth(label + ": "));
1261
- const expandedValAvail = () => Math.max(6, panelWidth() - INDENT - expandedMaxLabelW());
1262
- // ── header parts for colored spans ──
1263
- const summaryParts = createMemo(() => {
1264
- if (!anyEntry())
1265
- return null;
1266
- const dot = "\u25cf";
1267
- const cost = totalCost();
1268
- return {
1269
- done: `${dot}${doneCount()}`,
1270
- running: runningCount() > 0 ? `${dot}${runningCount()}` : null,
1271
- err: errCount() > 0 ? `${dot}${errCount()}` : null,
1272
- duration: totalTokens() > 0 ? fmtTokens(totalTokens()) : "",
1273
- cost: cost > 0 ? `$${cost.toFixed(2)}` : "",
1274
- };
1275
- });
1276
- const summaryCols = createMemo(() => {
1277
- const p = summaryParts();
1278
- if (!p)
1279
- return 0;
1280
- let w = visualWidth(p.done);
1281
- if (p.running)
1282
- w += 1 + visualWidth(p.running);
1283
- if (p.err)
1284
- w += 1 + visualWidth(p.err);
1285
- w += p.duration ? 1 + visualWidth(p.duration) : 0;
1286
- w += p.cost ? 1 + visualWidth(p.cost) : 0;
1287
- return w;
1288
- });
1289
- const versionText = ` v${PLUGIN_VERSION}`;
1290
- const versionW = visualWidth(versionText);
1291
- const showVersion = createMemo(() => {
1292
- if (!open())
1293
- return false;
1294
- const icon = "\u25bc";
1295
- const need = visualWidth(icon) + 1 + visualWidth(t("panel.title")) + versionW + summaryCols();
1296
- return need <= panelWidth();
1297
- });
1298
- const leftCols = createMemo(() => {
1299
- const icon = open() ? "\u25bc" : "\u25b6";
1300
- let w = visualWidth(icon) + 1 + visualWidth(t("panel.title"));
1301
- if (showVersion())
1302
- w += versionW;
1303
- return w;
1304
- });
1305
- const spacerCols = createMemo(() => {
1306
- if (!anyEntry())
1307
- return 0;
1308
- return Math.max(0, panelWidth() - leftCols() - summaryCols());
1309
- });
1310
- const valueCols = (label) => Math.max(4, panelWidth() - INDENT - visualWidth(label + ": "));
1311
- // ── render ──
1312
- return (_jsxs("box", { border: false, paddingTop: 0, paddingBottom: 0, paddingLeft: 0, paddingRight: 0, flexDirection: "column", gap: 0, ref: boxEl, onSizeChange: () => {
1313
- const w = boxEl ? Math.max(20, boxEl.width ?? 0) : 28;
1314
- setPanelWidth((prev) => (prev === w ? prev : w));
1315
- }, children: [_jsxs("text", { onMouseUp: () => {
1316
- setOpen((o) => {
1317
- const n = !o;
1318
- try {
1319
- props.api.kv.set(`${KV_PREFIX}.open`, n);
1320
- }
1321
- catch { }
1322
- return n;
1323
- });
1324
- bump();
1325
- }, children: [_jsx("span", { style: { fg: pal().muted }, children: renderTick() >= 0 && open() ? "\u25bc " : "\u25b6 " }), _jsx("span", { style: { fg: pal().primary }, children: t("panel.title") }), _jsx(Show, { when: showVersion(), children: _jsx("span", { style: { fg: dimColor(pal().muted, 0.75) }, children: versionText }) }), anyEntry() ? (_jsxs(_Fragment, { children: [_jsx("span", { style: { fg: pal().muted }, children: " ".repeat(spacerCols()) }), _jsx("span", { style: { fg: pal().success }, children: summaryParts().done }), runningCount() > 0 && (_jsxs("span", { style: { fg: pal().warning }, children: [" ", summaryParts().running] })), errCount() > 0 && (_jsxs("span", { style: { fg: pal().error }, children: [" ", summaryParts().err] })), summaryParts().duration ? (_jsxs("span", { style: { fg: pal().muted }, children: [" ", summaryParts().duration] })) : null, summaryParts().cost ? (_jsxs("span", { style: { fg: pal().warning }, children: [" ", summaryParts().cost] })) : null] })) : null] }), _jsxs(Show, { when: open(), children: [_jsx("text", { fg: pal().muted, children: sep() }), _jsx(Show, { when: anyEntry(), fallback: _jsxs("text", { style: { fg: pal().muted }, children: [" ", "> ", t("status.none"), " "] }), children: _jsxs("box", { onMouseScroll: (e) => {
1326
- if (props.scrollMode() === "click")
1327
- return;
1328
- const total = entryList().length;
1329
- const m = max();
1330
- if (total <= m)
1331
- return;
1332
- const dir = e.button === 0 ? 1 : -1;
1333
- setScrollOffset((prev) => {
1334
- const next = Math.max(0, Math.min(prev + dir, total - m));
1335
- try {
1336
- persistScroll(props.sessionId, next);
1337
- }
1338
- catch { }
1339
- return next;
1340
- });
1341
- }, children: [_jsx(Show, { when: hiddenAbove() > 0, children: _jsx("text", { onMouseOver: () => setHoveredMoreAbove(true), onMouseOut: () => setHoveredMoreAbove(false), onMouseUp: () => {
1342
- const total = entryList().length;
1343
- const m = max();
1344
- if (total <= m)
1345
- return;
1346
- const next = Math.max(0, scrollOffset() - m);
1347
- if (next === 0) {
1348
- setTimeout(() => {
1349
- setScrollOffset(next);
1350
- try {
1351
- persistScroll(props.sessionId, next);
1352
- }
1353
- catch { }
1354
- }, 0);
1355
- }
1356
- else {
1357
- setScrollOffset(next);
1358
- try {
1359
- persistScroll(props.sessionId, next);
1360
- }
1361
- catch { }
1362
- }
1363
- }, children: _jsxs("span", { style: { fg: hoveredMoreAbove() ? pal().warning : pal().muted }, children: [" ", "\u2191 ", hiddenAbove(), " ", t("scroll.more")] }) }) }), _jsx(For, { each: visibleList(), children: (entry) => {
1364
- const isExpanded = () => expanded() === entry.id;
1365
- const isRunning = entry.status === "running";
1366
- const isCancelRequested = entry.status === "cancel_requested";
1367
- const isCancelled = entry.status === "cancelled";
1368
- const isError = entry.status === "error";
1369
- const isActiveRunning = isRunning || isCancelRequested;
1370
- const elapsed = () => (entry.endedAt ?? now()) - entry.startedAt;
1371
- const statusDot = () => "\u25cf";
1372
- const statusColor = () => {
1373
- if (isCancelled)
1374
- return pal().muted;
1375
- if (!isActiveRunning)
1376
- return isError ? pal().error : pal().success;
1377
- const t = (Math.sin(((now() % 2000) / 2000) * Math.PI * 2 - Math.PI / 2) + 1) / 2;
1378
- const a = rgb(pal().muted), b = rgb(pal().warning);
1379
- if (!a || !b)
1380
- return pal().warning;
1381
- const r = Math.round(a.r + (b.r - a.r) * t);
1382
- const g = Math.round(a.g + (b.g - a.g) * t);
1383
- const bl = Math.round(a.b + (b.b - a.b) * t);
1384
- return "#" + [r, g, bl].map((v) => Math.max(0, Math.min(255, v)).toString(16).padStart(2, "0")).join("");
1385
- };
1386
- const timeColor = () => isActiveRunning ? pal().warning : isError ? pal().error : pal().muted;
1387
- // Entry label: collapsed shows title only, expanded shows title only too
1388
- const tokenText = () => !isExpanded() && entry.tokens !== undefined && entry.tokens > 0
1389
- ? ` ${fmtTokens(entry.tokens)}`
1390
- : "";
1391
- const timeText = () => !isExpanded() && (elapsed() >= 2000 || entry.endedAt !== undefined)
1392
- ? fmtDurationShort(elapsed(), isActiveRunning)
1393
- : "";
1394
- const suffixW = () => {
1395
- let w = 0;
1396
- const t = timeText();
1397
- if (t)
1398
- w += 1 + visualWidth(t);
1399
- const tk = tokenText();
1400
- if (tk)
1401
- w += visualWidth(tk);
1402
- return w;
1403
- };
1404
- const labelAvail = () => Math.max(6, panelWidth() - LEFT_PAD - suffixW());
1405
- const labelText = () => {
1406
- const max = labelAvail();
1407
- const text = entry.title || entry.agent;
1408
- const truncated = truncate(text, max);
1409
- const pad = Math.max(0, max - visualWidth(truncated));
1410
- return truncated + " ".repeat(pad);
1411
- };
1412
- return (_jsxs(_Fragment, { children: [_jsxs("text", { onMouseUp: () => toggleExpand(entry.id), children: [_jsx("span", { style: { fg: pal().muted }, children: isExpanded() ? "\u25bc" : "\u25b6" }), " ", _jsx("span", { style: { fg: statusColor() }, children: statusDot() }), " ", _jsx("span", { style: { fg: pal().text }, children: labelText() }), timeText() ? (_jsxs(_Fragment, { children: [" ", _jsx("span", { style: { fg: timeColor() }, children: timeText() })] })) : null, tokenText() ? (_jsx("span", { style: { fg: pal().muted }, children: tokenText() })) : null] }), _jsxs(Show, { when: isExpanded(), children: [_jsxs("text", { children: [" ", _jsxs("span", { style: { fg: pal().primary }, children: [t("agent.label"), ": "] }), _jsx("span", { style: { fg: pal().muted }, children: " ".repeat(expandedPad(t("agent.label"))) }), _jsx("span", { style: { fg: pal().muted }, children: entry.agent })] }), _jsxs("text", { children: [" ", _jsxs("span", { style: { fg: pal().primary }, children: [t("status.label"), ": "] }), _jsx("span", { style: { fg: pal().muted }, children: " ".repeat(expandedPad(t("status.label"))) }), _jsx("span", { style: { fg: isActiveRunning ? pal().warning : isCancelled ? pal().muted : isError ? pal().error : pal().success }, children: isActiveRunning ? t("status.running") : isCancelled ? t("status.cancelled") : isError ? t("status.error") : t("status.done") })] }), _jsx(Show, { when: elapsed() >= 2000 || entry.endedAt !== undefined, children: _jsxs("text", { children: [" ", _jsxs("span", { style: { fg: pal().primary }, children: [t("time.label"), ": "] }), _jsx("span", { style: { fg: pal().muted }, children: " ".repeat(expandedPad(t("time.label"))) }), _jsx("span", { style: { fg: pal().muted }, children: fmtDurationShort(elapsed(), isActiveRunning) })] }) }), _jsx(Show, { when: entry.tokens !== undefined, children: _jsxs("text", { children: [" ", _jsxs("span", { style: { fg: pal().primary }, children: [t("tokens.label"), ": "] }), _jsx("span", { style: { fg: pal().muted }, children: " ".repeat(expandedPad(t("tokens.label"))) }), _jsx("span", { style: { fg: pal().muted }, children: fmtTokens(entry.tokens) })] }) }), _jsx(Show, { when: entry.error, children: _jsxs("text", { children: [" ", _jsxs("span", { style: { fg: pal().error }, children: [t("error.label"), ": "] }), _jsx("span", { style: { fg: pal().muted }, children: " ".repeat(expandedPad(t("error.label"))) }), _jsx("span", { style: { fg: pal().error }, children: truncate(String(entry.error), expandedValAvail()) })] }) }), _jsx(Show, { when: entry.cost !== undefined, children: (() => {
1413
- const cost = entry.cost;
1414
- return (_jsxs("text", { children: [" ", _jsxs("span", { style: { fg: pal().primary }, children: [t("cost.label"), ": "] }), _jsx("span", { style: { fg: pal().muted }, children: " ".repeat(expandedPad(t("cost.label"))) }), _jsxs("span", { style: { fg: pal().muted }, children: ["$", cost.toFixed(4)] })] }));
1415
- })() }), _jsx(Show, { when: entry.model, children: _jsxs("text", { children: [" ", _jsxs("span", { style: { fg: pal().primary }, children: [t("model.label"), ": "] }), _jsx("span", { style: { fg: pal().muted }, children: " ".repeat(expandedPad(t("model.label"))) }), _jsx("span", { style: { fg: pal().muted }, children: truncate(entry.model, expandedValAvail()) })] }) }), _jsx(Show, { when: entry.todoTotal !== undefined, children: _jsxs("text", { children: [" ", _jsxs("span", { style: { fg: pal().primary }, children: [t("todo.label"), ": "] }), _jsx("span", { style: { fg: pal().muted }, children: " ".repeat(expandedPad(t("todo.label"))) }), _jsxs("span", { style: { fg: pal().muted }, children: [entry.todoDone, "/", entry.todoTotal] })] }) }), _jsx(Show, { when: entry.sessionId, children: _jsxs("text", { onMouseUp: async () => {
1416
- const sessionId = entry.sessionId;
1417
- if (!sessionId)
1418
- return;
1419
- const result = await copyText(sessionId);
1420
- if (result.copied) {
1421
- props.api.ui.toast({
1422
- variant: "success",
1423
- title: entry.title || entry.agent,
1424
- message: t("session.toast.copied"),
1425
- duration: 2500,
1426
- });
1427
- return;
1428
- }
1429
- props.api.ui.toast({
1430
- variant: "warning",
1431
- title: entry.title || entry.agent,
1432
- message: `${sessionId}\n\n${t("session.toast.copy_failed")}`,
1433
- duration: 8000,
1434
- });
1435
- }, children: [" ", _jsxs("span", { style: { fg: pal().primary }, children: [t("session.label"), ": "] }), _jsx("span", { style: { fg: pal().muted }, children: " ".repeat(expandedPad(t("session.label"))) }), _jsx("span", { style: { fg: pal().muted }, children: truncate(entry.sessionId, expandedValAvail() - visualWidth(" ⎘")) }), _jsx("span", { style: { fg: pal().warning }, children: " \u2398" })] }) }), _jsx(Show, { when: entry.sessionId || isRunning, children: (() => {
1436
- const openPrefix = () => " \u2192 ";
1437
- const openFull = () => entry.sessionId ? openPrefix() + t("open.label") : "";
1438
- const openW = () => entry.sessionId ? visualWidth(openFull()) : 0;
1439
- const cancelLabel = () => ` ${t("cancel.label")}`;
1440
- const dismissLabel = () => ` ${t("dismiss.label")}`;
1441
- const rightW = (isRunning ? visualWidth(dismissLabel()) : 0) + (isRunning && entry.sessionId ? visualWidth(cancelLabel()) : 0);
1442
- const spacerW = () => Math.max(1, panelWidth() - openW() - rightW - 2);
1443
- return (_jsxs("box", { flexDirection: "row", children: [_jsx(Show, { when: entry.sessionId, children: _jsxs("text", { onMouseOver: () => setHoveredOpen(entry.id), onMouseOut: () => setHoveredOpen(undefined), onMouseUp: () => {
1444
- if (entry.sessionId) {
1445
- props.api.route.navigate("session", { sessionID: entry.sessionId });
1446
- }
1447
- }, children: [_jsx("span", { style: { fg: hoveredOpen() === entry.id ? pal().warning : pal().primary }, children: openPrefix() }), _jsx("span", { style: { fg: hoveredOpen() === entry.id ? pal().warning : pal().primary }, children: t("open.label") })] }) }), _jsx("text", { style: { fg: pal().muted }, children: " ".repeat(spacerW()) }), _jsx(Show, { when: isRunning && entry.sessionId, children: _jsx("text", { onMouseOver: () => setHoveredCancel(entry.id), onMouseOut: () => setHoveredCancel(undefined), onMouseUp: () => cancelEntry(entry), children: _jsx("span", { style: { fg: hoveredCancel() === entry.id ? pal().warning : pal().error }, children: cancelLabel() }) }) }), _jsx(Show, { when: isRunning, children: _jsx("text", { onMouseOver: () => setHoveredDismiss(entry.id), onMouseOut: () => setHoveredDismiss(undefined), onMouseUp: () => {
1448
- upsertEntry({ id: entry.id, title: entry.title, agent: entry.agent, prompt: entry.prompt, status: "done" });
1449
- }, children: _jsx("span", { style: { fg: hoveredDismiss() === entry.id ? pal().warning : pal().muted }, children: dismissLabel() }) }) })] }));
1450
- })() })] })] }));
1451
- } }), _jsx(Show, { when: hiddenBelow() > 0 || (props.sortOrder() === "desc" ? scrollOffset() > 0 : entryList().length > max() && clampedOffset() < entryList().length - max()), children: (() => {
1452
- const showMore = hiddenBelow() > 0;
1453
- const showTop = props.sortOrder() === "desc"
1454
- ? scrollOffset() > 0
1455
- : entryList().length > max() && clampedOffset() < entryList().length - max();
1456
- const left = showMore ? ` \u2193 ${hiddenBelow()} ${t("scroll.more")}` : " ";
1457
- const right = props.sortOrder() === "desc"
1458
- ? `\u2191 ${t("scroll.top")}`
1459
- : `\u2193 ${t("scroll.bottom")}`;
1460
- const pad = showTop ? Math.max(1, panelWidth() - visualWidth(left) - visualWidth(right)) : 0;
1461
- return (_jsxs("box", { flexDirection: "row", children: [_jsx("text", { onMouseOver: () => showMore && setHoveredMoreBelow(true), onMouseOut: () => setHoveredMoreBelow(false), onMouseUp: () => {
1462
- if (!showMore)
1463
- return;
1464
- const total = entryList().length;
1465
- const m = max();
1466
- if (total <= m)
1467
- return;
1468
- setScrollOffset((prev) => Math.min(total - m, prev + m));
1469
- try {
1470
- persistScroll(props.sessionId, scrollOffset());
1471
- }
1472
- catch { }
1473
- setHoveredMoreBelow(false);
1474
- }, children: _jsx("span", { style: { fg: showMore && hoveredMoreBelow() ? pal().warning : pal().muted }, children: left }) }), showTop ? (_jsxs(_Fragment, { children: [_jsx("text", { style: { fg: pal().muted }, children: " ".repeat(pad) }), _jsx("text", { onMouseOver: () => setHoveredTop(true), onMouseOut: () => setHoveredTop(false), onMouseUp: () => {
1475
- const total = entryList().length;
1476
- const m = max();
1477
- if (props.sortOrder() === "desc") {
1478
- setScrollOffset(0);
1479
- }
1480
- else {
1481
- setScrollOffset(Math.max(0, total - m));
1482
- }
1483
- setHoveredTop(false);
1484
- }, children: _jsx("span", { style: { fg: hoveredTop() ? pal().warning : pal().muted }, children: right }) })] })) : null] }));
1485
- })() })] }) })] })] }));
1486
- }
1487
- function createSidebarSlot(api, sig) {
1488
- return {
1489
- order: 60,
1490
- slots: {
1491
- sidebar_content(ctx, input) {
1492
- sig.sessionId = input.session_id;
1493
- return (_jsx(SubAgentPanel, { theme: ctx.theme.current, api: api, lang: sig.lang, maxEntries: sig.maxEntries, sortOrder: sig.sortOrder, scrollMode: sig.scrollMode, sessionId: input.session_id }));
1494
158
  },
1495
159
  },
160
+ client: {
161
+ abort: (input) => api.client.session.abort(input).then(() => { }),
162
+ },
163
+ route: {
164
+ navigateSession: (sessionID) => api.route.navigate("session", { sessionID }),
165
+ },
166
+ ui: {
167
+ toast: (message, opts) => api.ui.toast({ ...opts, message }),
168
+ },
169
+ settings: {
170
+ lang: () => lang(),
171
+ maxEntries: () => maxEntries(),
172
+ sortOrder: () => sortOrder(),
173
+ scrollMode: () => scrollMode(),
174
+ },
1496
175
  };
1497
- }
1498
- const KV_PREFIX = "subagent_magazine";
1499
- const tui = async (api) => {
1500
- // ── language ──
1501
- const stored = String(api.kv.get(`${KV_PREFIX}.lang`, ""));
1502
- const initialLang = LANG_META.some((m) => m.code === stored) ? stored : detectLang();
1503
- const [lang, setLang] = createSignal(initialLang);
1504
- const [maxEntries, setMaxEntries] = createSignal(parseInt(String(api.kv.get(`${KV_PREFIX}.max_entries`, "10")), 10) || 10);
1505
- const [sortOrder, setSortOrder] = createSignal(String(api.kv.get(`${KV_PREFIX}.order`, "desc")) === "asc" ? "asc" : "desc");
1506
- const [scrollMode, setScrollMode] = createSignal(String(api.kv.get(`${KV_PREFIX}.scroll_mode`, "wheel")) === "click" ? "click" : "wheel");
1507
- const signals = { lang, setLang, maxEntries, setMaxEntries, sortOrder, setSortOrder, scrollMode, setScrollMode, sessionId: "" };
1508
- api.slots.register(createSidebarSlot(api, signals));
176
+ api.slots.register(createSidebarSlot(api, v1Api, signals));
1509
177
  // ── slash command: /subagent-lang ──
1510
178
  api.command?.register(() => [
1511
179
  {