@clagentic/console 1.7.1-beta.1 → 1.8.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 (39) hide show
  1. package/bin/cli.js +198 -2542
  2. package/lib/build-sha.json +2 -2
  3. package/lib/cli/daemon-launch.js +797 -0
  4. package/lib/cli/ipc-subcommands.js +186 -0
  5. package/lib/cli/menus.js +849 -0
  6. package/lib/cli/net-detect.js +209 -0
  7. package/lib/cli/tui.js +589 -0
  8. package/lib/pages.js +13 -17
  9. package/lib/public/css/diagnostics.css +15 -0
  10. package/lib/public/css/overlays.css +19 -0
  11. package/lib/public/index.html +12 -11
  12. package/lib/public/manifest.json +1 -1
  13. package/lib/public/modules/app-connection.js +150 -4
  14. package/lib/public/modules/app-history-replay.js +155 -0
  15. package/lib/public/modules/app-home-hub.js +2 -16
  16. package/lib/public/modules/app-messages.js +1245 -1489
  17. package/lib/public/modules/app-notifications.js +4 -4
  18. package/lib/public/modules/command-palette.js +11 -22
  19. package/lib/public/modules/context-sources.js +1 -6
  20. package/lib/public/modules/filebrowser.js +25 -13
  21. package/lib/public/modules/mcp-ui.js +2 -2
  22. package/lib/public/modules/notifications.js +22 -1
  23. package/lib/public/modules/playbook.js +6 -6
  24. package/lib/public/modules/project-settings.js +5 -13
  25. package/lib/public/modules/qrcode.js +2 -2
  26. package/lib/public/modules/relative-time.js +27 -0
  27. package/lib/public/modules/scheduler-history.js +1 -5
  28. package/lib/public/modules/server-settings.js +28 -15
  29. package/lib/public/modules/sidebar-projects.js +1 -1
  30. package/lib/public/modules/sidebar-sessions.js +1 -15
  31. package/lib/public/modules/sidebar.js +3 -3
  32. package/lib/public/modules/utils.js +1 -0
  33. package/lib/public/sw.js +24 -4
  34. package/lib/server-auth.js +48 -2
  35. package/lib/server-settings.js +70 -4
  36. package/lib/server.js +200 -4
  37. package/lib/smtp.js +6 -6
  38. package/lib/yoke/adapters/codex.js +1 -1
  39. package/package.json +1 -1
@@ -1,6 +1,24 @@
1
1
  // app-messages.js - WebSocket message router
2
2
  // Extracted from app.js (PR-23)
3
- // All dependencies are direct imports; no context injection needed.
3
+ //
4
+ // lr-4e49 Part 2: this file used to be a single 185-case switch — every new
5
+ // message type had to edit it, making it a permanent merge hotspot. It is
6
+ // now a thin handler registry: `handlers[type]` maps a message type to an
7
+ // array of handler functions, populated either by the core registration
8
+ // call at the bottom of this file (message types with no better single
9
+ // owner, or with more than one consumer module already imported together
10
+ // here) or by a domain module calling registerHandlers() itself at its own
11
+ // module load time (see filebrowser.js, server-settings.js,
12
+ // app-history-replay.js). processMessage() looks up the array for
13
+ // msg.type and invokes each handler in registration order — this preserves
14
+ // the exact per-type call order the original switch cases had (e.g.
15
+ // process_stats: updateStatusPanel() before updateSettingsStats()).
16
+ //
17
+ // Ordering risk (called out in the split task): history_meta/prepend/done
18
+ // drive sticky-bottom scroll arming across a whole replay batch — the
19
+ // riskiest sequencing in this file. That block is extracted verbatim to
20
+ // app-history-replay.js; see the module comment there for why it stays
21
+ // self-contained and doesn't change call order.
4
22
 
5
23
  import { store } from './store.js';
6
24
  import { getWs } from './ws-ref.js';
@@ -8,7 +26,6 @@ import { getWs } from './ws-ref.js';
8
26
  // --- Leaf module imports ---
9
27
  import { showToast } from './utils.js';
10
28
  import { refreshIcons, iconHtml } from './icons.js';
11
- import { renderMarkdown, highlightCodeBlocks, highlightCodeBlocksBatched, renderMermaidBlocks } from './markdown.js';
12
29
  import { updatePageTitle } from './sidebar.js';
13
30
  import { renderSessionList, updateSessionPresence, populateCliSessionList, handleSearchResults, updateSessionBadge } from './sidebar-sessions.js';
14
31
  import { updateDmBadge, renderSidebarPresence, setMentionActive } from './sidebar-users.js';
@@ -20,10 +37,9 @@ import { handleFindInSessionResults } from './session-search.js';
20
37
  import { handleInputSync, autoResize, resetAutoResize, builtinCommands, setScheduleBtnDisabled } from './input.js';
21
38
  import { startThinking, appendThinking, stopThinking, resetThinkingGroup, createToolItem, updateToolExecuting, updateToolResult, markAllToolsDone, closeToolGroup, removeToolFromGroup, resetToolState, getTools, getPlanContent, setPlanContent, renderPlanBanner, renderPlanCard, getTodoTools, handleTodoWrite, handleTaskCreate, handleTaskUpdate, applyDeadSessionTodoCompaction, isPlanFilePath, enableMainInput, addTurnMeta, updateSubagentActivity, addSubagentToolEntry, markSubagentDone, initSubagentStop, updateSubagentProgress, updateSubagentTaskStatus, renderAskUserQuestion, markAskUserAnswered, renderPermissionRequest, markPermissionCancelled, markPermissionResolved, renderElicitationRequest, markElicitationResolved } from './tools.js';
22
39
  import { showDoneNotification, playDoneSound, isNotifAlertEnabled, isNotifSoundEnabled } from './notifications.js';
23
- import { handleFsList, handleFsRead, handleFileChanged, handleDirChanged, handleFileHistory, handleGitDiff, handleFileAt, refreshIfOpen, handleFsSearch } from './filebrowser.js';
24
- import { getPendingNavigate, peekPendingNavigate } from './pending-navigate.js';
40
+ import { handleFsRead, refreshIfOpen } from './filebrowser.js';
25
41
  import { isProjectSettingsOpen, refreshProjectSettingsModels, handleInstructionsRead, handleInstructionsWrite, handleProjectEnv, handleProjectEnvSaved, handleProjectSharedEnv, handleProjectSharedEnvSaved, handleProjectOwnerChanged, updateLiteVisibility, handleLiteProjectStatus, handleLiteEnrollResult, handleLiteUnenrollResult } from './project-settings.js';
26
- import { updateSettingsModels, updateSettingsStats, updateDaemonConfig, handleSetPinResult, handleKeepAwakeChanged, handleAutoContinueChanged, handleRefreshAgentsResult, handleRestartResult, handleShutdownResult, handleSharedEnv, handleSharedEnvSaved, handleGlobalClaudeMdRead, handleGlobalClaudeMdWrite, updateSsLiteVisibility } from './server-settings.js';
42
+ import { updateSettingsModels, updateSettingsStats, updateDaemonConfig, handleSharedEnv, handleSharedEnvSaved, updateSsLiteVisibility } from './server-settings.js';
27
43
  import { handleRenameCustomIconResult } from './custom-icons-settings.js';
28
44
  import { handleTermList, handleTermCreated, sendTerminalCommand, handleTermOutput, handleTermResized, handleTermExited, handleTermClosed } from './terminal.js';
29
45
  import { updateTerminalList, handleContextSourcesState } from './context-sources.js';
@@ -36,10 +52,10 @@ import { handleMcpServersState } from './mcp-ui.js';
36
52
  import { handleLoopRegistryUpdated, handleScheduleRunStarted, handleScheduleRunFinished, handleLoopScheduled, isSchedulerOpen, enterCraftingMode, exitCraftingMode, handleLoopRegistryFiles } from './scheduler.js';
37
53
 
38
54
  // --- App module imports ---
39
- import { scrollToBottom, addToMessages, addUserMessage, addSystemMessage, appendDelta, finalizeAssistantBlock, addConflictMessage, addContextOverflowMessage, showSuggestionChips, armStickyBottom, disarmStickyBottom, removePreThinking } from './app-rendering.js';
55
+ import { scrollToBottom, addToMessages, addUserMessage, addSystemMessage, appendDelta, finalizeAssistantBlock, addConflictMessage, addContextOverflowMessage, showSuggestionChips, removePreThinking } from './app-rendering.js';
40
56
  import { setActivity, startUrgentBlink, stopUrgentBlink, blinkSessionDot, updateCrossProjectBlink } from './app-favicon.js';
41
57
  import { setStatus } from './app-connection.js';
42
- import { getModelEffortLevels, accumulateUsage, getSessionUsage, setSessionUsage, updateUsagePanel, accumulateContext, updateContextPanel, renderCtxPopover, updateStatusPanel } from './app-panels.js';
58
+ import { getModelEffortLevels, accumulateUsage, setSessionUsage, updateUsagePanel, accumulateContext, updateContextPanel, renderCtxPopover, updateStatusPanel } from './app-panels.js';
43
59
  import { updateProjectList, resetClientState, showUpdateAvailable, handleRemoveProjectCheckResult, handleRemoveProjectResult, handleBrowseDirResult, handleAddProjectResult, handleCloneProgress } from './app-projects.js';
44
60
  import { updateHistorySentinel, prependOlderHistory } from './app-header.js';
45
61
  import { hideHomeHub, handleHubSchedules, handleHubRecentSessions } from './app-home-hub.js';
@@ -52,1527 +68,1267 @@ import { handleNotificationsState, handleNotificationCreated, handleNotification
52
68
  import { handleMentionStart, handleMentionActivity, handleMentionStream, handleMentionDone, handleMentionError, renderMentionUser, renderMentionResponse, renderUserMention } from './mention.js';
53
69
  import { handleTeamState, handleTeamMemberUpdate, handleTeamTaskUpdate, handleTeamMessage as handleTeamMsg, handleTeamGone } from './team-panel.js';
54
70
  import { addDiagnostic } from './diagnostics.js';
71
+ import { handleHistoryMeta, handleHistoryDone } from './app-history-replay.js';
55
72
 
56
73
  // --- DOM refs (cached once, stable for page lifetime) ---
57
74
  var messagesEl = document.getElementById("messages");
58
75
  var headerTitleEl = document.getElementById("header-title");
59
76
  var inputEl = document.getElementById("input");
60
77
  var connectOverlay = document.getElementById("connect-overlay");
61
- var replayLoadingEl = document.getElementById("replay-loading");
78
+
79
+ // --- Handler registry ---
80
+ // type -> array of handler functions, called in registration order.
81
+ // May already be populated by the time this line runs — see the
82
+ // registerHandlers() doc comment below (lr-4c58ae circular-import boot
83
+ // halt). Do not unconditionally reassign: that would drop any
84
+ // registrations a circular caller already made before this module's own
85
+ // body reached this line.
86
+ var handlers = handlers || {};
87
+
88
+ /**
89
+ * Register one or more message-type handlers. Called by this module's own
90
+ * core registration (bottom of file) and by domain modules that own a
91
+ * message type outright (filebrowser.js, server-settings.js). Safe to call
92
+ * multiple times for the same type — each call appends, so two modules can
93
+ * both react to one broadcast (e.g. shared_env_result) without either
94
+ * having to import the other.
95
+ *
96
+ * lr-4c58ae: this module sits in an import cycle with several of the domain
97
+ * modules that call registerHandlers() at their own module-body top level
98
+ * (filebrowser.js, server-settings.js — both import registerHandlers from
99
+ * here, and this file imports back from them for their non-registry
100
+ * exports). Depending on which module app.js's graph reaches first, ESM's
101
+ * cycle-breaking semantics can run a caller's top-level registerHandlers()
102
+ * call before this file's own `var handlers = {}` line has executed —
103
+ * registerHandlers itself is always safely callable (function declarations
104
+ * are hoisted at instantiation), but the object it wrote into on the module
105
+ * scope was not yet assigned, throwing "Cannot read properties of
106
+ * undefined" and halting the whole app.js boot before connect() runs.
107
+ * Lazily initializing here (independent of module-body execution order)
108
+ * makes registration order-safe: the first call — whichever module makes
109
+ * it — creates the registry, and the `var handlers = {}` below becomes a
110
+ * no-op once this module's own body eventually runs.
111
+ *
112
+ * @param {Object<string, function(Object): void>} map - type -> handler
113
+ */
114
+ export function registerHandlers(map) {
115
+ if (!handlers) handlers = {};
116
+ Object.keys(map).forEach(function (type) {
117
+ if (!handlers[type]) handlers[type] = [];
118
+ handlers[type].push(map[type]);
119
+ });
120
+ }
62
121
 
63
122
  export function processMessage(msg) {
64
- // Preserve original timestamp from history replay
65
- store.set({ currentMsgTs: msg._ts || null });
66
-
67
- switch (msg.type) {
68
- case "history_meta":
69
- store.set({ historyFrom: msg.from, historyTotal: msg.total, replayingHistory: true });
70
- if (replayLoadingEl) replayLoadingEl.classList.remove("hidden");
71
- updateHistorySentinel();
72
- // Arm sticky-bottom at the START of replay so the scroll listener's
73
- // "user scrolled up" detection is suppressed for the entire history
74
- // append sequence. Without this, scroll events fired during DOM growth
75
- // can set isUserScrolledUp=true before history_done's arm fires, leaving
76
- // the user stranded mid-conversation on resume (especially on mobile).
77
- // Peek without consuming — getPendingNavigate() is the single consumer
78
- // in the history_done branch below. Calling getPendingNavigate() here
79
- // would clear the value before history_done can use it.
80
- var _metaNav = peekPendingNavigate();
81
- if (!_metaNav || !(_metaNav.toolId || _metaNav.assistantUuid)) {
82
- armStickyBottom(5000, true); // force: history replay must scroll to bottom
83
- }
84
- break;
85
-
86
- case "history_prepend":
87
- prependOlderHistory(msg.items, msg.meta);
88
- break;
89
-
90
- case "history_done":
91
- store.set({ replayingHistory: false });
92
- if (replayLoadingEl) replayLoadingEl.classList.add("hidden");
93
- // Arm sticky-bottom FIRST so the ResizeObserver is watching before the
94
- // bulk DOM mutations below (syntax highlighting, mermaid, todo
95
- // compaction) displace the scroll position. Arming after those writes
96
- // races the browser's layout resolution and can leave the user stranded
97
- // mid-conversation. The arm is later re-evaluated and potentially
98
- // replaced by the nav-target branch below; that branch calls
99
- // scrollToBottom() and does NOT re-arm, so this early arm is harmless.
100
- var nav = getPendingNavigate();
101
- var hasNavTarget = nav && (nav.toolId || nav.assistantUuid);
102
- if (!hasNavTarget) {
103
- // Scale the quiet window with history depth. A 20-item threshold
104
- // (old code) gave identical 2000ms to sessions with 21 and 1000
105
- // items. The scaled formula gives fast disarm for small sessions
106
- // and up to 3000ms for very large ones (≥500 events), without
107
- // a hard ceiling that cuts off still-settling content on mobile.
108
- var historyLen = store.get('historyTotal') || 0;
109
- var quietMs = Math.min(Math.max(500, Math.round(historyLen * 2.5)), 3000);
110
- armStickyBottom(quietMs, true); // force: history replay must scroll to bottom
111
- }
112
- // Batched syntax highlight + mermaid pass for the entire replayed
113
- // transcript. Per-message highlights are skipped during replay
114
- // (see markdown.js). Uses requestIdleCallback batching to avoid
115
- // blocking the main thread — the old synchronous highlightCodeBlocks()
116
- // fired hljs on every code block at once, each triggering a
117
- // ResizeObserver callback that reset the sticky-bottom quiet timer,
118
- // keeping the scroll pinned and the UI unresponsive for several
119
- // seconds on large sessions (especially on mobile). The completion
120
- // callback re-arms once after all blocks are done.
121
- if (messagesEl) {
122
- highlightCodeBlocksBatched(messagesEl, function () {
123
- if (!store.get('processing')) {
124
- armStickyBottom(500, true); // force: re-pin after all blocks settle
125
- }
126
- });
127
- renderMermaidBlocks(messagesEl);
128
- // NOTE: The old 300ms setTimeout re-arm is removed. The batched
129
- // highlight completion callback above replaces it. The 300ms timer
130
- // was a workaround for Highlight.js deferred work that no longer
131
- // applies with the idle-callback batching path.
132
- }
133
- // Compact dead-session todo widgets (unfinished items will never
134
- // resolve — the agent isn't coming back) so they don't anchor
135
- // visual position mid-page on resume.
136
- if (!store.get('sessionIsProcessing')) {
137
- applyDeadSessionTodoCompaction();
138
- }
139
- // Hide vendor toggle if session has history (vendor already locked)
140
- var _hTotal = store.get('historyTotal') || 0;
141
- var _vtw2 = document.getElementById("vendor-toggle-wrap");
142
- if (_vtw2 && _hTotal > 0) { _vtw2.classList.remove("hidden"); _vtw2.classList.add("locked"); }
143
- // Restore cached rich context usage BEFORE updateContextPanel runs
144
- if (msg.contextUsage) {
145
- store.set({ richContextUsage: msg.contextUsage });
146
- }
147
- // Restore accurate context data from the last result in full history.
148
- // accumulateContext handles context bar fill; accumulateUsage restores the
149
- // usage panel's context/cost values. Both assign (not sum) so replay
150
- // accumulation during history messages is correctly overwritten here.
151
- if (msg.lastUsage || msg.lastModelUsage) {
152
- accumulateContext(msg.lastCost, msg.lastUsage, msg.lastModelUsage, msg.lastStreamInputTokens);
153
- }
154
- // Restore usage panel from the last result in history.
155
- // output/cacheWrite are cumulative sums that were accumulated during replay above;
156
- // we keep them. cost and context come from the last result directly.
157
- if (msg.lastCost != null) {
158
- var su = getSessionUsage();
159
- su.cost = msg.lastCost;
160
- if (msg.lastStreamInputTokens) su.context = msg.lastStreamInputTokens;
161
- }
162
- updateContextPanel();
163
- updateUsagePanel();
164
- // Render + finalize any incomplete turn from the replayed history
165
- var _hs = store.snap();
166
- if (_hs.currentMsgEl && _hs.currentFullText) {
167
- var replayContentEl = _hs.currentMsgEl.querySelector(".md-content");
168
- if (replayContentEl) {
169
- replayContentEl.innerHTML = renderMarkdown(_hs.currentFullText);
170
- }
171
- }
172
- markAllToolsDone();
173
- finalizeAssistantBlock();
174
- stopUrgentBlink();
175
- // Scroll to tool element if navigating from file edit history.
176
- // nav/hasNavTarget are declared above (early arm block).
177
- if (hasNavTarget) {
178
- // Nav target: discard the early sticky-bottom arm and scroll to element.
179
- disarmStickyBottom();
180
- scrollToBottom();
181
- }
182
- if (hasNavTarget) {
183
- requestAnimationFrame(function() {
184
- // Prefer scrolling to the exact tool element
185
- var target = nav.toolId ? messagesEl.querySelector('[data-tool-id="' + nav.toolId + '"]') : null;
186
- if (!target && nav.assistantUuid) {
187
- target = messagesEl.querySelector('[data-uuid="' + nav.assistantUuid + '"]');
188
- }
189
- if (target) {
190
- // Auto-expand parent tool group if collapsed
191
- var parentGroup = target.closest(".tool-group");
192
- if (parentGroup) parentGroup.classList.remove("collapsed");
193
- target.scrollIntoView({ behavior: "smooth", block: "center" });
194
- target.classList.add("message-blink");
195
- setTimeout(function() { target.classList.remove("message-blink"); }, 2000);
196
- }
197
- });
198
- }
199
- break;
123
+ // Preserve original timestamp from history replay
124
+ store.set({ currentMsgTs: msg._ts || null });
125
+
126
+ var list = handlers[msg.type];
127
+ if (!list) return;
128
+ for (var i = 0; i < list.length; i++) {
129
+ list[i](msg);
130
+ }
131
+ }
200
132
 
201
- case "info":
202
- if (msg.text && !msg.project && !msg.cwd) {
203
- addSystemMessage(msg.text, false);
204
- break;
205
- }
206
- store.set({ projectName: msg.project || msg.cwd });
207
- if (msg.cwd) store.set({ cwd: msg.cwd });
208
- if (msg.slug) store.set({ currentSlug: msg.slug });
209
- try { var _is = store.snap(); localStorage.setItem("clagentic-project-name-" + (_is.currentSlug || "default"), _is.projectName); } catch (e) {}
210
- headerTitleEl.textContent = store.get('projectName');
211
- var tbProjectName = document.getElementById("title-bar-project-name");
212
- if (tbProjectName) tbProjectName.textContent = msg.title || store.get('projectName');
213
- updatePageTitle();
214
- if (msg.version) {
215
- setPaletteVersion(msg.version);
216
- var serverVersionEl = document.getElementById("settings-server-version");
217
- if (serverVersionEl) serverVersionEl.textContent = msg.version;
218
- }
219
- if (msg.projectOwnerId !== undefined) store.set({ currentProjectOwnerId: msg.projectOwnerId });
220
- if (msg.ownerLocked !== undefined) store.set({ ownerLocked: !!msg.ownerLocked });
221
- if (msg.osUsers !== undefined) store.set({ isOsUsers: !!msg.osUsers });
222
- if (msg.lanHost) window.__lanHost = msg.lanHost;
223
- if (msg.dangerouslySkipPermissions) {
224
- store.set({ skipPermsEnabled: true });
225
- var spBanner = document.getElementById("skip-perms-pill");
226
- if (spBanner) spBanner.classList.remove("hidden");
227
- }
228
- if (msg.dangerouslySkipPermissionsBlocked) {
229
- // The server config has dangerouslySkipPermissions=true but it is disabled
230
- // because multi-user mode is active. Warn admins so they know the config
231
- // flag has no effect and remove it to avoid confusion.
232
- if (store.get('permissions') && store.get('permissions').projectSettings !== false) {
233
- showToast("dangerouslySkipPermissions is set in config but is disabled in multi-user mode. All users have normal tool-approval rules.", "warn");
234
- }
235
- }
236
- updateProjectList(msg);
237
- if (msg.liteInstalled !== undefined) {
238
- updateLiteVisibility(!!msg.liteInstalled);
239
- updateSsLiteVisibility(!!msg.liteInstalled);
240
- }
241
- break;
242
-
243
- case "update_available":
244
- // In multi-user mode, only show update UI to admins
245
- checkAdminAccess().then(function (isAdmin) {
246
- if (!isAdmin) return;
247
- showUpdateAvailable(msg);
248
- showUpdateBanner(msg);
249
- });
250
- break;
251
-
252
- case "up_to_date":
253
- var utdBtn = document.getElementById("settings-update-check");
254
- if (utdBtn) {
255
- utdBtn.innerHTML = "";
256
- var utdIcon = document.createElement("i");
257
- utdIcon.setAttribute("data-lucide", "check");
258
- utdBtn.appendChild(utdIcon);
259
- utdBtn.appendChild(document.createTextNode(" Up to date (v" + msg.version + ")"));
260
- utdBtn.disabled = true;
261
- refreshIcons();
262
- setTimeout(function () {
263
- utdBtn.innerHTML = "";
264
- var rwIcon = document.createElement("i");
265
- rwIcon.setAttribute("data-lucide", "refresh-cw");
266
- utdBtn.appendChild(rwIcon);
267
- utdBtn.appendChild(document.createTextNode(" Check for updates"));
268
- utdBtn.disabled = false;
269
- utdBtn.classList.remove("settings-btn-update-available");
270
- refreshIcons();
271
- }, 3000);
272
- }
273
- break;
274
-
275
- case "update_started":
276
- var updNowBtn = document.getElementById("update-now");
277
- if (updNowBtn) {
278
- updNowBtn.innerHTML = '<i data-lucide="loader"></i> Updating...';
279
- updNowBtn.disabled = true;
280
- refreshIcons();
281
- var spinIcon = updNowBtn.querySelector(".lucide");
282
- if (spinIcon) spinIcon.classList.add("icon-spin-inline");
283
- }
284
- // Block the entire screen with the connect overlay
285
- connectOverlay.classList.remove("hidden");
286
- break;
287
-
288
- case "slash_commands": {
289
- // Backward compat: server sends {name,desc,type}[] since lr-1c7f;
290
- // older server versions may still send string[].
291
- var reserved = new Set(builtinCommands.map(function (c) { return c.name; }));
292
- var enriched = (msg.commands || []).map(function (cmd) {
293
- if (typeof cmd === "string") return { name: cmd, desc: "", type: "skill" };
294
- return cmd;
295
- });
296
- store.set({ slashCommands: enriched.filter(function (cmd) {
297
- return !reserved.has(cmd.name);
298
- }) });
299
- break;
133
+ // --- Core handlers ---
134
+ // Message types with no single better-fit domain module, or whose original
135
+ // case body already called into more than one module and needs both
136
+ // imports together (process_stats, shared_env_result, set_shared_env_result,
137
+ // daemon_config). See filebrowser.js / server-settings.js /
138
+ // app-history-replay.js for the handlers those modules register themselves.
139
+ registerHandlers({
140
+ history_meta: function (msg) {
141
+ handleHistoryMeta(msg, updateHistorySentinel);
142
+ },
143
+
144
+ history_prepend: function (msg) {
145
+ prependOlderHistory(msg.items, msg.meta);
146
+ },
147
+
148
+ history_done: handleHistoryDone,
149
+
150
+ info: function (msg) {
151
+ if (msg.text && !msg.project && !msg.cwd) {
152
+ addSystemMessage(msg.text, false);
153
+ return;
154
+ }
155
+ store.set({ projectName: msg.project || msg.cwd });
156
+ if (msg.cwd) store.set({ cwd: msg.cwd });
157
+ if (msg.slug) store.set({ currentSlug: msg.slug });
158
+ try { var _is = store.snap(); localStorage.setItem("clagentic-project-name-" + (_is.currentSlug || "default"), _is.projectName); } catch (e) {}
159
+ headerTitleEl.textContent = store.get('projectName');
160
+ var tbProjectName = document.getElementById("title-bar-project-name");
161
+ if (tbProjectName) tbProjectName.textContent = msg.title || store.get('projectName');
162
+ updatePageTitle();
163
+ if (msg.version) {
164
+ setPaletteVersion(msg.version);
165
+ var serverVersionEl = document.getElementById("settings-server-version");
166
+ if (serverVersionEl) serverVersionEl.textContent = msg.version;
167
+ }
168
+ if (msg.projectOwnerId !== undefined) store.set({ currentProjectOwnerId: msg.projectOwnerId });
169
+ if (msg.ownerLocked !== undefined) store.set({ ownerLocked: !!msg.ownerLocked });
170
+ if (msg.osUsers !== undefined) store.set({ isOsUsers: !!msg.osUsers });
171
+ if (msg.lanHost) window.__lanHost = msg.lanHost;
172
+ if (msg.dangerouslySkipPermissions) {
173
+ store.set({ skipPermsEnabled: true });
174
+ var spBanner = document.getElementById("skip-perms-pill");
175
+ if (spBanner) spBanner.classList.remove("hidden");
176
+ }
177
+ if (msg.dangerouslySkipPermissionsBlocked) {
178
+ // The server config has dangerouslySkipPermissions=true but it is disabled
179
+ // because multi-user mode is active. Warn admins so they know the config
180
+ // flag has no effect and remove it to avoid confusion.
181
+ if (store.get('permissions') && store.get('permissions').projectSettings !== false) {
182
+ showToast("dangerouslySkipPermissions is set in config but is disabled in multi-user mode. All users have normal tool-approval rules.", "warn");
300
183
  }
301
-
302
- case "model_info": {
303
- // Drop stale model_info from a vendor that doesn't match the active
304
- // session's vendor. On high-latency connections, the server's default-
305
- // adapter model_info can arrive after session_switched has already
306
- // bound the session to a different vendor. Applying it would replace
307
- // currentModels with the wrong vendor's list and trigger app-panels
308
- // to request models for the "wrong" vendor, which feeds back into a
309
- // ping-pong loop of vendor flapping. See issue #336.
310
- var _curV = store.get('currentVendor');
311
- if (msg.vendor && _curV && msg.vendor !== _curV) break;
312
-
313
- var _modelVal = msg.model;
314
- if (_modelVal && typeof _modelVal === "object") _modelVal = _modelVal.value || _modelVal.displayName || "";
315
- var _miUpdate = { currentModels: msg.models || [] };
316
- if (Object.prototype.hasOwnProperty.call(msg, "model")) {
317
- if (store.get('vendorSelectionLocked') && store.get('currentModel')) {
318
- // Keep the user's existing selection; only update models list
319
- } else {
320
- _miUpdate.currentModel = _modelVal || "";
321
- }
184
+ }
185
+ updateProjectList(msg);
186
+ if (msg.liteInstalled !== undefined) {
187
+ updateLiteVisibility(!!msg.liteInstalled);
188
+ updateSsLiteVisibility(!!msg.liteInstalled);
189
+ }
190
+ },
191
+
192
+ update_available: function (msg) {
193
+ // In multi-user mode, only show update UI to admins
194
+ checkAdminAccess().then(function (isAdmin) {
195
+ if (!isAdmin) return;
196
+ showUpdateAvailable(msg);
197
+ showUpdateBanner(msg);
198
+ });
199
+ },
200
+
201
+ up_to_date: function (msg) {
202
+ var utdBtn = document.getElementById("settings-update-check");
203
+ if (utdBtn) {
204
+ utdBtn.innerHTML = "";
205
+ var utdIcon = document.createElement("i");
206
+ utdIcon.setAttribute("data-lucide", "check");
207
+ utdBtn.appendChild(utdIcon);
208
+ utdBtn.appendChild(document.createTextNode(" Up to date (v" + msg.version + ")"));
209
+ utdBtn.disabled = true;
210
+ refreshIcons();
211
+ setTimeout(function () {
212
+ utdBtn.innerHTML = "";
213
+ var rwIcon = document.createElement("i");
214
+ rwIcon.setAttribute("data-lucide", "refresh-cw");
215
+ utdBtn.appendChild(rwIcon);
216
+ utdBtn.appendChild(document.createTextNode(" Check for updates"));
217
+ utdBtn.disabled = false;
218
+ utdBtn.classList.remove("settings-btn-update-available");
219
+ refreshIcons();
220
+ }, 3000);
221
+ }
222
+ },
223
+
224
+ update_started: function (msg) {
225
+ var updNowBtn = document.getElementById("update-now");
226
+ if (updNowBtn) {
227
+ updNowBtn.innerHTML = '<i data-lucide="loader"></i> Updating...';
228
+ updNowBtn.disabled = true;
229
+ refreshIcons();
230
+ var spinIcon = updNowBtn.querySelector(".lucide");
231
+ if (spinIcon) spinIcon.classList.add("icon-spin-inline");
232
+ }
233
+ // Block the entire screen with the connect overlay
234
+ connectOverlay.classList.remove("hidden");
235
+ },
236
+
237
+ slash_commands: function (msg) {
238
+ // Backward compat: server sends {name,desc,type}[] since lr-1c7f;
239
+ // older server versions may still send string[].
240
+ var reserved = new Set(builtinCommands.map(function (c) { return c.name; }));
241
+ var enriched = (msg.commands || []).map(function (cmd) {
242
+ if (typeof cmd === "string") return { name: cmd, desc: "", type: "skill" };
243
+ return cmd;
244
+ });
245
+ store.set({ slashCommands: enriched.filter(function (cmd) {
246
+ return !reserved.has(cmd.name);
247
+ }) });
248
+ },
249
+
250
+ model_info: function (msg) {
251
+ // Drop stale model_info from a vendor that doesn't match the active
252
+ // session's vendor. On high-latency connections, the server's default-
253
+ // adapter model_info can arrive after session_switched has already
254
+ // bound the session to a different vendor. Applying it would replace
255
+ // currentModels with the wrong vendor's list and trigger app-panels
256
+ // to request models for the "wrong" vendor, which feeds back into a
257
+ // ping-pong loop of vendor flapping. See issue #336.
258
+ var _curV = store.get('currentVendor');
259
+ if (msg.vendor && _curV && msg.vendor !== _curV) return;
260
+
261
+ var _modelVal = msg.model;
262
+ if (_modelVal && typeof _modelVal === "object") _modelVal = _modelVal.value || _modelVal.displayName || "";
263
+ var _miUpdate = { currentModels: msg.models || [] };
264
+ if (Object.prototype.hasOwnProperty.call(msg, "model")) {
265
+ if (store.get('vendorSelectionLocked') && store.get('currentModel')) {
266
+ // Keep the user's existing selection; only update models list
267
+ } else {
268
+ _miUpdate.currentModel = _modelVal || "";
269
+ }
270
+ } else {
271
+ _miUpdate.currentModel = store.get('currentModel');
272
+ }
273
+ if (msg.vendor && !store.get('vendorSelectionLocked')) _miUpdate.currentVendor = msg.vendor;
274
+ if (msg.availableVendors) _miUpdate.availableVendors = msg.availableVendors;
275
+ if (msg.installedVendors) _miUpdate.installedVendors = msg.installedVendors;
276
+ store.set(_miUpdate);
277
+ updateSettingsModels(_modelVal, msg.models || []);
278
+ refreshProjectSettingsModels();
279
+ },
280
+
281
+ config_state: function (msg) {
282
+ var _cs = {};
283
+ if (msg.model) _cs.currentModel = msg.model;
284
+ if (msg.mode) _cs.currentMode = msg.mode;
285
+ if (msg.effort) _cs.currentEffort = msg.effort;
286
+ if (msg.betas) _cs.currentBetas = msg.betas;
287
+ if (msg.thinking) _cs.currentThinking = msg.thinking;
288
+ if (msg.thinkingBudget) _cs.currentThinkingBudget = msg.thinkingBudget;
289
+ store.set(_cs);
290
+ // Validate effort against current model's supported levels
291
+ var _csRead = store.snap();
292
+ if (_csRead.currentModels.length > 0) {
293
+ var levels = getModelEffortLevels();
294
+ var effortValid = false;
295
+ for (var ei = 0; ei < levels.length; ei++) {
296
+ if (levels[ei] === _csRead.currentEffort) { effortValid = true; break; }
297
+ }
298
+ if (!effortValid) store.set({ currentEffort: "medium" });
299
+ }
300
+ },
301
+
302
+ codex_config: function (msg) {
303
+ store.set({
304
+ codexApproval: msg.approval,
305
+ codexSandbox: msg.sandbox,
306
+ codexWebSearch: msg.webSearch,
307
+ });
308
+ },
309
+
310
+ client_count: function (msg) {
311
+ // Sidebar presence: current project's online users
312
+ if (msg.users) {
313
+ renderSidebarPresence(msg.users);
314
+ }
315
+ // Non-multi-user mode: simple count in topbar
316
+ if (!msg.users) {
317
+ var countEl = document.getElementById("client-count");
318
+ var countTextEl = document.getElementById("client-count-text");
319
+ if (countEl && countTextEl) {
320
+ if (msg.count > 1) {
321
+ countTextEl.textContent = msg.count + " connected";
322
+ countEl.classList.remove("hidden");
322
323
  } else {
323
- _miUpdate.currentModel = store.get('currentModel');
324
+ countEl.classList.add("hidden");
324
325
  }
325
- if (msg.vendor && !store.get('vendorSelectionLocked')) _miUpdate.currentVendor = msg.vendor;
326
- if (msg.availableVendors) _miUpdate.availableVendors = msg.availableVendors;
327
- if (msg.installedVendors) _miUpdate.installedVendors = msg.installedVendors;
328
- store.set(_miUpdate);
329
- updateSettingsModels(_modelVal, msg.models || []);
330
- refreshProjectSettingsModels();
331
- break;
332
326
  }
333
-
334
- case "config_state": {
335
- var _cs = {};
336
- if (msg.model) _cs.currentModel = msg.model;
337
- if (msg.mode) _cs.currentMode = msg.mode;
338
- if (msg.effort) _cs.currentEffort = msg.effort;
339
- if (msg.betas) _cs.currentBetas = msg.betas;
340
- if (msg.thinking) _cs.currentThinking = msg.thinking;
341
- if (msg.thinkingBudget) _cs.currentThinkingBudget = msg.thinkingBudget;
342
- store.set(_cs);
343
- // Validate effort against current model's supported levels
344
- var _csRead = store.snap();
345
- if (_csRead.currentModels.length > 0) {
346
- var levels = getModelEffortLevels();
347
- var effortValid = false;
348
- for (var ei = 0; ei < levels.length; ei++) {
349
- if (levels[ei] === _csRead.currentEffort) { effortValid = true; break; }
350
- }
351
- if (!effortValid) store.set({ currentEffort: "medium" });
352
- }
353
- } break;
354
-
355
- case "codex_config":
356
- store.set({
357
- codexApproval: msg.approval,
358
- codexSandbox: msg.sandbox,
359
- codexWebSearch: msg.webSearch,
360
- });
361
- break;
362
-
363
- case "client_count":
364
- // Sidebar presence: current project's online users
365
- if (msg.users) {
366
- renderSidebarPresence(msg.users);
367
- }
368
- // Non-multi-user mode: simple count in topbar
369
- if (!msg.users) {
370
- var countEl = document.getElementById("client-count");
371
- var countTextEl = document.getElementById("client-count-text");
372
- if (countEl && countTextEl) {
373
- if (msg.count > 1) {
374
- countTextEl.textContent = msg.count + " connected";
375
- countEl.classList.remove("hidden");
376
- } else {
377
- countEl.classList.add("hidden");
378
- }
379
- }
380
- }
381
- break;
382
-
383
- case "toast":
384
- showToast(msg.message, msg.level, msg.detail);
385
- break;
386
-
387
- case "skill_installed":
388
- handleSkillInstalled(msg);
389
- if (msg.success) { var _kis = Object.assign({}, store.get('knownInstalledSkills')); _kis[msg.skill] = true; store.set({ knownInstalledSkills: _kis }); }
390
- handleSkillInstallWs(msg);
391
- break;
392
-
393
- case "skill_uninstalled":
394
- handleSkillUninstalled(msg);
395
- if (msg.success) { var _kis2 = Object.assign({}, store.get('knownInstalledSkills')); delete _kis2[msg.skill]; store.set({ knownInstalledSkills: _kis2 }); }
396
- break;
397
-
398
- case "loop_registry_updated":
399
- handleLoopRegistryUpdated(msg);
400
- break;
401
-
402
- case "schedule_run_started":
403
- handleScheduleRunStarted(msg);
404
- break;
405
-
406
- case "schedule_run_finished":
407
- handleScheduleRunFinished(msg);
408
- break;
409
-
410
- case "loop_scheduled":
411
- handleLoopScheduled(msg);
412
- break;
413
-
414
- case "schedule_move_result":
415
- if (msg.ok) {
416
- showToast("Task moved", "success");
417
- } else {
418
- showToast(msg.error || "Failed to move task", "error");
327
+ }
328
+ },
329
+
330
+ toast: function (msg) {
331
+ showToast(msg.message, msg.level, msg.detail);
332
+ },
333
+
334
+ skill_installed: function (msg) {
335
+ handleSkillInstalled(msg);
336
+ if (msg.success) { var _kis = Object.assign({}, store.get('knownInstalledSkills')); _kis[msg.skill] = true; store.set({ knownInstalledSkills: _kis }); }
337
+ handleSkillInstallWs(msg);
338
+ },
339
+
340
+ skill_uninstalled: function (msg) {
341
+ handleSkillUninstalled(msg);
342
+ if (msg.success) { var _kis2 = Object.assign({}, store.get('knownInstalledSkills')); delete _kis2[msg.skill]; store.set({ knownInstalledSkills: _kis2 }); }
343
+ },
344
+
345
+ loop_registry_updated: handleLoopRegistryUpdated,
346
+ schedule_run_started: handleScheduleRunStarted,
347
+ schedule_run_finished: handleScheduleRunFinished,
348
+ loop_scheduled: handleLoopScheduled,
349
+
350
+ schedule_move_result: function (msg) {
351
+ if (msg.ok) {
352
+ showToast("Task moved", "success");
353
+ } else {
354
+ showToast(msg.error || "Failed to move task", "error");
355
+ }
356
+ },
357
+
358
+ remove_project_check_result: handleRemoveProjectCheckResult,
359
+ hub_schedules: handleHubSchedules,
360
+ hub_recent_sessions: handleHubRecentSessions,
361
+
362
+ input_sync: function (msg) {
363
+ if (!store.get('dmMode')) handleInputSync(msg.text);
364
+ },
365
+
366
+ session_deleted: function (msg) {
367
+ // lr-0827ba (PEACHES follow-up): a session was actually deleted (not
368
+ // merely switched away from) — prune its per-session rate-limit /
369
+ // scheduled-message arming state, canceling any background reset
370
+ // timer, instead of leaking it forever. session_list alone never
371
+ // told the client WHICH id(s) disappeared, so nothing could target
372
+ // this cleanup before this message existed.
373
+ (msg.ids || []).forEach(function (deletedId) {
374
+ forgetSessionRateLimitState(deletedId);
375
+ });
376
+ },
377
+
378
+ session_list: function (msg) {
379
+ renderSessionList(msg.sessions || []);
380
+ handlePaletteSessionSwitch();
381
+ // Drain pending hub cross-project session switch (set by handleHubRecentSessions
382
+ // when switching to a session in a different project). Fires here because
383
+ // session_list is the first reliable post-connect message that guarantees
384
+ // the WS is open and the session roster is populated.
385
+ try {
386
+ var _pendingHubSess = sessionStorage.getItem("pending-hub-session");
387
+ if (_pendingHubSess) {
388
+ sessionStorage.removeItem("pending-hub-session");
389
+ var _phWs = getWs();
390
+ if (_phWs && _phWs.readyState === 1) {
391
+ _phWs.send(JSON.stringify({ type: "switch_session", id: parseInt(_pendingHubSess, 10) }));
419
392
  }
420
- break;
421
-
422
- case "remove_project_check_result":
423
- handleRemoveProjectCheckResult(msg);
424
- break;
425
-
426
- case "hub_schedules":
427
- handleHubSchedules(msg);
428
- break;
429
-
430
- case "hub_recent_sessions":
431
- handleHubRecentSessions(msg);
432
- break;
433
-
434
- case "input_sync":
435
- if (!store.get('dmMode')) handleInputSync(msg.text);
436
- break;
437
-
438
- case "session_deleted":
439
- // lr-0827ba (PEACHES follow-up): a session was actually deleted (not
440
- // merely switched away from) — prune its per-session rate-limit /
441
- // scheduled-message arming state, canceling any background reset
442
- // timer, instead of leaking it forever. session_list alone never
443
- // told the client WHICH id(s) disappeared, so nothing could target
444
- // this cleanup before this message existed.
445
- (msg.ids || []).forEach(function (deletedId) {
446
- forgetSessionRateLimitState(deletedId);
447
- });
448
- break;
449
-
450
- case "session_list":
451
- renderSessionList(msg.sessions || []);
452
- handlePaletteSessionSwitch();
453
- // Drain pending hub cross-project session switch (set by handleHubRecentSessions
454
- // when switching to a session in a different project). Fires here because
455
- // session_list is the first reliable post-connect message that guarantees
456
- // the WS is open and the session roster is populated.
457
- try {
458
- var _pendingHubSess = sessionStorage.getItem("pending-hub-session");
459
- if (_pendingHubSess) {
460
- sessionStorage.removeItem("pending-hub-session");
461
- var _phWs = getWs();
462
- if (_phWs && _phWs.readyState === 1) {
463
- _phWs.send(JSON.stringify({ type: "switch_session", id: parseInt(_pendingHubSess, 10) }));
464
- }
465
- }
466
- } catch (e) {}
467
- break;
468
-
469
- case "agents_list":
470
- handleAgentsList(msg);
471
- break;
472
-
473
- case "agent_favorite_toggled":
474
- handleAgentFavoriteToggled(msg);
475
- break;
476
-
477
- case "project_agents_list":
478
- handleProjectAgentsList(msg);
479
- break;
480
-
481
- case "session_presence":
482
- updateSessionPresence(msg.presence || {});
483
- break;
484
-
485
- case "cursor_move":
486
- handleRemoteCursorMove(msg);
487
- break;
393
+ }
394
+ } catch (e) {}
395
+ },
488
396
 
489
- case "cursor_leave":
490
- handleRemoteCursorLeave(msg);
491
- break;
397
+ agents_list: handleAgentsList,
398
+ agent_favorite_toggled: handleAgentFavoriteToggled,
399
+ project_agents_list: handleProjectAgentsList,
492
400
 
493
- case "text_select":
494
- handleRemoteSelection(msg);
495
- break;
401
+ session_presence: function (msg) {
402
+ updateSessionPresence(msg.presence || {});
403
+ },
496
404
 
497
- case "session_io":
498
- blinkSessionDot(msg.id);
499
- break;
405
+ cursor_move: handleRemoteCursorMove,
406
+ cursor_leave: handleRemoteCursorLeave,
407
+ text_select: handleRemoteSelection,
500
408
 
501
- case "session_unread":
502
- updateSessionBadge(msg.id, msg.count);
503
- break;
409
+ session_io: function (msg) {
410
+ blinkSessionDot(msg.id);
411
+ },
504
412
 
505
- case "search_results":
506
- handleSearchResults(msg);
507
- break;
413
+ session_unread: function (msg) {
414
+ updateSessionBadge(msg.id, msg.count);
415
+ },
508
416
 
509
- case "search_content_results":
510
- if (msg.source === "find_in_session") {
511
- handleFindInSessionResults(msg);
512
- }
513
- break;
514
-
515
- case "cli_session_list":
516
- populateCliSessionList(msg.sessions || []);
517
- break;
518
-
519
- case "session_switched":
520
- // Prefetch project agents so the @ menu is ready without a round-trip
521
- // the first time the user types @. Best-effort; at-agents.js handles
522
- // an empty list gracefully.
523
- requestProjectAgents();
524
- hideHomeHub();
525
- // Clear any stale replay indicator from a prior interrupted switch
526
- if (replayLoadingEl) replayLoadingEl.classList.add("hidden");
527
- // Save draft from outgoing session
528
- var _prevSid = store.get('activeSessionId');
529
- if (_prevSid && inputEl.value) {
530
- store.get('sessionDrafts')[_prevSid] = inputEl.value;
531
- } else if (_prevSid) {
532
- delete store.get('sessionDrafts')[_prevSid];
533
- }
534
- store.set({ activeSessionId: msg.id, cliSessionId: msg.cliSessionId || null, vendorCapabilities: msg.capabilities || {}, sessionIsProcessing: !!msg.isProcessing });
535
- if (msg.vendor) {
536
- if (!store.get('vendorSelectionLocked') || msg.hasHistory) {
537
- store.set({ currentVendor: msg.vendor });
538
- }
539
- // Sessions with history have their vendor structurally bound to
540
- // the session: lock so a late-arriving default-adapter model_info
541
- // can't flip the UI back. Previously this branch unlocked, which
542
- // is what allowed the feedback loop in issue #336.
543
- if (msg.hasHistory) {
544
- store.set({ vendorSelectionLocked: true });
545
- }
546
- } else if (msg.hasHistory) {
547
- // Existing session without explicit vendor: reset to claude
548
- store.set({ currentVendor: "claude" });
549
- store.set({ vendorSelectionLocked: false });
550
- } else if (!msg.hasHistory) {
551
- // New session without vendor: no mate vendor lookup needed
552
- }
553
- if (!msg.hasHistory && !msg.vendor) {
554
- // Preserve explicit pre-message vendor choice on brand-new sessions.
555
- }
556
- // Show vendor toggle only for new sessions (no history).
557
- // Agent sessions are Claude Code-only — hide the toggle entirely so
558
- // the user cannot switch an agent session to Codex (which has no
559
- // equivalent agent identity API and would silently drop the persona).
560
- var _vtw = document.getElementById("vendor-toggle-wrap");
561
- if (_vtw) {
562
- if (msg.agentName) {
563
- _vtw.classList.add("hidden");
564
- } else if (msg.hasHistory) {
565
- _vtw.classList.remove("hidden"); _vtw.classList.add("locked");
566
- } else {
567
- _vtw.classList.remove("locked"); _vtw.classList.remove("hidden");
568
- }
569
- }
570
- // Session presence is now tracked server-side (user-presence.json)
571
- clearRemoteCursors();
572
- resetClientState();
573
- // lr-0827ba: redraw the incoming session's own armed rate-limit /
574
- // scheduled-message state (arming happens per-session in the
575
- // background regardless of focus — see rate-limit-state.js) instead
576
- // of relying on chat-history replay to happen to repaint it.
577
- restoreRateLimitStateForSession(store.get('activeSessionId'));
578
-
579
- updateLoopInputVisibility(msg.loop);
580
- // Restore input area visibility (may have been hidden by auth_required)
581
- var inputAreaSw = document.getElementById("input-area");
582
- if (inputAreaSw) inputAreaSw.classList.remove("hidden");
583
- // Restore draft for incoming session
584
- var draft = store.get('sessionDrafts')[store.get('activeSessionId')] || "";
585
- inputEl.value = draft;
586
- // Reset the autoResize line-count cache before the rAF so the skip-
587
- // guard never freezes the textarea at the outgoing session's height.
588
- resetAutoResize();
589
- // Defer autoResize to next frame — avoids a forced synchronous layout
590
- // read (scrollHeight) immediately after the DOM write (value =).
591
- requestAnimationFrame(function () { autoResize(); });
592
- if (!("ontouchstart" in window)) {
593
- inputEl.focus();
594
- }
595
- break;
417
+ search_results: handleSearchResults,
596
418
 
597
- case "session_id":
598
- store.set({ cliSessionId: msg.cliSessionId });
599
- break;
419
+ search_content_results: function (msg) {
420
+ if (msg.source === "find_in_session") {
421
+ handleFindInSessionResults(msg);
422
+ }
423
+ },
424
+
425
+ cli_session_list: function (msg) {
426
+ populateCliSessionList(msg.sessions || []);
427
+ },
428
+
429
+ session_switched: function (msg) {
430
+ // Prefetch project agents so the @ menu is ready without a round-trip
431
+ // the first time the user types @. Best-effort; at-agents.js handles
432
+ // an empty list gracefully.
433
+ requestProjectAgents();
434
+ hideHomeHub();
435
+ // Clear any stale replay indicator from a prior interrupted switch
436
+ var replayLoadingEl = document.getElementById("replay-loading");
437
+ if (replayLoadingEl) replayLoadingEl.classList.add("hidden");
438
+ // Save draft from outgoing session
439
+ var _prevSid = store.get('activeSessionId');
440
+ if (_prevSid && inputEl.value) {
441
+ store.get('sessionDrafts')[_prevSid] = inputEl.value;
442
+ } else if (_prevSid) {
443
+ delete store.get('sessionDrafts')[_prevSid];
444
+ }
445
+ store.set({ activeSessionId: msg.id, cliSessionId: msg.cliSessionId || null, vendorCapabilities: msg.capabilities || {}, sessionIsProcessing: !!msg.isProcessing });
446
+ if (msg.vendor) {
447
+ if (!store.get('vendorSelectionLocked') || msg.hasHistory) {
448
+ store.set({ currentVendor: msg.vendor });
449
+ }
450
+ // Sessions with history have their vendor structurally bound to
451
+ // the session: lock so a late-arriving default-adapter model_info
452
+ // can't flip the UI back. Previously this branch unlocked, which
453
+ // is what allowed the feedback loop in issue #336.
454
+ if (msg.hasHistory) {
455
+ store.set({ vendorSelectionLocked: true });
456
+ }
457
+ } else if (msg.hasHistory) {
458
+ // Existing session without explicit vendor: reset to claude
459
+ store.set({ currentVendor: "claude" });
460
+ store.set({ vendorSelectionLocked: false });
461
+ } else if (!msg.hasHistory) {
462
+ // New session without vendor: no mate vendor lookup needed
463
+ }
464
+ if (!msg.hasHistory && !msg.vendor) {
465
+ // Preserve explicit pre-message vendor choice on brand-new sessions.
466
+ }
467
+ // Show vendor toggle only for new sessions (no history).
468
+ // Agent sessions are Claude Code-only — hide the toggle entirely so
469
+ // the user cannot switch an agent session to Codex (which has no
470
+ // equivalent agent identity API and would silently drop the persona).
471
+ var _vtw = document.getElementById("vendor-toggle-wrap");
472
+ if (_vtw) {
473
+ if (msg.agentName) {
474
+ _vtw.classList.add("hidden");
475
+ } else if (msg.hasHistory) {
476
+ _vtw.classList.remove("hidden"); _vtw.classList.add("locked");
477
+ } else {
478
+ _vtw.classList.remove("locked"); _vtw.classList.remove("hidden");
479
+ }
480
+ }
481
+ // Session presence is now tracked server-side (user-presence.json)
482
+ clearRemoteCursors();
483
+ resetClientState();
484
+ // lr-0827ba: redraw the incoming session's own armed rate-limit /
485
+ // scheduled-message state (arming happens per-session in the
486
+ // background regardless of focus — see rate-limit-state.js) instead
487
+ // of relying on chat-history replay to happen to repaint it.
488
+ restoreRateLimitStateForSession(store.get('activeSessionId'));
489
+
490
+ updateLoopInputVisibility(msg.loop);
491
+ // Restore input area visibility (may have been hidden by auth_required)
492
+ var inputAreaSw = document.getElementById("input-area");
493
+ if (inputAreaSw) inputAreaSw.classList.remove("hidden");
494
+ // Restore draft for incoming session
495
+ var draft = store.get('sessionDrafts')[store.get('activeSessionId')] || "";
496
+ inputEl.value = draft;
497
+ // Reset the autoResize line-count cache before the rAF so the skip-
498
+ // guard never freezes the textarea at the outgoing session's height.
499
+ resetAutoResize();
500
+ // Defer autoResize to next frame — avoids a forced synchronous layout
501
+ // read (scrollHeight) immediately after the DOM write (value =).
502
+ requestAnimationFrame(function () { autoResize(); });
503
+ if (!("ontouchstart" in window)) {
504
+ inputEl.focus();
505
+ }
506
+ },
507
+
508
+ session_id: function (msg) {
509
+ store.set({ cliSessionId: msg.cliSessionId });
510
+ },
511
+
512
+ message_uuid: function (msg) {
513
+ var uuidTarget;
514
+ if (msg.messageType === "user") {
515
+ var allUsers = messagesEl.querySelectorAll(".msg-user:not([data-uuid])");
516
+ if (allUsers.length > 0) uuidTarget = allUsers[allUsers.length - 1];
517
+ } else {
518
+ var allAssistants = messagesEl.querySelectorAll(".msg-assistant:not([data-uuid])");
519
+ if (allAssistants.length > 0) uuidTarget = allAssistants[allAssistants.length - 1];
520
+ }
521
+ if (uuidTarget) {
522
+ uuidTarget.dataset.uuid = msg.uuid;
523
+ if (msg.messageType === "user" && (store.get('vendorCapabilities') || {}).rewind !== false) addRewindButton(uuidTarget);
524
+ }
525
+ store.get('messageUuidMap').push({ uuid: msg.uuid, type: msg.messageType });
526
+ },
527
+
528
+ user_message: function (msg) {
529
+ if (msg._internal) return;
530
+ resetThinkingGroup();
531
+ if (msg.planContent) {
532
+ setPlanContent(msg.planContent);
533
+ renderPlanCard(msg.planContent);
534
+ addUserMessage("Execute the following plan. Do NOT re-enter plan mode — just implement it step by step.", msg.images || null, msg.pastes || null, msg.from, msg.fromName);
535
+ } else {
536
+ addUserMessage(msg.text, msg.images || null, msg.pastes || null, msg.from, msg.fromName);
537
+ }
538
+ },
539
+
540
+ plan_content: function (msg) {
541
+ setPlanContent(msg.content || "");
542
+ renderPlanCard(msg.content || "");
543
+ },
544
+
545
+ context_preview: function (msg) {
546
+ // Show a Context Card with tab screenshot between user message and assistant response
547
+ if (msg.tab) {
548
+ var card = document.createElement("div");
549
+ card.className = "context-card";
550
+
551
+ // Header
552
+ var header = document.createElement("div");
553
+ header.className = "context-card-header";
554
+ var icon = document.createElement("span");
555
+ icon.className = "context-card-icon";
556
+ icon.innerHTML = iconHtml("globe");
557
+ header.appendChild(icon);
558
+ var label = document.createElement("span");
559
+ label.textContent = "Viewing tab";
560
+ header.appendChild(label);
561
+ card.appendChild(header);
562
+
563
+ // Screenshot
564
+ if (msg.tab.screenshotUrl) {
565
+ var img = document.createElement("img");
566
+ img.className = "context-card-screenshot";
567
+ img.src = msg.tab.screenshotUrl;
568
+ img.loading = "lazy";
569
+ img.addEventListener("click", function () { showImageModal(this.src); });
570
+ card.appendChild(img);
571
+ }
600
572
 
601
- case "message_uuid":
602
- var uuidTarget;
603
- if (msg.messageType === "user") {
604
- var allUsers = messagesEl.querySelectorAll(".msg-user:not([data-uuid])");
605
- if (allUsers.length > 0) uuidTarget = allUsers[allUsers.length - 1];
606
- } else {
607
- var allAssistants = messagesEl.querySelectorAll(".msg-assistant:not([data-uuid])");
608
- if (allAssistants.length > 0) uuidTarget = allAssistants[allAssistants.length - 1];
573
+ // Meta: title + domain
574
+ var tabTitle = msg.tab.title || "";
575
+ var tabDomain = "";
576
+ try { tabDomain = new URL(msg.tab.url).hostname; } catch (e) {}
577
+ if (tabTitle || tabDomain) {
578
+ var meta = document.createElement("div");
579
+ meta.className = "context-card-meta";
580
+ if (msg.tab.favIconUrl) {
581
+ var fav = document.createElement("img");
582
+ fav.className = "context-card-favicon";
583
+ fav.src = msg.tab.favIconUrl;
584
+ fav.width = 14;
585
+ fav.height = 14;
586
+ fav.onerror = function () { this.style.display = "none"; };
587
+ meta.appendChild(fav);
609
588
  }
610
- if (uuidTarget) {
611
- uuidTarget.dataset.uuid = msg.uuid;
612
- if (msg.messageType === "user" && (store.get('vendorCapabilities') || {}).rewind !== false) addRewindButton(uuidTarget);
613
- }
614
- store.get('messageUuidMap').push({ uuid: msg.uuid, type: msg.messageType });
615
- break;
616
-
617
- case "user_message":
618
- if (msg._internal) break;
619
- resetThinkingGroup();
620
- if (msg.planContent) {
621
- setPlanContent(msg.planContent);
622
- renderPlanCard(msg.planContent);
623
- addUserMessage("Execute the following plan. Do NOT re-enter plan mode — just implement it step by step.", msg.images || null, msg.pastes || null, msg.from, msg.fromName);
624
- } else {
625
- addUserMessage(msg.text, msg.images || null, msg.pastes || null, msg.from, msg.fromName);
589
+ var titleEl = document.createElement("span");
590
+ titleEl.className = "context-card-title";
591
+ titleEl.textContent = tabTitle;
592
+ meta.appendChild(titleEl);
593
+ if (tabDomain) {
594
+ var domainEl = document.createElement("span");
595
+ domainEl.className = "context-card-domain";
596
+ domainEl.textContent = tabDomain;
597
+ meta.appendChild(domainEl);
626
598
  }
627
- break;
628
-
629
- case "plan_content":
630
- setPlanContent(msg.content || "");
631
- renderPlanCard(msg.content || "");
632
- break;
633
-
634
- case "context_preview":
635
- // Show a Context Card with tab screenshot between user message and assistant response
636
- if (msg.tab) {
637
- var card = document.createElement("div");
638
- card.className = "context-card";
639
-
640
- // Header
641
- var header = document.createElement("div");
642
- header.className = "context-card-header";
643
- var icon = document.createElement("span");
644
- icon.className = "context-card-icon";
645
- icon.innerHTML = iconHtml("globe");
646
- header.appendChild(icon);
647
- var label = document.createElement("span");
648
- label.textContent = "Viewing tab";
649
- header.appendChild(label);
650
- card.appendChild(header);
651
-
652
- // Screenshot
653
- if (msg.tab.screenshotUrl) {
654
- var img = document.createElement("img");
655
- img.className = "context-card-screenshot";
656
- img.src = msg.tab.screenshotUrl;
657
- img.loading = "lazy";
658
- img.addEventListener("click", function () { showImageModal(this.src); });
659
- card.appendChild(img);
660
- }
661
-
662
- // Meta: title + domain
663
- var tabTitle = msg.tab.title || "";
664
- var tabDomain = "";
665
- try { tabDomain = new URL(msg.tab.url).hostname; } catch (e) {}
666
- if (tabTitle || tabDomain) {
667
- var meta = document.createElement("div");
668
- meta.className = "context-card-meta";
669
- if (msg.tab.favIconUrl) {
670
- var fav = document.createElement("img");
671
- fav.className = "context-card-favicon";
672
- fav.src = msg.tab.favIconUrl;
673
- fav.width = 14;
674
- fav.height = 14;
675
- fav.onerror = function () { this.style.display = "none"; };
676
- meta.appendChild(fav);
677
- }
678
- var titleEl = document.createElement("span");
679
- titleEl.className = "context-card-title";
680
- titleEl.textContent = tabTitle;
681
- meta.appendChild(titleEl);
682
- if (tabDomain) {
683
- var domainEl = document.createElement("span");
684
- domainEl.className = "context-card-domain";
685
- domainEl.textContent = tabDomain;
686
- meta.appendChild(domainEl);
687
- }
688
- card.appendChild(meta);
689
- }
599
+ card.appendChild(meta);
600
+ }
690
601
 
691
- messagesEl.appendChild(card);
692
- scrollToBottom();
693
- }
694
- break;
695
-
696
- case "status":
697
- if (msg.status === "processing") {
698
- setStatus("processing");
699
- // Session became live — undo any dead-session todo compaction
700
- // applied at history_done time.
701
- store.set({ sessionIsProcessing: true });
702
- applyDeadSessionTodoCompaction();
703
- if (!store.get('dmMode')) {
704
- removePreThinking(); // drop pre-thinking dots before showing activity indicator
705
- setActivity("thinking");
706
- }
707
- }
708
- break;
602
+ messagesEl.appendChild(card);
603
+ scrollToBottom();
604
+ }
605
+ },
606
+
607
+ status: function (msg) {
608
+ if (msg.status === "processing") {
609
+ setStatus("processing");
610
+ // Session became live — undo any dead-session todo compaction
611
+ // applied at history_done time.
612
+ store.set({ sessionIsProcessing: true });
613
+ applyDeadSessionTodoCompaction();
614
+ if (!store.get('dmMode')) {
615
+ removePreThinking(); // drop pre-thinking dots before showing activity indicator
616
+ setActivity("thinking");
617
+ }
618
+ }
619
+ },
709
620
 
710
- case "compacting":
711
- if (msg.active) {
712
- setActivity("compacting");
713
- } else if (!store.get('dmMode')) {
714
- setActivity("thinking");
715
- }
716
- break;
621
+ compacting: function (msg) {
622
+ if (msg.active) {
623
+ setActivity("compacting");
624
+ } else if (!store.get('dmMode')) {
625
+ setActivity("thinking");
626
+ }
627
+ },
717
628
 
718
- case "thinking_start":
719
- removePreThinking();
720
- startThinking();
721
- break;
629
+ thinking_start: function (msg) {
630
+ removePreThinking();
631
+ startThinking();
632
+ },
722
633
 
723
- case "thinking_delta":
724
- if (typeof msg.text === "string") appendThinking(msg.text);
725
- break;
634
+ thinking_delta: function (msg) {
635
+ if (typeof msg.text === "string") appendThinking(msg.text);
636
+ },
726
637
 
727
- case "thinking_stop":
728
- stopThinking(msg.duration);
729
- if (!store.get('dmMode')) {
730
- setActivity("thinking");
731
- }
732
- break;
733
-
734
- case "delta":
735
- if (typeof msg.text !== "string") break;
736
- removePreThinking();
737
- stopThinking();
738
- resetThinkingGroup();
739
- setActivity(null);
740
- appendDelta(msg.text);
741
- break;
742
-
743
- case "tool_start":
744
- removePreThinking();
745
- stopThinking();
746
- markAllToolsDone();
747
- if (msg.name === "EnterPlanMode") {
748
- renderPlanBanner("enter");
749
- getTools()[msg.id] = { el: null, name: msg.name, input: null, done: true, hidden: true };
750
- } else if (msg.name === "ExitPlanMode") {
751
- if (getPlanContent()) {
752
- renderPlanCard(getPlanContent());
753
- }
754
- renderPlanBanner("exit");
755
- getTools()[msg.id] = { el: null, name: msg.name, input: null, done: true, hidden: true };
756
- } else if (msg.name === "ask_user_questions") {
757
- getTools()[msg.id] = { el: null, name: msg.name, input: null, done: true, hidden: true };
758
- } else if (getTodoTools()[msg.name]) {
759
- getTools()[msg.id] = { el: null, name: msg.name, input: null, done: true, hidden: true };
760
- } else {
761
- createToolItem(msg.id, msg.name);
762
- }
763
- break;
764
-
765
- case "tool_executing":
766
- if (msg.name === "AskUserQuestion" && msg.input && msg.input.questions) {
767
- var askTool = getTools()[msg.id];
768
- if (askTool) {
769
- if (askTool.el) askTool.el.style.display = "none";
770
- askTool.done = true;
771
- removeToolFromGroup(msg.id);
772
- }
773
- renderAskUserQuestion(msg.id, msg.input);
774
- startUrgentBlink();
775
- } else if (msg.name === "Write" && msg.input && isPlanFilePath(msg.input.file_path)) {
776
- setPlanContent(msg.input.content || "");
777
- updateToolExecuting(msg.id, msg.name, msg.input);
778
- } else if (msg.name === "Edit" && msg.input && isPlanFilePath(msg.input.file_path)) {
779
- var pc = getPlanContent() || "";
780
- if (msg.input.old_string && pc.indexOf(msg.input.old_string) !== -1) {
781
- if (msg.input.replace_all) {
782
- setPlanContent(pc.split(msg.input.old_string).join(msg.input.new_string || ""));
783
- } else {
784
- setPlanContent(pc.replace(msg.input.old_string, msg.input.new_string || ""));
785
- }
786
- }
787
- updateToolExecuting(msg.id, msg.name, msg.input);
788
- } else if (msg.name === "TodoWrite") {
789
- handleTodoWrite(msg.input);
790
- } else if (msg.name === "TaskCreate") {
791
- handleTaskCreate(msg.input);
792
- } else if (msg.name === "TaskUpdate") {
793
- handleTaskUpdate(msg.input);
794
- } else if (getTodoTools()[msg.name]) {
795
- // TaskList, TaskGet - silently skip
796
- } else {
797
- var t = getTools()[msg.id];
798
- if (t && t.hidden) break;
799
- updateToolExecuting(msg.id, msg.name, msg.input);
800
- }
801
- break;
802
-
803
- case "tool_result": {
804
- var tr = getTools()[msg.id];
805
- if (tr && tr.hidden) break; // skip hidden plan tools
806
- // Always call updateToolResult for Edit (to show diff from input), or when content exists
807
- if (msg.content != null || msg.images || (tr && tr.name === "Edit" && tr.input && tr.input.old_string)) {
808
- updateToolResult(msg.id, msg.content || "", msg.is_error || false, msg.images);
809
- }
810
- // Refresh file browser if an Edit/Write tool modified the open file
811
- if (!msg.is_error && tr && (tr.name === "Edit" || tr.name === "Write") && tr.input && tr.input.file_path) {
812
- refreshIfOpen(tr.input.file_path);
813
- }
814
- }
815
- break;
816
-
817
- case "ask_user_answered":
818
- markAskUserAnswered(msg.toolId, msg.answers);
819
- stopUrgentBlink();
820
- break;
821
-
822
- case "permission_request":
823
- renderPermissionRequest(msg.requestId, msg.toolName, msg.toolInput, msg.decisionReason);
824
- startUrgentBlink();
825
- break;
826
-
827
- case "permission_cancel":
828
- markPermissionCancelled(msg.requestId);
829
- stopUrgentBlink();
830
- break;
831
-
832
- case "permission_resolved":
833
- markPermissionResolved(msg.requestId, msg.decision);
834
- stopUrgentBlink();
835
- break;
836
-
837
- case "permission_request_pending":
838
- renderPermissionRequest(msg.requestId, msg.toolName, msg.toolInput, msg.decisionReason);
839
- startUrgentBlink();
840
- break;
841
-
842
- case "elicitation_request":
843
- renderElicitationRequest(msg);
844
- startUrgentBlink();
845
- break;
846
-
847
- case "elicitation_resolved":
848
- markElicitationResolved(msg.requestId, msg.action);
849
- stopUrgentBlink();
850
- break;
851
-
852
- case "slash_command_result":
853
- finalizeAssistantBlock();
854
- var cmdBlock = document.createElement("div");
855
- cmdBlock.className = "assistant-block";
856
- cmdBlock.style.maxWidth = "var(--content-width)";
857
- cmdBlock.style.margin = "12px auto";
858
- cmdBlock.style.padding = "0 20px";
859
- var pre = document.createElement("pre");
860
- pre.style.cssText = "background:var(--code-bg);border:1px solid var(--border-subtle);border-radius:10px;padding:12px 14px;font-family:'SF Mono',Menlo,Monaco,monospace;font-size:12px;line-height:1.55;color:var(--text-secondary);white-space:pre-wrap;word-break:break-word;max-height:400px;overflow-y:auto;margin:0";
861
- pre.textContent = msg.text;
862
- cmdBlock.appendChild(pre);
863
- addToMessages(cmdBlock);
864
- scrollToBottom();
865
- break;
866
-
867
- case "subagent_activity":
868
- updateSubagentActivity(msg.parentToolId, msg.text);
869
- break;
870
-
871
- case "subagent_tool":
872
- addSubagentToolEntry(msg.parentToolId, msg.toolName, msg.toolId, msg.text);
873
- break;
874
-
875
- case "subagent_done":
876
- markSubagentDone(msg.parentToolId, msg.status, msg.summary, msg.usage);
877
- break;
878
-
879
- case "task_started":
880
- initSubagentStop(msg.parentToolId, msg.taskId);
881
- break;
882
-
883
- case "task_progress":
884
- updateSubagentProgress(msg.parentToolId, msg.usage, msg.lastToolName, msg.summary);
885
- break;
886
-
887
- case "task_updated":
888
- updateSubagentTaskStatus(msg.parentToolId, msg.patch);
889
- break;
890
-
891
- case "result":
892
- setActivity(null);
893
- stopThinking();
894
- markAllToolsDone();
895
- closeToolGroup();
896
- finalizeAssistantBlock();
897
- addTurnMeta(msg.cost, msg.duration);
898
- accumulateUsage(msg.cost, msg.usage, msg.lastStreamInputTokens);
899
- accumulateContext(msg.cost, msg.usage, msg.modelUsage, msg.lastStreamInputTokens);
900
- break;
901
-
902
- case "context_usage":
903
- if (msg.data && !store.get('replayingHistory')) {
904
- store.set({ richContextUsage: msg.data });
905
- // UI sync handled by store subscriber in app-panels.js
906
- }
907
- break;
908
-
909
- case "done":
910
- removePreThinking();
911
- setActivity(null);
912
- stopThinking();
913
- markAllToolsDone();
914
- closeToolGroup();
915
- finalizeAssistantBlock();
916
- setStatus("connected");
917
- // Re-enable input unless this is one of the loop's own sessions (coder/judge).
918
- // A loop running in a separate session must not suppress input here.
919
- var _doneLoopSid = store.get('loopCurrentSessionId');
920
- if (!store.get('loopActive') || !_doneLoopSid || store.get('activeSessionId') !== _doneLoopSid) {
921
- enableMainInput();
922
- }
923
- resetToolState();
924
- stopUrgentBlink();
925
- if (document.hidden) {
926
- if (isNotifAlertEnabled() && !window._pushSubscription) showDoneNotification();
927
- if (isNotifSoundEnabled()) playDoneSound();
928
- }
929
- break;
930
-
931
- case "stderr":
932
- addSystemMessage(msg.text, false);
933
- break;
934
-
935
- case "error":
936
- removePreThinking();
937
- setActivity(null);
938
- addSystemMessage(msg.text, true);
939
- break;
940
-
941
- case "system_info":
942
- addSystemMessage(msg.text, false);
943
- break;
944
-
945
- case "sdk_notification":
946
- addSystemMessage(msg.text, false);
947
- break;
948
-
949
- case "process_conflict":
950
- removePreThinking();
951
- setActivity(null);
952
- addConflictMessage(msg);
953
- break;
954
-
955
- case "context_overflow":
956
- removePreThinking();
957
- setActivity(null);
958
- addContextOverflowMessage(msg);
959
- break;
960
-
961
- case "auth_required":
962
- removePreThinking();
963
- setActivity(null);
964
- stopThinking();
965
- markAllToolsDone();
966
- closeToolGroup();
967
- appendDelta((msg.text || "Authentication required.") + "\n");
968
- setStatus("connected");
969
- var _authLoopSid = store.get('loopCurrentSessionId');
970
- if (!store.get('loopActive') || !_authLoopSid || store.get('activeSessionId') !== _authLoopSid) {
971
- enableMainInput();
972
- }
973
- break;
974
-
975
- case "rate_limit":
976
- handleRateLimitEvent(msg);
977
- break;
978
-
979
- case "rate_limit_usage":
980
- updateRateLimitUsage(msg);
981
- break;
982
-
983
- case "scheduled_message_queued":
984
- // lr-0827ba: msg.localId identifies the session this schedule
985
- // actually belongs to — may not be the currently focused session.
986
- addScheduledMessageBubble(msg.text, msg.resetsAt, msg.localId);
987
- if (msg.localId == null || msg.localId === store.get('activeSessionId')) setScheduleBtnDisabled(true);
988
- break;
989
-
990
- case "scheduled_message_sent":
991
- clearScheduledMessage(msg.localId);
992
- if (msg.localId == null || msg.localId === store.get('activeSessionId')) {
993
- setScheduleBtnDisabled(false);
994
- setStatus("processing");
995
- }
996
- break;
997
-
998
- case "scheduled_message_cancelled":
999
- clearScheduledMessage(msg.localId);
1000
- if (msg.localId == null || msg.localId === store.get('activeSessionId')) setScheduleBtnDisabled(false);
1001
- break;
1002
-
1003
- case "auto_continue_scheduled":
1004
- // Scheduler auto-continue, just show info
1005
- break;
1006
-
1007
- case "auto_continue_fired":
1008
- setStatus("processing");
1009
- break;
1010
-
1011
- case "prompt_suggestion":
1012
- showSuggestionChips(msg.suggestion);
1013
- break;
1014
-
1015
- case "fast_mode_state":
1016
- handleFastModeState(msg.state);
1017
- break;
1018
-
1019
- case "process_killed":
1020
- addSystemMessage("Process " + msg.pid + " has been terminated. You can retry your message now.", false);
1021
- break;
1022
-
1023
- case "rewind_preview_result":
1024
- showRewindModal(msg);
1025
- break;
1026
-
1027
- case "rewind_complete":
1028
- onRewindComplete();
1029
- setRewindMode(false);
1030
- var rewindText = "Rewound to earlier point. Files have been restored.";
1031
- if (msg.mode === "chat") rewindText = "Conversation rewound to earlier point.";
1032
- else if (msg.mode === "files") rewindText = "Files restored to earlier point.";
1033
- addSystemMessage(rewindText, false);
1034
- break;
1035
-
1036
- case "rewind_error":
1037
- onRewindError();
1038
- clearPendingRewindUuid();
1039
- addSystemMessage(msg.text || "Rewind failed.", true);
1040
- break;
1041
-
1042
- case "fork_complete":
1043
- addSystemMessage("Session forked successfully.");
1044
- break;
1045
-
1046
- case "fs_list_result":
1047
- handleFsList(msg);
1048
- break;
1049
-
1050
- case "fs_search_result":
1051
- handleFsSearch(msg);
1052
- break;
1053
-
1054
- case "fs_read_result":
1055
- if (msg.path === "CLAUDE.md" && isProjectSettingsOpen()) {
1056
- handleInstructionsRead(msg);
638
+ thinking_stop: function (msg) {
639
+ stopThinking(msg.duration);
640
+ if (!store.get('dmMode')) {
641
+ setActivity("thinking");
642
+ }
643
+ },
644
+
645
+ delta: function (msg) {
646
+ if (typeof msg.text !== "string") return;
647
+ removePreThinking();
648
+ stopThinking();
649
+ resetThinkingGroup();
650
+ setActivity(null);
651
+ appendDelta(msg.text);
652
+ },
653
+
654
+ tool_start: function (msg) {
655
+ removePreThinking();
656
+ stopThinking();
657
+ markAllToolsDone();
658
+ if (msg.name === "EnterPlanMode") {
659
+ renderPlanBanner("enter");
660
+ getTools()[msg.id] = { el: null, name: msg.name, input: null, done: true, hidden: true };
661
+ } else if (msg.name === "ExitPlanMode") {
662
+ if (getPlanContent()) {
663
+ renderPlanCard(getPlanContent());
664
+ }
665
+ renderPlanBanner("exit");
666
+ getTools()[msg.id] = { el: null, name: msg.name, input: null, done: true, hidden: true };
667
+ } else if (msg.name === "ask_user_questions") {
668
+ getTools()[msg.id] = { el: null, name: msg.name, input: null, done: true, hidden: true };
669
+ } else if (getTodoTools()[msg.name]) {
670
+ getTools()[msg.id] = { el: null, name: msg.name, input: null, done: true, hidden: true };
671
+ } else {
672
+ createToolItem(msg.id, msg.name);
673
+ }
674
+ },
675
+
676
+ tool_executing: function (msg) {
677
+ if (msg.name === "AskUserQuestion" && msg.input && msg.input.questions) {
678
+ var askTool = getTools()[msg.id];
679
+ if (askTool) {
680
+ if (askTool.el) askTool.el.style.display = "none";
681
+ askTool.done = true;
682
+ removeToolFromGroup(msg.id);
683
+ }
684
+ renderAskUserQuestion(msg.id, msg.input);
685
+ startUrgentBlink();
686
+ } else if (msg.name === "Write" && msg.input && isPlanFilePath(msg.input.file_path)) {
687
+ setPlanContent(msg.input.content || "");
688
+ updateToolExecuting(msg.id, msg.name, msg.input);
689
+ } else if (msg.name === "Edit" && msg.input && isPlanFilePath(msg.input.file_path)) {
690
+ var pc = getPlanContent() || "";
691
+ if (msg.input.old_string && pc.indexOf(msg.input.old_string) !== -1) {
692
+ if (msg.input.replace_all) {
693
+ setPlanContent(pc.split(msg.input.old_string).join(msg.input.new_string || ""));
1057
694
  } else {
1058
- handleFsRead(msg);
695
+ setPlanContent(pc.replace(msg.input.old_string, msg.input.new_string || ""));
1059
696
  }
1060
- break;
1061
-
1062
- case "fs_write_result":
1063
- handleInstructionsWrite(msg);
1064
- break;
1065
-
1066
- case "project_env_result":
1067
- handleProjectEnv(msg);
1068
- break;
1069
-
1070
- case "set_project_env_result":
1071
- handleProjectEnvSaved(msg);
1072
- break;
1073
-
1074
- case "global_claude_md_result":
1075
- handleGlobalClaudeMdRead(msg);
1076
- break;
1077
-
1078
- case "write_global_claude_md_result":
1079
- handleGlobalClaudeMdWrite(msg);
1080
- break;
1081
-
1082
- case "shared_env_result":
1083
- handleSharedEnv(msg);
1084
- handleProjectSharedEnv(msg);
1085
- break;
1086
-
1087
- case "set_shared_env_result":
1088
- handleSharedEnvSaved(msg);
1089
- handleProjectSharedEnvSaved(msg);
1090
- break;
1091
-
1092
- case "fs_file_changed":
1093
- handleFileChanged(msg);
1094
- break;
1095
-
1096
- case "fs_dir_changed":
1097
- handleDirChanged(msg);
1098
- break;
1099
-
1100
- case "fs_file_history_result":
1101
- handleFileHistory(msg);
1102
- break;
1103
-
1104
- case "fs_git_diff_result":
1105
- handleGitDiff(msg);
1106
- break;
1107
-
1108
- case "fs_file_at_result":
1109
- handleFileAt(msg);
1110
- break;
1111
-
1112
- case "term_list":
1113
- handleTermList(msg);
1114
- updateTerminalList(msg.terminals);
1115
- break;
1116
-
1117
- case "context_sources_state":
1118
- handleContextSourcesState(msg);
1119
- break;
1120
-
1121
- case "extension_command":
1122
- sendExtensionCommand(msg.command, msg.args, msg.requestId);
1123
- break;
1124
-
1125
- case "mcp_tool_call":
1126
- handleMcpToolCallMessage(msg);
1127
- break;
1128
-
1129
- case "mcp_servers_state":
1130
- handleMcpServersState(msg);
1131
- break;
1132
-
1133
- case "term_created":
1134
- handleTermCreated(msg);
1135
- if (store.get('pendingTermCommand')) {
1136
- var cmd = store.get('pendingTermCommand');
1137
- store.set({ pendingTermCommand: null });
1138
- // Small delay to let terminal initialize
1139
- setTimeout(function() {
1140
- sendTerminalCommand(cmd);
1141
- }, 300);
1142
- }
1143
- break;
1144
-
1145
- case "term_output":
1146
- handleTermOutput(msg);
1147
- break;
1148
-
1149
- case "term_resized":
1150
- handleTermResized(msg);
1151
- break;
1152
-
1153
- case "term_exited":
1154
- handleTermExited(msg);
1155
- break;
1156
-
1157
- case "term_closed":
1158
- handleTermClosed(msg);
1159
- break;
1160
-
1161
- case "notes_list":
1162
- handleNotesList(msg);
1163
- break;
1164
-
1165
- case "note_created":
1166
- handleNoteCreated(msg);
1167
- break;
1168
-
1169
- case "note_updated":
1170
- handleNoteUpdated(msg);
1171
- break;
1172
-
1173
- case "note_deleted":
1174
- handleNoteDeleted(msg);
1175
- break;
1176
-
1177
- case "process_stats":
1178
- updateStatusPanel(msg);
1179
- updateSettingsStats(msg);
1180
- break;
1181
-
1182
- case "browse_dir_result":
1183
- handleBrowseDirResult(msg);
1184
- break;
1185
-
1186
- case "add_project_result":
1187
- handleAddProjectResult(msg);
1188
- break;
1189
-
1190
- case "clone_project_progress":
1191
- handleCloneProgress(msg);
1192
- break;
1193
-
1194
- case "remove_project_result":
1195
- handleRemoveProjectResult(msg);
1196
- break;
1197
-
1198
- case "reorder_projects_result":
1199
- if (!msg.ok) {
1200
- showToast(msg.error || "Failed to reorder projects", "error");
1201
- }
1202
- break;
1203
-
1204
- case "set_project_title_result":
1205
- if (!msg.ok) {
1206
- showToast(msg.error || "Failed to rename project", "error");
1207
- }
1208
- break;
697
+ }
698
+ updateToolExecuting(msg.id, msg.name, msg.input);
699
+ } else if (msg.name === "TodoWrite") {
700
+ handleTodoWrite(msg.input);
701
+ } else if (msg.name === "TaskCreate") {
702
+ handleTaskCreate(msg.input);
703
+ } else if (msg.name === "TaskUpdate") {
704
+ handleTaskUpdate(msg.input);
705
+ } else if (getTodoTools()[msg.name]) {
706
+ // TaskList, TaskGet - silently skip
707
+ } else {
708
+ var t = getTools()[msg.id];
709
+ if (t && t.hidden) return;
710
+ updateToolExecuting(msg.id, msg.name, msg.input);
711
+ }
712
+ },
713
+
714
+ tool_result: function (msg) {
715
+ var tr = getTools()[msg.id];
716
+ if (tr && tr.hidden) return; // skip hidden plan tools
717
+ // Always call updateToolResult for Edit (to show diff from input), or when content exists
718
+ if (msg.content != null || msg.images || (tr && tr.name === "Edit" && tr.input && tr.input.old_string)) {
719
+ updateToolResult(msg.id, msg.content || "", msg.is_error || false, msg.images);
720
+ }
721
+ // Refresh file browser if an Edit/Write tool modified the open file
722
+ if (!msg.is_error && tr && (tr.name === "Edit" || tr.name === "Write") && tr.input && tr.input.file_path) {
723
+ refreshIfOpen(tr.input.file_path);
724
+ }
725
+ },
726
+
727
+ ask_user_answered: function (msg) {
728
+ markAskUserAnswered(msg.toolId, msg.answers);
729
+ stopUrgentBlink();
730
+ },
731
+
732
+ permission_request: function (msg) {
733
+ renderPermissionRequest(msg.requestId, msg.toolName, msg.toolInput, msg.decisionReason);
734
+ startUrgentBlink();
735
+ },
736
+
737
+ permission_cancel: function (msg) {
738
+ markPermissionCancelled(msg.requestId);
739
+ stopUrgentBlink();
740
+ },
741
+
742
+ permission_resolved: function (msg) {
743
+ markPermissionResolved(msg.requestId, msg.decision);
744
+ stopUrgentBlink();
745
+ },
746
+
747
+ permission_request_pending: function (msg) {
748
+ renderPermissionRequest(msg.requestId, msg.toolName, msg.toolInput, msg.decisionReason);
749
+ startUrgentBlink();
750
+ },
751
+
752
+ elicitation_request: function (msg) {
753
+ renderElicitationRequest(msg);
754
+ startUrgentBlink();
755
+ },
756
+
757
+ elicitation_resolved: function (msg) {
758
+ markElicitationResolved(msg.requestId, msg.action);
759
+ stopUrgentBlink();
760
+ },
761
+
762
+ slash_command_result: function (msg) {
763
+ finalizeAssistantBlock();
764
+ var cmdBlock = document.createElement("div");
765
+ cmdBlock.className = "assistant-block";
766
+ cmdBlock.style.maxWidth = "var(--content-width)";
767
+ cmdBlock.style.margin = "12px auto";
768
+ cmdBlock.style.padding = "0 20px";
769
+ var pre = document.createElement("pre");
770
+ pre.style.cssText = "background:var(--code-bg);border:1px solid var(--border-subtle);border-radius:10px;padding:12px 14px;font-family:'SF Mono',Menlo,Monaco,monospace;font-size:12px;line-height:1.55;color:var(--text-secondary);white-space:pre-wrap;word-break:break-word;max-height:400px;overflow-y:auto;margin:0";
771
+ pre.textContent = msg.text;
772
+ cmdBlock.appendChild(pre);
773
+ addToMessages(cmdBlock);
774
+ scrollToBottom();
775
+ },
776
+
777
+ subagent_activity: function (msg) {
778
+ updateSubagentActivity(msg.parentToolId, msg.text);
779
+ },
780
+
781
+ subagent_tool: function (msg) {
782
+ addSubagentToolEntry(msg.parentToolId, msg.toolName, msg.toolId, msg.text);
783
+ },
784
+
785
+ subagent_done: function (msg) {
786
+ markSubagentDone(msg.parentToolId, msg.status, msg.summary, msg.usage);
787
+ },
788
+
789
+ task_started: function (msg) {
790
+ initSubagentStop(msg.parentToolId, msg.taskId);
791
+ },
792
+
793
+ task_progress: function (msg) {
794
+ updateSubagentProgress(msg.parentToolId, msg.usage, msg.lastToolName, msg.summary);
795
+ },
796
+
797
+ task_updated: function (msg) {
798
+ updateSubagentTaskStatus(msg.parentToolId, msg.patch);
799
+ },
800
+
801
+ result: function (msg) {
802
+ setActivity(null);
803
+ stopThinking();
804
+ markAllToolsDone();
805
+ closeToolGroup();
806
+ finalizeAssistantBlock();
807
+ addTurnMeta(msg.cost, msg.duration);
808
+ accumulateUsage(msg.cost, msg.usage, msg.lastStreamInputTokens);
809
+ accumulateContext(msg.cost, msg.usage, msg.modelUsage, msg.lastStreamInputTokens);
810
+ },
811
+
812
+ context_usage: function (msg) {
813
+ if (msg.data && !store.get('replayingHistory')) {
814
+ store.set({ richContextUsage: msg.data });
815
+ // UI sync handled by store subscriber in app-panels.js
816
+ }
817
+ },
818
+
819
+ done: function (msg) {
820
+ removePreThinking();
821
+ setActivity(null);
822
+ stopThinking();
823
+ markAllToolsDone();
824
+ closeToolGroup();
825
+ finalizeAssistantBlock();
826
+ setStatus("connected");
827
+ // Re-enable input unless this is one of the loop's own sessions (coder/judge).
828
+ // A loop running in a separate session must not suppress input here.
829
+ var _doneLoopSid = store.get('loopCurrentSessionId');
830
+ if (!store.get('loopActive') || !_doneLoopSid || store.get('activeSessionId') !== _doneLoopSid) {
831
+ enableMainInput();
832
+ }
833
+ resetToolState();
834
+ stopUrgentBlink();
835
+ if (document.hidden) {
836
+ if (isNotifAlertEnabled() && !window._pushSubscription) showDoneNotification();
837
+ if (isNotifSoundEnabled()) playDoneSound();
838
+ }
839
+ },
840
+
841
+ stderr: function (msg) {
842
+ addSystemMessage(msg.text, false);
843
+ },
844
+
845
+ error: function (msg) {
846
+ removePreThinking();
847
+ setActivity(null);
848
+ addSystemMessage(msg.text, true);
849
+ },
850
+
851
+ system_info: function (msg) {
852
+ addSystemMessage(msg.text, false);
853
+ },
854
+
855
+ sdk_notification: function (msg) {
856
+ addSystemMessage(msg.text, false);
857
+ },
858
+
859
+ process_conflict: function (msg) {
860
+ removePreThinking();
861
+ setActivity(null);
862
+ addConflictMessage(msg);
863
+ },
864
+
865
+ context_overflow: function (msg) {
866
+ removePreThinking();
867
+ setActivity(null);
868
+ addContextOverflowMessage(msg);
869
+ },
870
+
871
+ auth_required: function (msg) {
872
+ removePreThinking();
873
+ setActivity(null);
874
+ stopThinking();
875
+ markAllToolsDone();
876
+ closeToolGroup();
877
+ appendDelta((msg.text || "Authentication required.") + "\n");
878
+ setStatus("connected");
879
+ var _authLoopSid = store.get('loopCurrentSessionId');
880
+ if (!store.get('loopActive') || !_authLoopSid || store.get('activeSessionId') !== _authLoopSid) {
881
+ enableMainInput();
882
+ }
883
+ },
884
+
885
+ rate_limit: handleRateLimitEvent,
886
+ rate_limit_usage: updateRateLimitUsage,
887
+
888
+ scheduled_message_queued: function (msg) {
889
+ // lr-0827ba: msg.localId identifies the session this schedule
890
+ // actually belongs to — may not be the currently focused session.
891
+ addScheduledMessageBubble(msg.text, msg.resetsAt, msg.localId);
892
+ if (msg.localId == null || msg.localId === store.get('activeSessionId')) setScheduleBtnDisabled(true);
893
+ },
894
+
895
+ scheduled_message_sent: function (msg) {
896
+ clearScheduledMessage(msg.localId);
897
+ if (msg.localId == null || msg.localId === store.get('activeSessionId')) {
898
+ setScheduleBtnDisabled(false);
899
+ setStatus("processing");
900
+ }
901
+ },
902
+
903
+ scheduled_message_cancelled: function (msg) {
904
+ clearScheduledMessage(msg.localId);
905
+ if (msg.localId == null || msg.localId === store.get('activeSessionId')) setScheduleBtnDisabled(false);
906
+ },
907
+
908
+ auto_continue_scheduled: function (msg) {
909
+ // Scheduler auto-continue, just show info
910
+ },
911
+
912
+ auto_continue_fired: function (msg) {
913
+ setStatus("processing");
914
+ },
915
+
916
+ prompt_suggestion: function (msg) {
917
+ showSuggestionChips(msg.suggestion);
918
+ },
919
+
920
+ fast_mode_state: function (msg) {
921
+ handleFastModeState(msg.state);
922
+ },
923
+
924
+ process_killed: function (msg) {
925
+ addSystemMessage("Process " + msg.pid + " has been terminated. You can retry your message now.", false);
926
+ },
927
+
928
+ rewind_preview_result: function (msg) {
929
+ showRewindModal(msg);
930
+ },
931
+
932
+ rewind_complete: function (msg) {
933
+ onRewindComplete();
934
+ setRewindMode(false);
935
+ var rewindText = "Rewound to earlier point. Files have been restored.";
936
+ if (msg.mode === "chat") rewindText = "Conversation rewound to earlier point.";
937
+ else if (msg.mode === "files") rewindText = "Files restored to earlier point.";
938
+ addSystemMessage(rewindText, false);
939
+ },
940
+
941
+ rewind_error: function (msg) {
942
+ onRewindError();
943
+ clearPendingRewindUuid();
944
+ addSystemMessage(msg.text || "Rewind failed.", true);
945
+ },
946
+
947
+ fork_complete: function (msg) {
948
+ addSystemMessage("Session forked successfully.");
949
+ },
950
+
951
+ fs_read_result: function (msg) {
952
+ if (msg.path === "CLAUDE.md" && isProjectSettingsOpen()) {
953
+ handleInstructionsRead(msg);
954
+ } else {
955
+ handleFsRead(msg);
956
+ }
957
+ },
958
+
959
+ fs_write_result: handleInstructionsWrite,
960
+ project_env_result: handleProjectEnv,
961
+ set_project_env_result: handleProjectEnvSaved,
962
+
963
+ shared_env_result: function (msg) {
964
+ handleSharedEnv(msg);
965
+ handleProjectSharedEnv(msg);
966
+ },
967
+
968
+ set_shared_env_result: function (msg) {
969
+ handleSharedEnvSaved(msg);
970
+ handleProjectSharedEnvSaved(msg);
971
+ },
972
+
973
+ term_list: function (msg) {
974
+ handleTermList(msg);
975
+ updateTerminalList(msg.terminals);
976
+ },
977
+
978
+ context_sources_state: handleContextSourcesState,
979
+
980
+ extension_command: function (msg) {
981
+ sendExtensionCommand(msg.command, msg.args, msg.requestId);
982
+ },
983
+
984
+ mcp_tool_call: handleMcpToolCallMessage,
985
+ mcp_servers_state: handleMcpServersState,
986
+
987
+ term_created: function (msg) {
988
+ handleTermCreated(msg);
989
+ if (store.get('pendingTermCommand')) {
990
+ var cmd = store.get('pendingTermCommand');
991
+ store.set({ pendingTermCommand: null });
992
+ // Small delay to let terminal initialize
993
+ setTimeout(function() {
994
+ sendTerminalCommand(cmd);
995
+ }, 300);
996
+ }
997
+ },
998
+
999
+ term_output: handleTermOutput,
1000
+ term_resized: handleTermResized,
1001
+ term_exited: handleTermExited,
1002
+ term_closed: handleTermClosed,
1003
+
1004
+ notes_list: handleNotesList,
1005
+ note_created: handleNoteCreated,
1006
+ note_updated: handleNoteUpdated,
1007
+ note_deleted: handleNoteDeleted,
1008
+
1009
+ process_stats: function (msg) {
1010
+ updateStatusPanel(msg);
1011
+ updateSettingsStats(msg);
1012
+ },
1013
+
1014
+ browse_dir_result: handleBrowseDirResult,
1015
+ add_project_result: handleAddProjectResult,
1016
+ clone_project_progress: handleCloneProgress,
1017
+ remove_project_result: handleRemoveProjectResult,
1018
+
1019
+ reorder_projects_result: function (msg) {
1020
+ if (!msg.ok) {
1021
+ showToast(msg.error || "Failed to reorder projects", "error");
1022
+ }
1023
+ },
1209
1024
 
1210
- case "set_project_icon_result":
1211
- if (!msg.ok) {
1212
- showToast(msg.error || "Failed to set icon", "error");
1213
- }
1214
- break;
1025
+ set_project_title_result: function (msg) {
1026
+ if (!msg.ok) {
1027
+ showToast(msg.error || "Failed to rename project", "error");
1028
+ }
1029
+ },
1215
1030
 
1216
- case "set_project_preferred_agent_result":
1217
- if (!msg.ok) {
1218
- showToast(msg.error || "Failed to set preferred agent", "error");
1219
- }
1220
- break;
1031
+ set_project_icon_result: function (msg) {
1032
+ if (!msg.ok) {
1033
+ showToast(msg.error || "Failed to set icon", "error");
1034
+ }
1035
+ },
1221
1036
 
1222
- case "set_project_folder_result":
1223
- if (!msg.ok) {
1224
- showToast(msg.error || "Failed to move project to folder", "error");
1225
- }
1226
- break;
1037
+ set_project_preferred_agent_result: function (msg) {
1038
+ if (!msg.ok) {
1039
+ showToast(msg.error || "Failed to set preferred agent", "error");
1040
+ }
1041
+ },
1227
1042
 
1228
- case "rename_project_folder_result":
1229
- if (!msg.ok) {
1230
- showToast(msg.error || "Failed to rename folder", "error");
1231
- }
1232
- break;
1043
+ set_project_folder_result: function (msg) {
1044
+ if (!msg.ok) {
1045
+ showToast(msg.error || "Failed to move project to folder", "error");
1046
+ }
1047
+ },
1233
1048
 
1234
- case "set_folder_icon_result":
1235
- if (!msg.ok) {
1236
- showToast(msg.error || "Failed to set folder icon", "error");
1237
- }
1238
- break;
1239
-
1240
- case "projects_updated":
1241
- updateProjectList(msg);
1242
- break;
1243
-
1244
- case "rename_custom_icon_result":
1245
- handleRenameCustomIconResult(msg);
1246
- break;
1247
-
1248
- case "project_owner_changed":
1249
- store.set({ currentProjectOwnerId: msg.ownerId });
1250
- handleProjectOwnerChanged(msg);
1251
- break;
1252
-
1253
- // --- DM ---
1254
- case "dm_history":
1255
- enterDmMode(msg.dmKey, msg.targetUser, msg.messages);
1256
- break;
1257
-
1258
- case "dm_message":
1259
- if (store.get('dmMode') && msg.dmKey === store.get('dmKey')) {
1260
- showDmTypingIndicator(false); // hide typing when message arrives
1261
- appendDmMessage(msg.message);
1262
- scrollToBottom();
1263
- } else if (msg.message) {
1264
- // DM notification when not in that DM
1265
- var fromId = msg.message.from;
1266
- if (fromId && fromId !== store.get('myUserId')) {
1267
- var _du = Object.assign({}, store.get('dmUnread'));
1268
- _du[fromId] = (_du[fromId] || 0) + 1;
1269
- store.set({ dmUnread: _du });
1270
- // renderUserStrip is handled by the store subscriber
1271
- updateDmBadge(fromId, _du[fromId]);
1272
- }
1273
- }
1274
- break;
1049
+ rename_project_folder_result: function (msg) {
1050
+ if (!msg.ok) {
1051
+ showToast(msg.error || "Failed to rename folder", "error");
1052
+ }
1053
+ },
1275
1054
 
1276
- case "dm_typing":
1277
- if (store.get('dmMode') && msg.dmKey === store.get('dmKey')) {
1278
- showDmTypingIndicator(msg.typing);
1279
- }
1280
- break;
1281
-
1282
- case "dm_list":
1283
- // Could be used for DM list view later
1284
- break;
1285
-
1286
- case "dm_favorites_updated":
1287
- // Track users explicitly removed from favorites
1288
- var _cdf = store.get('cachedDmFavorites');
1289
- if (_cdf && msg.dmFavorites) {
1290
- for (var ri = 0; ri < _cdf.length; ri++) {
1291
- if (msg.dmFavorites.indexOf(_cdf[ri]) === -1) {
1292
- store.get('dmRemovedUsers')[_cdf[ri]] = true;
1293
- }
1294
- }
1295
- }
1296
- // Clear removed flag for users being added back
1297
- if (msg.dmFavorites) {
1298
- for (var ai = 0; ai < msg.dmFavorites.length; ai++) {
1299
- delete store.get('dmRemovedUsers')[msg.dmFavorites[ai]];
1300
- }
1301
- }
1302
- store.set({ cachedDmFavorites: msg.dmFavorites || [] });
1055
+ set_folder_icon_result: function (msg) {
1056
+ if (!msg.ok) {
1057
+ showToast(msg.error || "Failed to set folder icon", "error");
1058
+ }
1059
+ },
1060
+
1061
+ projects_updated: updateProjectList,
1062
+ rename_custom_icon_result: handleRenameCustomIconResult,
1063
+
1064
+ project_owner_changed: function (msg) {
1065
+ store.set({ currentProjectOwnerId: msg.ownerId });
1066
+ handleProjectOwnerChanged(msg);
1067
+ },
1068
+
1069
+ // --- DM ---
1070
+ dm_history: function (msg) {
1071
+ enterDmMode(msg.dmKey, msg.targetUser, msg.messages);
1072
+ },
1073
+
1074
+ dm_message: function (msg) {
1075
+ if (store.get('dmMode') && msg.dmKey === store.get('dmKey')) {
1076
+ showDmTypingIndicator(false); // hide typing when message arrives
1077
+ appendDmMessage(msg.message);
1078
+ scrollToBottom();
1079
+ } else if (msg.message) {
1080
+ // DM notification when not in that DM
1081
+ var fromId = msg.message.from;
1082
+ if (fromId && fromId !== store.get('myUserId')) {
1083
+ var _du = Object.assign({}, store.get('dmUnread'));
1084
+ _du[fromId] = (_du[fromId] || 0) + 1;
1085
+ store.set({ dmUnread: _du });
1303
1086
  // renderUserStrip is handled by the store subscriber
1304
- break;
1305
-
1306
- // --- @Mention ---
1307
- case "mention_start":
1308
- handleMentionStart(msg);
1309
- break;
1310
-
1311
- case "mention_activity":
1312
- handleMentionActivity(msg);
1313
- break;
1314
-
1315
- case "mention_stream":
1316
- handleMentionStream(msg);
1317
- break;
1318
-
1319
- case "mention_done":
1320
- handleMentionDone(msg);
1321
- break;
1322
-
1323
- case "mention_error":
1324
- handleMentionError(msg);
1325
- if (msg.error) showToast("@Mention: " + msg.error, "error");
1326
- break;
1327
-
1328
- case "mention_user":
1329
- // Finalize current assistant block so mention renders in correct DOM position
1330
- finalizeAssistantBlock();
1331
- renderMentionUser(msg);
1332
- break;
1333
-
1334
- case "mention_response":
1335
- finalizeAssistantBlock();
1336
- renderMentionResponse(msg);
1337
- break;
1338
-
1339
- case "user_mention":
1340
- // User-to-user side conversation entry. Renders for any session viewer
1341
- // (sender's other tabs and the mentioned user, if they are watching the
1342
- // session). On the sender's own tab, the server uses sendToSessionOthers
1343
- // so we never get a duplicate here.
1344
- finalizeAssistantBlock();
1345
- renderUserMention(msg);
1346
- break;
1347
- case "user_mention_error":
1348
- if (msg.error) showToast("@Mention: " + msg.error, "error");
1349
- break;
1350
-
1351
- // --- Team activity ---
1352
- case "team_state": handleTeamState(msg); break;
1353
- case "team_member_update": handleTeamMemberUpdate(msg); break;
1354
- case "team_task_update": handleTeamTaskUpdate(msg); break;
1355
- case "team_message": handleTeamMsg(msg); break;
1356
- case "team_gone": handleTeamGone(msg); break;
1357
-
1358
- case "diagnostic":
1359
- // Diagnostic events from CLI stderr (stage 4/5, lr-8294, epic lr-1a52).
1360
- // Future sources (e.g. settings preflight from stage 5/5 lr-1a26) will
1361
- // also arrive via this same type — the render path must not assume CLI origin.
1362
- addDiagnostic(msg);
1363
- break;
1364
-
1365
- case "daemon_config":
1366
- if (msg.config && msg.config.headless) store.set({ isHeadlessMode: true });
1367
- updateDaemonConfig(msg.config);
1368
- break;
1369
-
1370
- case "set_pin_result":
1371
- handleSetPinResult(msg);
1372
- break;
1373
-
1374
- case "set_keep_awake_result":
1375
- handleKeepAwakeChanged(msg);
1376
- break;
1377
-
1378
- case "keep_awake_changed":
1379
- handleKeepAwakeChanged(msg);
1380
- break;
1381
-
1382
- case "set_auto_continue_result":
1383
- case "auto_continue_changed":
1384
- handleAutoContinueChanged(msg);
1385
- break;
1386
-
1387
- case "refresh_agents_result":
1388
- handleRefreshAgentsResult(msg);
1389
- break;
1390
-
1391
- case "restart_server_result":
1392
- handleRestartResult(msg);
1393
- break;
1394
-
1395
- case "shutdown_server_result":
1396
- handleShutdownResult(msg);
1397
- break;
1398
-
1399
- // --- Ralph Loop ---
1400
- case "loop_available":
1401
- store.set({ loopAvailable: msg.available, loopActive: msg.active, loopIteration: msg.iteration || 0, loopMaxIterations: msg.maxIterations || 20, loopBannerName: msg.name || null });
1402
-
1403
- var _la = store.snap();
1404
- if (_la.loopActive) {
1405
- showLoopBanner(true);
1406
- if (_la.loopIteration > 0) {
1407
- updateLoopBanner(_la.loopIteration, _la.loopMaxIterations, "running");
1408
- }
1409
- // Only lock input if this session is actually a loop session (singleTurn).
1410
- // Other sessions in the project must not be locked by a loop running elsewhere.
1411
- updateLoopInputVisibility(null);
1412
- }
1413
- break;
1414
-
1415
- case "loop_started":
1416
- store.set({ loopActive: true, ralphPhase: "executing", loopIteration: 0, loopMaxIterations: msg.maxIterations, loopBannerName: msg.name || null });
1417
- showLoopBanner(true);
1418
-
1419
- var _lbn = store.get('loopBannerName');
1420
- addSystemMessage((_lbn || "Loop") + " started (max " + msg.maxIterations + " iterations)", false);
1421
- // Do not lock the input here — loop_iteration carries the session ID and will
1422
- // lock only the actual coder/judge session when it becomes active.
1423
- break;
1424
-
1425
- case "loop_iteration":
1426
- store.set({ loopIteration: msg.iteration, loopMaxIterations: msg.maxIterations, loopCurrentSessionId: msg.sessionId || null });
1427
- updateLoopBanner(msg.iteration, msg.maxIterations, "running");
1428
-
1429
- var _libn = store.get('loopBannerName');
1430
- addSystemMessage((_libn || "Loop") + " iteration #" + msg.iteration + " started", false);
1431
- // lr-e31b: The composer stays enabled (not locked) while viewing the
1432
- // loop's own session — updateLoopInputVisibility() already switched
1433
- // it into queue mode so a human message is queued for the next
1434
- // iteration boundary rather than dropped or blocked outright.
1435
- break;
1436
-
1437
- case "loop_judging":
1438
- var _ljs = store.snap();
1439
- store.set({ loopCurrentSessionId: msg.sessionId || _ljs.loopCurrentSessionId });
1440
- updateLoopBanner(_ljs.loopIteration, _ljs.loopMaxIterations, "judging");
1441
- addSystemMessage("Judging iteration #" + msg.iteration + "...", false);
1442
- // lr-e31b: composer stays enabled in queue mode (see loop_iteration above).
1443
- break;
1444
-
1445
- case "loop_verdict":
1446
- addSystemMessage("Judge: " + msg.verdict.toUpperCase() + " - " + (msg.summary || ""), false);
1447
- break;
1448
-
1449
- case "loop_stopping":
1450
- var _lss = store.snap();
1451
- updateLoopBanner(_lss.loopIteration, _lss.loopMaxIterations, "stopping");
1452
- break;
1453
-
1454
- case "loop_finished":
1455
- var _lfbn = store.get('loopBannerName');
1456
- store.set({ loopActive: false, ralphPhase: "done", loopBannerName: null, loopCurrentSessionId: null });
1457
- showLoopBanner(false);
1458
-
1459
- enableMainInput();
1460
- updateLoopInputVisibility(null);
1461
- var loopLabel = _lfbn || "Loop";
1462
- var finishMsg = msg.reason === "pass"
1463
- ? loopLabel + " completed successfully after " + msg.iterations + " iteration(s)."
1464
- : msg.reason === "max_iterations"
1465
- ? loopLabel + " reached maximum iterations (" + msg.iterations + ")."
1466
- : msg.reason === "stopped"
1467
- ? loopLabel + " stopped."
1468
- : loopLabel + " ended with error.";
1469
- addSystemMessage(finishMsg, false);
1470
- break;
1471
-
1472
- case "loop_error":
1473
- addSystemMessage((store.get('loopBannerName') || "Loop") + " error: " + msg.text, true);
1474
- break;
1475
-
1476
- // lr-e31b: server-confirmed queue of human messages awaiting delivery
1477
- // at the next loop iteration boundary.
1478
- case "loop_pending_messages":
1479
- store.set({ loopPendingMessages: msg.messages || [] });
1480
- updateLoopPendingBanner();
1481
- break;
1482
-
1483
- case "loop_message_error":
1484
- addSystemMessage((store.get('loopBannerName') || "Loop") + ": " + msg.text, true);
1485
- break;
1486
-
1487
- // --- Ralph Wizard / Crafting ---
1488
- case "ralph_phase":
1489
- var _rps = { ralphPhase: msg.phase || "idle" };
1490
- if (msg.craftingSessionId) _rps.ralphCraftingSessionId = msg.craftingSessionId;
1491
- if (msg.source !== undefined) _rps.ralphCraftingSource = msg.source;
1492
- store.set(_rps);
1493
- if (msg.wizardData) store.set({ wizardData: msg.wizardData });
1494
-
1495
-
1496
- break;
1497
-
1498
- case "ralph_crafting_started":
1499
- store.set({ ralphPhase: "crafting", ralphCraftingSessionId: msg.sessionId || store.get('activeSessionId'), ralphCraftingSource: msg.source || null });
1500
-
1501
-
1502
- if (msg.source !== "ralph") {
1503
- // Task sessions open in the scheduler calendar window
1504
- enterCraftingMode(msg.sessionId, msg.taskId);
1087
+ updateDmBadge(fromId, _du[fromId]);
1088
+ }
1089
+ }
1090
+ },
1091
+
1092
+ dm_typing: function (msg) {
1093
+ if (store.get('dmMode') && msg.dmKey === store.get('dmKey')) {
1094
+ showDmTypingIndicator(msg.typing);
1095
+ }
1096
+ },
1097
+
1098
+ dm_list: function (msg) {
1099
+ // Could be used for DM list view later
1100
+ },
1101
+
1102
+ dm_favorites_updated: function (msg) {
1103
+ // Track users explicitly removed from favorites
1104
+ var _cdf = store.get('cachedDmFavorites');
1105
+ if (_cdf && msg.dmFavorites) {
1106
+ for (var ri = 0; ri < _cdf.length; ri++) {
1107
+ if (msg.dmFavorites.indexOf(_cdf[ri]) === -1) {
1108
+ store.get('dmRemovedUsers')[_cdf[ri]] = true;
1505
1109
  }
1506
- // Ralph crafting sessions show in session list as part of the loop group
1507
- break;
1508
-
1509
- case "ralph_files_status":
1510
- store.set({ ralphFilesReady: {
1511
- promptReady: msg.promptReady,
1512
- judgeReady: msg.judgeReady,
1513
- bothReady: msg.bothReady,
1514
- } });
1515
- if (msg.bothReady) {
1516
- var _rfs = store.snap();
1517
- if (_rfs.ralphPhase === "crafting" || _rfs.ralphPhase === "approval") {
1518
- store.set({ ralphPhase: "approval" });
1519
- if (_rfs.ralphCraftingSource !== "ralph" || isSchedulerOpen()) {
1520
- // Task crafting in scheduler: switch from crafting chat to detail view showing files
1521
- exitCraftingMode(msg.taskId);
1522
- } else {
1523
- showRalphApprovalBar(true);
1524
- // Auto-show execution modal (one-time) for Ralph source
1525
- if (!store.get('execModalShown') && _rfs.ralphCraftingSource === "ralph") {
1526
- showExecModal();
1527
- }
1528
- }
1110
+ }
1111
+ }
1112
+ // Clear removed flag for users being added back
1113
+ if (msg.dmFavorites) {
1114
+ for (var ai = 0; ai < msg.dmFavorites.length; ai++) {
1115
+ delete store.get('dmRemovedUsers')[msg.dmFavorites[ai]];
1116
+ }
1117
+ }
1118
+ store.set({ cachedDmFavorites: msg.dmFavorites || [] });
1119
+ // renderUserStrip is handled by the store subscriber
1120
+ },
1121
+
1122
+ // --- @Mention ---
1123
+ mention_start: handleMentionStart,
1124
+ mention_activity: handleMentionActivity,
1125
+ mention_stream: handleMentionStream,
1126
+ mention_done: handleMentionDone,
1127
+
1128
+ mention_error: function (msg) {
1129
+ handleMentionError(msg);
1130
+ if (msg.error) showToast("@Mention: " + msg.error, "error");
1131
+ },
1132
+
1133
+ mention_user: function (msg) {
1134
+ // Finalize current assistant block so mention renders in correct DOM position
1135
+ finalizeAssistantBlock();
1136
+ renderMentionUser(msg);
1137
+ },
1138
+
1139
+ mention_response: function (msg) {
1140
+ finalizeAssistantBlock();
1141
+ renderMentionResponse(msg);
1142
+ },
1143
+
1144
+ user_mention: function (msg) {
1145
+ // User-to-user side conversation entry. Renders for any session viewer
1146
+ // (sender's other tabs and the mentioned user, if they are watching the
1147
+ // session). On the sender's own tab, the server uses sendToSessionOthers
1148
+ // so we never get a duplicate here.
1149
+ finalizeAssistantBlock();
1150
+ renderUserMention(msg);
1151
+ },
1152
+
1153
+ user_mention_error: function (msg) {
1154
+ if (msg.error) showToast("@Mention: " + msg.error, "error");
1155
+ },
1156
+
1157
+ // --- Team activity ---
1158
+ team_state: handleTeamState,
1159
+ team_member_update: handleTeamMemberUpdate,
1160
+ team_task_update: handleTeamTaskUpdate,
1161
+ team_message: handleTeamMsg,
1162
+ team_gone: handleTeamGone,
1163
+
1164
+ diagnostic: function (msg) {
1165
+ // Diagnostic events from CLI stderr (stage 4/5, lr-8294, epic lr-1a52).
1166
+ // Future sources (e.g. settings preflight from stage 5/5 lr-1a26) will
1167
+ // also arrive via this same type — the render path must not assume CLI origin.
1168
+ addDiagnostic(msg);
1169
+ },
1170
+
1171
+ daemon_config: function (msg) {
1172
+ if (msg.config && msg.config.headless) store.set({ isHeadlessMode: true });
1173
+ updateDaemonConfig(msg.config);
1174
+ },
1175
+
1176
+ daemon_config_changed: updateDaemonConfig,
1177
+
1178
+ lite_project_status: handleLiteProjectStatus,
1179
+ lite_enroll_result: handleLiteEnrollResult,
1180
+ lite_unenroll_result: handleLiteUnenrollResult,
1181
+
1182
+ // --- Ralph Loop ---
1183
+ loop_available: function (msg) {
1184
+ store.set({ loopAvailable: msg.available, loopActive: msg.active, loopIteration: msg.iteration || 0, loopMaxIterations: msg.maxIterations || 20, loopBannerName: msg.name || null });
1185
+
1186
+ var _la = store.snap();
1187
+ if (_la.loopActive) {
1188
+ showLoopBanner(true);
1189
+ if (_la.loopIteration > 0) {
1190
+ updateLoopBanner(_la.loopIteration, _la.loopMaxIterations, "running");
1191
+ }
1192
+ // Only lock input if this session is actually a loop session (singleTurn).
1193
+ // Other sessions in the project must not be locked by a loop running elsewhere.
1194
+ updateLoopInputVisibility(null);
1195
+ }
1196
+ },
1197
+
1198
+ loop_started: function (msg) {
1199
+ store.set({ loopActive: true, ralphPhase: "executing", loopIteration: 0, loopMaxIterations: msg.maxIterations, loopBannerName: msg.name || null });
1200
+ showLoopBanner(true);
1201
+
1202
+ var _lbn = store.get('loopBannerName');
1203
+ addSystemMessage((_lbn || "Loop") + " started (max " + msg.maxIterations + " iterations)", false);
1204
+ // Do not lock the input here — loop_iteration carries the session ID and will
1205
+ // lock only the actual coder/judge session when it becomes active.
1206
+ },
1207
+
1208
+ loop_iteration: function (msg) {
1209
+ store.set({ loopIteration: msg.iteration, loopMaxIterations: msg.maxIterations, loopCurrentSessionId: msg.sessionId || null });
1210
+ updateLoopBanner(msg.iteration, msg.maxIterations, "running");
1211
+
1212
+ var _libn = store.get('loopBannerName');
1213
+ addSystemMessage((_libn || "Loop") + " iteration #" + msg.iteration + " started", false);
1214
+ // lr-e31b: The composer stays enabled (not locked) while viewing the
1215
+ // loop's own session — updateLoopInputVisibility() already switched
1216
+ // it into queue mode so a human message is queued for the next
1217
+ // iteration boundary rather than dropped or blocked outright.
1218
+ },
1219
+
1220
+ loop_judging: function (msg) {
1221
+ var _ljs = store.snap();
1222
+ store.set({ loopCurrentSessionId: msg.sessionId || _ljs.loopCurrentSessionId });
1223
+ updateLoopBanner(_ljs.loopIteration, _ljs.loopMaxIterations, "judging");
1224
+ addSystemMessage("Judging iteration #" + msg.iteration + "...", false);
1225
+ // lr-e31b: composer stays enabled in queue mode (see loop_iteration above).
1226
+ },
1227
+
1228
+ loop_verdict: function (msg) {
1229
+ addSystemMessage("Judge: " + msg.verdict.toUpperCase() + " - " + (msg.summary || ""), false);
1230
+ },
1231
+
1232
+ loop_stopping: function (msg) {
1233
+ var _lss = store.snap();
1234
+ updateLoopBanner(_lss.loopIteration, _lss.loopMaxIterations, "stopping");
1235
+ },
1236
+
1237
+ loop_finished: function (msg) {
1238
+ var _lfbn = store.get('loopBannerName');
1239
+ store.set({ loopActive: false, ralphPhase: "done", loopBannerName: null, loopCurrentSessionId: null });
1240
+ showLoopBanner(false);
1241
+
1242
+ enableMainInput();
1243
+ updateLoopInputVisibility(null);
1244
+ var loopLabel = _lfbn || "Loop";
1245
+ var finishMsg = msg.reason === "pass"
1246
+ ? loopLabel + " completed successfully after " + msg.iterations + " iteration(s)."
1247
+ : msg.reason === "max_iterations"
1248
+ ? loopLabel + " reached maximum iterations (" + msg.iterations + ")."
1249
+ : msg.reason === "stopped"
1250
+ ? loopLabel + " stopped."
1251
+ : loopLabel + " ended with error.";
1252
+ addSystemMessage(finishMsg, false);
1253
+ },
1254
+
1255
+ loop_error: function (msg) {
1256
+ addSystemMessage((store.get('loopBannerName') || "Loop") + " error: " + msg.text, true);
1257
+ },
1258
+
1259
+ // lr-e31b: server-confirmed queue of human messages awaiting delivery
1260
+ // at the next loop iteration boundary.
1261
+ loop_pending_messages: function (msg) {
1262
+ store.set({ loopPendingMessages: msg.messages || [] });
1263
+ updateLoopPendingBanner();
1264
+ },
1265
+
1266
+ loop_message_error: function (msg) {
1267
+ addSystemMessage((store.get('loopBannerName') || "Loop") + ": " + msg.text, true);
1268
+ },
1269
+
1270
+ // --- Ralph Wizard / Crafting ---
1271
+ ralph_phase: function (msg) {
1272
+ var _rps = { ralphPhase: msg.phase || "idle" };
1273
+ if (msg.craftingSessionId) _rps.ralphCraftingSessionId = msg.craftingSessionId;
1274
+ if (msg.source !== undefined) _rps.ralphCraftingSource = msg.source;
1275
+ store.set(_rps);
1276
+ if (msg.wizardData) store.set({ wizardData: msg.wizardData });
1277
+ },
1278
+
1279
+ ralph_crafting_started: function (msg) {
1280
+ store.set({ ralphPhase: "crafting", ralphCraftingSessionId: msg.sessionId || store.get('activeSessionId'), ralphCraftingSource: msg.source || null });
1281
+
1282
+ if (msg.source !== "ralph") {
1283
+ // Task sessions open in the scheduler calendar window
1284
+ enterCraftingMode(msg.sessionId, msg.taskId);
1285
+ }
1286
+ // Ralph crafting sessions show in session list as part of the loop group
1287
+ },
1288
+
1289
+ ralph_files_status: function (msg) {
1290
+ store.set({ ralphFilesReady: {
1291
+ promptReady: msg.promptReady,
1292
+ judgeReady: msg.judgeReady,
1293
+ bothReady: msg.bothReady,
1294
+ } });
1295
+ if (msg.bothReady) {
1296
+ var _rfs = store.snap();
1297
+ if (_rfs.ralphPhase === "crafting" || _rfs.ralphPhase === "approval") {
1298
+ store.set({ ralphPhase: "approval" });
1299
+ if (_rfs.ralphCraftingSource !== "ralph" || isSchedulerOpen()) {
1300
+ // Task crafting in scheduler: switch from crafting chat to detail view showing files
1301
+ exitCraftingMode(msg.taskId);
1302
+ } else {
1303
+ showRalphApprovalBar(true);
1304
+ // Auto-show execution modal (one-time) for Ralph source
1305
+ if (!store.get('execModalShown') && _rfs.ralphCraftingSource === "ralph") {
1306
+ showExecModal();
1529
1307
  }
1530
1308
  }
1531
- updateRalphApprovalStatus();
1532
- updateExecModalStatus();
1533
- break;
1534
-
1535
- case "loop_registry_files_content":
1536
- handleLoopRegistryFiles(msg);
1537
- break;
1538
-
1539
- case "ralph_files_content":
1540
- store.set({ ralphPreviewContent: { prompt: msg.prompt || "", judge: msg.judge || "" } });
1541
- openRalphPreviewModal();
1542
- break;
1543
-
1544
- case "loop_registry_error":
1545
- addSystemMessage("Error: " + msg.text, true);
1546
- break;
1547
-
1548
- // --- Notifications ---
1549
- case "notifications_state":
1550
- handleNotificationsState(msg);
1551
- break;
1552
- case "notification_created":
1553
- handleNotificationCreated(msg);
1554
- break;
1555
- case "notification_dismissed":
1556
- handleNotificationDismissed(msg);
1557
- break;
1558
- case "notification_dismissed_all":
1559
- handleNotificationDismissedAll();
1560
- break;
1561
-
1562
- case "daemon_config_changed":
1563
- updateDaemonConfig(msg);
1564
- break;
1565
-
1566
- case "lite_project_status":
1567
- handleLiteProjectStatus(msg);
1568
- break;
1569
-
1570
- case "lite_enroll_result":
1571
- handleLiteEnrollResult(msg);
1572
- break;
1573
-
1574
- case "lite_unenroll_result":
1575
- handleLiteUnenrollResult(msg);
1576
- break;
1309
+ }
1577
1310
  }
1578
- }
1311
+ updateRalphApprovalStatus();
1312
+ updateExecModalStatus();
1313
+ },
1314
+
1315
+ loop_registry_files_content: handleLoopRegistryFiles,
1316
+
1317
+ ralph_files_content: function (msg) {
1318
+ store.set({ ralphPreviewContent: { prompt: msg.prompt || "", judge: msg.judge || "" } });
1319
+ openRalphPreviewModal();
1320
+ },
1321
+
1322
+ loop_registry_error: function (msg) {
1323
+ addSystemMessage("Error: " + msg.text, true);
1324
+ },
1325
+
1326
+ // --- Notifications ---
1327
+ notifications_state: handleNotificationsState,
1328
+ notification_created: handleNotificationCreated,
1329
+ notification_dismissed: handleNotificationDismissed,
1330
+
1331
+ notification_dismissed_all: function (msg) {
1332
+ handleNotificationDismissedAll();
1333
+ },
1334
+ });