herm-tui 1.0.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +54 -0
  3. package/package.json +82 -0
  4. package/scripts/postinstall.ts +29 -0
  5. package/src/app/gateway.tsx +83 -0
  6. package/src/app/gatewayEvents.ts +203 -0
  7. package/src/app/launch.ts +41 -0
  8. package/src/app/skin.tsx +31 -0
  9. package/src/app/spawnHistory.ts +75 -0
  10. package/src/app/tabs.ts +23 -0
  11. package/src/app/turnReducer.ts +390 -0
  12. package/src/app/useAppKeys.ts +268 -0
  13. package/src/app/useAtRefPopover.ts +99 -0
  14. package/src/app/useInputHistory.ts +66 -0
  15. package/src/app/useSession.ts +102 -0
  16. package/src/app/useSlashCommands.ts +70 -0
  17. package/src/app/useSlashPopover.ts +48 -0
  18. package/src/app.tsx +917 -0
  19. package/src/commands/slash.ts +151 -0
  20. package/src/components/avatar/AnimatedAvatar.tsx +66 -0
  21. package/src/components/avatar/eikon.ts +144 -0
  22. package/src/components/avatar/states/error.ts +1155 -0
  23. package/src/components/avatar/states/idle.ts +1155 -0
  24. package/src/components/avatar/states/index.ts +30 -0
  25. package/src/components/avatar/states/listening.ts +1155 -0
  26. package/src/components/avatar/states/speaking.ts +1155 -0
  27. package/src/components/avatar/states/thinking.ts +1155 -0
  28. package/src/components/avatar/states/working.ts +1155 -0
  29. package/src/components/chat/AtRefPopover.tsx +54 -0
  30. package/src/components/chat/CodeBlock.tsx +67 -0
  31. package/src/components/chat/Composer.tsx +347 -0
  32. package/src/components/chat/DiffBlock.tsx +116 -0
  33. package/src/components/chat/ErrorBlock.tsx +70 -0
  34. package/src/components/chat/MediaChip.tsx +114 -0
  35. package/src/components/chat/MessageItem.tsx +282 -0
  36. package/src/components/chat/MessageList.tsx +114 -0
  37. package/src/components/chat/PromptCard.tsx +359 -0
  38. package/src/components/chat/SlashPopover.tsx +158 -0
  39. package/src/components/chat/ThoughtCloud.tsx +185 -0
  40. package/src/components/chat/TypingIndicator.tsx +25 -0
  41. package/src/components/chat/tool/Subagent.tsx +75 -0
  42. package/src/components/chat/tool/frame.tsx +69 -0
  43. package/src/components/chat/tool/index.tsx +65 -0
  44. package/src/components/chat/tool/preview.ts +57 -0
  45. package/src/components/sidebar/ContextGauge.tsx +102 -0
  46. package/src/components/sidebar/Sidebar.tsx +143 -0
  47. package/src/components/tabs/TabBar.tsx +50 -0
  48. package/src/components/ui/FileLink.tsx +52 -0
  49. package/src/config/index.ts +156 -0
  50. package/src/config/lane.ts +161 -0
  51. package/src/config/models.ts +95 -0
  52. package/src/config/rules.ts +80 -0
  53. package/src/config/schema.ts +308 -0
  54. package/src/dialogs/alert.tsx +52 -0
  55. package/src/dialogs/chafa.tsx +72 -0
  56. package/src/dialogs/confirm.tsx +58 -0
  57. package/src/dialogs/curator.tsx +153 -0
  58. package/src/dialogs/eikon-picker.tsx +95 -0
  59. package/src/dialogs/help.tsx +80 -0
  60. package/src/dialogs/history.tsx +92 -0
  61. package/src/dialogs/info.tsx +115 -0
  62. package/src/dialogs/keys.tsx +170 -0
  63. package/src/dialogs/logs.tsx +42 -0
  64. package/src/dialogs/message.tsx +38 -0
  65. package/src/dialogs/model-picker.tsx +123 -0
  66. package/src/dialogs/new-profile.tsx +69 -0
  67. package/src/dialogs/new-task.tsx +103 -0
  68. package/src/dialogs/profile.tsx +55 -0
  69. package/src/dialogs/rollback.tsx +190 -0
  70. package/src/dialogs/spawn-history.tsx +80 -0
  71. package/src/dialogs/text-prompt.tsx +68 -0
  72. package/src/dialogs/theme-picker.tsx +50 -0
  73. package/src/home/index.ts +23 -0
  74. package/src/home/store.ts +267 -0
  75. package/src/index.tsx +113 -0
  76. package/src/keys/catalog.ts +115 -0
  77. package/src/keys/chord.ts +125 -0
  78. package/src/keys/conflicts.ts +48 -0
  79. package/src/keys/context.tsx +112 -0
  80. package/src/keys/index.ts +5 -0
  81. package/src/keys/list.ts +94 -0
  82. package/src/keys/oc-compat.ts +87 -0
  83. package/src/tabs/Agents.tsx +607 -0
  84. package/src/tabs/Analytics.tsx +154 -0
  85. package/src/tabs/Chat.tsx +50 -0
  86. package/src/tabs/Config.tsx +605 -0
  87. package/src/tabs/Context.tsx +599 -0
  88. package/src/tabs/Cron.tsx +294 -0
  89. package/src/tabs/Env.tsx +227 -0
  90. package/src/tabs/Kanban.tsx +367 -0
  91. package/src/tabs/Memory.tsx +294 -0
  92. package/src/tabs/Sessions.tsx +786 -0
  93. package/src/tabs/Skills.tsx +507 -0
  94. package/src/tabs/Toolsets.tsx +266 -0
  95. package/src/theme/builtin.ts +78 -0
  96. package/src/theme/context.tsx +106 -0
  97. package/src/theme/index.ts +4 -0
  98. package/src/theme/resolve.ts +134 -0
  99. package/src/theme/syntax.ts +31 -0
  100. package/src/theme/themes/aura.json +69 -0
  101. package/src/theme/themes/ayu.json +80 -0
  102. package/src/theme/themes/carbonfox.json +248 -0
  103. package/src/theme/themes/catppuccin-frappe.json +233 -0
  104. package/src/theme/themes/catppuccin-macchiato.json +233 -0
  105. package/src/theme/themes/catppuccin.json +112 -0
  106. package/src/theme/themes/cobalt2.json +228 -0
  107. package/src/theme/themes/cursor.json +249 -0
  108. package/src/theme/themes/dracula.json +219 -0
  109. package/src/theme/themes/everforest.json +241 -0
  110. package/src/theme/themes/flexoki.json +237 -0
  111. package/src/theme/themes/github.json +233 -0
  112. package/src/theme/themes/gruvbox.json +242 -0
  113. package/src/theme/themes/kanagawa.json +77 -0
  114. package/src/theme/themes/lucent-orng.json +237 -0
  115. package/src/theme/themes/material.json +235 -0
  116. package/src/theme/themes/matrix.json +77 -0
  117. package/src/theme/themes/mercury.json +252 -0
  118. package/src/theme/themes/monokai.json +221 -0
  119. package/src/theme/themes/nightowl.json +221 -0
  120. package/src/theme/themes/nord.json +223 -0
  121. package/src/theme/themes/one-dark.json +84 -0
  122. package/src/theme/themes/opencode.json +245 -0
  123. package/src/theme/themes/orng.json +249 -0
  124. package/src/theme/themes/osaka-jade.json +93 -0
  125. package/src/theme/themes/palenight.json +222 -0
  126. package/src/theme/themes/rosepine.json +234 -0
  127. package/src/theme/themes/solarized.json +223 -0
  128. package/src/theme/themes/synthwave84.json +226 -0
  129. package/src/theme/themes/tokyonight.json +243 -0
  130. package/src/theme/themes/vercel.json +245 -0
  131. package/src/theme/themes/vesper.json +218 -0
  132. package/src/theme/themes/zenburn.json +223 -0
  133. package/src/theme/types.ts +119 -0
  134. package/src/types/message.ts +97 -0
  135. package/src/ui/ChafaImage.tsx +64 -0
  136. package/src/ui/Splash.tsx +118 -0
  137. package/src/ui/borders.ts +28 -0
  138. package/src/ui/command.tsx +104 -0
  139. package/src/ui/dialog-select.tsx +164 -0
  140. package/src/ui/dialog.tsx +102 -0
  141. package/src/ui/fmt.ts +82 -0
  142. package/src/ui/kv.tsx +28 -0
  143. package/src/ui/shell.tsx +45 -0
  144. package/src/ui/spinner.tsx +59 -0
  145. package/src/ui/splash-art.ts +123 -0
  146. package/src/ui/table.tsx +117 -0
  147. package/src/ui/ticker.tsx +90 -0
  148. package/src/ui/toast.tsx +130 -0
  149. package/src/utils/categorical.ts +77 -0
  150. package/src/utils/chafa.ts +173 -0
  151. package/src/utils/clipboard.ts +67 -0
  152. package/src/utils/context-segments.ts +317 -0
  153. package/src/utils/control.ts +495 -0
  154. package/src/utils/drop.ts +25 -0
  155. package/src/utils/editor.ts +33 -0
  156. package/src/utils/fuzzy.ts +45 -0
  157. package/src/utils/gateway-client.ts +253 -0
  158. package/src/utils/gateway-types.ts +282 -0
  159. package/src/utils/git.ts +57 -0
  160. package/src/utils/hermes-analytics.ts +134 -0
  161. package/src/utils/hermes-home.ts +821 -0
  162. package/src/utils/hermes-kanban.ts +154 -0
  163. package/src/utils/hermes-profiles.ts +217 -0
  164. package/src/utils/interpolate.ts +31 -0
  165. package/src/utils/math-unicode.ts +818 -0
  166. package/src/utils/memory-activity.ts +140 -0
  167. package/src/utils/open-file.ts +13 -0
  168. package/src/utils/paths.ts +52 -0
  169. package/src/utils/perf.ts +235 -0
  170. package/src/utils/preferences.ts +150 -0
  171. package/src/utils/sessions-db.ts +396 -0
  172. package/src/utils/subagent-tree.ts +146 -0
  173. package/src/utils/terminal-reset.ts +129 -0
  174. package/src/utils/tips.ts +67 -0
  175. package/src/utils/tokens.ts +87 -0
@@ -0,0 +1,607 @@
1
+ import { useState, useEffect, useCallback, useRef, memo } from "react"
2
+ import { VBAR } from "../ui/table"
3
+ import { useKeyboard, useTerminalDimensions } from "@opentui/react"
4
+ import { useKeys, handleListKey, useFollow } from "../keys"
5
+ import { useGateway, useGatewayEvent } from "../app/gateway"
6
+ import { trail } from "../app/spawnHistory"
7
+ import { useTheme } from "../theme"
8
+ import { useDialog } from "../ui/dialog"
9
+ import { useToast } from "../ui/toast"
10
+ import { useCommand } from "../ui/command"
11
+ import { openConfirm } from "../dialogs/confirm"
12
+ import { openSpawnHistory } from "../dialogs/spawn-history"
13
+ import { openProfileMenu } from "../dialogs/profile"
14
+ import { openCreateProfile } from "../dialogs/new-profile"
15
+ import { TabShell } from "../ui/shell"
16
+ import { KV, KVBlock } from "../ui/kv"
17
+ import { KVLink } from "../components/ui/FileLink"
18
+ import { dur, trunc, fmt } from "../ui/fmt"
19
+ import {
20
+ listProfiles, stickyDefault, profileStats,
21
+ type ProfileInfo, type ProfileStats,
22
+ } from "../utils/hermes-profiles"
23
+ import type { DelegationStatus, DelegationRecord } from "../utils/gateway-types"
24
+ import { tree as buildTree, totals as treeTotals, summary, spark, heat, peak, type Agg } from "../utils/subagent-tree"
25
+
26
+ // Two panes:
27
+ // Profiles (left) — filesystem scan of `<root>/profiles/`. Each
28
+ // profile is an isolated HERMES_HOME (config, env, memory, skills).
29
+ // Switching profiles = restarting the gateway under a new
30
+ // HERMES_HOME, which would sever this session — so "switch" is
31
+ // deliberately NOT offered here. All mutations route through
32
+ // `shell.exec → hermes profile <verb>` so the authoritative CLI
33
+ // owns validation, skill seeding, aliases and gateway cleanup.
34
+ // Delegation (right) — live subagent tree via `delegation.status`
35
+ // (tools/delegate_tool registry). `p` toggles spawn-pause
36
+ // (`delegation.pause`), `k` interrupts the selected child
37
+ // (`subagent.interrupt`).
38
+
39
+ // ─── Profiles pane ───────────────────────────────────────────────────
40
+
41
+ const ProfileRow = memo((props: {
42
+ id: string
43
+ p: ProfileInfo; idx: number; selected: boolean
44
+ onHover: (i: number) => void; onEnter: (i: number) => void; onDelete: (i: number) => void
45
+ }) => {
46
+ const theme = useTheme().theme
47
+ const { p, idx: i } = props
48
+ const [x, setX] = useState(false)
49
+ return (
50
+ <box id={props.id} flexDirection="row" height={1}
51
+ backgroundColor={props.selected ? theme.backgroundElement : undefined}
52
+ onMouseOver={() => props.onHover(i)}
53
+ onMouseDown={() => props.onEnter(i)}>
54
+ <box width={2}><text fg={props.selected ? theme.primary : theme.text}>
55
+ {props.selected ? "▸ " : " "}
56
+ </text></box>
57
+ <box flexGrow={1} minWidth={8} height={1} overflow="hidden">
58
+ <text>
59
+ <span fg={p.is_active ? theme.accent : theme.text}>
60
+ {p.is_active ? <strong>{p.name}</strong> : p.name}
61
+ </span>
62
+ {p.is_sticky ? <span fg={theme.warning}>{" ★"}</span> : null}
63
+ {p.gateway_running ? <span fg={theme.success}>{" ●"}</span> : null}
64
+ </text>
65
+ </box>
66
+ <box width={4} height={1}>
67
+ <text fg={theme.textMuted}>{p.is_active ? " you" : ""}</text>
68
+ </box>
69
+ {p.is_default || p.is_active ? <box width={3} /> : (
70
+ <box width={3}
71
+ onMouseDown={(e) => { e.stopPropagation(); props.onDelete(i) }}
72
+ onMouseOver={() => setX(true)} onMouseOut={() => setX(false)}>
73
+ <text fg={x ? theme.error : theme.textMuted}>{" ✕"}</text>
74
+ </box>
75
+ )}
76
+ </box>
77
+ )
78
+ })
79
+
80
+ const ProfileDetail = memo((props: { p: ProfileInfo; stats?: ProfileStats }) => {
81
+ const { theme, syntaxStyle } = useTheme()
82
+ const p = props.p
83
+ const s = props.stats
84
+ return (
85
+ <scrollbox scrollY flexGrow={1}>
86
+ <box flexDirection="column" width="100%">
87
+ <box height={1}>
88
+ <text fg={theme.accent}>
89
+ <strong>{p.name}</strong>
90
+ {p.is_sticky ? <span fg={theme.warning}>{" ★ sticky default"}</span> : null}
91
+ </text>
92
+ </box>
93
+ <box height={1} />
94
+ <KVLink label="Path" source={p.sources.dir} text={p.sources.dir.relative} />
95
+ <KV label="Active" value={p.is_active ? "yes (this session)" : "no"}
96
+ fg={p.is_active ? theme.accent : theme.textMuted} />
97
+ <KV label="Model" value={p.model ?? "—"} />
98
+ <KV label="Provider" value={p.provider ?? "—"} />
99
+ <KV label="Skills" value={String(p.skill_count)} />
100
+ <KV label="Sessions" value={s ? s.sessions == null ? "—" : `${fmt(s.sessions)} (${fmt(s.messages ?? 0)} msgs)` : "…"} />
101
+ <KV label="Cron jobs" value={s ? s.crons == null ? "—" : String(s.crons) : "…"} />
102
+ <KV label="Gateway" value={p.gateway_running ? "running" : "stopped"}
103
+ fg={p.gateway_running ? theme.success : theme.textMuted} />
104
+ {p.has_alias ? <KV label="Alias" value={`${p.name} (shell)`} /> : null}
105
+ <box height={1} />
106
+ <KVLink label="Config" source={p.sources.config} />
107
+ <KVLink label="Soul" source={p.sources.soul} />
108
+ {p.has_env ? <KVLink label="Env" source={p.sources.env} /> : <KV label="Env" value="—" />}
109
+ {p.soul_preview ? <>
110
+ <box height={1} />
111
+ <box height={1}><text fg={theme.textMuted}>SOUL.md</text></box>
112
+ <markdown content={p.soul_preview} fg={theme.markdownText} syntaxStyle={syntaxStyle} />
113
+ </> : null}
114
+ </box>
115
+ </scrollbox>
116
+ )
117
+ })
118
+
119
+ // ─── Delegation pane ─────────────────────────────────────────────────
120
+
121
+ const HOT = ["⠀", "⠁", "⠃", "⠇", "⠏", "⠟", "⠿", "⡿", "⣿"] as const
122
+
123
+ const DelegRow = memo((props: {
124
+ id: string
125
+ r: DelegationRecord; idx: number; selected: boolean; now: number; hot: number
126
+ onHover: (i: number) => void; onKill: (i: number) => void
127
+ }) => {
128
+ const theme = useTheme().theme
129
+ const { r, idx: i, now } = props
130
+ const [x, setX] = useState(false)
131
+ const up = r.started_at ? dur(now - r.started_at) : "—"
132
+ const hotFg = [theme.textMuted, theme.textMuted, theme.text,
133
+ theme.info, theme.info, theme.accent, theme.accent,
134
+ theme.warning, theme.error][props.hot] ?? theme.textMuted
135
+ return (
136
+ <box id={props.id} flexDirection="row" height={1}
137
+ backgroundColor={props.selected ? theme.backgroundElement : undefined}
138
+ onMouseOver={() => props.onHover(i)}>
139
+ <box width={2}><text fg={props.selected ? theme.primary : theme.text}>
140
+ {props.selected ? "▸ " : " "}
141
+ </text></box>
142
+ <box width={2}><text fg={hotFg}>{HOT[props.hot]} </text></box>
143
+ <box flexGrow={1} minWidth={8} height={1} overflow="hidden">
144
+ <text>
145
+ <span fg={theme.textMuted}>{"· ".repeat(r.depth)}</span>
146
+ <span fg={theme.text}>{r.goal.replace(/\s+/g, " ")}</span>
147
+ </text>
148
+ </box>
149
+ <box width={14} height={1} overflow="hidden">
150
+ <text fg={theme.textMuted}>{trunc(r.model ?? "", 13)}</text>
151
+ </box>
152
+ <box width={5} height={1} flexDirection="row" justifyContent="flex-end">
153
+ <text fg={theme.textMuted}>{String(r.tool_count ?? 0)}</text>
154
+ </box>
155
+ <box width={8} height={1} flexDirection="row" justifyContent="flex-end">
156
+ <text fg={theme.textMuted}>{up}</text>
157
+ </box>
158
+ <box width={3}
159
+ onMouseDown={(e) => { e.stopPropagation(); props.onKill(i) }}
160
+ onMouseOver={() => setX(true)} onMouseOut={() => setX(false)}>
161
+ <text fg={x ? theme.error : theme.textMuted}>{" ✕"}</text>
162
+ </box>
163
+ </box>
164
+ )
165
+ })
166
+
167
+ // Sort the flat registry into a parent-before-child pre-order so depth
168
+ // dots draw a coherent tree. Orphans (parent already finished) go last.
169
+ function preorder(recs: DelegationRecord[]): DelegationRecord[] {
170
+ const byParent = new Map<string | null, DelegationRecord[]>()
171
+ for (const r of recs) {
172
+ const k = r.parent_id ?? null
173
+ ;(byParent.get(k) ?? byParent.set(k, []).get(k)!).push(r)
174
+ }
175
+ const out: DelegationRecord[] = []
176
+ const seen = new Set<string>()
177
+ const walk = (k: string | null) => {
178
+ for (const r of byParent.get(k) ?? []) {
179
+ if (seen.has(r.subagent_id)) continue
180
+ seen.add(r.subagent_id)
181
+ out.push(r)
182
+ walk(r.subagent_id)
183
+ }
184
+ }
185
+ walk(null)
186
+ for (const r of recs) if (!seen.has(r.subagent_id)) out.push(r)
187
+ return out
188
+ }
189
+
190
+ // Live per-subagent enrichment on top of the polled registry snapshot.
191
+ // Fed by subagent.* push events; `tool_count` here is authoritative
192
+ // between polls (the registry value lags).
193
+ type Live = {
194
+ tool_count: number
195
+ last_tool?: string
196
+ last_preview?: string
197
+ thinking?: string
198
+ status?: string
199
+ input_tokens?: number
200
+ output_tokens?: number
201
+ cost_usd?: number
202
+ }
203
+
204
+ const DelegDetail = memo((props: { r: DelegationRecord; live?: Live; agg?: Agg; now: number }) => {
205
+ const theme = useTheme().theme
206
+ const { r, live, agg, now } = props
207
+ const tc = live?.tool_count ?? r.tool_count ?? 0
208
+ const tr = trail(r.subagent_id)
209
+ return (
210
+ <scrollbox scrollY flexGrow={1}>
211
+ <box flexDirection="column" width="100%">
212
+ <box minHeight={1}><text fg={theme.accent} wrapMode="word"><strong>{r.goal}</strong></text></box>
213
+ {agg && agg.agents > 1 ? (
214
+ <box height={1}><text fg={theme.textMuted}>{summary(agg)}</text></box>
215
+ ) : null}
216
+ <box height={1} />
217
+ <KVBlock rows={[
218
+ ["Status", live?.status ?? r.status ?? "running"],
219
+ ["Model", r.model ?? "—"],
220
+ ["Depth", String(r.depth)],
221
+ ["Parent", r.parent_id ?? "(root)"],
222
+ ["Uptime", r.started_at ? dur(now - r.started_at) : "—"],
223
+ ["Tools", String(tc)],
224
+ ["Tokens", live ? `${fmt(live.input_tokens ?? 0)} in / ${fmt(live.output_tokens ?? 0)} out` : undefined],
225
+ ["Cost", live?.cost_usd != null ? `$${live.cost_usd.toFixed(4)}` : undefined],
226
+ ]} />
227
+ {live?.thinking ? <>
228
+ <box height={1} />
229
+ <box height={1}><text fg={theme.textMuted}>thinking</text></box>
230
+ <box minHeight={1}><text fg={theme.textMuted} wrapMode="word">{trunc(live.thinking, 200)}</text></box>
231
+ </> : null}
232
+ {tr.length > 0 ? <>
233
+ <box height={1} />
234
+ <box height={1}><text fg={theme.textMuted}>recent tools</text></box>
235
+ {tr.slice(-8).map((t, i) => (
236
+ <box key={i} height={1} overflow="hidden">
237
+ <text>
238
+ <span fg={theme.textMuted}>{"┃ "}</span>
239
+ <span fg={theme.text}>{t.name.padEnd(14)}</span>
240
+ <span fg={theme.textMuted}>{t.preview ? trunc(t.preview.replace(/\s+/g, " "), 40) : ""}</span>
241
+ </text>
242
+ </box>
243
+ ))}
244
+ </> : null}
245
+ </box>
246
+ </scrollbox>
247
+ )
248
+ })
249
+
250
+ // ─── Main ────────────────────────────────────────────────────────────
251
+
252
+ type ShellResult = { stdout: string; stderr: string; code: number }
253
+ type Pane = "profiles" | "deleg"
254
+ type View = "list" | "detail"
255
+ type Props = { focused?: boolean; sessionId: string }
256
+
257
+ export const Agents = memo((props: Props) => {
258
+ const theme = useTheme().theme
259
+ const gw = useGateway()
260
+ const dialog = useDialog()
261
+ const toast = useToast()
262
+ const cmd = useCommand()
263
+
264
+ const [pane, setPane] = useState<Pane>("profiles")
265
+ // Profiles-pane list↔detail swap for narrow terminals — in wide
266
+ // layouts both render side-by-side and this is ignored.
267
+ const [pView, setPView] = useState<View>("list")
268
+ const [profiles, setProfiles] = useState<ProfileInfo[]>([])
269
+ const [deleg, setDeleg] = useState<DelegationStatus | null>(null)
270
+ const [liveMap, setLiveMap] = useState<ReadonlyMap<string, Live>>(() => new Map())
271
+ const [now, setNow] = useState(() => Date.now() / 1000)
272
+ const [pSel, setPSel] = useState(0)
273
+ const [dSel, setDSel] = useState(0)
274
+ const [err, setErr] = useState("")
275
+
276
+ const active = preorder(deleg?.active ?? [])
277
+ // Aggregates: rebuild the tree from the same snapshot + live
278
+ // enrichment. O(n) per poll (n≤max_concurrent×depth, tiny).
279
+ const nodes = buildTree(deleg?.active ?? [], liveMap, now)
280
+ const all = treeTotals(nodes)
281
+ const hotPeak = peak(nodes)
282
+ // Flat lookup: subagent_id → subtree aggregate, for the selected
283
+ // row's detail pane and per-row hotness colouring.
284
+ const aggOf = new Map<string, Agg>()
285
+ {
286
+ const walk = (ns: typeof nodes) => {
287
+ for (const n of ns) { aggOf.set(n.rec.subagent_id, n.agg); walk(n.kids) }
288
+ }
289
+ walk(nodes)
290
+ }
291
+ const live = useRef({ profiles, active })
292
+ live.current = { profiles, active }
293
+
294
+ // Gateway's own HERMES_HOME (may differ from herm's process env).
295
+ // Fetched once on mount; listProfiles() derives is_active from it.
296
+ const gwHome = useRef<string | undefined>(undefined)
297
+ // Lazy per-profile stats (session/msg/cron counts) — fetched when a
298
+ // profile is first selected, cached by path, cleared on `r`.
299
+ const [stats, setStats] = useState<ReadonlyMap<string, ProfileStats>>(() => new Map())
300
+
301
+ const loadProfiles = useCallback(() => {
302
+ setStats(new Map())
303
+ listProfiles(gwHome.current)
304
+ .then(ps => { setProfiles(ps); setErr("") })
305
+ .catch((e: Error) => setErr(`profiles: ${e.message}`))
306
+ }, [])
307
+
308
+ useEffect(() => {
309
+ gw.request<{ home?: string }>("config.get", { key: "profile" })
310
+ .then(r => { gwHome.current = r.home })
311
+ .catch(() => {})
312
+ .finally(loadProfiles)
313
+ }, [gw, loadProfiles])
314
+
315
+ const loadDeleg = useCallback(() => {
316
+ gw.request<DelegationStatus>("delegation.status")
317
+ .then(r => { setDeleg(r); setNow(Date.now() / 1000) })
318
+ .catch(() => setDeleg({ active: [], paused: false, max_spawn_depth: 0, max_concurrent_children: 0 }))
319
+ }, [gw])
320
+
321
+ useEffect(loadDeleg, [loadDeleg])
322
+
323
+ // Poll delegation while focused + agents are live; back off when idle.
324
+ useEffect(() => {
325
+ if (!props.focused) return
326
+ const ms = (deleg?.active.length ?? 0) > 0 ? 1500 : 5000
327
+ const t = setInterval(loadDeleg, ms)
328
+ return () => clearInterval(t)
329
+ }, [props.focused, deleg?.active.length, loadDeleg])
330
+
331
+ // Push enrichment: subagent.* events arrive regardless of focus; we
332
+ // fold them into a per-id map so rows/detail show fresh tool counts
333
+ // and the last tool/preview between registry polls. start/complete
334
+ // also trigger an immediate registry refresh so the list is instant.
335
+ useGatewayEvent(ev => {
336
+ if (!ev.type.startsWith("subagent.")) return
337
+ const p = ev.payload as { subagent_id?: string; tool_name?: string; tool_preview?: string;
338
+ text?: string; status?: string; input_tokens?: number; output_tokens?: number; cost_usd?: number }
339
+ const id = p.subagent_id
340
+ if (!id) return
341
+ setLiveMap(prev => {
342
+ const next = new Map(prev)
343
+ const cur = next.get(id) ?? { tool_count: 0 }
344
+ switch (ev.type) {
345
+ case "subagent.start":
346
+ next.set(id, { tool_count: 0 }); break
347
+ case "subagent.tool":
348
+ next.set(id, { ...cur, tool_count: cur.tool_count + 1,
349
+ last_tool: p.tool_name, last_preview: p.tool_preview }); break
350
+ case "subagent.thinking":
351
+ next.set(id, { ...cur, thinking: p.text }); break
352
+ case "subagent.complete":
353
+ next.set(id, { ...cur, status: p.status,
354
+ input_tokens: p.input_tokens, output_tokens: p.output_tokens, cost_usd: p.cost_usd }); break
355
+ }
356
+ return next
357
+ })
358
+ if (ev.type === "subagent.start" || ev.type === "subagent.complete") loadDeleg()
359
+ })
360
+
361
+ // Thin wrapper for `hermes profile <verb>` — all profile mutations go
362
+ // through the CLI so validation/skill-seeding/alias/cleanup stay
363
+ // upstream-owned. Returns stdout on success, throws on non-zero.
364
+ const sh = useCallback((cmd: string) =>
365
+ gw.request<ShellResult>("shell.exec", { command: cmd }).then(r => {
366
+ if (r.code !== 0) throw new Error((r.stderr || r.stdout || "exit " + r.code).trim())
367
+ return r.stdout
368
+ }), [gw])
369
+
370
+ // ── Stable callbacks ──────────────────────────────────────────────
371
+ const pHover = useCallback((i: number) => setPSel(i), [])
372
+ const dHover = useCallback((i: number) => setDSel(i), [])
373
+
374
+ const pDelete = useCallback(async (i: number) => {
375
+ const p = live.current.profiles[i]
376
+ if (!p || p.is_default || p.is_active) return
377
+ // `hermes profile delete` stops that profile's gateway first
378
+ // (SIGTERM + up to 10s wait). shell.exec is capped at 30s —
379
+ // usually fine, but warn so a rare timeout isn't mysterious.
380
+ const warn = p.gateway_running
381
+ ? "\n\nIts gateway is running and will be stopped first (may take up to ~10s)."
382
+ : ""
383
+ const ok = await openConfirm(dialog, {
384
+ title: "Delete Profile?",
385
+ body: `'${p.name}' — config, env, memory, skills, and sessions will be removed. This cannot be undone.${warn}`,
386
+ yes: "delete", danger: true,
387
+ })
388
+ if (!ok) return
389
+ sh(`hermes profile delete ${p.name} -y`)
390
+ .then(() => {
391
+ toast.show({ variant: "success", message: `Deleted '${p.name}'` })
392
+ loadProfiles()
393
+ })
394
+ .catch((e: Error) => toast.show({ variant: "error", message: e.message }))
395
+ }, [sh, dialog, toast, loadProfiles])
396
+
397
+ const pEnter = useCallback((i: number) => {
398
+ setPSel(i)
399
+ const p = live.current.profiles[i]
400
+ if (!p) return
401
+ openProfileMenu(dialog, p, {
402
+ sticky: (pp) => sh(`hermes profile use ${pp.name}`)
403
+ .then(() => { toast.show({ variant: "success", message: `Sticky default → '${pp.name}'` }); loadProfiles() })
404
+ .catch((e: Error) => toast.show({ variant: "error", message: e.message })),
405
+ unsticky: () => sh("hermes profile use --clear")
406
+ .then(() => { toast.show({ variant: "info", message: "Cleared sticky default" }); loadProfiles() })
407
+ .catch((e: Error) => toast.show({ variant: "error", message: e.message })),
408
+ export: (pp) => sh(`hermes profile export ${pp.name}`)
409
+ .then(out => toast.show({ variant: "success", message: trunc(out.trim() || `Exported '${pp.name}'`, 80) }))
410
+ .catch((e: Error) => toast.show({ variant: "error", message: e.message })),
411
+ remove: () => pDelete(i),
412
+ })
413
+ }, [sh, dialog, toast, loadProfiles, pDelete])
414
+
415
+ const dKill = useCallback(async (i: number) => {
416
+ const r = live.current.active[i]
417
+ if (!r) return
418
+ const ok = await openConfirm(dialog, {
419
+ title: "Interrupt subagent?",
420
+ body: `${trunc(r.goal, 120)}\n\nThe child returns whatever partial result it has so far.`,
421
+ yes: "interrupt", danger: true,
422
+ })
423
+ if (!ok) return
424
+ gw.request<{ found: boolean }>("subagent.interrupt", { subagent_id: r.subagent_id })
425
+ .then(res => {
426
+ toast.show(res.found
427
+ ? { variant: "success", message: `Interrupted ${r.subagent_id}` }
428
+ : { variant: "info", message: "Already finished" })
429
+ loadDeleg()
430
+ })
431
+ .catch((e: Error) => toast.show({ variant: "error", message: e.message }))
432
+ }, [gw, dialog, toast, loadDeleg])
433
+
434
+ const create = useCallback(() => {
435
+ openCreateProfile(dialog, { existing: live.current.profiles.map(p => p.name) })
436
+ .then(r => {
437
+ if (!r) return
438
+ const flags = [
439
+ r.cloneFrom ? `--clone --clone-from ${r.cloneFrom}` : "",
440
+ r.alias ? "" : "--no-alias",
441
+ ].filter(Boolean).join(" ")
442
+ toast.show({ variant: "info", message: `Creating '${r.name}'…` })
443
+ return sh(`hermes profile create ${r.name} ${flags}`.trim())
444
+ .then(() => {
445
+ toast.show({ variant: "success", message: `Created '${r.name}'` })
446
+ loadProfiles()
447
+ })
448
+ })
449
+ .catch((e: Error) => toast.show({ variant: "error", message: e.message }))
450
+ }, [sh, dialog, toast, loadProfiles])
451
+
452
+ const selected = profiles[pSel]
453
+
454
+ useEffect(() => {
455
+ const path = selected?.path
456
+ if (!path || stats.has(path)) return
457
+ let dead = false
458
+ profileStats(path).then(s => {
459
+ if (dead) return
460
+ setStats(prev => new Map(prev).set(path, s))
461
+ })
462
+ return () => { dead = true }
463
+ }, [selected?.path, stats])
464
+
465
+ const dims = useTerminalDimensions()
466
+ const wide = dims.width >= 130
467
+ const pWide = dims.width >= 170 || (!wide && dims.width >= 90)
468
+ const pFollow = useFollow("prof")
469
+ const dFollow = useFollow("deleg")
470
+
471
+ const keys = useKeys()
472
+ useKeyboard((key) => {
473
+ if (!props.focused || dialog.stack.length > 0) return
474
+ if (key.name === "tab") return setPane(p => p === "profiles" ? "deleg" : "profiles")
475
+ if (keys.match("list.refresh", key)) { loadProfiles(); loadDeleg(); toast.show({ variant: "info", message: "Reloaded", duration: 1000 }); return }
476
+ if (pane === "profiles") {
477
+ if (key.name === "escape" && !pWide && pView === "detail") return setPView("list")
478
+ handleListKey(keys, key, {
479
+ count: profiles.length, setSel: setPSel, ...pFollow.opts,
480
+ onNew: create,
481
+ onDelete: () => pDelete(pSel),
482
+ onActivate: () => {
483
+ if (!pWide && pView === "list") return setPView("detail")
484
+ pEnter(pSel)
485
+ },
486
+ })
487
+ return
488
+ }
489
+ const matched = handleListKey(keys, key, {
490
+ count: active.length, setSel: setDSel, ...dFollow.opts,
491
+ onDelete: () => dKill(dSel),
492
+ })
493
+ if (matched) return
494
+ if (keys.match("agents.kill", key)) return dKill(dSel)
495
+ if (keys.match("agents.history", key)) return openSpawnHistory(dialog, gw, props.sessionId)
496
+ })
497
+
498
+ const showProfiles = wide || pane === "profiles"
499
+ const showDeleg = wide || pane === "deleg"
500
+ const showList = pWide || pView === "list"
501
+ const showDetail = pWide || pView === "detail"
502
+
503
+ const sticky = stickyDefault()
504
+ const limits = deleg
505
+ ? `depth≤${deleg.max_spawn_depth} · conc≤${deleg.max_concurrent_children}` : ""
506
+ const dHint = active.length > 0
507
+ ? `${spark(nodes)} ${summary(all)}`
508
+ : limits
509
+
510
+ const togglePause = useCallback(() => {
511
+ const next = !deleg?.paused
512
+ gw.request<{ paused: boolean }>("delegation.pause", { paused: next })
513
+ .then(r => {
514
+ setDeleg(d => d ? { ...d, paused: r.paused } : d)
515
+ toast.show({ variant: "info", message: r.paused ? "Delegation paused" : "Delegation resumed" })
516
+ })
517
+ .catch((e: Error) => toast.show({ variant: "error", message: e.message }))
518
+ }, [gw, toast, deleg?.paused])
519
+
520
+ useEffect(() => cmd.register([
521
+ { title: deleg?.paused ? "Resume Delegation" : "Pause Delegation", value: "deleg.pause",
522
+ category: "Agents", onSelect: togglePause },
523
+ ]), [cmd, togglePause, deleg?.paused])
524
+
525
+ const pHint = pWide
526
+ ? `↑↓ nav ${keys.print("list.activate")} actions ${keys.print("list.new")} new ${keys.print("list.delete")} delete ${keys.print("list.refresh")} refresh`
527
+ : pView === "list" ? `↑↓ nav ${keys.print("list.activate")} detail ${keys.print("list.new")} new ${keys.print("list.delete")} delete`
528
+ : `${keys.print("list.activate")} actions Esc back ${keys.print("list.delete")} delete`
529
+
530
+ return (
531
+ <box flexDirection="row" flexGrow={1}>
532
+ {/* ── Profiles ── */}
533
+ {showProfiles ? (
534
+ <TabShell title={`Profiles (${profiles.length})${sticky ? ` · ★ ${sticky}` : ""}`}
535
+ hint={`${pHint} Tab ${wide ? "→" : "↔"} delegation`}
536
+ error={err || null}
537
+ focus={pane === "profiles"} grow={3}>
538
+ <box flexDirection="row" flexGrow={1} minWidth={0}>
539
+ {showList ? (
540
+ <box flexDirection="column" flexGrow={1} flexBasis={0} minWidth={14}>
541
+ <scrollbox ref={pFollow.ref} scrollY flexGrow={1} verticalScrollbarOptions={VBAR}>
542
+ {profiles.map((p, i) => (
543
+ <ProfileRow key={p.name} id={pFollow.id(i)} p={p} idx={i} selected={i === pSel}
544
+ onHover={pHover} onEnter={pEnter} onDelete={pDelete} />
545
+ ))}
546
+ </scrollbox>
547
+ </box>
548
+ ) : null}
549
+ {showList && showDetail ? <box width={2} /> : null}
550
+ {showDetail ? (
551
+ <box flexDirection="column" flexGrow={2} flexBasis={0} minWidth={0}>
552
+ {selected ? <ProfileDetail p={selected} stats={stats.get(selected.path)} />
553
+ : <box height={1}><text fg={theme.textMuted}>No profiles</text></box>}
554
+ </box>
555
+ ) : null}
556
+ </box>
557
+ </TabShell>
558
+ ) : null}
559
+
560
+ {/* ── Delegation ── */}
561
+ {showDeleg ? (
562
+ <TabShell title={`Delegation (${active.length})`}
563
+ hint={`↑↓ nav ${keys.print("agents.kill")} interrupt ${keys.print("agents.history")} history ${keys.print("list.refresh")} refresh · ${dHint}`}
564
+ focus={pane === "deleg"} grow={2}>
565
+ <box height={1} flexDirection="row" marginBottom={1}>
566
+ <box flexShrink={0} paddingX={1}
567
+ backgroundColor={deleg?.paused ? theme.warning : theme.backgroundElement}
568
+ onMouseDown={togglePause}>
569
+ <text fg={deleg?.paused ? theme.background : theme.text}>
570
+ {deleg?.paused ? "⏸ paused" : "▶ active"}
571
+ </text>
572
+ </box>
573
+ <box flexGrow={1} />
574
+ <text fg={theme.textMuted}>click to {deleg?.paused ? "resume" : "pause"}</text>
575
+ </box>
576
+ {active.length === 0 ? (
577
+ <box key="empty" flexGrow={1}>
578
+ <text fg={theme.textMuted}>
579
+ {deleg?.paused ? "Paused — new subagents will queue" : "No subagents running · h for history"}
580
+ </text>
581
+ </box>
582
+ ) : (
583
+ <box key="body" flexDirection="column" flexGrow={1} minHeight={0}>
584
+ <scrollbox ref={dFollow.ref} scrollY flexGrow={3} flexBasis={0} verticalScrollbarOptions={VBAR}>
585
+ {active.map((r, i) => {
586
+ const lv = liveMap.get(r.subagent_id)
587
+ const row = lv ? { ...r, tool_count: lv.tool_count } : r
588
+ const h = heat(aggOf.get(r.subagent_id)?.hot ?? 0, hotPeak, HOT.length)
589
+ return <DelegRow key={r.subagent_id} id={dFollow.id(i)} r={row} idx={i}
590
+ selected={i === dSel} now={now} hot={h}
591
+ onHover={dHover} onKill={dKill} />
592
+ })}
593
+ </scrollbox>
594
+ <box height={1}><text fg={theme.border}>{"─".repeat(4)}</text></box>
595
+ <box flexGrow={2} flexBasis={0} minHeight={0}>
596
+ {active[dSel]
597
+ ? <DelegDetail r={active[dSel]} live={liveMap.get(active[dSel].subagent_id)}
598
+ agg={aggOf.get(active[dSel].subagent_id)} now={now} />
599
+ : null}
600
+ </box>
601
+ </box>
602
+ )}
603
+ </TabShell>
604
+ ) : null}
605
+ </box>
606
+ )
607
+ })