@clagentic/console 1.0.0-beta.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 (221) hide show
  1. package/CREDITS.md +3 -0
  2. package/LICENSE +21 -0
  3. package/README.md +250 -0
  4. package/bin/cli.js +2812 -0
  5. package/lib/agents-favorites.js +164 -0
  6. package/lib/agents.js +282 -0
  7. package/lib/ask-user-mcp-server.js +120 -0
  8. package/lib/browser-mcp-server.js +484 -0
  9. package/lib/build-user-env.js +63 -0
  10. package/lib/certs/fullchain.pem +47 -0
  11. package/lib/certs/privkey.pem +5 -0
  12. package/lib/cli-sessions.js +265 -0
  13. package/lib/codex-defaults.js +18 -0
  14. package/lib/config.js +332 -0
  15. package/lib/crisis-safety.js +60 -0
  16. package/lib/daemon-projects.js +164 -0
  17. package/lib/daemon.js +1602 -0
  18. package/lib/dm.js +128 -0
  19. package/lib/ipc.js +125 -0
  20. package/lib/ipv4-only.js +39 -0
  21. package/lib/mcp-local.js +385 -0
  22. package/lib/notes.js +141 -0
  23. package/lib/os-users.js +529 -0
  24. package/lib/pages.js +1325 -0
  25. package/lib/project-connection.js +302 -0
  26. package/lib/project-external-trigger.js +236 -0
  27. package/lib/project-file-watch.js +120 -0
  28. package/lib/project-filesystem.js +528 -0
  29. package/lib/project-http.js +753 -0
  30. package/lib/project-image.js +95 -0
  31. package/lib/project-knowledge.js +88 -0
  32. package/lib/project-loop.js +1304 -0
  33. package/lib/project-mcp.js +374 -0
  34. package/lib/project-memory.js +39 -0
  35. package/lib/project-notifications.js +262 -0
  36. package/lib/project-sessions.js +1581 -0
  37. package/lib/project-user-mention.js +193 -0
  38. package/lib/project-user-message.js +628 -0
  39. package/lib/project.js +1303 -0
  40. package/lib/public/app.js +1031 -0
  41. package/lib/public/apple-touch-icon.png +0 -0
  42. package/lib/public/claude-code-avatar.png +0 -0
  43. package/lib/public/codex-avatar.png +0 -0
  44. package/lib/public/console-icon.png +0 -0
  45. package/lib/public/css/admin.css +736 -0
  46. package/lib/public/css/agent-picker.css +119 -0
  47. package/lib/public/css/base.css +235 -0
  48. package/lib/public/css/channel-layout.css +441 -0
  49. package/lib/public/css/command-palette.css +559 -0
  50. package/lib/public/css/debate.css +1609 -0
  51. package/lib/public/css/diff.css +139 -0
  52. package/lib/public/css/filebrowser.css +1976 -0
  53. package/lib/public/css/highlight.css +144 -0
  54. package/lib/public/css/home-hub.css +545 -0
  55. package/lib/public/css/icon-strip.css +1856 -0
  56. package/lib/public/css/input.css +1349 -0
  57. package/lib/public/css/loop.css +1248 -0
  58. package/lib/public/css/mention.css +317 -0
  59. package/lib/public/css/menus.css +857 -0
  60. package/lib/public/css/messages.css +1833 -0
  61. package/lib/public/css/mobile-nav.css +1332 -0
  62. package/lib/public/css/notifications-center.css +296 -0
  63. package/lib/public/css/overlays.css +1273 -0
  64. package/lib/public/css/playbook.css +264 -0
  65. package/lib/public/css/profile.css +397 -0
  66. package/lib/public/css/rewind.css +671 -0
  67. package/lib/public/css/scheduler-modal.css +1495 -0
  68. package/lib/public/css/scheduler.css +1420 -0
  69. package/lib/public/css/server-settings.css +909 -0
  70. package/lib/public/css/session-search.css +159 -0
  71. package/lib/public/css/sidebar.css +2012 -0
  72. package/lib/public/css/skills.css +789 -0
  73. package/lib/public/css/sticky-notes.css +854 -0
  74. package/lib/public/css/stt.css +155 -0
  75. package/lib/public/css/title-bar.css +674 -0
  76. package/lib/public/css/tooltip.css +67 -0
  77. package/lib/public/css/user-settings.css +702 -0
  78. package/lib/public/emoji-data.json +1 -0
  79. package/lib/public/favicon-banded-32.png +0 -0
  80. package/lib/public/favicon-banded.png +0 -0
  81. package/lib/public/favicon-dark.svg +32 -0
  82. package/lib/public/favicon.svg +32 -0
  83. package/lib/public/icon-192.png +0 -0
  84. package/lib/public/icon-512.png +0 -0
  85. package/lib/public/icon-banded-76.png +0 -0
  86. package/lib/public/icon-banded-96.png +0 -0
  87. package/lib/public/icon-mono.svg +25 -0
  88. package/lib/public/icons/email/gmail.svg +7 -0
  89. package/lib/public/icons/email/outlook.svg +35 -0
  90. package/lib/public/icons/email/yahoo.svg +1 -0
  91. package/lib/public/index.html +1946 -0
  92. package/lib/public/manifest.json +27 -0
  93. package/lib/public/markdown-worker.js +43 -0
  94. package/lib/public/marked.min.js +6 -0
  95. package/lib/public/modules/admin.js +954 -0
  96. package/lib/public/modules/agent-picker.js +429 -0
  97. package/lib/public/modules/app-connection.js +216 -0
  98. package/lib/public/modules/app-cursors.js +492 -0
  99. package/lib/public/modules/app-dm.js +265 -0
  100. package/lib/public/modules/app-favicon.js +231 -0
  101. package/lib/public/modules/app-header.js +242 -0
  102. package/lib/public/modules/app-home-hub.js +432 -0
  103. package/lib/public/modules/app-loop-ui.js +691 -0
  104. package/lib/public/modules/app-loop-wizard.js +439 -0
  105. package/lib/public/modules/app-messages.js +1415 -0
  106. package/lib/public/modules/app-misc.js +463 -0
  107. package/lib/public/modules/app-notifications.js +651 -0
  108. package/lib/public/modules/app-panels.js +1061 -0
  109. package/lib/public/modules/app-projects.js +875 -0
  110. package/lib/public/modules/app-rate-limit.js +529 -0
  111. package/lib/public/modules/app-rendering.js +739 -0
  112. package/lib/public/modules/app-skills-install.js +285 -0
  113. package/lib/public/modules/avatar.js +36 -0
  114. package/lib/public/modules/command-palette.js +491 -0
  115. package/lib/public/modules/console-logo.js +162 -0
  116. package/lib/public/modules/context-sources.js +365 -0
  117. package/lib/public/modules/diff.js +412 -0
  118. package/lib/public/modules/dom-refs.js +21 -0
  119. package/lib/public/modules/emoji-picker.js +222 -0
  120. package/lib/public/modules/events.js +21 -0
  121. package/lib/public/modules/filebrowser.js +1966 -0
  122. package/lib/public/modules/fileicons.js +172 -0
  123. package/lib/public/modules/icons.js +80 -0
  124. package/lib/public/modules/input.js +1102 -0
  125. package/lib/public/modules/longpress.js +74 -0
  126. package/lib/public/modules/markdown.js +486 -0
  127. package/lib/public/modules/mcp-ui.js +295 -0
  128. package/lib/public/modules/mention.js +1093 -0
  129. package/lib/public/modules/notifications.js +613 -0
  130. package/lib/public/modules/playbook.js +578 -0
  131. package/lib/public/modules/profile.js +594 -0
  132. package/lib/public/modules/project-settings.js +849 -0
  133. package/lib/public/modules/project-switcher.js +375 -0
  134. package/lib/public/modules/qrcode.js +87 -0
  135. package/lib/public/modules/rewind.js +381 -0
  136. package/lib/public/modules/scheduler-config.js +1611 -0
  137. package/lib/public/modules/scheduler-history.js +131 -0
  138. package/lib/public/modules/scheduler.js +1689 -0
  139. package/lib/public/modules/server-settings.js +842 -0
  140. package/lib/public/modules/session-search.js +456 -0
  141. package/lib/public/modules/settings-defaults.js +253 -0
  142. package/lib/public/modules/sidebar-mobile.js +1425 -0
  143. package/lib/public/modules/sidebar-projects.js +2022 -0
  144. package/lib/public/modules/sidebar-sessions.js +1548 -0
  145. package/lib/public/modules/sidebar-users.js +449 -0
  146. package/lib/public/modules/sidebar.js +348 -0
  147. package/lib/public/modules/skills.js +793 -0
  148. package/lib/public/modules/state.js +3 -0
  149. package/lib/public/modules/sticky-notes.js +1221 -0
  150. package/lib/public/modules/store.js +34 -0
  151. package/lib/public/modules/stt.js +266 -0
  152. package/lib/public/modules/terminal.js +987 -0
  153. package/lib/public/modules/theme.js +812 -0
  154. package/lib/public/modules/tool-palette.js +562 -0
  155. package/lib/public/modules/tools.js +2285 -0
  156. package/lib/public/modules/tooltip.js +150 -0
  157. package/lib/public/modules/user-settings.js +544 -0
  158. package/lib/public/modules/utils.js +56 -0
  159. package/lib/public/modules/ws-ref.js +26 -0
  160. package/lib/public/style.css +34 -0
  161. package/lib/public/sw.js +159 -0
  162. package/lib/push.js +149 -0
  163. package/lib/scheduler.js +471 -0
  164. package/lib/sdk-bridge.js +1792 -0
  165. package/lib/sdk-message-processor.js +740 -0
  166. package/lib/sdk-message-queue.js +42 -0
  167. package/lib/sdk-skill-discovery.js +131 -0
  168. package/lib/sdk-worker.js +677 -0
  169. package/lib/server-admin.js +712 -0
  170. package/lib/server-auth.js +737 -0
  171. package/lib/server-dm.js +170 -0
  172. package/lib/server-palette.js +104 -0
  173. package/lib/server-settings.js +553 -0
  174. package/lib/server-skills.js +280 -0
  175. package/lib/server.js +1390 -0
  176. package/lib/session-search.js +693 -0
  177. package/lib/sessions.js +946 -0
  178. package/lib/smtp.js +221 -0
  179. package/lib/terminal-manager.js +219 -0
  180. package/lib/terminal.js +39 -0
  181. package/lib/themes/ayu-light.json +9 -0
  182. package/lib/themes/catppuccin-latte.json +9 -0
  183. package/lib/themes/catppuccin-mocha.json +9 -0
  184. package/lib/themes/clagentic-dark.json +10 -0
  185. package/lib/themes/clagentic-light.json +10 -0
  186. package/lib/themes/dracula.json +9 -0
  187. package/lib/themes/everforest-light.json +9 -0
  188. package/lib/themes/everforest.json +9 -0
  189. package/lib/themes/github-light.json +9 -0
  190. package/lib/themes/gruvbox-dark.json +9 -0
  191. package/lib/themes/gruvbox-light.json +9 -0
  192. package/lib/themes/monokai.json +9 -0
  193. package/lib/themes/nord-light.json +9 -0
  194. package/lib/themes/nord.json +9 -0
  195. package/lib/themes/one-dark.json +9 -0
  196. package/lib/themes/one-light.json +9 -0
  197. package/lib/themes/rose-pine-dawn.json +9 -0
  198. package/lib/themes/rose-pine.json +9 -0
  199. package/lib/themes/solarized-dark.json +9 -0
  200. package/lib/themes/solarized-light.json +9 -0
  201. package/lib/themes/tokyo-night-light.json +9 -0
  202. package/lib/themes/tokyo-night.json +9 -0
  203. package/lib/updater.js +124 -0
  204. package/lib/user-presence.js +92 -0
  205. package/lib/users-auth.js +146 -0
  206. package/lib/users-permissions.js +118 -0
  207. package/lib/users-preferences.js +254 -0
  208. package/lib/users.js +465 -0
  209. package/lib/utils.js +64 -0
  210. package/lib/worktree.js +134 -0
  211. package/lib/ws-schema.js +464 -0
  212. package/lib/yoke/adapters/claude-worker.js +759 -0
  213. package/lib/yoke/adapters/claude.js +1599 -0
  214. package/lib/yoke/adapters/codex.js +1559 -0
  215. package/lib/yoke/codex-app-server.js +352 -0
  216. package/lib/yoke/index.js +319 -0
  217. package/lib/yoke/instructions.js +61 -0
  218. package/lib/yoke/interface.js +98 -0
  219. package/lib/yoke/mcp-bridge-server.js +302 -0
  220. package/lib/yoke/package.json +7 -0
  221. package/package.json +72 -0
@@ -0,0 +1,1061 @@
1
+ // app-panels.js - Config chip, usage panel, status panel, context panel
2
+ // Extracted from app.js (PR-30)
3
+
4
+ import { refreshIcons } from "./icons.js";
5
+ import { escapeHtml, showToast } from "./utils.js";
6
+ import { store } from './store.js';
7
+ import { getWs } from './ws-ref.js';
8
+ import { VENDOR_NAMES } from './app-rendering.js';
9
+
10
+ // --- Module-owned state (not in store) ---
11
+ var sessionUsage = { cost: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, turns: 0 };
12
+ var contextData = { contextWindow: 0, maxOutputTokens: 0, model: "-", cost: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, turns: 0 };
13
+ var ctxPopoverEl = null;
14
+ var ctxHoverTimer = null;
15
+ var statusRefreshTimer = null;
16
+
17
+ // --- DOM refs ---
18
+ var configChipWrap = null;
19
+ var configChip = null;
20
+ var configChipLabel = null;
21
+ var configPopover = null;
22
+ var configModelList = null;
23
+ var configModeList = null;
24
+ var configEffortSection = null;
25
+ var configEffortBar = null;
26
+ var configBetaSection = null;
27
+ var configBeta1mBtn = null;
28
+ var configThinkingSection = null;
29
+ var configThinkingBar = null;
30
+ var configThinkingBudgetRow = null;
31
+ var configThinkingBudgetInput = null;
32
+ var configApprovalSection = null;
33
+ var configApprovalBar = null;
34
+ var configSandboxSection = null;
35
+ var configSandboxBar = null;
36
+ var configWebsearchSection = null;
37
+ var configWebsearchBar = null;
38
+
39
+ var usagePanel = null;
40
+ var usagePanelClose = null;
41
+ var usageCostEl = null;
42
+ var usageInputEl = null;
43
+ var usageOutputEl = null;
44
+ var usageCacheReadEl = null;
45
+ var usageCacheWriteEl = null;
46
+ var usageTurnsEl = null;
47
+
48
+ var statusPanel = null;
49
+ var statusPanelClose = null;
50
+ var statusPidEl = null;
51
+ var statusUptimeEl = null;
52
+ var statusRssEl = null;
53
+ var statusHeapUsedEl = null;
54
+ var statusHeapTotalEl = null;
55
+ var statusExternalEl = null;
56
+ var statusSessionsEl = null;
57
+ var statusProcessingEl = null;
58
+ var statusClientsEl = null;
59
+ var statusTerminalsEl = null;
60
+
61
+ var contextPanel = null;
62
+ var contextPanelClose = null;
63
+ var contextPanelMinimize = null;
64
+ var contextBarFill = null;
65
+ var contextBarPct = null;
66
+ var contextUsedEl = null;
67
+ var contextWindowEl = null;
68
+ var contextMaxOutputEl = null;
69
+ var contextInputEl = null;
70
+ var contextOutputEl = null;
71
+ var contextCacheReadEl = null;
72
+ var contextCacheWriteEl = null;
73
+ var contextModelEl = null;
74
+ var contextCostEl = null;
75
+ var contextTurnsEl = null;
76
+ var contextMini = null;
77
+ var contextMiniFill = null;
78
+ var contextMiniLabel = null;
79
+
80
+ // --- Constants ---
81
+ var MODE_OPTIONS = [
82
+ { value: "default", label: "Default" },
83
+ { value: "plan", label: "Plan" },
84
+ { value: "acceptEdits", label: "Auto-accept edits" },
85
+ ];
86
+ var MODE_FULL_AUTO = { value: "bypassPermissions", label: "Full auto" };
87
+ var EFFORT_LEVELS = ["low", "medium", "high", "xhigh", "max"];
88
+ var EFFORT_LEVELS_BY_VENDOR = {
89
+ claude: ["low", "medium", "high", "xhigh", "max"],
90
+ codex: ["minimal", "low", "medium", "high", "xhigh"],
91
+ };
92
+ var THINKING_OPTIONS = ["disabled", "adaptive", "budget"];
93
+ var CODEX_APPROVAL_OPTIONS = [
94
+ { value: "never", label: "Auto" },
95
+ { value: "on-failure", label: "On Fail" },
96
+ { value: "on-request", label: "Ask" },
97
+ ];
98
+ var CODEX_SANDBOX_OPTIONS = [
99
+ { value: "read-only", label: "Read Only" },
100
+ { value: "workspace-write", label: "Workspace" },
101
+ { value: "danger-full-access", label: "Full Access" },
102
+ ];
103
+ var CODEX_WEBSEARCH_OPTIONS = [
104
+ { value: "disabled", label: "Off" },
105
+ { value: "cached", label: "Cached" },
106
+ { value: "live", label: "Live" },
107
+ ];
108
+ var KNOWN_CONTEXT_WINDOWS = {
109
+ "opus-4-6": 1000000,
110
+ "claude-sonnet-4": 1000000,
111
+ "gpt-5.4": 1048576,
112
+ "gpt-5.3": 1048576,
113
+ "gpt-5.2": 1048576,
114
+ "gpt-4.1": 1047576,
115
+ "o3": 200000,
116
+ "o4-mini": 200000,
117
+ };
118
+ // Categories to hide from the legend (noise, not actionable)
119
+ var CTX_HIDDEN_CATS = { "Free space": 1, "Autocompact buffer": 1 };
120
+
121
+ // --- Non-store state accessors (module-owned, not in store) ---
122
+ export function getSessionUsage() { return sessionUsage; }
123
+ export function setSessionUsage(v) { sessionUsage = v; }
124
+ export function getContextData() { return contextData; }
125
+ export function setContextData(v) { contextData = v; }
126
+
127
+ // --- Internal helpers ---
128
+
129
+ function modelDisplayName(value, models) {
130
+ if (!value) return "";
131
+ if (models) {
132
+ for (var i = 0; i < models.length; i++) {
133
+ var m = models[i];
134
+ if (typeof m === "string") { if (m === value) return m; }
135
+ else if (m.value === value && m.displayName) return m.displayName;
136
+ }
137
+ }
138
+ return value;
139
+ }
140
+
141
+ function modeDisplayName(value) {
142
+ for (var i = 0; i < MODE_OPTIONS.length; i++) {
143
+ if (MODE_OPTIONS[i].value === value) return MODE_OPTIONS[i].label;
144
+ }
145
+ if (value === "bypassPermissions") return "Full auto";
146
+ if (value === "dontAsk") return "Don\u2019t ask";
147
+ return value;
148
+ }
149
+
150
+ function effortDisplayName(value) {
151
+ if (!value) return "";
152
+ if (value === "xhigh") return "X-High";
153
+ return value.charAt(0).toUpperCase() + value.slice(1);
154
+ }
155
+
156
+ function thinkingDisplayName(value) {
157
+ if (value === "disabled") return "Off";
158
+ if (value === "adaptive") return "Adaptive";
159
+ if (value === "budget") return "Budget";
160
+ return value || "Adaptive";
161
+ }
162
+
163
+ function isSonnetModel(model) {
164
+ if (!model) return false;
165
+ var lower = model.toLowerCase();
166
+ return lower.indexOf("sonnet") !== -1;
167
+ }
168
+
169
+ function hasBeta(name) {
170
+ var betas = store.get('currentBetas');
171
+ for (var i = 0; i < betas.length; i++) {
172
+ if (betas[i].indexOf(name) !== -1) return true;
173
+ }
174
+ return false;
175
+ }
176
+
177
+ function rebuildModelList() {
178
+ if (!configModelList) return;
179
+ configModelList.innerHTML = "";
180
+ var s = store.snap();
181
+ var list = s.currentModels.length > 0 ? s.currentModels : (s.currentModel ? [{ value: s.currentModel, displayName: s.currentModel }] : []);
182
+ for (var i = 0; i < list.length; i++) {
183
+ var item = list[i];
184
+ // Support both object { value, displayName } and plain string formats
185
+ var value = typeof item === "string" ? item : (item.value || "");
186
+ var label = typeof item === "string" ? item : (item.displayName || value);
187
+ var btn = document.createElement("button");
188
+ btn.className = "config-radio-item";
189
+ if (value === s.currentModel) btn.classList.add("active");
190
+ btn.dataset.model = value;
191
+ btn.textContent = label;
192
+ btn.addEventListener("click", function () {
193
+ var model = this.dataset.model;
194
+ var ws = getWs();
195
+ if (ws && ws.readyState === 1) {
196
+ ws.send(JSON.stringify({ type: "set_model", model: model }));
197
+ }
198
+ configPopover.classList.add("hidden");
199
+ configChip.classList.remove("active");
200
+ });
201
+ configModelList.appendChild(btn);
202
+ }
203
+ }
204
+
205
+ function rebuildModeList() {
206
+ if (!configModeList) return;
207
+ configModeList.innerHTML = "";
208
+ var options = MODE_OPTIONS.slice();
209
+ if (store.get('skipPermsEnabled')) {
210
+ options.push(MODE_FULL_AUTO);
211
+ }
212
+ for (var i = 0; i < options.length; i++) {
213
+ var opt = options[i];
214
+ var btn = document.createElement("button");
215
+ btn.className = "config-radio-item";
216
+ if (opt.value === store.get('currentMode')) btn.classList.add("active");
217
+ btn.dataset.mode = opt.value;
218
+ btn.textContent = opt.label;
219
+ btn.addEventListener("click", function () {
220
+ var mode = this.dataset.mode;
221
+ var ws = getWs();
222
+ if (ws && ws.readyState === 1) {
223
+ ws.send(JSON.stringify({ type: "set_permission_mode", mode: mode }));
224
+ }
225
+ configPopover.classList.add("hidden");
226
+ configChip.classList.remove("active");
227
+ });
228
+ configModeList.appendChild(btn);
229
+ }
230
+ }
231
+
232
+ function rebuildEffortBar() {
233
+ if (!configEffortBar || !configEffortSection) return;
234
+ var supportsEffort = getModelSupportsEffort();
235
+ if (!supportsEffort) {
236
+ configEffortSection.style.display = "none";
237
+ return;
238
+ }
239
+ configEffortSection.style.display = "";
240
+ configEffortBar.innerHTML = "";
241
+ var levels = getModelEffortLevels();
242
+ for (var i = 0; i < levels.length; i++) {
243
+ var level = levels[i];
244
+ var btn = document.createElement("button");
245
+ btn.className = "config-segment-btn";
246
+ if (level === store.get('currentEffort')) btn.classList.add("active");
247
+ btn.dataset.effort = level;
248
+ btn.textContent = effortDisplayName(level);
249
+ btn.addEventListener("click", function () {
250
+ var effort = this.dataset.effort;
251
+ var ws = getWs();
252
+ if (ws && ws.readyState === 1) {
253
+ ws.send(JSON.stringify({ type: "set_effort", effort: effort }));
254
+ }
255
+ configPopover.classList.add("hidden");
256
+ configChip.classList.remove("active");
257
+ });
258
+ configEffortBar.appendChild(btn);
259
+ }
260
+ }
261
+
262
+ function rebuildBetaSection() {
263
+ if (!configBetaSection || !configBeta1mBtn) return;
264
+ // Only show for Sonnet models
265
+ if (!isSonnetModel(store.get('currentModel'))) {
266
+ configBetaSection.style.display = "none";
267
+ return;
268
+ }
269
+ configBetaSection.style.display = "";
270
+ var active = hasBeta("context-1m");
271
+ configBeta1mBtn.classList.toggle("active", active);
272
+ configBeta1mBtn.setAttribute("aria-checked", active ? "true" : "false");
273
+ }
274
+
275
+ function rebuildThinkingSection() {
276
+ if (!configThinkingBar || !configThinkingSection) return;
277
+ configThinkingSection.style.display = "";
278
+ configThinkingBar.innerHTML = "";
279
+ var s = store.snap();
280
+ for (var i = 0; i < THINKING_OPTIONS.length; i++) {
281
+ var opt = THINKING_OPTIONS[i];
282
+ var btn = document.createElement("button");
283
+ btn.className = "config-segment-btn";
284
+ if (opt === s.currentThinking) btn.classList.add("active");
285
+ btn.dataset.thinking = opt;
286
+ btn.textContent = thinkingDisplayName(opt);
287
+ btn.addEventListener("click", function () {
288
+ var thinking = this.dataset.thinking;
289
+ var msg = { type: "set_thinking", thinking: thinking };
290
+ if (thinking === "budget") {
291
+ msg.budgetTokens = store.get('currentThinkingBudget');
292
+ }
293
+ var ws = getWs();
294
+ if (ws && ws.readyState === 1) {
295
+ ws.send(JSON.stringify(msg));
296
+ }
297
+ });
298
+ configThinkingBar.appendChild(btn);
299
+ }
300
+ // Show/hide budget input
301
+ if (configThinkingBudgetRow) {
302
+ configThinkingBudgetRow.style.display = s.currentThinking === "budget" ? "" : "none";
303
+ }
304
+ if (configThinkingBudgetInput) {
305
+ configThinkingBudgetInput.value = s.currentThinkingBudget;
306
+ }
307
+ }
308
+
309
+ function buildSegmentedBar(barEl, options, currentValue, msgType, msgKey) {
310
+ if (!barEl) return;
311
+ barEl.innerHTML = "";
312
+ for (var i = 0; i < options.length; i++) {
313
+ var opt = options[i];
314
+ var btn = document.createElement("button");
315
+ btn.className = "config-segment-btn";
316
+ if (opt.value === currentValue) btn.classList.add("active");
317
+ btn.dataset.val = opt.value;
318
+ btn.textContent = opt.label;
319
+ btn.addEventListener("click", function () {
320
+ var val = this.dataset.val;
321
+ var msg = { type: msgType };
322
+ msg[msgKey] = val;
323
+ var ws = getWs();
324
+ if (ws && ws.readyState === 1) ws.send(JSON.stringify(msg));
325
+ configPopover.classList.add("hidden");
326
+ configChip.classList.remove("active");
327
+ });
328
+ barEl.appendChild(btn);
329
+ }
330
+ }
331
+
332
+ function rebuildCodexSections() {
333
+ var s = store.snap();
334
+ var isCodex = (s.currentVendor || "claude") === "codex";
335
+
336
+ if (configApprovalSection) {
337
+ configApprovalSection.style.display = isCodex ? "" : "none";
338
+ if (isCodex) buildSegmentedBar(configApprovalBar, CODEX_APPROVAL_OPTIONS, s.codexApproval, "set_codex_approval", "approval");
339
+ }
340
+ if (configSandboxSection) {
341
+ configSandboxSection.style.display = isCodex ? "" : "none";
342
+ if (isCodex) buildSegmentedBar(configSandboxBar, CODEX_SANDBOX_OPTIONS, s.codexSandbox, "set_codex_sandbox", "sandbox");
343
+ }
344
+ if (configWebsearchSection) {
345
+ configWebsearchSection.style.display = isCodex ? "" : "none";
346
+ if (isCodex) buildSegmentedBar(configWebsearchBar, CODEX_WEBSEARCH_OPTIONS, s.codexWebSearch, "set_codex_websearch", "webSearch");
347
+ }
348
+ }
349
+
350
+ function escHtml(s) {
351
+ var div = document.createElement("div");
352
+ div.textContent = s;
353
+ return div.innerHTML;
354
+ }
355
+
356
+ function em(emoji) {
357
+ return '<span class="ctx-emoji">' + emoji + '</span>';
358
+ }
359
+
360
+ // --- Exported functions ---
361
+
362
+ export function initPanels() {
363
+ var $ = function (id) { return document.getElementById(id); };
364
+
365
+ // Config chip DOM refs
366
+ configChipWrap = $("config-chip-wrap");
367
+ configChip = $("config-chip");
368
+ configChipLabel = $("config-chip-label");
369
+ configPopover = $("config-popover");
370
+ configModelList = $("config-model-list");
371
+ configModeList = $("config-mode-list");
372
+ configEffortSection = $("config-effort-section");
373
+ configEffortBar = $("config-effort-bar");
374
+ configBetaSection = $("config-beta-section");
375
+ configBeta1mBtn = $("config-beta-1m");
376
+ configThinkingSection = $("config-thinking-section");
377
+ configThinkingBar = $("config-thinking-bar");
378
+ configThinkingBudgetRow = $("config-thinking-budget-row");
379
+ configThinkingBudgetInput = $("config-thinking-budget");
380
+ configApprovalSection = $("config-approval-section");
381
+ configApprovalBar = $("config-approval-bar");
382
+ configSandboxSection = $("config-sandbox-section");
383
+ configSandboxBar = $("config-sandbox-bar");
384
+ configWebsearchSection = $("config-websearch-section");
385
+ configWebsearchBar = $("config-websearch-bar");
386
+
387
+ // --- Vendor toggle ---
388
+ var vendorToggleWrap = $("vendor-toggle-wrap");
389
+ var vendorBtnClaude = $("vendor-btn-claude");
390
+ var vendorBtnCodex = $("vendor-btn-codex");
391
+ var vendorBtns = { claude: vendorBtnClaude, codex: vendorBtnCodex };
392
+
393
+ function updateVendorToggle() {
394
+ var installed = store.get('installedVendors') || [];
395
+ var current = store.get('currentVendor') || "claude";
396
+
397
+ var vendors = Object.keys(vendorBtns);
398
+ for (var i = 0; i < vendors.length; i++) {
399
+ var v = vendors[i];
400
+ var btn = vendorBtns[v];
401
+ if (!btn) continue;
402
+ var isInstalled = installed.indexOf(v) !== -1;
403
+ btn.classList.toggle("active", v === current);
404
+ btn.classList.toggle("disabled", !isInstalled);
405
+ btn.title = isInstalled ? (VENDOR_NAMES[v] || v) : (VENDOR_NAMES[v] || v) + " is not installed";
406
+ }
407
+ }
408
+
409
+ function onVendorClick(vendor) {
410
+ if (vendor === (store.get('currentVendor') || "claude")) return;
411
+ var installed = store.get('installedVendors') || [];
412
+ if (installed.indexOf(vendor) === -1) return;
413
+ store.set({ currentVendor: vendor, currentModel: "", currentModels: [], vendorSelectionLocked: true });
414
+ var ws = getWs();
415
+ if (ws) ws.send(JSON.stringify({ type: "set_vendor", vendor: vendor }));
416
+ }
417
+
418
+ if (vendorBtnClaude) vendorBtnClaude.addEventListener("click", function() { onVendorClick("claude"); });
419
+ if (vendorBtnCodex) vendorBtnCodex.addEventListener("click", function() { onVendorClick("codex"); });
420
+
421
+ // --- Reactive UI sync ---
422
+ store.subscribe(function (state, prev) {
423
+ // Vendor toggle state
424
+ if (state.availableVendors !== prev.availableVendors ||
425
+ state.installedVendors !== prev.installedVendors ||
426
+ state.currentVendor !== prev.currentVendor) {
427
+ updateVendorToggle();
428
+ }
429
+
430
+ // richContextUsage changed -> update popover + panel
431
+ if (state.richContextUsage !== prev.richContextUsage) {
432
+ if (state.richContextUsage) {
433
+ var hce = store.get('headerContextEl');
434
+ if (hce) hce.removeAttribute("data-tip");
435
+ if (state.ctxPopoverVisible) renderCtxPopover();
436
+ } else {
437
+ hideCtxPopover();
438
+ }
439
+ updateContextPanel();
440
+ }
441
+ // Vendor changed -> switch model list and current model to match
442
+ if (state.currentVendor !== prev.currentVendor && state.currentVendor) {
443
+ var ws = getWs();
444
+ if (ws) ws.send(JSON.stringify({ type: "get_vendor_models", vendor: state.currentVendor }));
445
+ }
446
+
447
+ // config chip
448
+ if (state.currentModel !== prev.currentModel ||
449
+ state.currentMode !== prev.currentMode ||
450
+ state.currentEffort !== prev.currentEffort ||
451
+ state.currentBetas !== prev.currentBetas ||
452
+ state.currentThinking !== prev.currentThinking ||
453
+ state.currentVendor !== prev.currentVendor ||
454
+ state.codexApproval !== prev.codexApproval ||
455
+ state.codexSandbox !== prev.codexSandbox ||
456
+ state.codexWebSearch !== prev.codexWebSearch) {
457
+ updateConfigChip();
458
+ }
459
+ // Betas changed (e.g. context-1m toggled) -> repaint context panel so the
460
+ // window size is re-resolved with the new beta state
461
+ if (state.currentBetas !== prev.currentBetas) {
462
+ if (contextData.input > 0) updateContextPanel();
463
+ }
464
+ });
465
+
466
+ // Usage panel DOM refs
467
+ usagePanel = $("usage-panel");
468
+ usagePanelClose = $("usage-panel-close");
469
+ usageCostEl = $("usage-cost");
470
+ usageInputEl = $("usage-input");
471
+ usageOutputEl = $("usage-output");
472
+ usageCacheReadEl = $("usage-cache-read");
473
+ usageCacheWriteEl = $("usage-cache-write");
474
+ usageTurnsEl = $("usage-turns");
475
+
476
+ // Status panel DOM refs
477
+ statusPanel = $("status-panel");
478
+ statusPanelClose = $("status-panel-close");
479
+ statusPidEl = $("status-pid");
480
+ statusUptimeEl = $("status-uptime");
481
+ statusRssEl = $("status-rss");
482
+ statusHeapUsedEl = $("status-heap-used");
483
+ statusHeapTotalEl = $("status-heap-total");
484
+ statusExternalEl = $("status-external");
485
+ statusSessionsEl = $("status-sessions");
486
+ statusProcessingEl = $("status-processing");
487
+ statusClientsEl = $("status-clients");
488
+ statusTerminalsEl = $("status-terminals");
489
+
490
+ // Context panel DOM refs
491
+ contextPanel = $("context-panel");
492
+ contextPanelClose = $("context-panel-close");
493
+ contextPanelMinimize = $("context-panel-minimize");
494
+ contextBarFill = $("context-bar-fill");
495
+ contextBarPct = $("context-bar-pct");
496
+ contextUsedEl = $("context-used");
497
+ contextWindowEl = $("context-window");
498
+ contextMaxOutputEl = $("context-max-output");
499
+ contextInputEl = $("context-input");
500
+ contextOutputEl = $("context-output");
501
+ contextCacheReadEl = $("context-cache-read");
502
+ contextCacheWriteEl = $("context-cache-write");
503
+ contextModelEl = $("context-model");
504
+ contextCostEl = $("context-cost");
505
+ contextTurnsEl = $("context-turns");
506
+ contextMini = $("context-mini");
507
+ contextMiniFill = $("context-mini-fill");
508
+ contextMiniLabel = $("context-mini-label");
509
+
510
+ // --- Event listeners ---
511
+
512
+ if (configThinkingBudgetInput) {
513
+ configThinkingBudgetInput.addEventListener("change", function () {
514
+ var val = parseInt(this.value, 10);
515
+ if (isNaN(val) || val < 1024) val = 1024;
516
+ if (val > 128000) val = 128000;
517
+ store.set({ currentThinkingBudget: val });
518
+ this.value = val;
519
+ var ws = getWs();
520
+ if (ws && ws.readyState === 1) {
521
+ ws.send(JSON.stringify({ type: "set_thinking", thinking: "budget", budgetTokens: val }));
522
+ }
523
+ });
524
+ }
525
+
526
+ if (configBeta1mBtn) {
527
+ configBeta1mBtn.addEventListener("click", function (e) {
528
+ e.stopPropagation();
529
+ var active = hasBeta("context-1m");
530
+ var betas = store.get('currentBetas');
531
+ var newBetas;
532
+ if (active) {
533
+ // Remove context-1m beta
534
+ newBetas = [];
535
+ for (var i = 0; i < betas.length; i++) {
536
+ if (betas[i].indexOf("context-1m") === -1) {
537
+ newBetas.push(betas[i]);
538
+ }
539
+ }
540
+ } else {
541
+ // Add context-1m beta
542
+ newBetas = betas.slice();
543
+ newBetas.push("context-1m-2025-08-07");
544
+ }
545
+ var ws = getWs();
546
+ if (ws && ws.readyState === 1) {
547
+ ws.send(JSON.stringify({ type: "set_betas", betas: newBetas }));
548
+ }
549
+ });
550
+ }
551
+
552
+ if (configChip) {
553
+ configChip.addEventListener("click", function (e) {
554
+ e.stopPropagation();
555
+ var wasHidden = configPopover.classList.toggle("hidden");
556
+ configChip.classList.toggle("active", !wasHidden);
557
+ });
558
+ }
559
+
560
+ document.addEventListener("click", function (e) {
561
+ if (configPopover && configChip && !configPopover.contains(e.target) && e.target !== configChip) {
562
+ configPopover.classList.add("hidden");
563
+ configChip.classList.remove("active");
564
+ }
565
+ });
566
+
567
+ if (usagePanelClose) {
568
+ usagePanelClose.addEventListener("click", function () {
569
+ usagePanel.classList.add("hidden");
570
+ });
571
+ }
572
+
573
+ if (statusPanelClose) {
574
+ statusPanelClose.addEventListener("click", function () {
575
+ statusPanel.classList.add("hidden");
576
+ if (statusRefreshTimer) {
577
+ clearInterval(statusRefreshTimer);
578
+ statusRefreshTimer = null;
579
+ }
580
+ });
581
+ }
582
+
583
+ if (contextPanelClose) {
584
+ contextPanelClose.addEventListener("click", function () {
585
+ setContextView("off");
586
+ applyContextView("off");
587
+ });
588
+ }
589
+
590
+ if (contextPanelMinimize) {
591
+ contextPanelMinimize.addEventListener("click", minimizeContext);
592
+ }
593
+
594
+ if (contextMini) {
595
+ contextMini.addEventListener("click", expandContext);
596
+ }
597
+
598
+ // Restore context view on load
599
+ applyContextView(getContextView());
600
+ }
601
+
602
+ // --- Config chip ---
603
+
604
+ export function updateConfigChip() {
605
+ if (!configChipWrap || !configChip) return;
606
+ configChipWrap.classList.remove("hidden");
607
+ var s = store.snap();
608
+ var vendor = s.currentVendor || "claude";
609
+ configChipLabel.textContent = modelDisplayName(s.currentModel, s.currentModels);
610
+ rebuildModelList();
611
+ rebuildModeList();
612
+ rebuildEffortBar();
613
+
614
+ // Vendor-specific sections
615
+ var isClaude = vendor === "claude";
616
+ // MODE, THINKING, BETA are Claude-only
617
+ if (configModeList && configModeList.parentElement) configModeList.parentElement.style.display = isClaude ? "" : "none";
618
+ rebuildThinkingSection();
619
+ if (configThinkingSection) configThinkingSection.style.display = isClaude ? "" : "none";
620
+ // BETA section deprecated (1M context is now standard)
621
+ if (configBetaSection) configBetaSection.style.display = "none";
622
+ // APPROVAL, SANDBOX, WEB SEARCH are Codex-only
623
+ rebuildCodexSections();
624
+ }
625
+
626
+ export function getModelSupportsEffort() {
627
+ var s = store.snap();
628
+ if (!s.currentModels || s.currentModels.length === 0) return true; // assume yes if no info
629
+ for (var i = 0; i < s.currentModels.length; i++) {
630
+ if (s.currentModels[i].value === s.currentModel) {
631
+ if (s.currentModels[i].supportsEffort === false) return false;
632
+ return true;
633
+ }
634
+ }
635
+ return true;
636
+ }
637
+
638
+ export function getModelEffortLevels() {
639
+ var s = store.snap();
640
+ var vendor = s.currentVendor || "claude";
641
+ var defaultLevels = EFFORT_LEVELS_BY_VENDOR[vendor] || EFFORT_LEVELS;
642
+ if (!s.currentModels || s.currentModels.length === 0) return defaultLevels;
643
+ for (var i = 0; i < s.currentModels.length; i++) {
644
+ if (s.currentModels[i].value === s.currentModel) {
645
+ if (s.currentModels[i].supportedEffortLevels && s.currentModels[i].supportedEffortLevels.length > 0) {
646
+ return s.currentModels[i].supportedEffortLevels;
647
+ }
648
+ return defaultLevels;
649
+ }
650
+ }
651
+ return defaultLevels;
652
+ }
653
+
654
+ // --- Usage panel ---
655
+
656
+ export function formatTokens(n) {
657
+ if (n >= 1000000) return (n / 1000000).toFixed(1) + "M";
658
+ if (n >= 1000) return (n / 1000).toFixed(1) + "K";
659
+ return String(n);
660
+ }
661
+
662
+ export function updateUsagePanel() {
663
+ if (!usageCostEl) return;
664
+ usageCostEl.textContent = "$" + sessionUsage.cost.toFixed(4);
665
+ usageInputEl.textContent = formatTokens(sessionUsage.input);
666
+ usageOutputEl.textContent = formatTokens(sessionUsage.output);
667
+ usageCacheReadEl.textContent = formatTokens(sessionUsage.cacheRead);
668
+ usageCacheWriteEl.textContent = formatTokens(sessionUsage.cacheWrite);
669
+ usageTurnsEl.textContent = String(sessionUsage.turns);
670
+ }
671
+
672
+ export function accumulateUsage(cost, usage) {
673
+ // cost is the SDK's total_cost_usd -- a cumulative running total, not a delta.
674
+ // Assign directly instead of summing to avoid overcounting.
675
+ if (cost != null) sessionUsage.cost = cost;
676
+ if (usage) {
677
+ sessionUsage.input += usage.input_tokens || usage.inputTokens || 0;
678
+ sessionUsage.output += usage.output_tokens || usage.outputTokens || 0;
679
+ sessionUsage.cacheRead += usage.cache_read_input_tokens || usage.cacheReadInputTokens || 0;
680
+ sessionUsage.cacheWrite += usage.cache_creation_input_tokens || usage.cacheCreationInputTokens || 0;
681
+ }
682
+ sessionUsage.turns++;
683
+ if (!store.get('replayingHistory')) updateUsagePanel();
684
+ }
685
+
686
+ export function resetUsage() {
687
+ sessionUsage = { cost: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, turns: 0 };
688
+ updateUsagePanel();
689
+ if (usagePanel) usagePanel.classList.add("hidden");
690
+ }
691
+
692
+ export function toggleUsagePanel() {
693
+ if (!usagePanel) return;
694
+ usagePanel.classList.toggle("hidden");
695
+ refreshIcons();
696
+ }
697
+
698
+ // --- Status panel ---
699
+
700
+ export function formatBytes(n) {
701
+ if (n >= 1073741824) return (n / 1073741824).toFixed(1) + " GB";
702
+ if (n >= 1048576) return (n / 1048576).toFixed(1) + " MB";
703
+ if (n >= 1024) return (n / 1024).toFixed(1) + " KB";
704
+ return n + " B";
705
+ }
706
+
707
+ export function formatUptime(seconds) {
708
+ var d = Math.floor(seconds / 86400);
709
+ var h = Math.floor((seconds % 86400) / 3600);
710
+ var m = Math.floor((seconds % 3600) / 60);
711
+ var s = Math.floor(seconds % 60);
712
+ if (d > 0) return d + "d " + h + "h " + m + "m";
713
+ if (h > 0) return h + "h " + m + "m " + s + "s";
714
+ return m + "m " + s + "s";
715
+ }
716
+
717
+ export function updateStatusPanel(data) {
718
+ if (!statusPidEl) return;
719
+ statusPidEl.textContent = String(data.pid);
720
+ statusUptimeEl.textContent = formatUptime(data.uptime);
721
+ statusRssEl.textContent = formatBytes(data.memory.rss);
722
+ statusHeapUsedEl.textContent = formatBytes(data.memory.heapUsed);
723
+ statusHeapTotalEl.textContent = formatBytes(data.memory.heapTotal);
724
+ statusExternalEl.textContent = formatBytes(data.memory.external);
725
+ statusSessionsEl.textContent = String(data.sessions);
726
+ statusProcessingEl.textContent = String(data.processing);
727
+ statusClientsEl.textContent = String(data.clients);
728
+ statusTerminalsEl.textContent = String(data.terminals);
729
+ }
730
+
731
+ export function requestProcessStats() {
732
+ var ws = getWs();
733
+ if (ws && ws.readyState === 1) {
734
+ ws.send(JSON.stringify({ type: "process_stats" }));
735
+ }
736
+ }
737
+
738
+ export function toggleStatusPanel() {
739
+ if (!statusPanel) return;
740
+ var opening = statusPanel.classList.contains("hidden");
741
+ statusPanel.classList.toggle("hidden");
742
+ if (opening) {
743
+ requestProcessStats();
744
+ statusRefreshTimer = setInterval(requestProcessStats, 5000);
745
+ } else {
746
+ if (statusRefreshTimer) {
747
+ clearInterval(statusRefreshTimer);
748
+ statusRefreshTimer = null;
749
+ }
750
+ }
751
+ refreshIcons();
752
+ }
753
+
754
+ // --- Context panel ---
755
+
756
+ export function resolveContextWindow(model, sdkValue) {
757
+ // If the 1M context beta is active, the real context window is always 1M.
758
+ // The SDK reports the model's base window (200K) in both ModelUsage.contextWindow
759
+ // and getContextUsage().maxTokens — it does not reflect the beta-extended limit.
760
+ // Check active betas first so we override the stale SDK value.
761
+ if (hasBeta("context-1m")) return 1000000;
762
+ var lc = (model || "").toLowerCase();
763
+ if (lc.includes("[1m]")) return 1000000;
764
+ if (sdkValue) return sdkValue;
765
+ for (var key in KNOWN_CONTEXT_WINDOWS) {
766
+ if (lc.includes(key)) return KNOWN_CONTEXT_WINDOWS[key];
767
+ }
768
+ return 200000;
769
+ }
770
+
771
+ export function contextPctClass(pct) {
772
+ return pct >= 85 ? " danger" : pct >= 60 ? " warn" : "";
773
+ }
774
+
775
+ export function updateContextPanel() {
776
+ if (!contextUsedEl) return;
777
+ // Context window usage = input tokens only (includes cache read/write)
778
+ var used = contextData.input;
779
+ // Re-resolve each paint so beta changes (e.g. context-1m toggle) are
780
+ // reflected immediately without waiting for the next turn's result event.
781
+ var win = resolveContextWindow(contextData.model, contextData.contextWindow);
782
+ var pct = win > 0 ? Math.min(100, (used / win) * 100) : 0;
783
+ var cls = contextPctClass(pct);
784
+ // Panel bar
785
+ contextBarFill.style.width = pct.toFixed(1) + "%";
786
+ contextBarFill.className = "context-bar-fill" + cls;
787
+ contextBarPct.textContent = pct.toFixed(0) + "%";
788
+ // Mini bar
789
+ if (contextMiniFill) {
790
+ contextMiniFill.style.width = pct.toFixed(1) + "%";
791
+ contextMiniFill.className = "context-mini-fill" + cls;
792
+ }
793
+ if (contextMiniLabel) {
794
+ contextMiniLabel.textContent = (win > 0 ? formatTokens(used) + "/" + formatTokens(win) : "0%");
795
+ }
796
+ // Header bar
797
+ if (pct > 0) {
798
+ var statusArea = document.querySelector(".title-bar-content .status");
799
+ var hCtxEl = store.get('headerContextEl');
800
+ if (statusArea && !hCtxEl) {
801
+ hCtxEl = document.createElement("div");
802
+ hCtxEl.className = "header-context";
803
+ hCtxEl.innerHTML = '<div class="header-context-bar"><div class="header-context-fill"></div></div><span class="header-context-label"></span>';
804
+ statusArea.insertBefore(hCtxEl, statusArea.firstChild);
805
+ hCtxEl.addEventListener("mouseenter", function() {
806
+ if (store.get('richContextUsage')) {
807
+ showCtxPopover();
808
+ }
809
+ });
810
+ hCtxEl.addEventListener("mouseleave", function() {
811
+ ctxHoverTimer = setTimeout(hideCtxPopover, 120);
812
+ });
813
+ store.set({ headerContextEl: hCtxEl });
814
+ }
815
+ if (hCtxEl) {
816
+ var hFill = hCtxEl.querySelector(".header-context-fill");
817
+ var hLabel = hCtxEl.querySelector(".header-context-label");
818
+ hFill.style.width = pct.toFixed(1) + "%";
819
+ hFill.className = "header-context-fill" + cls;
820
+ hLabel.textContent = pct.toFixed(0) + "%";
821
+ // Use data-tip as fallback when rich data is not yet loaded
822
+ if (store.get('richContextUsage')) {
823
+ hCtxEl.removeAttribute("data-tip");
824
+ } else {
825
+ hCtxEl.dataset.tip = "Context window " + pct.toFixed(0) + "% used (" + formatTokens(used) + " / " + formatTokens(win) + " tokens)";
826
+ }
827
+ }
828
+ }
829
+ contextUsedEl.textContent = formatTokens(used);
830
+ contextWindowEl.textContent = win > 0 ? formatTokens(win) : "-";
831
+ contextMaxOutputEl.textContent = contextData.maxOutputTokens > 0 ? formatTokens(contextData.maxOutputTokens) : "-";
832
+ contextInputEl.textContent = formatTokens(contextData.input);
833
+ contextOutputEl.textContent = formatTokens(contextData.output);
834
+ contextCacheReadEl.textContent = formatTokens(contextData.cacheRead);
835
+ contextCacheWriteEl.textContent = formatTokens(contextData.cacheWrite);
836
+ contextModelEl.textContent = contextData.model;
837
+ contextCostEl.textContent = "$" + contextData.cost.toFixed(4);
838
+ contextTurnsEl.textContent = String(contextData.turns);
839
+ }
840
+
841
+ export function accumulateContext(cost, usage, modelUsage, lastStreamInputTokens) {
842
+ // cost is the SDK's total_cost_usd -- a cumulative running total, not a delta.
843
+ if (cost != null) contextData.cost = cost;
844
+ // Use latest turn values (not cumulative) since each turn's input_tokens
845
+ // already includes the full conversation context up to that point
846
+ if (usage) {
847
+ // Prefer per-call input_tokens from the last stream message_start event
848
+ // when available -- result.usage.input_tokens sums all API calls in a turn,
849
+ // inflating context usage when tools are involved.
850
+ // Falls back to the summed value for setups that don't emit message_start.
851
+ if (lastStreamInputTokens) {
852
+ contextData.input = lastStreamInputTokens;
853
+ } else {
854
+ contextData.input = (usage.input_tokens || usage.inputTokens || 0)
855
+ + (usage.cache_read_input_tokens || usage.cacheReadInputTokens || 0);
856
+ }
857
+ contextData.output = usage.output_tokens || usage.outputTokens || 0;
858
+ contextData.cacheRead = usage.cache_read_input_tokens || usage.cacheReadInputTokens || 0;
859
+ contextData.cacheWrite = usage.cache_creation_input_tokens || usage.cacheCreationInputTokens || 0;
860
+ }
861
+ contextData.turns++;
862
+ if (modelUsage) {
863
+ var models = Object.keys(modelUsage);
864
+ if (models.length > 0) {
865
+ var m = models[0];
866
+ var mu = modelUsage[m];
867
+ // Prefer the user-configured model name over the API-reported one
868
+ // (e.g. CLI reports "claude-sonnet-4-6" even when running as opus[1m])
869
+ var displayModel = store.get('currentModel') || m;
870
+ contextData.model = displayModel;
871
+ contextData.contextWindow = resolveContextWindow(displayModel, mu.contextWindow);
872
+ if (mu.maxOutputTokens) contextData.maxOutputTokens = mu.maxOutputTokens;
873
+ }
874
+ }
875
+ if (!store.get('replayingHistory')) updateContextPanel();
876
+ }
877
+
878
+ // contextView: "off" | "mini" | "panel"
879
+ export function getContextView() {
880
+ try { return localStorage.getItem("clagentic-context-view") || localStorage.getItem("clay-context-view") || "off"; } catch (e) { return "off"; }
881
+ }
882
+
883
+ export function setContextView(v) {
884
+ try { localStorage.setItem("clagentic-context-view", v); } catch (e) {}
885
+ }
886
+
887
+ export function applyContextView(view) {
888
+ if (contextPanel) contextPanel.classList.toggle("hidden", view !== "panel");
889
+ if (contextMini) contextMini.classList.toggle("hidden", view !== "mini");
890
+ if (view === "panel") refreshIcons();
891
+ }
892
+
893
+ export function resetContextData() {
894
+ contextData = { contextWindow: 0, maxOutputTokens: 0, model: "-", cost: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, turns: 0 };
895
+ store.set({ richContextUsage: null });
896
+ // hideCtxPopover + updateContextPanel handled by store subscriber
897
+ }
898
+
899
+ export function resetContext() {
900
+ resetContextData();
901
+ // Keep view state, just reset data
902
+ applyContextView(getContextView());
903
+ }
904
+
905
+ export function minimizeContext() {
906
+ setContextView("mini");
907
+ applyContextView("mini");
908
+ }
909
+
910
+ export function expandContext() {
911
+ setContextView("panel");
912
+ applyContextView("panel");
913
+ }
914
+
915
+ export function toggleContextPanel() {
916
+ if (!contextPanel) return;
917
+ var view = getContextView();
918
+ if (view === "panel") {
919
+ setContextView("mini");
920
+ applyContextView("mini");
921
+ } else {
922
+ setContextView("panel");
923
+ applyContextView("panel");
924
+ }
925
+ }
926
+
927
+ // --- Rich context usage popover ---
928
+
929
+ export function ensureCtxPopover() {
930
+ if (ctxPopoverEl) return;
931
+ ctxPopoverEl = document.createElement("div");
932
+ ctxPopoverEl.className = "context-usage-popover hidden";
933
+ // Keep popover open when hovering over it
934
+ ctxPopoverEl.addEventListener("mouseenter", function() {
935
+ if (ctxHoverTimer) { clearTimeout(ctxHoverTimer); ctxHoverTimer = null; }
936
+ });
937
+ ctxPopoverEl.addEventListener("mouseleave", function() {
938
+ hideCtxPopover();
939
+ });
940
+ }
941
+
942
+ export function showCtxPopover() {
943
+ var s = store.snap();
944
+ if (!s.headerContextEl || !s.richContextUsage) return;
945
+ if (ctxHoverTimer) { clearTimeout(ctxHoverTimer); ctxHoverTimer = null; }
946
+ ensureCtxPopover();
947
+ s.headerContextEl.appendChild(ctxPopoverEl);
948
+ renderCtxPopover();
949
+ ctxPopoverEl.classList.remove("hidden");
950
+ store.set({ ctxPopoverVisible: true });
951
+ }
952
+
953
+ export function hideCtxPopover() {
954
+ if (!ctxPopoverEl) return;
955
+ ctxPopoverEl.classList.add("hidden");
956
+ store.set({ ctxPopoverVisible: false });
957
+ }
958
+
959
+ export function renderCtxPopover() {
960
+ var richContextUsage = store.get('richContextUsage');
961
+ if (!ctxPopoverEl || !richContextUsage) return;
962
+ var d = richContextUsage;
963
+ var cats = d.categories || [];
964
+ var total = d.totalTokens || 0;
965
+ // SDK reports the model's base window in maxTokens; override with the
966
+ // beta-aware resolved window so 1M sessions show the correct denominator.
967
+ var max = resolveContextWindow(d.model || contextData.model, d.maxTokens || 0);
968
+ var pct = max > 0 ? Math.min(100, (total / max) * 100) : (d.percentage != null ? d.percentage : 0);
969
+
970
+ var html = "";
971
+
972
+ // Header
973
+ html += '<div class="ctx-pop-header">';
974
+ html += '<span class="ctx-pop-model">' + escHtml(d.model || contextData.model || "-") + '</span>';
975
+ html += '<span class="ctx-pop-pct">' + pct.toFixed(0) + '%';
976
+ html += '<span class="ctx-pop-tokens">' + formatTokens(total) + ' / ' + formatTokens(max) + '</span>';
977
+ html += '</span>';
978
+ html += '</div>';
979
+
980
+ // Category emoji map
981
+ var CTX_EMOJI = {
982
+ "System prompt": "\ud83d\udcdc", "System tools": "\ud83d\udee0\ufe0f",
983
+ "Memory files": "\ud83d\udcc1", "Skills": "\u26a1", "Messages": "\ud83d\udcac",
984
+ "MCP tools": "\ud83d\udd0c", "Agents": "\ud83e\udd16", "Deferred tools": "\ud83d\udce6"
985
+ };
986
+
987
+ // Stacked bar
988
+ if (cats.length > 0 && max > 0) {
989
+ html += '<div class="ctx-cat-bar">';
990
+ for (var i = 0; i < cats.length; i++) {
991
+ var cat = cats[i];
992
+ if (cat.isDeferred || !cat.tokens || CTX_HIDDEN_CATS[cat.name]) continue;
993
+ var w = Math.max(0.3, (cat.tokens / max) * 100);
994
+ html += '<div style="width:' + w.toFixed(2) + '%;background:' + escHtml(cat.color) + '"></div>';
995
+ }
996
+ html += '</div>';
997
+
998
+ // Legend
999
+ html += '<div class="ctx-cat-legend">';
1000
+ for (var j = 0; j < cats.length; j++) {
1001
+ var c = cats[j];
1002
+ if (c.isDeferred || !c.tokens || CTX_HIDDEN_CATS[c.name]) continue;
1003
+ var emoji = CTX_EMOJI[c.name] || "\ud83d\udcca";
1004
+ html += '<div class="ctx-cat-item">';
1005
+ html += '<span class="ctx-cat-name">' + em(emoji) + ' ' + escHtml(c.name) + '</span>';
1006
+ html += '<span class="ctx-cat-value">' + formatTokens(c.tokens) + '</span>';
1007
+ html += '</div>';
1008
+ }
1009
+ html += '</div>';
1010
+ }
1011
+
1012
+ // Message breakdown
1013
+ var mb = d.messageBreakdown;
1014
+ if (mb) {
1015
+ html += '<div class="ctx-pop-divider"></div>';
1016
+ html += '<div class="ctx-pop-section-label">' + em("\ud83d\udcac") + ' Messages</div>';
1017
+ if (mb.userMessageTokens) {
1018
+ html += '<div class="ctx-pop-row"><span class="ctx-pop-row-label">' + em("\ud83d\udc64") + ' User</span><span class="ctx-pop-row-value">' + formatTokens(mb.userMessageTokens) + '</span></div>';
1019
+ }
1020
+ if (mb.assistantMessageTokens) {
1021
+ html += '<div class="ctx-pop-row"><span class="ctx-pop-row-label">' + em("\ud83e\udd16") + ' Assistant</span><span class="ctx-pop-row-value">' + formatTokens(mb.assistantMessageTokens) + '</span></div>';
1022
+ }
1023
+ if (mb.toolCallTokens) {
1024
+ html += '<div class="ctx-pop-row"><span class="ctx-pop-row-label">' + em("\ud83d\udee0\ufe0f") + ' Tool calls</span><span class="ctx-pop-row-value">' + formatTokens(mb.toolCallTokens) + '</span></div>';
1025
+ }
1026
+ if (mb.toolResultTokens) {
1027
+ html += '<div class="ctx-pop-row"><span class="ctx-pop-row-label">' + em("\ud83d\udccb") + ' Tool results</span><span class="ctx-pop-row-value">' + formatTokens(mb.toolResultTokens) + '</span></div>';
1028
+ }
1029
+ if (mb.attachmentTokens) {
1030
+ html += '<div class="ctx-pop-row"><span class="ctx-pop-row-label">' + em("\ud83d\udcce") + ' Attachments</span><span class="ctx-pop-row-value">' + formatTokens(mb.attachmentTokens) + '</span></div>';
1031
+ }
1032
+ }
1033
+
1034
+ // Memory files
1035
+ var mf = d.memoryFiles;
1036
+ if (mf && mf.length > 0) {
1037
+ html += '<div class="ctx-pop-divider"></div>';
1038
+ html += '<div class="ctx-pop-section-label">' + em("\ud83d\udcc1") + ' Memory Files</div>';
1039
+ var baseCount = {};
1040
+ for (var mc = 0; mc < mf.length; mc++) {
1041
+ var bn = mf[mc].path.split("/").pop() || mf[mc].path;
1042
+ baseCount[bn] = (baseCount[bn] || 0) + 1;
1043
+ }
1044
+ for (var mi = 0; mi < mf.length; mi++) {
1045
+ var fpath = mf[mi].path;
1046
+ var fname = fpath.split("/").pop() || fpath;
1047
+ if (baseCount[fname] > 1) {
1048
+ var parts = fpath.split("/");
1049
+ fname = parts.length >= 2 ? parts[parts.length - 2] + "/" + fname : fpath;
1050
+ }
1051
+ html += '<div class="ctx-pop-row"><span class="ctx-pop-row-label">' + em("\ud83d\udcc4") + ' ' + escHtml(fname) + '</span><span class="ctx-pop-row-value">' + formatTokens(mf[mi].tokens) + '</span></div>';
1052
+ }
1053
+ }
1054
+
1055
+ // Auto-compact note
1056
+ if (d.isAutoCompactEnabled && d.autoCompactThreshold) {
1057
+ html += '<div class="ctx-pop-note">' + em("\u267b\ufe0f") + ' Auto-compact at ' + formatTokens(d.autoCompactThreshold) + '</div>';
1058
+ }
1059
+
1060
+ ctxPopoverEl.innerHTML = html;
1061
+ }