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,599 @@
1
+ /**
2
+ * Context tab — two-level drill-down context window visualizer.
3
+ *
4
+ * Level 0: System Prompt | System Tools | MCP Tools | Memory |
5
+ * Skills | Conversation | Free
6
+ * Level 1: Click a group → grid expands to show children
7
+ * Detail: Click a leaf → right panel shows content
8
+ *
9
+ * The grid always fills 16×16 = 256 cells.
10
+ * At level 0, cells are proportional to the full context window.
11
+ * At level 1, cells are proportional to the drilled group's total.
12
+ */
13
+
14
+ import { useEffect, useState, useRef, useMemo, memo, type Dispatch, type SetStateAction } from "react"
15
+ import { CORNERS } from "../ui/borders"
16
+ import { useKeyboard } from "@opentui/react"
17
+
18
+ import type { Message } from "../types/message"
19
+ import { text as msgText } from "../types/message"
20
+ import type { ToolInfo, HermesConfig } from "../utils/hermes-home"
21
+ import type { SessionInfo } from "../utils/gateway-types"
22
+ import { useHome, home } from "../home"
23
+ import { useGateway } from "../app/gateway"
24
+ import { useKeys, handleListKey } from "../keys"
25
+ import { useDialog } from "../ui/dialog"
26
+ import { useToast } from "../ui/toast"
27
+ import { openTextPrompt } from "../dialogs/text-prompt"
28
+ import { count } from "../utils/tokens"
29
+ import {
30
+ parse,
31
+ build,
32
+ drill,
33
+ cells as buildCells,
34
+ classifyTools,
35
+ toolTokens,
36
+ type Segment,
37
+ } from "../utils/context-segments"
38
+ import { FileLink } from "../components/ui/FileLink"
39
+ import { useTheme, type Theme } from "../theme"
40
+ import { TabShell } from "../ui/shell"
41
+ import { categorical } from "../utils/categorical"
42
+ import type { RGBA } from "@opentui/core"
43
+
44
+ // ─── Types ───────────────────────────────────────────────────────────
45
+
46
+ type Props = {
47
+ description?: string
48
+ messages?: Message[]
49
+ sessionStart?: number
50
+ info?: SessionInfo
51
+ focused?: boolean
52
+ }
53
+
54
+ type Wire = { input: number; output: number; total: number; calls: number }
55
+
56
+ // ─── Constants ───────────────────────────────────────────────────────
57
+
58
+ // Conservative fallback when gateway hasn't surfaced info.context_max
59
+ // yet (fresh session, pre-session.info). Real value comes from
60
+ // SessionInfo.context_max on the wire.
61
+ const DEFAULT_CTX = 128_000
62
+ const COLS = 16
63
+
64
+ // ─── Colors ──────────────────────────────────────────────────────────
65
+
66
+ // Slot assignment for the categorical ramp. Order matters only in that it
67
+ // fixes each id to a stable hue family across themes; `free` is not a slot
68
+ // (it renders as borderSubtle since it's absence-of-content, not a category).
69
+ export const SLOTS = [
70
+ "system_prompt",
71
+ "system_tools",
72
+ "mcp_tools",
73
+ "memory",
74
+ "skills",
75
+ "conversation",
76
+ "soul",
77
+ "mem0",
78
+ "user",
79
+ "project",
80
+ "meta",
81
+ "other",
82
+ ] as const
83
+
84
+ const SLOT: Record<string, number> = Object.fromEntries(SLOTS.map((id, i) => [id, i]))
85
+
86
+ // Ramp is deterministic per theme; cache on theme identity so every clr()
87
+ // call across all panels resolves from one array. Theme objects are stable
88
+ // (resolved once in ThemeProvider), so WeakMap keying is safe.
89
+ const rampCache = new WeakMap<Theme, RGBA[]>()
90
+
91
+ function ramp(theme: Theme): RGBA[] {
92
+ let r = rampCache.get(theme)
93
+ if (!r) rampCache.set(theme, r = categorical(theme.primary, theme.background, SLOTS.length))
94
+ return r
95
+ }
96
+
97
+ export function clr(id: string, theme: Theme): RGBA {
98
+ if (id === "free") return theme.borderSubtle
99
+ return ramp(theme)[SLOT[id] ?? SLOT.other]
100
+ }
101
+
102
+ // ─── Utilities ───────────────────────────────────────────────────────
103
+
104
+ const fmt = (n: number) => {
105
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`
106
+ if (n >= 10_000) return `${Math.round(n / 1000)}k`
107
+ if (n >= 1_000) return `${(n / 1000).toFixed(1)}k`
108
+ return String(n)
109
+ }
110
+
111
+ const est = (s: string) => s ? count(s) : 0
112
+
113
+ const bar = (pct: number, w = 20) => {
114
+ const f = Math.round((Math.max(0, Math.min(100, pct)) / 100) * w)
115
+ return `[${"█".repeat(f)}${"░".repeat(Math.max(0, w - f))}]`
116
+ }
117
+
118
+ // ─── Detail Panels ──────────────────────────────────────────────────
119
+
120
+ /** Generic section detail — renders the raw document body as markdown. */
121
+ const SectionPanel = memo(({ seg, theme }: { seg: Segment; theme: Theme }) => {
122
+ const { syntaxStyle } = useTheme()
123
+ const sec = seg.section
124
+ if (!sec) return null
125
+ return (
126
+ <scrollbox borderStyle="single" padding={1} flexGrow={1} scrollY>
127
+ <text>
128
+ <strong><span fg={clr(seg.id, theme)}>◼</span> {seg.label} — {fmt(seg.tokens)} tokens ({seg.percent.toFixed(1)}%)</strong>
129
+ </text>
130
+ <text>{sec.chars.toLocaleString()} chars · ~{fmt(sec.tokens)} tokens</text>
131
+ {sec.source ? <box flexDirection="row" height={1}><text>Source: </text><FileLink source={sec.source} /></box> : null}
132
+ <text> </text>
133
+ <markdown content={sec.text} fg={theme.markdownText} syntaxStyle={syntaxStyle} />
134
+ </scrollbox>
135
+ )
136
+ })
137
+
138
+ /** Memory detail with capacity bar + entries */
139
+ const MemoryPanel = memo(({ seg, theme, label, chars, limit, pct, entries, source }: {
140
+ seg: Segment; theme: Theme; label: string
141
+ chars: number; limit: number; pct: number; entries: string[]
142
+ source?: { file: string; relative: string; label: string }
143
+ }) => (
144
+ <scrollbox borderStyle="single" padding={1} flexGrow={1} scrollY>
145
+ <text>
146
+ <strong><span fg={clr(seg.id, theme)}>◼</span> {seg.label} — {fmt(seg.tokens)} tokens ({seg.percent.toFixed(1)}%)</strong>
147
+ </text>
148
+ <text> </text>
149
+ <box flexDirection="row" height={1}>
150
+ <text><strong>{label}</strong></text>
151
+ {source ? <><text> (</text><FileLink source={source} /><text>)</text></> : null}
152
+ </box>
153
+ <text>{chars.toLocaleString()} / {limit.toLocaleString()} chars ({pct}%)</text>
154
+ <text>{bar(pct, 25)}{pct >= 95 ? " ⚠ near limit" : ""}</text>
155
+ <text> </text>
156
+ <text>{entries.length} entries:</text>
157
+ {entries.map((e, i) => <text key={i} fg={theme.text}>· {e}</text>)}
158
+ </scrollbox>
159
+ ))
160
+
161
+ /** Skills detail with category breakdown */
162
+ const SkillsPanel = memo(({ seg, theme }: { seg: Segment; theme: Theme }) => {
163
+ const sec = seg.section
164
+ if (!sec) return null
165
+ const cats: Record<string, number> = {}
166
+ for (const line of sec.text.split("\n")) {
167
+ if (line.match(/^\s{2}(\S[\w-]*(?:\/\S+)?):\s/)) {
168
+ const cat = line.match(/^\s{2}(\S[\w-]*(?:\/\S+)?):\s/)![1]
169
+ if (!cats[cat]) cats[cat] = 0
170
+ }
171
+ if (line.match(/^\s{4}- \S+:/)) {
172
+ const last = Object.keys(cats).pop()
173
+ if (last) cats[last]++
174
+ }
175
+ }
176
+ const sorted = Object.entries(cats).sort((a, b) => b[1] - a[1])
177
+ const total = sorted.reduce((s, [, n]) => s + n, 0)
178
+
179
+ return (
180
+ <scrollbox borderStyle="single" padding={1} flexGrow={1} scrollY>
181
+ <text>
182
+ <strong><span fg={clr("skills", theme)}>◼</span> Skills Catalog — {fmt(seg.tokens)} tokens ({seg.percent.toFixed(1)}%)</strong>
183
+ </text>
184
+ {sec.source ? <box flexDirection="row" height={1}><text>Source: </text><FileLink source={sec.source} /></box> : null}
185
+ <text> </text>
186
+ <text>{total} skills in {sorted.length} categories · {sec.chars.toLocaleString()} chars</text>
187
+ <text fg={theme.textMuted}>Largest context section — skill names + descriptions injected every turn.</text>
188
+ <text> </text>
189
+ {sorted.map(([cat, n]) => <text key={cat} fg={theme.text}>· {cat} ({n})</text>)}
190
+ </scrollbox>
191
+ )
192
+ })
193
+
194
+ /** Tools detail — handles system builtins or MCP depending on `kind` */
195
+ const ToolsPanel = memo(({ seg, theme, tools, kind }: {
196
+ seg: Segment; theme: Theme; tools: ReadonlyArray<ToolInfo>
197
+ kind: "system_tools" | "mcp_tools"
198
+ }) => {
199
+ const sorted = [...tools].sort((a, b) =>
200
+ (b.descriptionLength + b.paramsLength) - (a.descriptionLength + a.paramsLength),
201
+ )
202
+ const label = kind === "mcp_tools" ? "MCP Tools" : "System Tools"
203
+ const blurb = kind === "mcp_tools"
204
+ ? "MCP-loaded tools — schemas injected via mcp_ prefix."
205
+ : "Built-in tool schemas sent with every API call."
206
+ return (
207
+ <scrollbox borderStyle="single" padding={1} flexGrow={1} scrollY>
208
+ <text>
209
+ <strong><span fg={clr(kind, theme)}>◼</span> {label} — {fmt(seg.tokens)} tokens ({seg.percent.toFixed(1)}%)</strong>
210
+ </text>
211
+ <text> </text>
212
+ <text>{tools.length} tools — {blurb}</text>
213
+ <text> </text>
214
+ {sorted.map(t => (
215
+ <text key={t.name} fg={theme.text}>
216
+ · {t.name} ({fmt(toolTokens(t))} tok)
217
+ </text>
218
+ ))}
219
+ </scrollbox>
220
+ )
221
+ })
222
+
223
+ /** Conversation detail */
224
+ const ConvPanel = memo(({ seg, theme, messages, output }: {
225
+ seg: Segment; theme: Theme; messages: Message[]; output: number
226
+ }) => {
227
+ const user = messages.filter(m => m.role === "user")
228
+ const asst = messages.filter(m => m.role === "assistant")
229
+ const non = messages.filter(m => m.role !== "system")
230
+ return (
231
+ <scrollbox borderStyle="single" padding={1} flexGrow={1} scrollY>
232
+ <text>
233
+ <strong><span fg={clr("conversation", theme)}>◼</span> Conversation — {fmt(seg.tokens)} tokens ({seg.percent.toFixed(1)}%)</strong>
234
+ </text>
235
+ <text> </text>
236
+ <text>User: {user.length} msgs (~{fmt(est(user.map(m => msgText(m)).join("")))} tok)</text>
237
+ <text>Agent: {asst.length} msgs (~{fmt(est(asst.map(m => msgText(m)).join("")))} tok)</text>
238
+ {output > 0 ? <text>Output generated: {fmt(output)} tokens</text> : null}
239
+ <text> </text>
240
+ {non.length > 0 ? (
241
+ <>
242
+ <text fg={theme.info}>Messages:</text>
243
+ <text> </text>
244
+ {non.map((m, i) => (
245
+ <text key={i}>
246
+ <span fg={m.role === "user" ? theme.info : theme.success}>
247
+ {m.role === "user" ? "▸ You" : "◂ Agent"}
248
+ </span>{" "}({fmt(est(msgText(m)))}) {msgText(m).replace(/\n/g, " ")}
249
+ </text>
250
+ ))}
251
+ </>
252
+ ) : <text fg={theme.warning}>No messages yet</text>}
253
+ </scrollbox>
254
+ )
255
+ })
256
+
257
+ /** Free space detail */
258
+ const FreePanel = memo(({ seg, theme, ctxLen, comp, onEditThreshold }: {
259
+ seg: Segment; theme: Theme; ctxLen: number
260
+ comp: HermesConfig["compression"] | undefined
261
+ onEditThreshold: () => void
262
+ }) => {
263
+ const used = ctxLen - seg.tokens
264
+ const threshold = Math.round(ctxLen * (comp?.threshold ?? 0.5))
265
+ const pct = threshold > 0 ? Math.min(100, Math.round((used / threshold) * 100)) : 0
266
+ return (
267
+ <scrollbox borderStyle="single" padding={1} flexGrow={1} scrollY>
268
+ <text><strong><span fg={clr("free", theme)}>◻</span> Free Space — {fmt(seg.tokens)} tokens</strong></text>
269
+ <text> </text>
270
+ <text>Context window: {fmt(ctxLen)}</text>
271
+ <text>Used: {fmt(used)} ({Math.round((used / ctxLen) * 100)}%)</text>
272
+ <text>Available: {fmt(seg.tokens)} ({seg.percent.toFixed(1)}%)</text>
273
+ <text> </text>
274
+ {comp ? (
275
+ <>
276
+ <text><strong>Compression</strong></text>
277
+ <box height={1} flexDirection="row">
278
+ <text>{comp.enabled ? "✓ Enabled" : "✗ Disabled"} · threshold </text>
279
+ <box flexShrink={0} onMouseDown={onEditThreshold}>
280
+ <text fg={theme.info}><u>{Math.round(comp.threshold * 100)}%</u></text>
281
+ </box>
282
+ <text> ({fmt(threshold)})</text>
283
+ </box>
284
+ <text>{bar(pct)} {pct}%</text>
285
+ <text>Protect last {comp.protect_last_n} messages · target ratio {Math.round(comp.target_ratio * 100)}%</text>
286
+ {comp.summary_model ? <text>Summary model: {comp.summary_model}</text> : null}
287
+ </>
288
+ ) : null}
289
+ </scrollbox>
290
+ )
291
+ })
292
+
293
+ // Stable empty default so memo comparison and downstream useEffect
294
+ // deps don't see a fresh [] reference on every render.
295
+ const NO_MESSAGES: readonly Message[] = Object.freeze([])
296
+
297
+ // ─── Main Component ──────────────────────────────────────────────────
298
+
299
+ export const Context = memo(({ messages = NO_MESSAGES as Message[], info, focused }: Props) => {
300
+ const config = useHome("config")
301
+ const memory = useHome("memory")
302
+ const userProfile = useHome("userProfile")
303
+ const gw = useGateway()
304
+ const dialog = useDialog()
305
+ const toast = useToast()
306
+ const systemPrompt = useHome("systemPrompt")
307
+ const toolsInfo = useHome("toolsInfo")
308
+ const soul = useHome("soul")
309
+ const recentSessions = useHome("recentSessions")
310
+ const liveSessions = useHome("liveSessions")
311
+
312
+ const [wire, setWire] = useState<Wire>({ input: 0, output: 0, total: 0, calls: 0 })
313
+ const wireRef = useRef(wire)
314
+ const theme = useTheme().theme
315
+ const [hovered, setHovered] = useState<string | null>(null)
316
+ const [selected, setSelected] = useState<string | null>(null)
317
+ const [drilled, setDrilled] = useState<string | null>(null)
318
+
319
+ // Track wire usage from messages
320
+ useEffect(() => {
321
+ let input = 0, output = 0, total = 0, calls = 0
322
+ for (const m of messages) {
323
+ if (m.usage) {
324
+ input += m.usage.input
325
+ output += m.usage.output
326
+ total += m.usage.total
327
+ calls++
328
+ }
329
+ }
330
+ const next: Wire = { input, output, total, calls }
331
+ wireRef.current = next
332
+ setWire(next)
333
+ }, [messages])
334
+
335
+ // Derived
336
+ const session = recentSessions?.[0]
337
+ // Gateway's context_max is the authoritative runtime value. Fall back
338
+ // to DEFAULT_CTX only during the fresh-session window before
339
+ // session.info lands.
340
+ const ctxLen = info?.context_max ?? DEFAULT_CTX
341
+
342
+ const live = session
343
+ ? Object.values(liveSessions ?? {}).find(ls => ls.session_id === session.id)
344
+ : undefined
345
+
346
+ const lastPrompt = live?.last_prompt_tokens ?? 0
347
+ const fill = wire.calls > 0 ? wire.input : lastPrompt > 0 ? lastPrompt : (session?.input_tokens ?? 0)
348
+ const cumulative = wire.calls === 0 && lastPrompt === 0 && (session?.input_tokens ?? 0) > 0
349
+ const output = wire.calls > 0 ? wire.output : (session?.output_tokens ?? 0)
350
+ const pct = ctxLen > 0 ? Math.round((fill / ctxLen) * 100) : 0
351
+
352
+ // Threshold marker inputs. `config.compression.threshold` is the
353
+ // single source of truth; server reads the same key.
354
+ const thresholdPct = config?.compression?.threshold ?? 0.5
355
+ // Linear cell index (0..255) at threshold; cells at/past render ◼ in textMuted.
356
+ const thresholdIdx = Math.min(COLS * COLS, Math.max(0, Math.round(thresholdPct * COLS * COLS)))
357
+ const compressions = info?.usage?.compressions ?? 0
358
+
359
+ // Parse + build
360
+ const sections = useMemo(() => parse(systemPrompt?.text ?? ""), [systemPrompt?.text])
361
+ const convTok = useMemo(() => est(messages.filter(m => m.role !== "system").map(m => msgText(m)).join("")), [messages])
362
+
363
+ const top = useMemo(() => build({
364
+ contextLength: ctxLen,
365
+ inputTokens: fill,
366
+ sections,
367
+ conversationTokens: convTok,
368
+ tools: toolsInfo?.tools ?? [],
369
+ }), [ctxLen, fill, sections, convTok, toolsInfo?.tools])
370
+
371
+ // Current view: top-level or drilled
372
+ const drilledGroup = drilled ? top.find(s => s.id === drilled) : null
373
+ const view = drilledGroup ? drill(drilledGroup) : top
374
+ const grid = useMemo(
375
+ () => buildCells(view, drilledGroup ? drilledGroup.children?.[0]?.id ?? "other" : "free"),
376
+ [view, drilledGroup],
377
+ )
378
+
379
+ // Helpers
380
+ const findSeg = (id: string) => {
381
+ if (drilledGroup) return view.find(s => s.id === id)
382
+ return top.find(s => s.id === id)
383
+ }
384
+
385
+ const memEntries = useMemo(() => (memory?.content ?? "").split("§").map(s => s.trim()).filter(Boolean), [memory?.content])
386
+ const userEntries = useMemo(() => (userProfile?.content ?? "").split("§").map(s => s.trim()).filter(Boolean), [userProfile?.content])
387
+
388
+ // Click handler
389
+ const click = (id: string) => {
390
+ // Already drilled — clicking selects detail or deselects
391
+ if (drilled) {
392
+ setSelected(selected === id ? null : id)
393
+ return
394
+ }
395
+ // Top level — if group with children, drill in
396
+ const seg = top.find(s => s.id === id)
397
+ if (seg?.children && seg.children.length > 0) {
398
+ setDrilled(id)
399
+ setSelected(null)
400
+ return
401
+ }
402
+ // Leaf at top level — toggle detail
403
+ setSelected(selected === id ? null : id)
404
+ }
405
+
406
+ // Esc pops one drill level (detail → group → overview); double-tap
407
+ // within 400ms jumps straight to overview. Replaces the '◀ Back to
408
+ // overview' row, which stole a line above the grid and broke
409
+ // top-alignment with the breakdown pane.
410
+ const lastEsc = useRef(0)
411
+ // Keyboard: grid navigates via shared list.* vocabulary so rebinds
412
+ // (j/k, home/end, PgUp/PgDn) flow here for free. Flattened row-major
413
+ // segs is the 'list'; setSel maps index ↔ selected id. ←/→ are tab-
414
+ // local aliases since the grid reads 2D but traversal is linear.
415
+ const segs = view.filter(s => s.tokens > 0)
416
+ const idx = selected ? segs.findIndex(s => s.id === selected) : -1
417
+ const setSel: Dispatch<SetStateAction<number>> = (v) => {
418
+ const n = Math.max(0, Math.min(segs.length - 1, typeof v === "function" ? v(idx) : v))
419
+ setSelected(segs[n]?.id ?? null)
420
+ }
421
+ const keys = useKeys()
422
+ useKeyboard((key) => {
423
+ if (!focused || dialog.stack.length > 0) return
424
+ if (handleListKey(keys, key, {
425
+ count: segs.length, setSel,
426
+ onActivate: () => {
427
+ if (drilled || !selected) return
428
+ const seg = top.find(s => s.id === selected)
429
+ if (seg?.children?.length) { setDrilled(selected); setSelected(null) }
430
+ },
431
+ })) return
432
+ if (key.name === "right") return setSel(p => p + 1)
433
+ if (key.name === "left") return setSel(p => p - 1)
434
+ if (key.name !== "escape") return
435
+ const now = Date.now()
436
+ if (now - lastEsc.current < 400) {
437
+ setSelected(null); setDrilled(null); lastEsc.current = 0; return
438
+ }
439
+ lastEsc.current = now
440
+ if (selected) return setSelected(null)
441
+ if (drilled) return setDrilled(null)
442
+ })
443
+
444
+ const editThreshold = async () => {
445
+ const cur = Math.round((config?.compression?.threshold ?? 0.5) * 100)
446
+ const v = await openTextPrompt(dialog, {
447
+ title: "Compression threshold", label: "Percent (10–95)", initial: String(cur),
448
+ })
449
+ if (v === null) return
450
+ const n = Math.max(10, Math.min(95, Number(v) || cur))
451
+ const { writeConfig } = await import("../config/lane")
452
+ const r = await writeConfig(gw, [{ key: "compression.threshold", to: n / 100 }])
453
+ if (r.failed.length) return toast.show({ variant: "error", message: r.failed[0].err })
454
+ home.invalidate("config")
455
+ toast.show({ variant: "success", message: `Threshold → ${n}%` })
456
+ }
457
+
458
+ // Detail panel router
459
+ const detail = () => {
460
+ if (!selected) return null
461
+ const seg = findSeg(selected)
462
+ if (!seg) return null
463
+
464
+ // Memory children (accessible when drilled into memory group)
465
+ if (selected === "memory" && drilled === "memory" && memory) {
466
+ return <MemoryPanel seg={seg} theme={theme} label="Agent Notes" chars={memory.charCount} limit={memory.charLimit} pct={memory.usagePercent} entries={memEntries} source={memory.source} />
467
+ }
468
+ if (selected === "user" && userProfile) {
469
+ return <MemoryPanel seg={seg} theme={theme} label="User Profile" chars={userProfile.charCount} limit={userProfile.charLimit} pct={userProfile.usagePercent} entries={userEntries} source={userProfile.source} />
470
+ }
471
+ if (selected === "skills") return <SkillsPanel seg={seg} theme={theme} />
472
+ if (selected === "system_tools" && toolsInfo) {
473
+ const { system } = classifyTools(toolsInfo.tools)
474
+ return <ToolsPanel seg={seg} theme={theme} tools={system} kind="system_tools" />
475
+ }
476
+ if (selected === "mcp_tools" && toolsInfo) {
477
+ const { mcp } = classifyTools(toolsInfo.tools)
478
+ return <ToolsPanel seg={seg} theme={theme} tools={mcp} kind="mcp_tools" />
479
+ }
480
+ // SOUL drill: prefer the file-backed slice (authoritative read) over
481
+ // the parsed segment from systemPrompt.text.
482
+ if (selected === "soul" && soul) {
483
+ const soulSeg: Segment = {
484
+ ...seg,
485
+ section: {
486
+ id: "soul",
487
+ label: "SOUL.md",
488
+ chars: soul.charCount,
489
+ tokens: soul.tokenEstimate,
490
+ text: soul.content,
491
+ source: soul.source,
492
+ },
493
+ }
494
+ return <SectionPanel seg={soulSeg} theme={theme} />
495
+ }
496
+ if (selected === "conversation") return <ConvPanel seg={seg} theme={theme} messages={messages} output={output} />
497
+ if (selected === "free") return <FreePanel seg={seg} theme={theme} ctxLen={ctxLen} comp={config?.compression} onEditThreshold={editThreshold} />
498
+ return <SectionPanel seg={seg} theme={theme} />
499
+ }
500
+
501
+ // Breakdown panel
502
+ const breakdown = () => (
503
+ <box flexDirection="column" marginBottom={1}>
504
+ <text>
505
+ <strong>Breakdown</strong>
506
+ {drilledGroup ? (
507
+ <span fg={theme.info}> · {drilledGroup.label} ({fmt(drilledGroup.tokens)} tok)</span>
508
+ ) : (
509
+ <span fg={theme.info}> (click group to expand)</span>
510
+ )}
511
+ </text>
512
+ {view.filter(s => s.tokens > 0).map(s => (
513
+ <text key={s.id}>
514
+ <span fg={clr(s.id, theme)}>{s.id === "free" ? "◻" : "◼"}</span>{" "}
515
+ {s.label} — {fmt(s.tokens)} ({s.percent.toFixed(1)}%)
516
+ {s.children ? <span fg={theme.textMuted}> ▸</span> : null}
517
+ </text>
518
+ ))}
519
+ {output > 0 && !drilled ? (
520
+ <text><span fg={theme.success}>◼</span> Output — {fmt(output)} tokens</text>
521
+ ) : null}
522
+ <text>
523
+ <span fg={theme.textMuted}>◼ Beyond compression threshold ({Math.round(thresholdPct * 100)}%)</span>
524
+ </text>
525
+ </box>
526
+ )
527
+
528
+ const crumb = drilled
529
+ ? `${drilledGroup?.label}${selected ? ` · ${findSeg(selected)?.label}` : ""}`
530
+ : wire.calls === 0 && fill === 0 ? "[no data]"
531
+ : cumulative ? "[cumulative — not current fill]"
532
+ : wire.calls === 0 && fill > 0 ? "[live session]"
533
+ : "↑↓ nav · click a group to drill in"
534
+ const escHint = selected || drilled ? " · Esc back" : ""
535
+
536
+ const focus = selected || hovered
537
+ const focusSeg = focus ? findSeg(focus) : null
538
+
539
+ return (
540
+ <TabShell
541
+ title={`Context · ${fmt(fill)} / ${fmt(ctxLen)} (${pct}%)`}
542
+ hint={crumb + escHint}
543
+ >
544
+ <box height={1}>
545
+ {focusSeg ? (
546
+ <text fg={clr(focusSeg.id, theme)}>
547
+ ◼ {focusSeg.label} — {fmt(focusSeg.tokens)} tok ({focusSeg.percent.toFixed(1)}%)
548
+ </text>
549
+ ) : <text>{" "}</text>}
550
+ </box>
551
+ <box height={1} />
552
+ <box flexDirection="row" flexGrow={1}>
553
+ <box flexDirection="column" marginRight={2} flexShrink={0}>
554
+ {/* Compression badge — shown inline above the grid when any
555
+ compression events have fired this session. */}
556
+ {compressions > 0 ? (
557
+ <box height={1} marginBottom={1}>
558
+ <text fg={theme.warning}>×{compressions} compressed</text>
559
+ </box>
560
+ ) : null}
561
+ <box border
562
+ customBorderChars={CORNERS}
563
+ borderColor={theme.border}>
564
+ {[...Array(COLS)].map((_, row) => (
565
+ <box key={row} flexDirection="row" height={1}>
566
+ {[...Array(COLS)].map((_, col) => {
567
+ const cell = grid[row * COLS + col]
568
+ // Selection wins over hover — otherwise hovering a
569
+ // different segment lights both groups at once.
570
+ const hl = selected ? selected === cell.id : hovered === cell.id
571
+ // Past-threshold cells: ◼ in textMuted; hover still shows category color.
572
+ const past = row * COLS + col >= thresholdIdx
573
+ const glyph = !past && cell.id === "free" ? "◻" : "◼"
574
+ return (
575
+ <box
576
+ height={1} width={2} key={col}
577
+ backgroundColor={hl ? clr(cell.id, theme) : undefined}
578
+ onMouseOver={() => setHovered(cell.id)}
579
+ onMouseOut={() => setHovered(null)}
580
+ onMouseDown={() => click(cell.id)}
581
+ >
582
+ <text fg={past ? theme.textMuted : clr(cell.id, theme)}>
583
+ {glyph}
584
+ </text>
585
+ </box>
586
+ )
587
+ })}
588
+ </box>
589
+ ))}
590
+ </box>
591
+ </box>
592
+
593
+ <box flexDirection="column" flexGrow={1} minWidth={0}>
594
+ {selected ? detail() : breakdown()}
595
+ </box>
596
+ </box>
597
+ </TabShell>
598
+ )
599
+ })