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