@clagentic/console 1.7.0 → 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 (58) hide show
  1. package/bin/cli.js +198 -2542
  2. package/lib/build-sha.json +4 -0
  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/daemon.js +15 -6
  9. package/lib/memory-shed.js +81 -2
  10. package/lib/pages.js +13 -17
  11. package/lib/project-connection.js +13 -0
  12. package/lib/project-loop.js +4 -0
  13. package/lib/project-sessions.js +9 -3
  14. package/lib/project.js +3 -2
  15. package/lib/public/css/diagnostics.css +29 -1
  16. package/lib/public/css/home-hub.css +10 -0
  17. package/lib/public/css/overlays.css +19 -0
  18. package/lib/public/index.html +12 -11
  19. package/lib/public/manifest.json +1 -1
  20. package/lib/public/modules/app-connection.js +150 -4
  21. package/lib/public/modules/app-history-replay.js +155 -0
  22. package/lib/public/modules/app-home-hub.js +24 -14
  23. package/lib/public/modules/app-messages.js +1246 -1469
  24. package/lib/public/modules/app-notifications.js +4 -4
  25. package/lib/public/modules/app-rate-limit.js +128 -27
  26. package/lib/public/modules/command-palette.js +11 -22
  27. package/lib/public/modules/context-sources.js +1 -6
  28. package/lib/public/modules/filebrowser.js +25 -13
  29. package/lib/public/modules/input.js +47 -12
  30. package/lib/public/modules/mcp-ui.js +2 -2
  31. package/lib/public/modules/notifications.js +22 -1
  32. package/lib/public/modules/playbook.js +6 -6
  33. package/lib/public/modules/project-settings.js +5 -13
  34. package/lib/public/modules/qrcode.js +2 -2
  35. package/lib/public/modules/rate-limit-state.js +133 -0
  36. package/lib/public/modules/relative-time.js +27 -0
  37. package/lib/public/modules/scheduler-history.js +1 -5
  38. package/lib/public/modules/server-settings.js +28 -15
  39. package/lib/public/modules/sidebar-mobile.js +8 -3
  40. package/lib/public/modules/sidebar-projects.js +1 -1
  41. package/lib/public/modules/sidebar-sessions.js +1 -15
  42. package/lib/public/modules/sidebar.js +3 -3
  43. package/lib/public/modules/utils.js +1 -0
  44. package/lib/public/sw.js +24 -4
  45. package/lib/sdk-bridge.js +22 -0
  46. package/lib/sdk-message-processor.js +27 -1
  47. package/lib/server-auth.js +48 -2
  48. package/lib/server-palette.js +17 -1
  49. package/lib/server-settings.js +70 -4
  50. package/lib/server.js +200 -4
  51. package/lib/session-search.js +20 -5
  52. package/lib/sessions.js +84 -3
  53. package/lib/smtp.js +6 -6
  54. package/lib/yoke/adapters/codex.js +1 -1
  55. package/package.json +4 -2
  56. package/scripts/install-local-test.js +97 -0
  57. package/scripts/verify-installed-build.js +80 -0
  58. package/scripts/write-build-sha.js +53 -0
@@ -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,15 +52,15 @@ 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';
46
62
  import { openDm, enterDmMode, exitDmMode, appendDmMessage, showDmTypingIndicator } from './app-dm.js';
47
- import { handleRateLimitEvent, updateRateLimitUsage, addScheduledMessageBubble, removeScheduledMessageBubble, handleFastModeState } from './app-rate-limit.js';
63
+ import { handleRateLimitEvent, updateRateLimitUsage, addScheduledMessageBubble, removeScheduledMessageBubble, clearScheduledMessage, handleFastModeState, restoreRateLimitStateForSession, forgetSessionRateLimitState } from './app-rate-limit.js';
48
64
  import { handleRemoteCursorMove, handleRemoteCursorLeave, handleRemoteSelection, clearRemoteCursors } from './app-cursors.js';
49
65
  import { showLoopBanner, updateLoopBanner, updateLoopInputVisibility, updateLoopPendingBanner, showRalphApprovalBar, updateRalphApprovalStatus, openRalphPreviewModal, showExecModal, updateExecModalStatus } from './app-loop-ui.js';
50
66
  import { handleSkillInstallWs } from './app-skills-install.js';
@@ -52,1506 +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_list":
439
- renderSessionList(msg.sessions || []);
440
- handlePaletteSessionSwitch();
441
- // Drain pending hub cross-project session switch (set by handleHubRecentSessions
442
- // when switching to a session in a different project). Fires here because
443
- // session_list is the first reliable post-connect message that guarantees
444
- // the WS is open and the session roster is populated.
445
- try {
446
- var _pendingHubSess = sessionStorage.getItem("pending-hub-session");
447
- if (_pendingHubSess) {
448
- sessionStorage.removeItem("pending-hub-session");
449
- var _phWs = getWs();
450
- if (_phWs && _phWs.readyState === 1) {
451
- _phWs.send(JSON.stringify({ type: "switch_session", id: parseInt(_pendingHubSess, 10) }));
452
- }
453
- }
454
- } catch (e) {}
455
- break;
456
-
457
- case "agents_list":
458
- handleAgentsList(msg);
459
- break;
460
-
461
- case "agent_favorite_toggled":
462
- handleAgentFavoriteToggled(msg);
463
- break;
464
-
465
- case "project_agents_list":
466
- handleProjectAgentsList(msg);
467
- break;
468
-
469
- case "session_presence":
470
- updateSessionPresence(msg.presence || {});
471
- break;
472
-
473
- case "cursor_move":
474
- handleRemoteCursorMove(msg);
475
- break;
393
+ }
394
+ } catch (e) {}
395
+ },
476
396
 
477
- case "cursor_leave":
478
- handleRemoteCursorLeave(msg);
479
- break;
397
+ agents_list: handleAgentsList,
398
+ agent_favorite_toggled: handleAgentFavoriteToggled,
399
+ project_agents_list: handleProjectAgentsList,
480
400
 
481
- case "text_select":
482
- handleRemoteSelection(msg);
483
- break;
401
+ session_presence: function (msg) {
402
+ updateSessionPresence(msg.presence || {});
403
+ },
484
404
 
485
- case "session_io":
486
- blinkSessionDot(msg.id);
487
- break;
405
+ cursor_move: handleRemoteCursorMove,
406
+ cursor_leave: handleRemoteCursorLeave,
407
+ text_select: handleRemoteSelection,
488
408
 
489
- case "session_unread":
490
- updateSessionBadge(msg.id, msg.count);
491
- break;
409
+ session_io: function (msg) {
410
+ blinkSessionDot(msg.id);
411
+ },
492
412
 
493
- case "search_results":
494
- handleSearchResults(msg);
495
- break;
413
+ session_unread: function (msg) {
414
+ updateSessionBadge(msg.id, msg.count);
415
+ },
496
416
 
497
- case "search_content_results":
498
- if (msg.source === "find_in_session") {
499
- handleFindInSessionResults(msg);
500
- }
501
- break;
502
-
503
- case "cli_session_list":
504
- populateCliSessionList(msg.sessions || []);
505
- break;
506
-
507
- case "session_switched":
508
- // Prefetch project agents so the @ menu is ready without a round-trip
509
- // the first time the user types @. Best-effort; at-agents.js handles
510
- // an empty list gracefully.
511
- requestProjectAgents();
512
- hideHomeHub();
513
- // Clear any stale replay indicator from a prior interrupted switch
514
- if (replayLoadingEl) replayLoadingEl.classList.add("hidden");
515
- // Save draft from outgoing session
516
- var _prevSid = store.get('activeSessionId');
517
- if (_prevSid && inputEl.value) {
518
- store.get('sessionDrafts')[_prevSid] = inputEl.value;
519
- } else if (_prevSid) {
520
- delete store.get('sessionDrafts')[_prevSid];
521
- }
522
- store.set({ activeSessionId: msg.id, cliSessionId: msg.cliSessionId || null, vendorCapabilities: msg.capabilities || {}, sessionIsProcessing: !!msg.isProcessing });
523
- if (msg.vendor) {
524
- if (!store.get('vendorSelectionLocked') || msg.hasHistory) {
525
- store.set({ currentVendor: msg.vendor });
526
- }
527
- // Sessions with history have their vendor structurally bound to
528
- // the session: lock so a late-arriving default-adapter model_info
529
- // can't flip the UI back. Previously this branch unlocked, which
530
- // is what allowed the feedback loop in issue #336.
531
- if (msg.hasHistory) {
532
- store.set({ vendorSelectionLocked: true });
533
- }
534
- } else if (msg.hasHistory) {
535
- // Existing session without explicit vendor: reset to claude
536
- store.set({ currentVendor: "claude" });
537
- store.set({ vendorSelectionLocked: false });
538
- } else if (!msg.hasHistory) {
539
- // New session without vendor: no mate vendor lookup needed
540
- }
541
- if (!msg.hasHistory && !msg.vendor) {
542
- // Preserve explicit pre-message vendor choice on brand-new sessions.
543
- }
544
- // Show vendor toggle only for new sessions (no history).
545
- // Agent sessions are Claude Code-only — hide the toggle entirely so
546
- // the user cannot switch an agent session to Codex (which has no
547
- // equivalent agent identity API and would silently drop the persona).
548
- var _vtw = document.getElementById("vendor-toggle-wrap");
549
- if (_vtw) {
550
- if (msg.agentName) {
551
- _vtw.classList.add("hidden");
552
- } else if (msg.hasHistory) {
553
- _vtw.classList.remove("hidden"); _vtw.classList.add("locked");
554
- } else {
555
- _vtw.classList.remove("locked"); _vtw.classList.remove("hidden");
556
- }
557
- }
558
- // Session presence is now tracked server-side (user-presence.json)
559
- clearRemoteCursors();
560
- resetClientState();
561
-
562
- updateLoopInputVisibility(msg.loop);
563
- // Restore input area visibility (may have been hidden by auth_required)
564
- var inputAreaSw = document.getElementById("input-area");
565
- if (inputAreaSw) inputAreaSw.classList.remove("hidden");
566
- // Restore draft for incoming session
567
- var draft = store.get('sessionDrafts')[store.get('activeSessionId')] || "";
568
- inputEl.value = draft;
569
- // Reset the autoResize line-count cache before the rAF so the skip-
570
- // guard never freezes the textarea at the outgoing session's height.
571
- resetAutoResize();
572
- // Defer autoResize to next frame — avoids a forced synchronous layout
573
- // read (scrollHeight) immediately after the DOM write (value =).
574
- requestAnimationFrame(function () { autoResize(); });
575
- if (!("ontouchstart" in window)) {
576
- inputEl.focus();
577
- }
578
- break;
417
+ search_results: handleSearchResults,
579
418
 
580
- case "session_id":
581
- store.set({ cliSessionId: msg.cliSessionId });
582
- 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
+ }
583
572
 
584
- case "message_uuid":
585
- var uuidTarget;
586
- if (msg.messageType === "user") {
587
- var allUsers = messagesEl.querySelectorAll(".msg-user:not([data-uuid])");
588
- if (allUsers.length > 0) uuidTarget = allUsers[allUsers.length - 1];
589
- } else {
590
- var allAssistants = messagesEl.querySelectorAll(".msg-assistant:not([data-uuid])");
591
- 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);
592
588
  }
593
- if (uuidTarget) {
594
- uuidTarget.dataset.uuid = msg.uuid;
595
- if (msg.messageType === "user" && (store.get('vendorCapabilities') || {}).rewind !== false) addRewindButton(uuidTarget);
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);
596
598
  }
597
- store.get('messageUuidMap').push({ uuid: msg.uuid, type: msg.messageType });
598
- break;
599
-
600
- case "user_message":
601
- if (msg._internal) break;
602
- resetThinkingGroup();
603
- if (msg.planContent) {
604
- setPlanContent(msg.planContent);
605
- renderPlanCard(msg.planContent);
606
- 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);
607
- } else {
608
- addUserMessage(msg.text, msg.images || null, msg.pastes || null, msg.from, msg.fromName);
609
- }
610
- break;
611
-
612
- case "plan_content":
613
- setPlanContent(msg.content || "");
614
- renderPlanCard(msg.content || "");
615
- break;
616
-
617
- case "context_preview":
618
- // Show a Context Card with tab screenshot between user message and assistant response
619
- if (msg.tab) {
620
- var card = document.createElement("div");
621
- card.className = "context-card";
622
-
623
- // Header
624
- var header = document.createElement("div");
625
- header.className = "context-card-header";
626
- var icon = document.createElement("span");
627
- icon.className = "context-card-icon";
628
- icon.innerHTML = iconHtml("globe");
629
- header.appendChild(icon);
630
- var label = document.createElement("span");
631
- label.textContent = "Viewing tab";
632
- header.appendChild(label);
633
- card.appendChild(header);
634
-
635
- // Screenshot
636
- if (msg.tab.screenshotUrl) {
637
- var img = document.createElement("img");
638
- img.className = "context-card-screenshot";
639
- img.src = msg.tab.screenshotUrl;
640
- img.loading = "lazy";
641
- img.addEventListener("click", function () { showImageModal(this.src); });
642
- card.appendChild(img);
643
- }
644
-
645
- // Meta: title + domain
646
- var tabTitle = msg.tab.title || "";
647
- var tabDomain = "";
648
- try { tabDomain = new URL(msg.tab.url).hostname; } catch (e) {}
649
- if (tabTitle || tabDomain) {
650
- var meta = document.createElement("div");
651
- meta.className = "context-card-meta";
652
- if (msg.tab.favIconUrl) {
653
- var fav = document.createElement("img");
654
- fav.className = "context-card-favicon";
655
- fav.src = msg.tab.favIconUrl;
656
- fav.width = 14;
657
- fav.height = 14;
658
- fav.onerror = function () { this.style.display = "none"; };
659
- meta.appendChild(fav);
660
- }
661
- var titleEl = document.createElement("span");
662
- titleEl.className = "context-card-title";
663
- titleEl.textContent = tabTitle;
664
- meta.appendChild(titleEl);
665
- if (tabDomain) {
666
- var domainEl = document.createElement("span");
667
- domainEl.className = "context-card-domain";
668
- domainEl.textContent = tabDomain;
669
- meta.appendChild(domainEl);
670
- }
671
- card.appendChild(meta);
672
- }
599
+ card.appendChild(meta);
600
+ }
673
601
 
674
- messagesEl.appendChild(card);
675
- scrollToBottom();
676
- }
677
- break;
678
-
679
- case "status":
680
- if (msg.status === "processing") {
681
- setStatus("processing");
682
- // Session became live — undo any dead-session todo compaction
683
- // applied at history_done time.
684
- store.set({ sessionIsProcessing: true });
685
- applyDeadSessionTodoCompaction();
686
- if (!store.get('dmMode')) {
687
- removePreThinking(); // drop pre-thinking dots before showing activity indicator
688
- setActivity("thinking");
689
- }
690
- }
691
- 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
+ },
692
620
 
693
- case "compacting":
694
- if (msg.active) {
695
- setActivity("compacting");
696
- } else if (!store.get('dmMode')) {
697
- setActivity("thinking");
698
- }
699
- break;
621
+ compacting: function (msg) {
622
+ if (msg.active) {
623
+ setActivity("compacting");
624
+ } else if (!store.get('dmMode')) {
625
+ setActivity("thinking");
626
+ }
627
+ },
700
628
 
701
- case "thinking_start":
702
- removePreThinking();
703
- startThinking();
704
- break;
629
+ thinking_start: function (msg) {
630
+ removePreThinking();
631
+ startThinking();
632
+ },
705
633
 
706
- case "thinking_delta":
707
- if (typeof msg.text === "string") appendThinking(msg.text);
708
- break;
634
+ thinking_delta: function (msg) {
635
+ if (typeof msg.text === "string") appendThinking(msg.text);
636
+ },
709
637
 
710
- case "thinking_stop":
711
- stopThinking(msg.duration);
712
- if (!store.get('dmMode')) {
713
- setActivity("thinking");
714
- }
715
- break;
716
-
717
- case "delta":
718
- if (typeof msg.text !== "string") break;
719
- removePreThinking();
720
- stopThinking();
721
- resetThinkingGroup();
722
- setActivity(null);
723
- appendDelta(msg.text);
724
- break;
725
-
726
- case "tool_start":
727
- removePreThinking();
728
- stopThinking();
729
- markAllToolsDone();
730
- if (msg.name === "EnterPlanMode") {
731
- renderPlanBanner("enter");
732
- getTools()[msg.id] = { el: null, name: msg.name, input: null, done: true, hidden: true };
733
- } else if (msg.name === "ExitPlanMode") {
734
- if (getPlanContent()) {
735
- renderPlanCard(getPlanContent());
736
- }
737
- renderPlanBanner("exit");
738
- getTools()[msg.id] = { el: null, name: msg.name, input: null, done: true, hidden: true };
739
- } else if (msg.name === "ask_user_questions") {
740
- getTools()[msg.id] = { el: null, name: msg.name, input: null, done: true, hidden: true };
741
- } else if (getTodoTools()[msg.name]) {
742
- getTools()[msg.id] = { el: null, name: msg.name, input: null, done: true, hidden: true };
743
- } else {
744
- createToolItem(msg.id, msg.name);
745
- }
746
- break;
747
-
748
- case "tool_executing":
749
- if (msg.name === "AskUserQuestion" && msg.input && msg.input.questions) {
750
- var askTool = getTools()[msg.id];
751
- if (askTool) {
752
- if (askTool.el) askTool.el.style.display = "none";
753
- askTool.done = true;
754
- removeToolFromGroup(msg.id);
755
- }
756
- renderAskUserQuestion(msg.id, msg.input);
757
- startUrgentBlink();
758
- } else if (msg.name === "Write" && msg.input && isPlanFilePath(msg.input.file_path)) {
759
- setPlanContent(msg.input.content || "");
760
- updateToolExecuting(msg.id, msg.name, msg.input);
761
- } else if (msg.name === "Edit" && msg.input && isPlanFilePath(msg.input.file_path)) {
762
- var pc = getPlanContent() || "";
763
- if (msg.input.old_string && pc.indexOf(msg.input.old_string) !== -1) {
764
- if (msg.input.replace_all) {
765
- setPlanContent(pc.split(msg.input.old_string).join(msg.input.new_string || ""));
766
- } else {
767
- setPlanContent(pc.replace(msg.input.old_string, msg.input.new_string || ""));
768
- }
769
- }
770
- updateToolExecuting(msg.id, msg.name, msg.input);
771
- } else if (msg.name === "TodoWrite") {
772
- handleTodoWrite(msg.input);
773
- } else if (msg.name === "TaskCreate") {
774
- handleTaskCreate(msg.input);
775
- } else if (msg.name === "TaskUpdate") {
776
- handleTaskUpdate(msg.input);
777
- } else if (getTodoTools()[msg.name]) {
778
- // TaskList, TaskGet - silently skip
779
- } else {
780
- var t = getTools()[msg.id];
781
- if (t && t.hidden) break;
782
- updateToolExecuting(msg.id, msg.name, msg.input);
783
- }
784
- break;
785
-
786
- case "tool_result": {
787
- var tr = getTools()[msg.id];
788
- if (tr && tr.hidden) break; // skip hidden plan tools
789
- // Always call updateToolResult for Edit (to show diff from input), or when content exists
790
- if (msg.content != null || msg.images || (tr && tr.name === "Edit" && tr.input && tr.input.old_string)) {
791
- updateToolResult(msg.id, msg.content || "", msg.is_error || false, msg.images);
792
- }
793
- // Refresh file browser if an Edit/Write tool modified the open file
794
- if (!msg.is_error && tr && (tr.name === "Edit" || tr.name === "Write") && tr.input && tr.input.file_path) {
795
- refreshIfOpen(tr.input.file_path);
796
- }
797
- }
798
- break;
799
-
800
- case "ask_user_answered":
801
- markAskUserAnswered(msg.toolId, msg.answers);
802
- stopUrgentBlink();
803
- break;
804
-
805
- case "permission_request":
806
- renderPermissionRequest(msg.requestId, msg.toolName, msg.toolInput, msg.decisionReason);
807
- startUrgentBlink();
808
- break;
809
-
810
- case "permission_cancel":
811
- markPermissionCancelled(msg.requestId);
812
- stopUrgentBlink();
813
- break;
814
-
815
- case "permission_resolved":
816
- markPermissionResolved(msg.requestId, msg.decision);
817
- stopUrgentBlink();
818
- break;
819
-
820
- case "permission_request_pending":
821
- renderPermissionRequest(msg.requestId, msg.toolName, msg.toolInput, msg.decisionReason);
822
- startUrgentBlink();
823
- break;
824
-
825
- case "elicitation_request":
826
- renderElicitationRequest(msg);
827
- startUrgentBlink();
828
- break;
829
-
830
- case "elicitation_resolved":
831
- markElicitationResolved(msg.requestId, msg.action);
832
- stopUrgentBlink();
833
- break;
834
-
835
- case "slash_command_result":
836
- finalizeAssistantBlock();
837
- var cmdBlock = document.createElement("div");
838
- cmdBlock.className = "assistant-block";
839
- cmdBlock.style.maxWidth = "var(--content-width)";
840
- cmdBlock.style.margin = "12px auto";
841
- cmdBlock.style.padding = "0 20px";
842
- var pre = document.createElement("pre");
843
- 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";
844
- pre.textContent = msg.text;
845
- cmdBlock.appendChild(pre);
846
- addToMessages(cmdBlock);
847
- scrollToBottom();
848
- break;
849
-
850
- case "subagent_activity":
851
- updateSubagentActivity(msg.parentToolId, msg.text);
852
- break;
853
-
854
- case "subagent_tool":
855
- addSubagentToolEntry(msg.parentToolId, msg.toolName, msg.toolId, msg.text);
856
- break;
857
-
858
- case "subagent_done":
859
- markSubagentDone(msg.parentToolId, msg.status, msg.summary, msg.usage);
860
- break;
861
-
862
- case "task_started":
863
- initSubagentStop(msg.parentToolId, msg.taskId);
864
- break;
865
-
866
- case "task_progress":
867
- updateSubagentProgress(msg.parentToolId, msg.usage, msg.lastToolName, msg.summary);
868
- break;
869
-
870
- case "task_updated":
871
- updateSubagentTaskStatus(msg.parentToolId, msg.patch);
872
- break;
873
-
874
- case "result":
875
- setActivity(null);
876
- stopThinking();
877
- markAllToolsDone();
878
- closeToolGroup();
879
- finalizeAssistantBlock();
880
- addTurnMeta(msg.cost, msg.duration);
881
- accumulateUsage(msg.cost, msg.usage, msg.lastStreamInputTokens);
882
- accumulateContext(msg.cost, msg.usage, msg.modelUsage, msg.lastStreamInputTokens);
883
- break;
884
-
885
- case "context_usage":
886
- if (msg.data && !store.get('replayingHistory')) {
887
- store.set({ richContextUsage: msg.data });
888
- // UI sync handled by store subscriber in app-panels.js
889
- }
890
- break;
891
-
892
- case "done":
893
- removePreThinking();
894
- setActivity(null);
895
- stopThinking();
896
- markAllToolsDone();
897
- closeToolGroup();
898
- finalizeAssistantBlock();
899
- setStatus("connected");
900
- // Re-enable input unless this is one of the loop's own sessions (coder/judge).
901
- // A loop running in a separate session must not suppress input here.
902
- var _doneLoopSid = store.get('loopCurrentSessionId');
903
- if (!store.get('loopActive') || !_doneLoopSid || store.get('activeSessionId') !== _doneLoopSid) {
904
- enableMainInput();
905
- }
906
- resetToolState();
907
- stopUrgentBlink();
908
- if (document.hidden) {
909
- if (isNotifAlertEnabled() && !window._pushSubscription) showDoneNotification();
910
- if (isNotifSoundEnabled()) playDoneSound();
911
- }
912
- break;
913
-
914
- case "stderr":
915
- addSystemMessage(msg.text, false);
916
- break;
917
-
918
- case "error":
919
- removePreThinking();
920
- setActivity(null);
921
- addSystemMessage(msg.text, true);
922
- break;
923
-
924
- case "system_info":
925
- addSystemMessage(msg.text, false);
926
- break;
927
-
928
- case "sdk_notification":
929
- addSystemMessage(msg.text, false);
930
- break;
931
-
932
- case "process_conflict":
933
- removePreThinking();
934
- setActivity(null);
935
- addConflictMessage(msg);
936
- break;
937
-
938
- case "context_overflow":
939
- removePreThinking();
940
- setActivity(null);
941
- addContextOverflowMessage(msg);
942
- break;
943
-
944
- case "auth_required":
945
- removePreThinking();
946
- setActivity(null);
947
- stopThinking();
948
- markAllToolsDone();
949
- closeToolGroup();
950
- appendDelta((msg.text || "Authentication required.") + "\n");
951
- setStatus("connected");
952
- var _authLoopSid = store.get('loopCurrentSessionId');
953
- if (!store.get('loopActive') || !_authLoopSid || store.get('activeSessionId') !== _authLoopSid) {
954
- enableMainInput();
955
- }
956
- break;
957
-
958
- case "rate_limit":
959
- handleRateLimitEvent(msg);
960
- break;
961
-
962
- case "rate_limit_usage":
963
- updateRateLimitUsage(msg);
964
- break;
965
-
966
- case "scheduled_message_queued":
967
- addScheduledMessageBubble(msg.text, msg.resetsAt);
968
- setScheduleBtnDisabled(true);
969
- break;
970
-
971
- case "scheduled_message_sent":
972
- removeScheduledMessageBubble();
973
- setScheduleBtnDisabled(false);
974
- setStatus("processing");
975
- break;
976
-
977
- case "scheduled_message_cancelled":
978
- removeScheduledMessageBubble();
979
- setScheduleBtnDisabled(false);
980
- break;
981
-
982
- case "auto_continue_scheduled":
983
- // Scheduler auto-continue, just show info
984
- break;
985
-
986
- case "auto_continue_fired":
987
- setStatus("processing");
988
- break;
989
-
990
- case "prompt_suggestion":
991
- showSuggestionChips(msg.suggestion);
992
- break;
993
-
994
- case "fast_mode_state":
995
- handleFastModeState(msg.state);
996
- break;
997
-
998
- case "process_killed":
999
- addSystemMessage("Process " + msg.pid + " has been terminated. You can retry your message now.", false);
1000
- break;
1001
-
1002
- case "rewind_preview_result":
1003
- showRewindModal(msg);
1004
- break;
1005
-
1006
- case "rewind_complete":
1007
- onRewindComplete();
1008
- setRewindMode(false);
1009
- var rewindText = "Rewound to earlier point. Files have been restored.";
1010
- if (msg.mode === "chat") rewindText = "Conversation rewound to earlier point.";
1011
- else if (msg.mode === "files") rewindText = "Files restored to earlier point.";
1012
- addSystemMessage(rewindText, false);
1013
- break;
1014
-
1015
- case "rewind_error":
1016
- onRewindError();
1017
- clearPendingRewindUuid();
1018
- addSystemMessage(msg.text || "Rewind failed.", true);
1019
- break;
1020
-
1021
- case "fork_complete":
1022
- addSystemMessage("Session forked successfully.");
1023
- break;
1024
-
1025
- case "fs_list_result":
1026
- handleFsList(msg);
1027
- break;
1028
-
1029
- case "fs_search_result":
1030
- handleFsSearch(msg);
1031
- break;
1032
-
1033
- case "fs_read_result":
1034
- if (msg.path === "CLAUDE.md" && isProjectSettingsOpen()) {
1035
- 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 || ""));
1036
694
  } else {
1037
- handleFsRead(msg);
695
+ setPlanContent(pc.replace(msg.input.old_string, msg.input.new_string || ""));
1038
696
  }
1039
- break;
1040
-
1041
- case "fs_write_result":
1042
- handleInstructionsWrite(msg);
1043
- break;
1044
-
1045
- case "project_env_result":
1046
- handleProjectEnv(msg);
1047
- break;
1048
-
1049
- case "set_project_env_result":
1050
- handleProjectEnvSaved(msg);
1051
- break;
1052
-
1053
- case "global_claude_md_result":
1054
- handleGlobalClaudeMdRead(msg);
1055
- break;
1056
-
1057
- case "write_global_claude_md_result":
1058
- handleGlobalClaudeMdWrite(msg);
1059
- break;
1060
-
1061
- case "shared_env_result":
1062
- handleSharedEnv(msg);
1063
- handleProjectSharedEnv(msg);
1064
- break;
1065
-
1066
- case "set_shared_env_result":
1067
- handleSharedEnvSaved(msg);
1068
- handleProjectSharedEnvSaved(msg);
1069
- break;
1070
-
1071
- case "fs_file_changed":
1072
- handleFileChanged(msg);
1073
- break;
1074
-
1075
- case "fs_dir_changed":
1076
- handleDirChanged(msg);
1077
- break;
1078
-
1079
- case "fs_file_history_result":
1080
- handleFileHistory(msg);
1081
- break;
1082
-
1083
- case "fs_git_diff_result":
1084
- handleGitDiff(msg);
1085
- break;
1086
-
1087
- case "fs_file_at_result":
1088
- handleFileAt(msg);
1089
- break;
1090
-
1091
- case "term_list":
1092
- handleTermList(msg);
1093
- updateTerminalList(msg.terminals);
1094
- break;
1095
-
1096
- case "context_sources_state":
1097
- handleContextSourcesState(msg);
1098
- break;
1099
-
1100
- case "extension_command":
1101
- sendExtensionCommand(msg.command, msg.args, msg.requestId);
1102
- break;
1103
-
1104
- case "mcp_tool_call":
1105
- handleMcpToolCallMessage(msg);
1106
- break;
1107
-
1108
- case "mcp_servers_state":
1109
- handleMcpServersState(msg);
1110
- break;
1111
-
1112
- case "term_created":
1113
- handleTermCreated(msg);
1114
- if (store.get('pendingTermCommand')) {
1115
- var cmd = store.get('pendingTermCommand');
1116
- store.set({ pendingTermCommand: null });
1117
- // Small delay to let terminal initialize
1118
- setTimeout(function() {
1119
- sendTerminalCommand(cmd);
1120
- }, 300);
1121
- }
1122
- break;
1123
-
1124
- case "term_output":
1125
- handleTermOutput(msg);
1126
- break;
1127
-
1128
- case "term_resized":
1129
- handleTermResized(msg);
1130
- break;
1131
-
1132
- case "term_exited":
1133
- handleTermExited(msg);
1134
- break;
1135
-
1136
- case "term_closed":
1137
- handleTermClosed(msg);
1138
- break;
1139
-
1140
- case "notes_list":
1141
- handleNotesList(msg);
1142
- break;
1143
-
1144
- case "note_created":
1145
- handleNoteCreated(msg);
1146
- break;
1147
-
1148
- case "note_updated":
1149
- handleNoteUpdated(msg);
1150
- break;
1151
-
1152
- case "note_deleted":
1153
- handleNoteDeleted(msg);
1154
- break;
1155
-
1156
- case "process_stats":
1157
- updateStatusPanel(msg);
1158
- updateSettingsStats(msg);
1159
- break;
1160
-
1161
- case "browse_dir_result":
1162
- handleBrowseDirResult(msg);
1163
- break;
1164
-
1165
- case "add_project_result":
1166
- handleAddProjectResult(msg);
1167
- break;
1168
-
1169
- case "clone_project_progress":
1170
- handleCloneProgress(msg);
1171
- break;
1172
-
1173
- case "remove_project_result":
1174
- handleRemoveProjectResult(msg);
1175
- break;
1176
-
1177
- case "reorder_projects_result":
1178
- if (!msg.ok) {
1179
- showToast(msg.error || "Failed to reorder projects", "error");
1180
- }
1181
- break;
1182
-
1183
- case "set_project_title_result":
1184
- if (!msg.ok) {
1185
- showToast(msg.error || "Failed to rename project", "error");
1186
- }
1187
- 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
+ },
1188
1024
 
1189
- case "set_project_icon_result":
1190
- if (!msg.ok) {
1191
- showToast(msg.error || "Failed to set icon", "error");
1192
- }
1193
- break;
1025
+ set_project_title_result: function (msg) {
1026
+ if (!msg.ok) {
1027
+ showToast(msg.error || "Failed to rename project", "error");
1028
+ }
1029
+ },
1194
1030
 
1195
- case "set_project_preferred_agent_result":
1196
- if (!msg.ok) {
1197
- showToast(msg.error || "Failed to set preferred agent", "error");
1198
- }
1199
- break;
1031
+ set_project_icon_result: function (msg) {
1032
+ if (!msg.ok) {
1033
+ showToast(msg.error || "Failed to set icon", "error");
1034
+ }
1035
+ },
1200
1036
 
1201
- case "set_project_folder_result":
1202
- if (!msg.ok) {
1203
- showToast(msg.error || "Failed to move project to folder", "error");
1204
- }
1205
- 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
+ },
1206
1042
 
1207
- case "rename_project_folder_result":
1208
- if (!msg.ok) {
1209
- showToast(msg.error || "Failed to rename folder", "error");
1210
- }
1211
- 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
+ },
1212
1048
 
1213
- case "set_folder_icon_result":
1214
- if (!msg.ok) {
1215
- showToast(msg.error || "Failed to set folder icon", "error");
1216
- }
1217
- break;
1218
-
1219
- case "projects_updated":
1220
- updateProjectList(msg);
1221
- break;
1222
-
1223
- case "rename_custom_icon_result":
1224
- handleRenameCustomIconResult(msg);
1225
- break;
1226
-
1227
- case "project_owner_changed":
1228
- store.set({ currentProjectOwnerId: msg.ownerId });
1229
- handleProjectOwnerChanged(msg);
1230
- break;
1231
-
1232
- // --- DM ---
1233
- case "dm_history":
1234
- enterDmMode(msg.dmKey, msg.targetUser, msg.messages);
1235
- break;
1236
-
1237
- case "dm_message":
1238
- if (store.get('dmMode') && msg.dmKey === store.get('dmKey')) {
1239
- showDmTypingIndicator(false); // hide typing when message arrives
1240
- appendDmMessage(msg.message);
1241
- scrollToBottom();
1242
- } else if (msg.message) {
1243
- // DM notification when not in that DM
1244
- var fromId = msg.message.from;
1245
- if (fromId && fromId !== store.get('myUserId')) {
1246
- var _du = Object.assign({}, store.get('dmUnread'));
1247
- _du[fromId] = (_du[fromId] || 0) + 1;
1248
- store.set({ dmUnread: _du });
1249
- // renderUserStrip is handled by the store subscriber
1250
- updateDmBadge(fromId, _du[fromId]);
1251
- }
1252
- }
1253
- break;
1049
+ rename_project_folder_result: function (msg) {
1050
+ if (!msg.ok) {
1051
+ showToast(msg.error || "Failed to rename folder", "error");
1052
+ }
1053
+ },
1254
1054
 
1255
- case "dm_typing":
1256
- if (store.get('dmMode') && msg.dmKey === store.get('dmKey')) {
1257
- showDmTypingIndicator(msg.typing);
1258
- }
1259
- break;
1260
-
1261
- case "dm_list":
1262
- // Could be used for DM list view later
1263
- break;
1264
-
1265
- case "dm_favorites_updated":
1266
- // Track users explicitly removed from favorites
1267
- var _cdf = store.get('cachedDmFavorites');
1268
- if (_cdf && msg.dmFavorites) {
1269
- for (var ri = 0; ri < _cdf.length; ri++) {
1270
- if (msg.dmFavorites.indexOf(_cdf[ri]) === -1) {
1271
- store.get('dmRemovedUsers')[_cdf[ri]] = true;
1272
- }
1273
- }
1274
- }
1275
- // Clear removed flag for users being added back
1276
- if (msg.dmFavorites) {
1277
- for (var ai = 0; ai < msg.dmFavorites.length; ai++) {
1278
- delete store.get('dmRemovedUsers')[msg.dmFavorites[ai]];
1279
- }
1280
- }
1281
- 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 });
1282
1086
  // renderUserStrip is handled by the store subscriber
1283
- break;
1284
-
1285
- // --- @Mention ---
1286
- case "mention_start":
1287
- handleMentionStart(msg);
1288
- break;
1289
-
1290
- case "mention_activity":
1291
- handleMentionActivity(msg);
1292
- break;
1293
-
1294
- case "mention_stream":
1295
- handleMentionStream(msg);
1296
- break;
1297
-
1298
- case "mention_done":
1299
- handleMentionDone(msg);
1300
- break;
1301
-
1302
- case "mention_error":
1303
- handleMentionError(msg);
1304
- if (msg.error) showToast("@Mention: " + msg.error, "error");
1305
- break;
1306
-
1307
- case "mention_user":
1308
- // Finalize current assistant block so mention renders in correct DOM position
1309
- finalizeAssistantBlock();
1310
- renderMentionUser(msg);
1311
- break;
1312
-
1313
- case "mention_response":
1314
- finalizeAssistantBlock();
1315
- renderMentionResponse(msg);
1316
- break;
1317
-
1318
- case "user_mention":
1319
- // User-to-user side conversation entry. Renders for any session viewer
1320
- // (sender's other tabs and the mentioned user, if they are watching the
1321
- // session). On the sender's own tab, the server uses sendToSessionOthers
1322
- // so we never get a duplicate here.
1323
- finalizeAssistantBlock();
1324
- renderUserMention(msg);
1325
- break;
1326
- case "user_mention_error":
1327
- if (msg.error) showToast("@Mention: " + msg.error, "error");
1328
- break;
1329
-
1330
- // --- Team activity ---
1331
- case "team_state": handleTeamState(msg); break;
1332
- case "team_member_update": handleTeamMemberUpdate(msg); break;
1333
- case "team_task_update": handleTeamTaskUpdate(msg); break;
1334
- case "team_message": handleTeamMsg(msg); break;
1335
- case "team_gone": handleTeamGone(msg); break;
1336
-
1337
- case "diagnostic":
1338
- // Diagnostic events from CLI stderr (stage 4/5, lr-8294, epic lr-1a52).
1339
- // Future sources (e.g. settings preflight from stage 5/5 lr-1a26) will
1340
- // also arrive via this same type — the render path must not assume CLI origin.
1341
- addDiagnostic(msg);
1342
- break;
1343
-
1344
- case "daemon_config":
1345
- if (msg.config && msg.config.headless) store.set({ isHeadlessMode: true });
1346
- updateDaemonConfig(msg.config);
1347
- break;
1348
-
1349
- case "set_pin_result":
1350
- handleSetPinResult(msg);
1351
- break;
1352
-
1353
- case "set_keep_awake_result":
1354
- handleKeepAwakeChanged(msg);
1355
- break;
1356
-
1357
- case "keep_awake_changed":
1358
- handleKeepAwakeChanged(msg);
1359
- break;
1360
-
1361
- case "set_auto_continue_result":
1362
- case "auto_continue_changed":
1363
- handleAutoContinueChanged(msg);
1364
- break;
1365
-
1366
- case "refresh_agents_result":
1367
- handleRefreshAgentsResult(msg);
1368
- break;
1369
-
1370
- case "restart_server_result":
1371
- handleRestartResult(msg);
1372
- break;
1373
-
1374
- case "shutdown_server_result":
1375
- handleShutdownResult(msg);
1376
- break;
1377
-
1378
- // --- Ralph Loop ---
1379
- case "loop_available":
1380
- store.set({ loopAvailable: msg.available, loopActive: msg.active, loopIteration: msg.iteration || 0, loopMaxIterations: msg.maxIterations || 20, loopBannerName: msg.name || null });
1381
-
1382
- var _la = store.snap();
1383
- if (_la.loopActive) {
1384
- showLoopBanner(true);
1385
- if (_la.loopIteration > 0) {
1386
- updateLoopBanner(_la.loopIteration, _la.loopMaxIterations, "running");
1387
- }
1388
- // Only lock input if this session is actually a loop session (singleTurn).
1389
- // Other sessions in the project must not be locked by a loop running elsewhere.
1390
- updateLoopInputVisibility(null);
1391
- }
1392
- break;
1393
-
1394
- case "loop_started":
1395
- store.set({ loopActive: true, ralphPhase: "executing", loopIteration: 0, loopMaxIterations: msg.maxIterations, loopBannerName: msg.name || null });
1396
- showLoopBanner(true);
1397
-
1398
- var _lbn = store.get('loopBannerName');
1399
- addSystemMessage((_lbn || "Loop") + " started (max " + msg.maxIterations + " iterations)", false);
1400
- // Do not lock the input here — loop_iteration carries the session ID and will
1401
- // lock only the actual coder/judge session when it becomes active.
1402
- break;
1403
-
1404
- case "loop_iteration":
1405
- store.set({ loopIteration: msg.iteration, loopMaxIterations: msg.maxIterations, loopCurrentSessionId: msg.sessionId || null });
1406
- updateLoopBanner(msg.iteration, msg.maxIterations, "running");
1407
-
1408
- var _libn = store.get('loopBannerName');
1409
- addSystemMessage((_libn || "Loop") + " iteration #" + msg.iteration + " started", false);
1410
- // lr-e31b: The composer stays enabled (not locked) while viewing the
1411
- // loop's own session — updateLoopInputVisibility() already switched
1412
- // it into queue mode so a human message is queued for the next
1413
- // iteration boundary rather than dropped or blocked outright.
1414
- break;
1415
-
1416
- case "loop_judging":
1417
- var _ljs = store.snap();
1418
- store.set({ loopCurrentSessionId: msg.sessionId || _ljs.loopCurrentSessionId });
1419
- updateLoopBanner(_ljs.loopIteration, _ljs.loopMaxIterations, "judging");
1420
- addSystemMessage("Judging iteration #" + msg.iteration + "...", false);
1421
- // lr-e31b: composer stays enabled in queue mode (see loop_iteration above).
1422
- break;
1423
-
1424
- case "loop_verdict":
1425
- addSystemMessage("Judge: " + msg.verdict.toUpperCase() + " - " + (msg.summary || ""), false);
1426
- break;
1427
-
1428
- case "loop_stopping":
1429
- var _lss = store.snap();
1430
- updateLoopBanner(_lss.loopIteration, _lss.loopMaxIterations, "stopping");
1431
- break;
1432
-
1433
- case "loop_finished":
1434
- var _lfbn = store.get('loopBannerName');
1435
- store.set({ loopActive: false, ralphPhase: "done", loopBannerName: null, loopCurrentSessionId: null });
1436
- showLoopBanner(false);
1437
-
1438
- enableMainInput();
1439
- updateLoopInputVisibility(null);
1440
- var loopLabel = _lfbn || "Loop";
1441
- var finishMsg = msg.reason === "pass"
1442
- ? loopLabel + " completed successfully after " + msg.iterations + " iteration(s)."
1443
- : msg.reason === "max_iterations"
1444
- ? loopLabel + " reached maximum iterations (" + msg.iterations + ")."
1445
- : msg.reason === "stopped"
1446
- ? loopLabel + " stopped."
1447
- : loopLabel + " ended with error.";
1448
- addSystemMessage(finishMsg, false);
1449
- break;
1450
-
1451
- case "loop_error":
1452
- addSystemMessage((store.get('loopBannerName') || "Loop") + " error: " + msg.text, true);
1453
- break;
1454
-
1455
- // lr-e31b: server-confirmed queue of human messages awaiting delivery
1456
- // at the next loop iteration boundary.
1457
- case "loop_pending_messages":
1458
- store.set({ loopPendingMessages: msg.messages || [] });
1459
- updateLoopPendingBanner();
1460
- break;
1461
-
1462
- case "loop_message_error":
1463
- addSystemMessage((store.get('loopBannerName') || "Loop") + ": " + msg.text, true);
1464
- break;
1465
-
1466
- // --- Ralph Wizard / Crafting ---
1467
- case "ralph_phase":
1468
- var _rps = { ralphPhase: msg.phase || "idle" };
1469
- if (msg.craftingSessionId) _rps.ralphCraftingSessionId = msg.craftingSessionId;
1470
- if (msg.source !== undefined) _rps.ralphCraftingSource = msg.source;
1471
- store.set(_rps);
1472
- if (msg.wizardData) store.set({ wizardData: msg.wizardData });
1473
-
1474
-
1475
- break;
1476
-
1477
- case "ralph_crafting_started":
1478
- store.set({ ralphPhase: "crafting", ralphCraftingSessionId: msg.sessionId || store.get('activeSessionId'), ralphCraftingSource: msg.source || null });
1479
-
1480
-
1481
- if (msg.source !== "ralph") {
1482
- // Task sessions open in the scheduler calendar window
1483
- 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;
1484
1109
  }
1485
- // Ralph crafting sessions show in session list as part of the loop group
1486
- break;
1487
-
1488
- case "ralph_files_status":
1489
- store.set({ ralphFilesReady: {
1490
- promptReady: msg.promptReady,
1491
- judgeReady: msg.judgeReady,
1492
- bothReady: msg.bothReady,
1493
- } });
1494
- if (msg.bothReady) {
1495
- var _rfs = store.snap();
1496
- if (_rfs.ralphPhase === "crafting" || _rfs.ralphPhase === "approval") {
1497
- store.set({ ralphPhase: "approval" });
1498
- if (_rfs.ralphCraftingSource !== "ralph" || isSchedulerOpen()) {
1499
- // Task crafting in scheduler: switch from crafting chat to detail view showing files
1500
- exitCraftingMode(msg.taskId);
1501
- } else {
1502
- showRalphApprovalBar(true);
1503
- // Auto-show execution modal (one-time) for Ralph source
1504
- if (!store.get('execModalShown') && _rfs.ralphCraftingSource === "ralph") {
1505
- showExecModal();
1506
- }
1507
- }
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();
1508
1307
  }
1509
1308
  }
1510
- updateRalphApprovalStatus();
1511
- updateExecModalStatus();
1512
- break;
1513
-
1514
- case "loop_registry_files_content":
1515
- handleLoopRegistryFiles(msg);
1516
- break;
1517
-
1518
- case "ralph_files_content":
1519
- store.set({ ralphPreviewContent: { prompt: msg.prompt || "", judge: msg.judge || "" } });
1520
- openRalphPreviewModal();
1521
- break;
1522
-
1523
- case "loop_registry_error":
1524
- addSystemMessage("Error: " + msg.text, true);
1525
- break;
1526
-
1527
- // --- Notifications ---
1528
- case "notifications_state":
1529
- handleNotificationsState(msg);
1530
- break;
1531
- case "notification_created":
1532
- handleNotificationCreated(msg);
1533
- break;
1534
- case "notification_dismissed":
1535
- handleNotificationDismissed(msg);
1536
- break;
1537
- case "notification_dismissed_all":
1538
- handleNotificationDismissedAll();
1539
- break;
1540
-
1541
- case "daemon_config_changed":
1542
- updateDaemonConfig(msg);
1543
- break;
1544
-
1545
- case "lite_project_status":
1546
- handleLiteProjectStatus(msg);
1547
- break;
1548
-
1549
- case "lite_enroll_result":
1550
- handleLiteEnrollResult(msg);
1551
- break;
1552
-
1553
- case "lite_unenroll_result":
1554
- handleLiteUnenrollResult(msg);
1555
- break;
1309
+ }
1556
1310
  }
1557
- }
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
+ });