herm-tui 1.0.0-dev.1 → 1.0.0-dev.3

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 (188) hide show
  1. package/db.worker.js +81 -0
  2. package/highlights-eq9cgrbb.scm +604 -0
  3. package/highlights-ghv9g403.scm +205 -0
  4. package/highlights-hk7bwhj4.scm +284 -0
  5. package/highlights-r812a2qc.scm +150 -0
  6. package/highlights-x6tmsnaa.scm +115 -0
  7. package/index.js +10374 -0
  8. package/injections-73j83es3.scm +27 -0
  9. package/package.json +14 -64
  10. package/parser.worker.js +8 -0
  11. package/tree-sitter-3jzf13jk.wasm +0 -0
  12. package/tree-sitter-javascript-nd0q4pe9.wasm +0 -0
  13. package/tree-sitter-markdown-411r6y9b.wasm +0 -0
  14. package/tree-sitter-markdown_inline-j5349f42.wasm +0 -0
  15. package/tree-sitter-typescript-zxjzwt75.wasm +0 -0
  16. package/tree-sitter-zig-e78zbjpm.wasm +0 -0
  17. package/scripts/postinstall.ts +0 -29
  18. package/src/app/gateway.tsx +0 -83
  19. package/src/app/gatewayEvents.ts +0 -203
  20. package/src/app/launch.ts +0 -41
  21. package/src/app/skin.tsx +0 -31
  22. package/src/app/spawnHistory.ts +0 -75
  23. package/src/app/tabs.ts +0 -23
  24. package/src/app/turnReducer.ts +0 -390
  25. package/src/app/useAppKeys.ts +0 -268
  26. package/src/app/useAtRefPopover.ts +0 -99
  27. package/src/app/useInputHistory.ts +0 -66
  28. package/src/app/useSession.ts +0 -102
  29. package/src/app/useSlashCommands.ts +0 -70
  30. package/src/app/useSlashPopover.ts +0 -48
  31. package/src/app.tsx +0 -917
  32. package/src/commands/slash.ts +0 -151
  33. package/src/components/avatar/AnimatedAvatar.tsx +0 -66
  34. package/src/components/avatar/eikon.ts +0 -144
  35. package/src/components/avatar/states/error.ts +0 -1155
  36. package/src/components/avatar/states/idle.ts +0 -1155
  37. package/src/components/avatar/states/index.ts +0 -30
  38. package/src/components/avatar/states/listening.ts +0 -1155
  39. package/src/components/avatar/states/speaking.ts +0 -1155
  40. package/src/components/avatar/states/thinking.ts +0 -1155
  41. package/src/components/avatar/states/working.ts +0 -1155
  42. package/src/components/chat/AtRefPopover.tsx +0 -54
  43. package/src/components/chat/CodeBlock.tsx +0 -67
  44. package/src/components/chat/Composer.tsx +0 -347
  45. package/src/components/chat/DiffBlock.tsx +0 -116
  46. package/src/components/chat/ErrorBlock.tsx +0 -70
  47. package/src/components/chat/MediaChip.tsx +0 -114
  48. package/src/components/chat/MessageItem.tsx +0 -282
  49. package/src/components/chat/MessageList.tsx +0 -114
  50. package/src/components/chat/PromptCard.tsx +0 -359
  51. package/src/components/chat/SlashPopover.tsx +0 -158
  52. package/src/components/chat/ThoughtCloud.tsx +0 -185
  53. package/src/components/chat/TypingIndicator.tsx +0 -25
  54. package/src/components/chat/tool/Subagent.tsx +0 -75
  55. package/src/components/chat/tool/frame.tsx +0 -69
  56. package/src/components/chat/tool/index.tsx +0 -65
  57. package/src/components/chat/tool/preview.ts +0 -57
  58. package/src/components/sidebar/ContextGauge.tsx +0 -102
  59. package/src/components/sidebar/Sidebar.tsx +0 -143
  60. package/src/components/tabs/TabBar.tsx +0 -50
  61. package/src/components/ui/FileLink.tsx +0 -52
  62. package/src/config/index.ts +0 -156
  63. package/src/config/lane.ts +0 -161
  64. package/src/config/models.ts +0 -95
  65. package/src/config/rules.ts +0 -80
  66. package/src/config/schema.ts +0 -308
  67. package/src/dialogs/alert.tsx +0 -52
  68. package/src/dialogs/chafa.tsx +0 -72
  69. package/src/dialogs/confirm.tsx +0 -58
  70. package/src/dialogs/curator.tsx +0 -153
  71. package/src/dialogs/eikon-picker.tsx +0 -95
  72. package/src/dialogs/help.tsx +0 -80
  73. package/src/dialogs/history.tsx +0 -92
  74. package/src/dialogs/info.tsx +0 -115
  75. package/src/dialogs/keys.tsx +0 -170
  76. package/src/dialogs/logs.tsx +0 -42
  77. package/src/dialogs/message.tsx +0 -38
  78. package/src/dialogs/model-picker.tsx +0 -123
  79. package/src/dialogs/new-profile.tsx +0 -69
  80. package/src/dialogs/new-task.tsx +0 -103
  81. package/src/dialogs/profile.tsx +0 -55
  82. package/src/dialogs/rollback.tsx +0 -190
  83. package/src/dialogs/spawn-history.tsx +0 -80
  84. package/src/dialogs/text-prompt.tsx +0 -68
  85. package/src/dialogs/theme-picker.tsx +0 -50
  86. package/src/home/index.ts +0 -23
  87. package/src/home/store.ts +0 -267
  88. package/src/index.tsx +0 -113
  89. package/src/keys/catalog.ts +0 -115
  90. package/src/keys/chord.ts +0 -125
  91. package/src/keys/conflicts.ts +0 -48
  92. package/src/keys/context.tsx +0 -112
  93. package/src/keys/index.ts +0 -5
  94. package/src/keys/list.ts +0 -94
  95. package/src/keys/oc-compat.ts +0 -87
  96. package/src/tabs/Agents.tsx +0 -607
  97. package/src/tabs/Analytics.tsx +0 -154
  98. package/src/tabs/Chat.tsx +0 -50
  99. package/src/tabs/Config.tsx +0 -605
  100. package/src/tabs/Context.tsx +0 -599
  101. package/src/tabs/Cron.tsx +0 -294
  102. package/src/tabs/Env.tsx +0 -227
  103. package/src/tabs/Kanban.tsx +0 -367
  104. package/src/tabs/Memory.tsx +0 -294
  105. package/src/tabs/Sessions.tsx +0 -786
  106. package/src/tabs/Skills.tsx +0 -507
  107. package/src/tabs/Toolsets.tsx +0 -266
  108. package/src/theme/builtin.ts +0 -78
  109. package/src/theme/context.tsx +0 -106
  110. package/src/theme/index.ts +0 -4
  111. package/src/theme/resolve.ts +0 -134
  112. package/src/theme/syntax.ts +0 -31
  113. package/src/theme/themes/aura.json +0 -69
  114. package/src/theme/themes/ayu.json +0 -80
  115. package/src/theme/themes/carbonfox.json +0 -248
  116. package/src/theme/themes/catppuccin-frappe.json +0 -233
  117. package/src/theme/themes/catppuccin-macchiato.json +0 -233
  118. package/src/theme/themes/catppuccin.json +0 -112
  119. package/src/theme/themes/cobalt2.json +0 -228
  120. package/src/theme/themes/cursor.json +0 -249
  121. package/src/theme/themes/dracula.json +0 -219
  122. package/src/theme/themes/everforest.json +0 -241
  123. package/src/theme/themes/flexoki.json +0 -237
  124. package/src/theme/themes/github.json +0 -233
  125. package/src/theme/themes/gruvbox.json +0 -242
  126. package/src/theme/themes/kanagawa.json +0 -77
  127. package/src/theme/themes/lucent-orng.json +0 -237
  128. package/src/theme/themes/material.json +0 -235
  129. package/src/theme/themes/matrix.json +0 -77
  130. package/src/theme/themes/mercury.json +0 -252
  131. package/src/theme/themes/monokai.json +0 -221
  132. package/src/theme/themes/nightowl.json +0 -221
  133. package/src/theme/themes/nord.json +0 -223
  134. package/src/theme/themes/one-dark.json +0 -84
  135. package/src/theme/themes/opencode.json +0 -245
  136. package/src/theme/themes/orng.json +0 -249
  137. package/src/theme/themes/osaka-jade.json +0 -93
  138. package/src/theme/themes/palenight.json +0 -222
  139. package/src/theme/themes/rosepine.json +0 -234
  140. package/src/theme/themes/solarized.json +0 -223
  141. package/src/theme/themes/synthwave84.json +0 -226
  142. package/src/theme/themes/tokyonight.json +0 -243
  143. package/src/theme/themes/vercel.json +0 -245
  144. package/src/theme/themes/vesper.json +0 -218
  145. package/src/theme/themes/zenburn.json +0 -223
  146. package/src/theme/types.ts +0 -119
  147. package/src/types/message.ts +0 -97
  148. package/src/ui/ChafaImage.tsx +0 -64
  149. package/src/ui/Splash.tsx +0 -118
  150. package/src/ui/borders.ts +0 -28
  151. package/src/ui/command.tsx +0 -104
  152. package/src/ui/dialog-select.tsx +0 -164
  153. package/src/ui/dialog.tsx +0 -102
  154. package/src/ui/fmt.ts +0 -82
  155. package/src/ui/kv.tsx +0 -28
  156. package/src/ui/shell.tsx +0 -45
  157. package/src/ui/spinner.tsx +0 -59
  158. package/src/ui/splash-art.ts +0 -123
  159. package/src/ui/table.tsx +0 -117
  160. package/src/ui/ticker.tsx +0 -90
  161. package/src/ui/toast.tsx +0 -130
  162. package/src/utils/categorical.ts +0 -77
  163. package/src/utils/chafa.ts +0 -173
  164. package/src/utils/clipboard.ts +0 -67
  165. package/src/utils/context-segments.ts +0 -317
  166. package/src/utils/control.ts +0 -495
  167. package/src/utils/drop.ts +0 -25
  168. package/src/utils/editor.ts +0 -33
  169. package/src/utils/fuzzy.ts +0 -45
  170. package/src/utils/gateway-client.ts +0 -253
  171. package/src/utils/gateway-types.ts +0 -282
  172. package/src/utils/git.ts +0 -57
  173. package/src/utils/hermes-analytics.ts +0 -134
  174. package/src/utils/hermes-home.ts +0 -821
  175. package/src/utils/hermes-kanban.ts +0 -154
  176. package/src/utils/hermes-profiles.ts +0 -217
  177. package/src/utils/interpolate.ts +0 -31
  178. package/src/utils/math-unicode.ts +0 -818
  179. package/src/utils/memory-activity.ts +0 -140
  180. package/src/utils/open-file.ts +0 -13
  181. package/src/utils/paths.ts +0 -52
  182. package/src/utils/perf.ts +0 -235
  183. package/src/utils/preferences.ts +0 -150
  184. package/src/utils/sessions-db.ts +0 -396
  185. package/src/utils/subagent-tree.ts +0 -146
  186. package/src/utils/terminal-reset.ts +0 -129
  187. package/src/utils/tips.ts +0 -67
  188. package/src/utils/tokens.ts +0 -87
@@ -1,599 +0,0 @@
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
- })