opencode-subagent-magazine 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +174 -0
- package/dist/_version.d.ts +1 -0
- package/dist/_version.js +2 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +1128 -0
- package/install.mjs +103 -0
- package/package.json +56 -0
- package/src/_version.ts +2 -0
- package/src/index.tsx +1380 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1128 @@
|
|
|
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";
|
|
3
|
+
import { PLUGIN_VERSION } from "./_version";
|
|
4
|
+
/** OpenCode built-in tool names that spawn sub-agents or delegate tasks. */
|
|
5
|
+
const SUBAGENT_TOOLS = new Set(["task", "delegate", "call_omo_agent"]);
|
|
6
|
+
// ===================================================================
|
|
7
|
+
// i18n
|
|
8
|
+
// ===================================================================
|
|
9
|
+
const I18N = {
|
|
10
|
+
zh: {
|
|
11
|
+
"panel.title": "子代理",
|
|
12
|
+
"status.none": "暂无子代理",
|
|
13
|
+
"agent.label": "代理",
|
|
14
|
+
"time.label": "耗时",
|
|
15
|
+
"tokens.label": "上下文",
|
|
16
|
+
"error.label": "错误",
|
|
17
|
+
"model.label": "模型",
|
|
18
|
+
"todo.label": "进度",
|
|
19
|
+
"open.label": "进入会话",
|
|
20
|
+
"cost.label": "费用",
|
|
21
|
+
"scroll.more": "更多",
|
|
22
|
+
"scroll.top": "回顶",
|
|
23
|
+
},
|
|
24
|
+
en: {
|
|
25
|
+
"panel.title": "SubAgent",
|
|
26
|
+
"status.none": "No sub-agents yet",
|
|
27
|
+
"agent.label": "agent",
|
|
28
|
+
"time.label": "time",
|
|
29
|
+
"tokens.label": "tokens",
|
|
30
|
+
"error.label": "error",
|
|
31
|
+
"model.label": "model",
|
|
32
|
+
"todo.label": "todo",
|
|
33
|
+
"open.label": "Open session",
|
|
34
|
+
"cost.label": "cost",
|
|
35
|
+
"scroll.more": "more",
|
|
36
|
+
"scroll.top": "Top",
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
function detectLang() {
|
|
40
|
+
const env = process?.env?.OPENCODE_LANG ?? process?.env?.LANG ?? "";
|
|
41
|
+
if (env.startsWith("zh"))
|
|
42
|
+
return "zh";
|
|
43
|
+
return "en";
|
|
44
|
+
}
|
|
45
|
+
// ===================================================================
|
|
46
|
+
// Helpers — visual width
|
|
47
|
+
// ===================================================================
|
|
48
|
+
function charColumns(c) {
|
|
49
|
+
const code = c.codePointAt(0) ?? 0;
|
|
50
|
+
if (code < 0x20)
|
|
51
|
+
return 0;
|
|
52
|
+
if (code < 0x7f)
|
|
53
|
+
return 1;
|
|
54
|
+
if (code < 0xa0)
|
|
55
|
+
return 0;
|
|
56
|
+
if ((code >= 0x1100 && code <= 0x115f) ||
|
|
57
|
+
(code >= 0x2e80 && code <= 0xa4cf) ||
|
|
58
|
+
(code >= 0xac00 && code <= 0xd7a3) ||
|
|
59
|
+
(code >= 0xf900 && code <= 0xfaff) ||
|
|
60
|
+
(code >= 0xfe10 && code <= 0xfe6f) ||
|
|
61
|
+
(code >= 0xff01 && code <= 0xff60) ||
|
|
62
|
+
(code >= 0xffe0 && code <= 0xffe6) ||
|
|
63
|
+
(code >= 0x1f300 && code <= 0x1f64f) ||
|
|
64
|
+
(code >= 0x20000 && code <= 0x3fffd))
|
|
65
|
+
return 2;
|
|
66
|
+
return 1;
|
|
67
|
+
}
|
|
68
|
+
function visualWidth(s) {
|
|
69
|
+
let w = 0;
|
|
70
|
+
for (const c of s)
|
|
71
|
+
w += charColumns(c);
|
|
72
|
+
return w;
|
|
73
|
+
}
|
|
74
|
+
function truncate(text, maxCols) {
|
|
75
|
+
if (visualWidth(text) <= maxCols)
|
|
76
|
+
return text;
|
|
77
|
+
let cols = 0;
|
|
78
|
+
let i = 0;
|
|
79
|
+
for (const c of text) {
|
|
80
|
+
const w = charColumns(c);
|
|
81
|
+
if (cols + w > maxCols - 1)
|
|
82
|
+
break;
|
|
83
|
+
cols += w;
|
|
84
|
+
i += c.length;
|
|
85
|
+
}
|
|
86
|
+
return text.slice(0, i) + "\u2026";
|
|
87
|
+
}
|
|
88
|
+
function fmtDurationShort(ms, running) {
|
|
89
|
+
if (running && ms < 2000)
|
|
90
|
+
return "";
|
|
91
|
+
if (ms < 1000)
|
|
92
|
+
return (ms / 1000).toFixed(2) + "s";
|
|
93
|
+
if (ms < 60000)
|
|
94
|
+
return (ms / 1000).toFixed(2) + "s";
|
|
95
|
+
const m = Math.floor(ms / 60000);
|
|
96
|
+
const s = Math.round((ms % 60000) / 1000);
|
|
97
|
+
return `${m}m${s}s`;
|
|
98
|
+
}
|
|
99
|
+
function fmtTokens(n) {
|
|
100
|
+
if (n < 1000)
|
|
101
|
+
return `${n}`;
|
|
102
|
+
if (n < 1000000)
|
|
103
|
+
return `${(n / 1000).toFixed(1)}k`;
|
|
104
|
+
return `${(n / 1000000).toFixed(1)}M`;
|
|
105
|
+
}
|
|
106
|
+
// ===================================================================
|
|
107
|
+
// Color helpers — Morandi palette
|
|
108
|
+
// ===================================================================
|
|
109
|
+
function rgb(raw) {
|
|
110
|
+
if (typeof raw === "string" && raw.startsWith("#")) {
|
|
111
|
+
const h = raw.slice(1);
|
|
112
|
+
return {
|
|
113
|
+
r: parseInt(h.slice(0, 2), 16),
|
|
114
|
+
g: parseInt(h.slice(2, 4), 16),
|
|
115
|
+
b: parseInt(h.slice(4, 6), 16),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
if (raw && typeof raw === "object") {
|
|
119
|
+
const o = raw;
|
|
120
|
+
if (typeof o.r === "number" && typeof o.g === "number" && typeof o.b === "number") {
|
|
121
|
+
const scale = o.r > 1 || o.g > 1 || o.b > 1 ? 1 : 255;
|
|
122
|
+
return { r: Math.round(o.r * scale), g: Math.round(o.g * scale), b: Math.round(o.b * scale) };
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
function saturation(r, g, b) {
|
|
128
|
+
const max = Math.max(r, g, b) / 255;
|
|
129
|
+
const min = Math.min(r, g, b) / 255;
|
|
130
|
+
const delta = max - min;
|
|
131
|
+
if (delta === 0)
|
|
132
|
+
return 0;
|
|
133
|
+
const L = (max + min) / 2;
|
|
134
|
+
return L <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
|
|
135
|
+
}
|
|
136
|
+
function desaturateTo(raw, maxSat, fallback) {
|
|
137
|
+
const c = rgb(raw);
|
|
138
|
+
if (!c)
|
|
139
|
+
return fallback;
|
|
140
|
+
const sat = saturation(c.r, c.g, c.b);
|
|
141
|
+
if (sat <= maxSat) {
|
|
142
|
+
return "#" + [c.r, c.g, c.b].map((v) => v.toString(16).padStart(2, "0")).join("");
|
|
143
|
+
}
|
|
144
|
+
const luma = c.r * 0.299 + c.g * 0.587 + c.b * 0.114;
|
|
145
|
+
let lo = 0, hi = 1;
|
|
146
|
+
for (let i = 0; i < 12; i++) {
|
|
147
|
+
const mid = (lo + hi) / 2;
|
|
148
|
+
const nr = Math.round(c.r + (luma - c.r) * mid);
|
|
149
|
+
const ng = Math.round(c.g + (luma - c.g) * mid);
|
|
150
|
+
const nb = Math.round(c.b + (luma - c.b) * mid);
|
|
151
|
+
if (saturation(nr, ng, nb) > maxSat)
|
|
152
|
+
lo = mid;
|
|
153
|
+
else
|
|
154
|
+
hi = mid;
|
|
155
|
+
}
|
|
156
|
+
const nr = Math.round(c.r + (luma - c.r) * hi);
|
|
157
|
+
const ng = Math.round(c.g + (luma - c.g) * hi);
|
|
158
|
+
const nb = Math.round(c.b + (luma - c.b) * hi);
|
|
159
|
+
return "#" + [nr, ng, nb].map((v) => Math.max(0, Math.min(255, v)).toString(16).padStart(2, "0")).join("");
|
|
160
|
+
}
|
|
161
|
+
function dimColor(hex, factor = 0.5) {
|
|
162
|
+
const c = rgb(hex);
|
|
163
|
+
if (!c)
|
|
164
|
+
return hex;
|
|
165
|
+
const r = Math.round(c.r * factor);
|
|
166
|
+
const g = Math.round(c.g * factor);
|
|
167
|
+
const b = Math.round(c.b * factor);
|
|
168
|
+
return "#" + [r, g, b].map((v) => Math.max(0, Math.min(255, v)).toString(16).padStart(2, "0")).join("");
|
|
169
|
+
}
|
|
170
|
+
const FALLBACK = {
|
|
171
|
+
primary: "#8B9DAF", text: "#C5C5BB", muted: "#7A7A72",
|
|
172
|
+
success: "#9CAF8B", warning: "#C5B88D", error: "#B08A8A", border: "#6B6B63",
|
|
173
|
+
};
|
|
174
|
+
const MAX_SAT = 0.28;
|
|
175
|
+
/** Entry line left prefix: icon + space + status dot + space */
|
|
176
|
+
const LEFT_PAD = 4;
|
|
177
|
+
/** Detail row indent: two spaces */
|
|
178
|
+
const INDENT = 2;
|
|
179
|
+
function safeErrorMsg(err) {
|
|
180
|
+
if (!err)
|
|
181
|
+
return "";
|
|
182
|
+
if (typeof err === "string")
|
|
183
|
+
return err;
|
|
184
|
+
if (typeof err === "object")
|
|
185
|
+
return String(err.message || err.code || "");
|
|
186
|
+
return "";
|
|
187
|
+
}
|
|
188
|
+
// ===================================================================
|
|
189
|
+
// Sidebar component
|
|
190
|
+
// ===================================================================
|
|
191
|
+
function SubAgentPanel(props) {
|
|
192
|
+
const t = (key) => I18N[props.lang()][key] ?? key;
|
|
193
|
+
// ── session data (single-key, true deletion on cleanup) ──
|
|
194
|
+
const SESSION_DATA_KEY = `${KV_PREFIX}.session_data`;
|
|
195
|
+
const TTL_MS = 3 * 24 * 60 * 60 * 1000;
|
|
196
|
+
const loadSessionData = () => {
|
|
197
|
+
try {
|
|
198
|
+
const raw = props.api.kv.get(SESSION_DATA_KEY, "{}");
|
|
199
|
+
return JSON.parse(String(raw));
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
return {};
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
const saveSessionData = (data) => {
|
|
206
|
+
try {
|
|
207
|
+
props.api.kv.set(SESSION_DATA_KEY, JSON.stringify(data));
|
|
208
|
+
}
|
|
209
|
+
catch { }
|
|
210
|
+
};
|
|
211
|
+
const loadEntries = (sid) => {
|
|
212
|
+
const m = new Map();
|
|
213
|
+
try {
|
|
214
|
+
const rec = loadSessionData()[sid];
|
|
215
|
+
if (rec?.entries) {
|
|
216
|
+
for (const e of rec.entries)
|
|
217
|
+
m.set(e.id, e);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
catch { }
|
|
221
|
+
return m;
|
|
222
|
+
};
|
|
223
|
+
let persistTimer;
|
|
224
|
+
const persistEntries = (sid, entries) => {
|
|
225
|
+
clearTimeout(persistTimer);
|
|
226
|
+
persistTimer = setTimeout(() => {
|
|
227
|
+
try {
|
|
228
|
+
const data = loadSessionData();
|
|
229
|
+
data[sid] = { ...data[sid], ts: Date.now(), entries: [...entries.values()] };
|
|
230
|
+
saveSessionData(data);
|
|
231
|
+
}
|
|
232
|
+
catch { }
|
|
233
|
+
}, 200);
|
|
234
|
+
};
|
|
235
|
+
const persistScroll = (sid, scroll) => {
|
|
236
|
+
try {
|
|
237
|
+
const data = loadSessionData();
|
|
238
|
+
data[sid] = { ...data[sid], ts: Date.now(), scroll };
|
|
239
|
+
saveSessionData(data);
|
|
240
|
+
}
|
|
241
|
+
catch { }
|
|
242
|
+
};
|
|
243
|
+
const persistExpanded = (sid, expanded) => {
|
|
244
|
+
try {
|
|
245
|
+
const data = loadSessionData();
|
|
246
|
+
data[sid] = { ...data[sid], ts: Date.now(), expanded };
|
|
247
|
+
saveSessionData(data);
|
|
248
|
+
}
|
|
249
|
+
catch { }
|
|
250
|
+
};
|
|
251
|
+
const cleanupOldSessions = () => {
|
|
252
|
+
try {
|
|
253
|
+
const data = loadSessionData();
|
|
254
|
+
const cutoff = Date.now() - TTL_MS;
|
|
255
|
+
let changed = false;
|
|
256
|
+
for (const sid of Object.keys(data)) {
|
|
257
|
+
if (data[sid].ts < cutoff) {
|
|
258
|
+
delete data[sid];
|
|
259
|
+
changed = true;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
if (changed)
|
|
263
|
+
saveSessionData(data);
|
|
264
|
+
}
|
|
265
|
+
catch { }
|
|
266
|
+
};
|
|
267
|
+
cleanupOldSessions();
|
|
268
|
+
const [entryMap, setEntryMapRaw] = createSignal(loadEntries(props.sessionId));
|
|
269
|
+
// Wrapped setter — also persists to kv on every mutation
|
|
270
|
+
const setEntryMap = (arg) => {
|
|
271
|
+
setEntryMapRaw((prev) => {
|
|
272
|
+
const next = typeof arg === "function" ? arg(prev) : arg;
|
|
273
|
+
persistEntries(props.sessionId, next);
|
|
274
|
+
return next;
|
|
275
|
+
});
|
|
276
|
+
};
|
|
277
|
+
const [panelWidth, setPanelWidth] = createSignal(28);
|
|
278
|
+
const [open, setOpen] = createSignal((() => { try {
|
|
279
|
+
return props.api.kv.get(`${KV_PREFIX}.open`, true);
|
|
280
|
+
}
|
|
281
|
+
catch {
|
|
282
|
+
return true;
|
|
283
|
+
} })());
|
|
284
|
+
const [expanded, setExpanded] = createSignal((() => { try {
|
|
285
|
+
return loadSessionData()[props.sessionId]?.expanded || undefined;
|
|
286
|
+
}
|
|
287
|
+
catch {
|
|
288
|
+
return undefined;
|
|
289
|
+
} })());
|
|
290
|
+
const [hoveredOpen, setHoveredOpen] = createSignal(undefined);
|
|
291
|
+
const [hoveredTop, setHoveredTop] = createSignal(false);
|
|
292
|
+
const [scrollOffset, setScrollOffset] = createSignal((() => { try {
|
|
293
|
+
return loadSessionData()[props.sessionId]?.scroll ?? 0;
|
|
294
|
+
}
|
|
295
|
+
catch {
|
|
296
|
+
return 0;
|
|
297
|
+
} })());
|
|
298
|
+
const [now, setNow] = createSignal(Date.now());
|
|
299
|
+
const [renderTick, setRenderTick] = createSignal(0);
|
|
300
|
+
let boxEl;
|
|
301
|
+
let disposed = false;
|
|
302
|
+
/** Total context tokens for a sub-agent session.
|
|
303
|
+
* Matches opencode-visual-cache's "总计": last assistant message's input + cache.read. */
|
|
304
|
+
const readSessionTokens = (sid) => {
|
|
305
|
+
if (!sid)
|
|
306
|
+
return undefined;
|
|
307
|
+
try {
|
|
308
|
+
const msgs = props.api.state.session.messages(sid);
|
|
309
|
+
if (msgs) {
|
|
310
|
+
for (let i = msgs.length - 1; i >= 0; i--) {
|
|
311
|
+
const m = msgs[i];
|
|
312
|
+
if (m.role !== "assistant")
|
|
313
|
+
continue;
|
|
314
|
+
const t = m.tokens;
|
|
315
|
+
if (!t)
|
|
316
|
+
continue;
|
|
317
|
+
const cache = t.cache;
|
|
318
|
+
const ctx = (Number(t.input) || 0) + (cache?.read ?? 0);
|
|
319
|
+
if (ctx > 0)
|
|
320
|
+
return ctx;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
return undefined;
|
|
324
|
+
}
|
|
325
|
+
catch {
|
|
326
|
+
return undefined;
|
|
327
|
+
}
|
|
328
|
+
};
|
|
329
|
+
/** Sum USD cost from a session's messages.
|
|
330
|
+
* Prefers the database-level aggregate (`session.cost`) which is not affected
|
|
331
|
+
* by the sync layer's `limit: 100` message window. Falls back to message
|
|
332
|
+
* traversal when the aggregate is unavailable (older SDK versions). */
|
|
333
|
+
const readSessionCost = (sid) => {
|
|
334
|
+
if (!sid)
|
|
335
|
+
return undefined;
|
|
336
|
+
try {
|
|
337
|
+
const session = props.api.state.session.get(sid);
|
|
338
|
+
if (session?.cost != null && session.cost > 0)
|
|
339
|
+
return session.cost;
|
|
340
|
+
const msgs = props.api.state.session.messages(sid);
|
|
341
|
+
if (!msgs)
|
|
342
|
+
return undefined;
|
|
343
|
+
let total = 0;
|
|
344
|
+
for (const m of msgs) {
|
|
345
|
+
if (m.role === "assistant" && typeof m.cost === "number")
|
|
346
|
+
total += m.cost;
|
|
347
|
+
}
|
|
348
|
+
return total > 0 ? total : undefined;
|
|
349
|
+
}
|
|
350
|
+
catch {
|
|
351
|
+
return undefined;
|
|
352
|
+
}
|
|
353
|
+
};
|
|
354
|
+
/** Last assistant message's modelID for a sub-agent session. */
|
|
355
|
+
const readSessionModel = (sid) => {
|
|
356
|
+
if (!sid)
|
|
357
|
+
return undefined;
|
|
358
|
+
try {
|
|
359
|
+
const msgs = props.api.state.session.messages(sid);
|
|
360
|
+
if (msgs) {
|
|
361
|
+
for (let i = msgs.length - 1; i >= 0; i--) {
|
|
362
|
+
const m = msgs[i];
|
|
363
|
+
if (m.role === "assistant" && m.modelID)
|
|
364
|
+
return String(m.modelID);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
return undefined;
|
|
368
|
+
}
|
|
369
|
+
catch {
|
|
370
|
+
return undefined;
|
|
371
|
+
}
|
|
372
|
+
};
|
|
373
|
+
/** Todo completion stats for a sub-agent session.
|
|
374
|
+
* `done` counts completed + cancelled items. */
|
|
375
|
+
const readSessionTodo = (sid) => {
|
|
376
|
+
if (!sid)
|
|
377
|
+
return undefined;
|
|
378
|
+
try {
|
|
379
|
+
const todos = props.api.state.session.todo(sid);
|
|
380
|
+
if (!todos || todos.length === 0)
|
|
381
|
+
return undefined;
|
|
382
|
+
let done = 0;
|
|
383
|
+
for (const t of todos) {
|
|
384
|
+
if (t.status === "completed" || t.status === "cancelled")
|
|
385
|
+
done++;
|
|
386
|
+
}
|
|
387
|
+
return { total: todos.length, done };
|
|
388
|
+
}
|
|
389
|
+
catch {
|
|
390
|
+
return undefined;
|
|
391
|
+
}
|
|
392
|
+
};
|
|
393
|
+
// ── upsert ──
|
|
394
|
+
const upsertEntry = (partial) => {
|
|
395
|
+
setEntryMap((prev) => {
|
|
396
|
+
const existing = prev.get(partial.id);
|
|
397
|
+
const next = new Map(prev);
|
|
398
|
+
const nowTs = Date.now();
|
|
399
|
+
const e = partial.status;
|
|
400
|
+
const ended = e === "done" || e === "error";
|
|
401
|
+
next.set(partial.id, {
|
|
402
|
+
...(existing ?? { startedAt: nowTs }),
|
|
403
|
+
...partial,
|
|
404
|
+
startedAt: existing?.startedAt || partial.startedAt || nowTs,
|
|
405
|
+
endedAt: ended ? (existing?.endedAt || nowTs) : undefined,
|
|
406
|
+
});
|
|
407
|
+
return next;
|
|
408
|
+
});
|
|
409
|
+
};
|
|
410
|
+
// ── event handlers ──
|
|
411
|
+
const handlePartUpdated = (event) => {
|
|
412
|
+
const e = event;
|
|
413
|
+
const props_ = e.properties;
|
|
414
|
+
const part = props_?.part;
|
|
415
|
+
if (!part)
|
|
416
|
+
return;
|
|
417
|
+
// SubtaskPart
|
|
418
|
+
if (part.type === "subtask") {
|
|
419
|
+
const agent = String(part.agent ?? "?");
|
|
420
|
+
const prompt = String(part.prompt ?? "");
|
|
421
|
+
const desc = String(part.description ?? "");
|
|
422
|
+
const title = desc || truncate(prompt.replace(/\n/g, " ").replace(/\s+/g, " ").trim(), 40);
|
|
423
|
+
const id = `sub:${String(part.id ?? crypto.randomUUID())}`;
|
|
424
|
+
const subSid = part.sessionID !== undefined ? String(part.sessionID) : undefined;
|
|
425
|
+
const partModel = part.model;
|
|
426
|
+
const modelId = partModel?.modelID ? String(partModel.modelID) : undefined;
|
|
427
|
+
upsertEntry({ id, title, agent, prompt, sessionId: subSid, status: "running", model: modelId });
|
|
428
|
+
}
|
|
429
|
+
// ToolPart
|
|
430
|
+
if (part.type === "tool") {
|
|
431
|
+
const tool = String(part.tool ?? "");
|
|
432
|
+
if (!SUBAGENT_TOOLS.has(tool))
|
|
433
|
+
return;
|
|
434
|
+
const st = part.state;
|
|
435
|
+
const rawStatus = String(st?.status ?? "");
|
|
436
|
+
// Only create entries for tool calls that actually entered execution.
|
|
437
|
+
// "pending" / empty → state unknown yet, wait for next event
|
|
438
|
+
if (rawStatus === "pending" || rawStatus === "")
|
|
439
|
+
return;
|
|
440
|
+
// "error" → tool call failed, sub-agent never spawned.
|
|
441
|
+
// Only update an existing entry (e.g. previously running → now error),
|
|
442
|
+
// never create a new one.
|
|
443
|
+
if (rawStatus === "error") {
|
|
444
|
+
const id = `tool:${String(part.id ?? "")}`;
|
|
445
|
+
if (!part.id)
|
|
446
|
+
return;
|
|
447
|
+
const existing = entryMap().get(id);
|
|
448
|
+
if (existing) {
|
|
449
|
+
upsertEntry({ id, title: existing.title, agent: existing.agent, prompt: existing.prompt, status: "error" });
|
|
450
|
+
}
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
// rawStatus is "running" or "completed" — tool entered execution, track it.
|
|
454
|
+
const input = st?.input;
|
|
455
|
+
let status = "running";
|
|
456
|
+
if (rawStatus === "completed")
|
|
457
|
+
status = "done";
|
|
458
|
+
// Background tasks: tool completion ≠ agent completion — keep running until session.idle
|
|
459
|
+
// Only keep running if state metadata confirms a child session was spawned;
|
|
460
|
+
// otherwise (failed spawn, invalid agent) mark as done so the entry isn't stuck forever.
|
|
461
|
+
if (input?.run_in_background === true && status === "done") {
|
|
462
|
+
const stMetaCheck = st?.metadata;
|
|
463
|
+
const hasChild = stMetaCheck?.session_id !== undefined || stMetaCheck?.sessionId !== undefined;
|
|
464
|
+
if (hasChild)
|
|
465
|
+
status = "running";
|
|
466
|
+
}
|
|
467
|
+
const agent = String(part.subagent_type ?? input?.subagent_type ?? input?.category ?? tool);
|
|
468
|
+
const prompt = String(input?.prompt ?? part.description ?? "");
|
|
469
|
+
const desc = input?.description !== undefined ? String(input.description) : "";
|
|
470
|
+
const title = desc || truncate(prompt.replace(/\n/g, " ").replace(/\s+/g, " ").trim(), 40);
|
|
471
|
+
const id = `tool:${String(part.id ?? crypto.randomUUID())}`;
|
|
472
|
+
// Child session ID lives in state-level metadata (ToolStateCompleted.metadata),
|
|
473
|
+
// injected by the tool executor. ToolPart.sessionID is the parent session.
|
|
474
|
+
const stMeta = st?.metadata;
|
|
475
|
+
const subSid = stMeta?.session_id !== undefined ? String(stMeta.session_id)
|
|
476
|
+
: stMeta?.sessionId !== undefined ? String(stMeta.sessionId)
|
|
477
|
+
: undefined;
|
|
478
|
+
upsertEntry({ id, title, agent, prompt, sessionId: subSid, status });
|
|
479
|
+
}
|
|
480
|
+
};
|
|
481
|
+
const handleSessionEnd = (event, status) => {
|
|
482
|
+
const e = event;
|
|
483
|
+
const props_ = e.properties;
|
|
484
|
+
const sid = String(props_?.sessionID ?? "");
|
|
485
|
+
if (!sid)
|
|
486
|
+
return;
|
|
487
|
+
const sessionTokens = readSessionTokens(sid);
|
|
488
|
+
const sessionCost = readSessionCost(sid);
|
|
489
|
+
const sessionModel = readSessionModel(sid);
|
|
490
|
+
const sessionTodo = readSessionTodo(sid);
|
|
491
|
+
let sessionAgent;
|
|
492
|
+
let errorMsg;
|
|
493
|
+
try {
|
|
494
|
+
const s = props.api.state.session.get(sid);
|
|
495
|
+
sessionAgent = s?.agent;
|
|
496
|
+
if (status === "error") {
|
|
497
|
+
const evtErr = props_?.error;
|
|
498
|
+
errorMsg = safeErrorMsg(evtErr) || safeErrorMsg(props_?.message);
|
|
499
|
+
if (!errorMsg) {
|
|
500
|
+
const msgs = props.api.state.session.messages(sid);
|
|
501
|
+
if (msgs) {
|
|
502
|
+
for (let i = msgs.length - 1; i >= 0; i--) {
|
|
503
|
+
const m = msgs[i];
|
|
504
|
+
if (m.role === "assistant" && m.error) {
|
|
505
|
+
errorMsg = safeErrorMsg(m.error);
|
|
506
|
+
break;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
catch { }
|
|
514
|
+
setEntryMap((prev) => {
|
|
515
|
+
let changed = false;
|
|
516
|
+
const next = new Map(prev);
|
|
517
|
+
for (const [id, entry] of next) {
|
|
518
|
+
if (entry.sessionId !== sid)
|
|
519
|
+
continue;
|
|
520
|
+
if (entry.status !== "running" && entry.status !== "done")
|
|
521
|
+
continue;
|
|
522
|
+
// Skip parent session idle — subagent entries belong to child sessions only
|
|
523
|
+
if (sid === props.sessionId)
|
|
524
|
+
continue;
|
|
525
|
+
// For "done" entries (sync tasks completed before session.idle), only backfill tokens/cost
|
|
526
|
+
const alreadySettled = entry.status !== "running";
|
|
527
|
+
next.set(id, {
|
|
528
|
+
...entry,
|
|
529
|
+
...(alreadySettled ? {} : { status, endedAt: Date.now() }),
|
|
530
|
+
tokens: entry.tokens ?? sessionTokens,
|
|
531
|
+
cost: entry.cost ?? sessionCost,
|
|
532
|
+
model: entry.model ?? sessionModel,
|
|
533
|
+
todoTotal: entry.todoTotal ?? sessionTodo?.total,
|
|
534
|
+
todoDone: entry.todoDone ?? sessionTodo?.done,
|
|
535
|
+
error: errorMsg || entry.error,
|
|
536
|
+
});
|
|
537
|
+
changed = true;
|
|
538
|
+
}
|
|
539
|
+
if (!changed && sessionAgent) {
|
|
540
|
+
const nowTs = Date.now();
|
|
541
|
+
const normalize = (s) => s.toLowerCase().replace(/[^a-z0-9-]/g, "");
|
|
542
|
+
const saNorm = normalize(sessionAgent);
|
|
543
|
+
let best = null;
|
|
544
|
+
// Phase 1: try matching by agent name(agent 名有交集)
|
|
545
|
+
for (const [id, entry] of next) {
|
|
546
|
+
if (entry.status !== "running")
|
|
547
|
+
continue;
|
|
548
|
+
const eaNorm = normalize(entry.agent);
|
|
549
|
+
if (!eaNorm || !saNorm)
|
|
550
|
+
continue;
|
|
551
|
+
if (!eaNorm.includes(saNorm) && !saNorm.includes(eaNorm))
|
|
552
|
+
continue;
|
|
553
|
+
const gap = nowTs - (entry.startedAt || 0);
|
|
554
|
+
if (!best || gap > best.gap)
|
|
555
|
+
best = { id, gap };
|
|
556
|
+
}
|
|
557
|
+
// Phase 2: if agent name has no overlap (e.g. category calls: agent="deep" vs sessionAgent="Sisyphus-Junior"),
|
|
558
|
+
// fall back to time proximity for entries that have no sessionId yet
|
|
559
|
+
if (!best) {
|
|
560
|
+
for (const [id, entry] of next) {
|
|
561
|
+
if (entry.status !== "running")
|
|
562
|
+
continue;
|
|
563
|
+
if (entry.sessionId)
|
|
564
|
+
continue;
|
|
565
|
+
const gap = nowTs - (entry.startedAt || 0);
|
|
566
|
+
if (!best || gap > best.gap)
|
|
567
|
+
best = { id, gap };
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
if (best) {
|
|
571
|
+
const entry = next.get(best.id);
|
|
572
|
+
next.set(best.id, {
|
|
573
|
+
...entry, status, endedAt: nowTs,
|
|
574
|
+
tokens: sessionTokens || entry.tokens,
|
|
575
|
+
cost: sessionCost || entry.cost,
|
|
576
|
+
sessionId: sid,
|
|
577
|
+
error: errorMsg || entry.error,
|
|
578
|
+
});
|
|
579
|
+
changed = true;
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
return changed ? next : prev;
|
|
583
|
+
});
|
|
584
|
+
// Delayed backfill: re-read data after state sync catches up, to capture the final
|
|
585
|
+
// token/cost values that may not have been available when session.idle fired.
|
|
586
|
+
setTimeout(() => {
|
|
587
|
+
if (disposed)
|
|
588
|
+
return;
|
|
589
|
+
const finalTokens = readSessionTokens(sid);
|
|
590
|
+
const finalCost = readSessionCost(sid);
|
|
591
|
+
const finalModel = readSessionModel(sid);
|
|
592
|
+
const finalTodo = readSessionTodo(sid);
|
|
593
|
+
setEntryMap((prev) => {
|
|
594
|
+
let changed = false;
|
|
595
|
+
const next = new Map(prev);
|
|
596
|
+
for (const [id, entry] of next) {
|
|
597
|
+
if (entry.sessionId !== sid)
|
|
598
|
+
continue;
|
|
599
|
+
const t = finalTokens ?? entry.tokens;
|
|
600
|
+
const c = finalCost ?? entry.cost;
|
|
601
|
+
const m = finalModel ?? entry.model;
|
|
602
|
+
const tt = finalTodo?.total ?? entry.todoTotal;
|
|
603
|
+
const td = finalTodo?.done ?? entry.todoDone;
|
|
604
|
+
if (t !== entry.tokens || c !== entry.cost || m !== entry.model ||
|
|
605
|
+
tt !== entry.todoTotal || td !== entry.todoDone) {
|
|
606
|
+
next.set(id, { ...entry, tokens: t, cost: c, model: m, todoTotal: tt, todoDone: td });
|
|
607
|
+
changed = true;
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
return changed ? next : prev;
|
|
611
|
+
});
|
|
612
|
+
bump();
|
|
613
|
+
}, 150);
|
|
614
|
+
};
|
|
615
|
+
// ── bumpRenderTick: force re-render (visual-cache pattern) ──
|
|
616
|
+
const bump = () => setRenderTick((v) => v + 1);
|
|
617
|
+
onMount(() => {
|
|
618
|
+
// Fast clock for smooth time display, separate from token polling
|
|
619
|
+
const clock = setInterval(() => { setNow(Date.now()); bump(); }, 100);
|
|
620
|
+
// Token poll — runs every 500ms for running entries
|
|
621
|
+
const tokenTimer = setInterval(() => {
|
|
622
|
+
untrack(() => {
|
|
623
|
+
setEntryMapRaw((prev) => {
|
|
624
|
+
let changed = false;
|
|
625
|
+
const next = new Map(prev);
|
|
626
|
+
for (const [id, entry] of next) {
|
|
627
|
+
if (entry.status === "running" && entry.sessionId) {
|
|
628
|
+
// Only read from child sessions, never the parent
|
|
629
|
+
let isChild = false;
|
|
630
|
+
try {
|
|
631
|
+
const s = props.api.state.session.get(entry.sessionId);
|
|
632
|
+
isChild = s?.parentID === props.sessionId;
|
|
633
|
+
}
|
|
634
|
+
catch { }
|
|
635
|
+
if (!isChild)
|
|
636
|
+
continue;
|
|
637
|
+
const total = readSessionTokens(entry.sessionId);
|
|
638
|
+
const todo = readSessionTodo(entry.sessionId);
|
|
639
|
+
const model = entry.model ?? readSessionModel(entry.sessionId);
|
|
640
|
+
const nextEntry = { ...entry };
|
|
641
|
+
if (total !== undefined && total !== entry.tokens) {
|
|
642
|
+
nextEntry.tokens = total;
|
|
643
|
+
changed = true;
|
|
644
|
+
}
|
|
645
|
+
if (todo !== undefined) {
|
|
646
|
+
if (todo.total !== entry.todoTotal || todo.done !== entry.todoDone) {
|
|
647
|
+
nextEntry.todoTotal = todo.total;
|
|
648
|
+
nextEntry.todoDone = todo.done;
|
|
649
|
+
changed = true;
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
if (model && !entry.model) {
|
|
653
|
+
nextEntry.model = model;
|
|
654
|
+
changed = true;
|
|
655
|
+
}
|
|
656
|
+
if (changed)
|
|
657
|
+
next.set(id, nextEntry);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
return changed ? next : prev;
|
|
661
|
+
});
|
|
662
|
+
});
|
|
663
|
+
bump();
|
|
664
|
+
}, 500);
|
|
665
|
+
bump();
|
|
666
|
+
const unsubPart = props.api.event.on("message.part.updated", (e) => {
|
|
667
|
+
handlePartUpdated(e);
|
|
668
|
+
bump();
|
|
669
|
+
});
|
|
670
|
+
const unsubMsg = props.api.event.on("message.updated", () => bump());
|
|
671
|
+
const unsubIdle = props.api.event.on("session.idle", (e) => {
|
|
672
|
+
handleSessionEnd(e, "done");
|
|
673
|
+
bump();
|
|
674
|
+
});
|
|
675
|
+
const unsubError = props.api.event.on("session.error", (e) => {
|
|
676
|
+
handleSessionEnd(e, "error");
|
|
677
|
+
bump();
|
|
678
|
+
});
|
|
679
|
+
onCleanup(() => {
|
|
680
|
+
disposed = true;
|
|
681
|
+
clearInterval(clock);
|
|
682
|
+
clearInterval(tokenTimer);
|
|
683
|
+
unsubPart();
|
|
684
|
+
unsubMsg();
|
|
685
|
+
unsubIdle();
|
|
686
|
+
unsubError();
|
|
687
|
+
});
|
|
688
|
+
});
|
|
689
|
+
// ── session‑switch & initial‑load scan ──
|
|
690
|
+
// On session change: load from kv (entries survive component unmount), then scan+merge.
|
|
691
|
+
// On same session: only scan+merge (keep event‑driven running entries).
|
|
692
|
+
let lastSid = props.sessionId;
|
|
693
|
+
createEffect(() => {
|
|
694
|
+
const sid = props.sessionId;
|
|
695
|
+
const switched = sid !== lastSid;
|
|
696
|
+
lastSid = sid;
|
|
697
|
+
const t = setTimeout(() => {
|
|
698
|
+
untrack(() => {
|
|
699
|
+
if (switched) {
|
|
700
|
+
const saved = loadSessionData()[sid]?.scroll ?? 0;
|
|
701
|
+
setScrollOffset(saved);
|
|
702
|
+
}
|
|
703
|
+
// scan uses setEntryMapRaw — ephemeral data, not persisted to kv.
|
|
704
|
+
// Only event-driven changes (handlePartUpdated, handleSessionEnd) persist.
|
|
705
|
+
setEntryMapRaw((prev) => {
|
|
706
|
+
const next = switched ? loadEntries(sid) : new Map(prev);
|
|
707
|
+
try {
|
|
708
|
+
const msgs = props.api.state.session.messages(sid);
|
|
709
|
+
if (msgs && msgs.length) {
|
|
710
|
+
for (const msg of msgs) {
|
|
711
|
+
const parts = props.api.state.part(msg.id) ?? [];
|
|
712
|
+
for (const partRaw of parts) {
|
|
713
|
+
const part = partRaw;
|
|
714
|
+
// Subtask entries are purely event-driven — never created by scan.
|
|
715
|
+
// (SubtaskPart exists from spawn, not completion, so we cannot infer status.)
|
|
716
|
+
if (part.type === "tool") {
|
|
717
|
+
const tool = String(part.tool ?? "");
|
|
718
|
+
if (!SUBAGENT_TOOLS.has(tool))
|
|
719
|
+
continue;
|
|
720
|
+
const id = `tool:${String(part.id ?? "")}`;
|
|
721
|
+
if (!part.id)
|
|
722
|
+
continue;
|
|
723
|
+
const st = part.state;
|
|
724
|
+
const rawStatus = String(st?.status ?? "");
|
|
725
|
+
const exists = next.get(id);
|
|
726
|
+
// Only create entries for tool calls that entered execution.
|
|
727
|
+
// "pending" / empty: skip new entries; allow heuristics for existing ones below.
|
|
728
|
+
if ((rawStatus === "pending" || rawStatus === "") && !exists)
|
|
729
|
+
continue;
|
|
730
|
+
// "error": only update existing, never create a new entry
|
|
731
|
+
if (rawStatus === "error") {
|
|
732
|
+
if (exists && exists.status === "running") {
|
|
733
|
+
next.set(id, { ...exists, status: "error", endedAt: Date.now() });
|
|
734
|
+
}
|
|
735
|
+
continue;
|
|
736
|
+
}
|
|
737
|
+
let status = "running";
|
|
738
|
+
if (rawStatus === "completed")
|
|
739
|
+
status = "done";
|
|
740
|
+
// Background tasks: tool completion ≠ agent completion — keep running until session.idle
|
|
741
|
+
// Only keep running if state metadata confirms a child session was spawned.
|
|
742
|
+
if (st?.input?.run_in_background === true && status === "done") {
|
|
743
|
+
const scanStMeta = st?.metadata;
|
|
744
|
+
const scanHasChild = scanStMeta?.session_id !== undefined || scanStMeta?.sessionId !== undefined;
|
|
745
|
+
if (scanHasChild)
|
|
746
|
+
status = "running";
|
|
747
|
+
}
|
|
748
|
+
// Already settled → skip
|
|
749
|
+
if (exists && exists.status !== "running")
|
|
750
|
+
continue;
|
|
751
|
+
// Running entry with no explicit status improvement from part:
|
|
752
|
+
// try message-level heuristics first, then time-based fallback.
|
|
753
|
+
if (exists && status === "running") {
|
|
754
|
+
if (!rawStatus) {
|
|
755
|
+
const msgTokens = msg?.tokens;
|
|
756
|
+
if (msgTokens && (Number(msgTokens.input) > 0 || Number(msgTokens.output) > 0)) {
|
|
757
|
+
status = "done"; // LLM returned tokens → agent completed
|
|
758
|
+
}
|
|
759
|
+
else if (Date.now() - exists.startedAt > 30 * 60 * 1000) {
|
|
760
|
+
status = "done"; // >30 min idle → assume completed
|
|
761
|
+
}
|
|
762
|
+
else {
|
|
763
|
+
continue;
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
else {
|
|
767
|
+
continue;
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
// If already tracked as running but tool state says completed/error → update
|
|
771
|
+
// If not tracked → add fresh
|
|
772
|
+
const input = st?.input;
|
|
773
|
+
const agent = String(part.subagent_type ?? input?.subagent_type ?? tool);
|
|
774
|
+
const prompt = String(input?.prompt ?? part.description ?? "");
|
|
775
|
+
const desc = input?.description !== undefined ? String(input.description) : "";
|
|
776
|
+
const title = desc || truncate(prompt.replace(/\n/g, " ").trim(), 40);
|
|
777
|
+
let tokens;
|
|
778
|
+
const scanStMeta2 = st?.metadata;
|
|
779
|
+
const scanSubSid = scanStMeta2?.session_id !== undefined ? String(scanStMeta2.session_id)
|
|
780
|
+
: scanStMeta2?.sessionId !== undefined ? String(scanStMeta2.sessionId)
|
|
781
|
+
: undefined;
|
|
782
|
+
if (scanSubSid)
|
|
783
|
+
tokens = readSessionTokens(scanSubSid);
|
|
784
|
+
const ended = status === "done"; // "error" handled above, never reaches here
|
|
785
|
+
next.set(id, {
|
|
786
|
+
id, title, agent, prompt,
|
|
787
|
+
// Preserve existing values (from handleSessionEnd / KV) — scan must not overwrite
|
|
788
|
+
tokens: exists?.tokens ?? tokens,
|
|
789
|
+
sessionId: exists?.sessionId ?? scanSubSid,
|
|
790
|
+
status,
|
|
791
|
+
startedAt: exists?.startedAt || Date.now(),
|
|
792
|
+
endedAt: ended ? (exists?.endedAt || Date.now()) : undefined,
|
|
793
|
+
});
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
catch { }
|
|
800
|
+
return next;
|
|
801
|
+
});
|
|
802
|
+
// Reconcile: check running entries against live child session status.
|
|
803
|
+
// Covers session.idle events missed while user was inside a child session.
|
|
804
|
+
setEntryMapRaw((prev) => {
|
|
805
|
+
let changed = false;
|
|
806
|
+
const next = new Map(prev);
|
|
807
|
+
for (const [id, entry] of next) {
|
|
808
|
+
if (entry.status !== "running" || !entry.sessionId)
|
|
809
|
+
continue;
|
|
810
|
+
try {
|
|
811
|
+
const st = props.api.state.session.status(entry.sessionId);
|
|
812
|
+
if (!st || st.type !== "idle")
|
|
813
|
+
continue;
|
|
814
|
+
const tokens = readSessionTokens(entry.sessionId);
|
|
815
|
+
const cost = readSessionCost(entry.sessionId);
|
|
816
|
+
next.set(id, {
|
|
817
|
+
...entry, status: "done", endedAt: Date.now(),
|
|
818
|
+
tokens: tokens ?? entry.tokens,
|
|
819
|
+
cost: cost ?? entry.cost,
|
|
820
|
+
});
|
|
821
|
+
changed = true;
|
|
822
|
+
}
|
|
823
|
+
catch { }
|
|
824
|
+
}
|
|
825
|
+
return changed ? next : prev;
|
|
826
|
+
});
|
|
827
|
+
bump();
|
|
828
|
+
});
|
|
829
|
+
}, 150);
|
|
830
|
+
onCleanup(() => clearTimeout(t));
|
|
831
|
+
});
|
|
832
|
+
// ── palette ──
|
|
833
|
+
const pal = createMemo(() => {
|
|
834
|
+
const th = props.theme;
|
|
835
|
+
const sat = (k, fb) => desaturateTo(th[k], MAX_SAT, fb);
|
|
836
|
+
return {
|
|
837
|
+
primary: sat("primary", FALLBACK.primary),
|
|
838
|
+
text: sat("text", FALLBACK.text),
|
|
839
|
+
muted: sat("textMuted", FALLBACK.muted),
|
|
840
|
+
success: sat("success", FALLBACK.success),
|
|
841
|
+
warning: sat("warning", FALLBACK.warning),
|
|
842
|
+
error: sat("error", FALLBACK.error),
|
|
843
|
+
border: sat("border", FALLBACK.border),
|
|
844
|
+
};
|
|
845
|
+
});
|
|
846
|
+
// ── derived signals ──
|
|
847
|
+
// Stable list — only changes when entryMap changes
|
|
848
|
+
const entryList = createMemo(() => {
|
|
849
|
+
return [...entryMap().values()].sort((a, b) => b.startedAt - a.startedAt);
|
|
850
|
+
});
|
|
851
|
+
const max = props.maxEntries;
|
|
852
|
+
const clampedOffset = createMemo(() => {
|
|
853
|
+
const total = entryList().length;
|
|
854
|
+
const m = max();
|
|
855
|
+
if (total <= m)
|
|
856
|
+
return 0;
|
|
857
|
+
return Math.min(scrollOffset(), total - m);
|
|
858
|
+
});
|
|
859
|
+
const visibleList = createMemo(() => entryList().slice(clampedOffset(), clampedOffset() + max()));
|
|
860
|
+
const hiddenAbove = createMemo(() => clampedOffset());
|
|
861
|
+
const hiddenBelow = createMemo(() => Math.max(0, entryList().length - clampedOffset() - max()));
|
|
862
|
+
const entries = createMemo(() => {
|
|
863
|
+
const nowVal = now();
|
|
864
|
+
return entryList().map((e) => ({
|
|
865
|
+
...e,
|
|
866
|
+
elapsed: (e.endedAt ?? nowVal) - e.startedAt,
|
|
867
|
+
}));
|
|
868
|
+
});
|
|
869
|
+
const doneCount = createMemo(() => entryList().filter((e) => e.status === "done").length);
|
|
870
|
+
const runningCount = createMemo(() => entryList().filter((e) => e.status === "running").length);
|
|
871
|
+
const errCount = createMemo(() => entryList().filter((e) => e.status === "error").length);
|
|
872
|
+
const anyEntry = () => entryList().length > 0;
|
|
873
|
+
const totalTokens = createMemo(() => {
|
|
874
|
+
let sum = 0;
|
|
875
|
+
for (const e of entryList()) {
|
|
876
|
+
if (e.tokens)
|
|
877
|
+
sum += e.tokens;
|
|
878
|
+
}
|
|
879
|
+
return sum;
|
|
880
|
+
});
|
|
881
|
+
const totalCost = createMemo(() => {
|
|
882
|
+
let sum = 0;
|
|
883
|
+
for (const e of entryList()) {
|
|
884
|
+
if (e.cost)
|
|
885
|
+
sum += e.cost;
|
|
886
|
+
}
|
|
887
|
+
return sum;
|
|
888
|
+
});
|
|
889
|
+
const toggleExpand = (id) => {
|
|
890
|
+
setExpanded((prev) => {
|
|
891
|
+
const next = prev === id ? undefined : id;
|
|
892
|
+
try {
|
|
893
|
+
persistExpanded(props.sessionId, next ?? "");
|
|
894
|
+
}
|
|
895
|
+
catch { }
|
|
896
|
+
return next;
|
|
897
|
+
});
|
|
898
|
+
};
|
|
899
|
+
const sep = () => "\u2500".repeat(Math.max(1, panelWidth()));
|
|
900
|
+
// ── expanded detail right-align ──
|
|
901
|
+
const expandedMaxLabelW = createMemo(() => {
|
|
902
|
+
const labels = [
|
|
903
|
+
t("agent.label"), t("time.label"), t("tokens.label"),
|
|
904
|
+
t("error.label"), t("cost.label"), t("model.label"), t("todo.label"),
|
|
905
|
+
];
|
|
906
|
+
return Math.max(...labels.map(l => visualWidth(l + ": ")));
|
|
907
|
+
});
|
|
908
|
+
const expandedPad = (label) => Math.max(0, expandedMaxLabelW() - visualWidth(label + ": "));
|
|
909
|
+
const expandedValAvail = () => Math.max(6, panelWidth() - INDENT - expandedMaxLabelW());
|
|
910
|
+
// ── header parts for colored spans ──
|
|
911
|
+
const summaryParts = createMemo(() => {
|
|
912
|
+
if (!anyEntry())
|
|
913
|
+
return null;
|
|
914
|
+
const dot = "\u25cf";
|
|
915
|
+
const cost = totalCost();
|
|
916
|
+
return {
|
|
917
|
+
done: `${dot}${doneCount()}`,
|
|
918
|
+
running: runningCount() > 0 ? `${dot}${runningCount()}` : null,
|
|
919
|
+
err: errCount() > 0 ? `${dot}${errCount()}` : null,
|
|
920
|
+
duration: totalTokens() > 0 ? fmtTokens(totalTokens()) : "",
|
|
921
|
+
cost: cost > 0 ? `$${cost.toFixed(2)}` : "",
|
|
922
|
+
};
|
|
923
|
+
});
|
|
924
|
+
const summaryCols = createMemo(() => {
|
|
925
|
+
const p = summaryParts();
|
|
926
|
+
if (!p)
|
|
927
|
+
return 0;
|
|
928
|
+
let w = visualWidth(p.done);
|
|
929
|
+
if (p.running)
|
|
930
|
+
w += 1 + visualWidth(p.running);
|
|
931
|
+
if (p.err)
|
|
932
|
+
w += 1 + visualWidth(p.err);
|
|
933
|
+
w += p.duration ? 1 + visualWidth(p.duration) : 0;
|
|
934
|
+
w += p.cost ? 1 + visualWidth(p.cost) : 0;
|
|
935
|
+
return w;
|
|
936
|
+
});
|
|
937
|
+
const versionText = ` v${PLUGIN_VERSION}`;
|
|
938
|
+
const versionW = visualWidth(versionText);
|
|
939
|
+
const showVersion = createMemo(() => {
|
|
940
|
+
if (!open())
|
|
941
|
+
return false;
|
|
942
|
+
const icon = "\u25bc";
|
|
943
|
+
const need = visualWidth(icon) + 1 + visualWidth(t("panel.title")) + versionW + summaryCols();
|
|
944
|
+
return need <= panelWidth();
|
|
945
|
+
});
|
|
946
|
+
const leftCols = createMemo(() => {
|
|
947
|
+
const icon = open() ? "\u25bc" : "\u25b6";
|
|
948
|
+
let w = visualWidth(icon) + 1 + visualWidth(t("panel.title"));
|
|
949
|
+
if (showVersion())
|
|
950
|
+
w += versionW;
|
|
951
|
+
return w;
|
|
952
|
+
});
|
|
953
|
+
const spacerCols = createMemo(() => {
|
|
954
|
+
if (!anyEntry())
|
|
955
|
+
return 0;
|
|
956
|
+
return Math.max(0, panelWidth() - leftCols() - summaryCols());
|
|
957
|
+
});
|
|
958
|
+
const valueCols = (label) => Math.max(4, panelWidth() - INDENT - visualWidth(label + ": "));
|
|
959
|
+
// ── render ──
|
|
960
|
+
return (_jsxs("box", { border: false, paddingTop: 0, paddingBottom: 0, paddingLeft: 0, paddingRight: 0, flexDirection: "column", gap: 0, ref: boxEl, onSizeChange: () => {
|
|
961
|
+
const w = boxEl ? Math.max(20, boxEl.width ?? 0) : 28;
|
|
962
|
+
setPanelWidth((prev) => (prev === w ? prev : w));
|
|
963
|
+
}, children: [_jsxs("text", { onMouseUp: () => {
|
|
964
|
+
setOpen((o) => {
|
|
965
|
+
const n = !o;
|
|
966
|
+
try {
|
|
967
|
+
props.api.kv.set(`${KV_PREFIX}.open`, n);
|
|
968
|
+
}
|
|
969
|
+
catch { }
|
|
970
|
+
return n;
|
|
971
|
+
});
|
|
972
|
+
bump();
|
|
973
|
+
}, 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) => {
|
|
974
|
+
const total = entryList().length;
|
|
975
|
+
const m = max();
|
|
976
|
+
if (total <= m)
|
|
977
|
+
return;
|
|
978
|
+
const dir = e.button === 0 ? 1 : -1;
|
|
979
|
+
setScrollOffset((prev) => {
|
|
980
|
+
const next = Math.max(0, Math.min(prev + dir, total - m));
|
|
981
|
+
try {
|
|
982
|
+
persistScroll(props.sessionId, next);
|
|
983
|
+
}
|
|
984
|
+
catch { }
|
|
985
|
+
return next;
|
|
986
|
+
});
|
|
987
|
+
}, children: [_jsx(Show, { when: hiddenAbove() > 0, children: _jsxs("text", { style: { fg: pal().muted }, children: [" ", "\u2191 ", hiddenAbove(), " ", t("scroll.more")] }) }), _jsx(For, { each: visibleList(), children: (entry) => {
|
|
988
|
+
const isExpanded = () => expanded() === entry.id;
|
|
989
|
+
const isRunning = entry.status === "running";
|
|
990
|
+
const isError = entry.status === "error";
|
|
991
|
+
const elapsed = () => (entry.endedAt ?? now()) - entry.startedAt;
|
|
992
|
+
const statusDot = () => "\u25cf";
|
|
993
|
+
const statusColor = () => {
|
|
994
|
+
if (!isRunning)
|
|
995
|
+
return isError ? pal().error : pal().success;
|
|
996
|
+
const t = (Math.sin(((now() % 2000) / 2000) * Math.PI * 2 - Math.PI / 2) + 1) / 2;
|
|
997
|
+
const a = rgb(pal().muted), b = rgb(pal().warning);
|
|
998
|
+
if (!a || !b)
|
|
999
|
+
return pal().warning;
|
|
1000
|
+
const r = Math.round(a.r + (b.r - a.r) * t);
|
|
1001
|
+
const g = Math.round(a.g + (b.g - a.g) * t);
|
|
1002
|
+
const bl = Math.round(a.b + (b.b - a.b) * t);
|
|
1003
|
+
return "#" + [r, g, bl].map((v) => Math.max(0, Math.min(255, v)).toString(16).padStart(2, "0")).join("");
|
|
1004
|
+
};
|
|
1005
|
+
const timeColor = () => isRunning ? pal().warning : isError ? pal().error : pal().muted;
|
|
1006
|
+
// Entry label: collapsed shows title only, expanded shows title only too
|
|
1007
|
+
const tokenText = () => !isExpanded() && entry.tokens !== undefined && entry.tokens > 0
|
|
1008
|
+
? ` ${fmtTokens(entry.tokens)}`
|
|
1009
|
+
: "";
|
|
1010
|
+
const timeText = () => !isExpanded() && (elapsed() >= 2000 || entry.endedAt !== undefined)
|
|
1011
|
+
? fmtDurationShort(elapsed(), isRunning)
|
|
1012
|
+
: "";
|
|
1013
|
+
const suffixW = () => {
|
|
1014
|
+
let w = 0;
|
|
1015
|
+
const t = timeText();
|
|
1016
|
+
if (t)
|
|
1017
|
+
w += 1 + visualWidth(t);
|
|
1018
|
+
const tk = tokenText();
|
|
1019
|
+
if (tk)
|
|
1020
|
+
w += visualWidth(tk);
|
|
1021
|
+
return w;
|
|
1022
|
+
};
|
|
1023
|
+
const labelAvail = () => Math.max(6, panelWidth() - LEFT_PAD - suffixW());
|
|
1024
|
+
const labelText = () => {
|
|
1025
|
+
const max = labelAvail();
|
|
1026
|
+
const text = entry.title || entry.agent;
|
|
1027
|
+
const truncated = truncate(text, max);
|
|
1028
|
+
const pad = Math.max(0, max - visualWidth(truncated));
|
|
1029
|
+
return truncated + " ".repeat(pad);
|
|
1030
|
+
};
|
|
1031
|
+
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 })] }), _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(), isRunning) })] }) }), _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: _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: ["$", entry.cost.toFixed(4)] })] }) }), _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", { onMouseOver: () => setHoveredOpen(entry.id), onMouseOut: () => setHoveredOpen(undefined), onMouseUp: () => {
|
|
1032
|
+
if (entry.sessionId) {
|
|
1033
|
+
props.api.route.navigate("session", { sessionID: entry.sessionId });
|
|
1034
|
+
}
|
|
1035
|
+
}, children: [" ", _jsx("span", { style: { fg: hoveredOpen() === entry.id ? pal().warning : pal().primary }, children: "\u2192 " }), _jsx("span", { style: { fg: hoveredOpen() === entry.id ? pal().warning : pal().primary }, children: t("open.label") })] }) })] })] }));
|
|
1036
|
+
} }), _jsx(Show, { when: hiddenBelow() > 0 || scrollOffset() > 0, children: (() => {
|
|
1037
|
+
const showMore = hiddenBelow() > 0;
|
|
1038
|
+
const showTop = scrollOffset() > 0;
|
|
1039
|
+
const left = showMore ? ` \u2193 ${hiddenBelow()} ${t("scroll.more")}` : " ";
|
|
1040
|
+
const right = `\u2191 ${t("scroll.top")}`;
|
|
1041
|
+
const pad = showTop ? Math.max(1, panelWidth() - visualWidth(left) - visualWidth(right)) : 0;
|
|
1042
|
+
return (_jsxs("box", { flexDirection: "row", children: [_jsx("text", { style: { fg: 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: () => { setScrollOffset(0); setHoveredTop(false); }, children: _jsx("span", { style: { fg: hoveredTop() ? pal().warning : pal().muted }, children: right }) })] })) : null] }));
|
|
1043
|
+
})() })] }) })] })] }));
|
|
1044
|
+
}
|
|
1045
|
+
function createSidebarSlot(api, sig) {
|
|
1046
|
+
return {
|
|
1047
|
+
order: 60,
|
|
1048
|
+
slots: {
|
|
1049
|
+
sidebar_content(ctx, input) {
|
|
1050
|
+
sig.sessionId = input.session_id;
|
|
1051
|
+
return (_jsx(SubAgentPanel, { theme: ctx.theme.current, api: api, lang: sig.lang, maxEntries: sig.maxEntries, sessionId: input.session_id }));
|
|
1052
|
+
},
|
|
1053
|
+
},
|
|
1054
|
+
};
|
|
1055
|
+
}
|
|
1056
|
+
const KV_PREFIX = "subagent_magazine";
|
|
1057
|
+
const tui = async (api) => {
|
|
1058
|
+
// ── language ──
|
|
1059
|
+
const stored = String(api.kv.get(`${KV_PREFIX}.lang`, ""));
|
|
1060
|
+
const initialLang = stored === "zh" || stored === "en" ? stored : detectLang();
|
|
1061
|
+
const [lang, setLang] = createSignal(initialLang);
|
|
1062
|
+
const [maxEntries, setMaxEntries] = createSignal(parseInt(String(api.kv.get(`${KV_PREFIX}.max_entries`, "10")), 10) || 10);
|
|
1063
|
+
const signals = { lang, setLang, maxEntries, setMaxEntries, sessionId: "" };
|
|
1064
|
+
api.slots.register(createSidebarSlot(api, signals));
|
|
1065
|
+
// ── slash command: /subagent-lang ──
|
|
1066
|
+
api.command?.register(() => [
|
|
1067
|
+
{
|
|
1068
|
+
title: "SubAgent Magazine: Language",
|
|
1069
|
+
value: "subagent-lang",
|
|
1070
|
+
description: "Switch display language (中文 / English)",
|
|
1071
|
+
slash: { name: "subagent-lang" },
|
|
1072
|
+
onSelect: (dialog) => {
|
|
1073
|
+
dialog?.replace(() => (_jsx(api.ui.DialogSelect, { title: "Language / \u8BED\u8A00", options: [
|
|
1074
|
+
{ title: "中文", value: "zh" },
|
|
1075
|
+
{ title: "English", value: "en" },
|
|
1076
|
+
], onSelect: (opt) => {
|
|
1077
|
+
const l = opt.value;
|
|
1078
|
+
setLang(l);
|
|
1079
|
+
api.kv.set(`${KV_PREFIX}.lang`, l);
|
|
1080
|
+
api.ui.toast({
|
|
1081
|
+
message: l === "zh" ? "语言: 中文" : "Language: English",
|
|
1082
|
+
});
|
|
1083
|
+
dialog?.clear();
|
|
1084
|
+
} })));
|
|
1085
|
+
},
|
|
1086
|
+
},
|
|
1087
|
+
{
|
|
1088
|
+
title: "SubAgent Magazine: Max Entries",
|
|
1089
|
+
value: "subagent-max",
|
|
1090
|
+
description: "Set max visible sub-agent entries in sidebar",
|
|
1091
|
+
slash: { name: "subagent-max" },
|
|
1092
|
+
onSelect: (dialog) => {
|
|
1093
|
+
dialog?.replace(() => (_jsx(api.ui.DialogPrompt, { title: "Max Visible Entries", description: () => (_jsx("text", { children: "Number of entries to show in the sidebar (1\u201350)" })), value: String(maxEntries()), onConfirm: (val) => {
|
|
1094
|
+
const n = Math.max(1, Math.min(50, parseInt(val, 10) || 10));
|
|
1095
|
+
setMaxEntries(n);
|
|
1096
|
+
api.kv.set(`${KV_PREFIX}.max_entries`, n);
|
|
1097
|
+
api.ui.toast({ message: `Max entries: ${n}` });
|
|
1098
|
+
dialog?.clear();
|
|
1099
|
+
} })));
|
|
1100
|
+
},
|
|
1101
|
+
},
|
|
1102
|
+
{
|
|
1103
|
+
title: "SubAgent Magazine: Version",
|
|
1104
|
+
value: "subagent-version",
|
|
1105
|
+
description: "Show plugin version",
|
|
1106
|
+
slash: { name: "subagent-version" },
|
|
1107
|
+
onSelect: (dialog) => {
|
|
1108
|
+
api.ui.toast({ message: `opencode-subagent-magazine v${PLUGIN_VERSION}` });
|
|
1109
|
+
dialog?.clear();
|
|
1110
|
+
},
|
|
1111
|
+
},
|
|
1112
|
+
{
|
|
1113
|
+
title: "SubAgent Magazine: Session",
|
|
1114
|
+
value: "subagent-session",
|
|
1115
|
+
description: "Show current session ID",
|
|
1116
|
+
slash: { name: "subagent-session" },
|
|
1117
|
+
onSelect: (dialog) => {
|
|
1118
|
+
api.ui.toast({ message: `Session: ${signals.sessionId}` });
|
|
1119
|
+
dialog?.clear();
|
|
1120
|
+
},
|
|
1121
|
+
},
|
|
1122
|
+
]);
|
|
1123
|
+
};
|
|
1124
|
+
const mod = {
|
|
1125
|
+
id: "opencode-subagent-magazine",
|
|
1126
|
+
tui,
|
|
1127
|
+
};
|
|
1128
|
+
export default mod;
|