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