@clagentic/console 1.7.1-beta.1 → 1.8.0-beta.2

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 (46) hide show
  1. package/bin/cli.js +199 -2545
  2. package/lib/build-sha.json +2 -2
  3. package/lib/cli/daemon-launch.js +797 -0
  4. package/lib/cli/ipc-subcommands.js +186 -0
  5. package/lib/cli/menus.js +847 -0
  6. package/lib/cli/net-detect.js +209 -0
  7. package/lib/cli/tui.js +589 -0
  8. package/lib/pages.js +13 -17
  9. package/lib/project-loop.js +10 -2
  10. package/lib/project.js +6 -0
  11. package/lib/public/css/base.css +14 -1
  12. package/lib/public/css/diagnostics.css +15 -0
  13. package/lib/public/css/home-hub.css +32 -15
  14. package/lib/public/css/overlays.css +19 -0
  15. package/lib/public/index.html +12 -11
  16. package/lib/public/manifest.json +1 -1
  17. package/lib/public/modules/app-connection.js +187 -4
  18. package/lib/public/modules/app-history-replay.js +155 -0
  19. package/lib/public/modules/app-home-hub.js +33 -30
  20. package/lib/public/modules/app-messages.js +1245 -1489
  21. package/lib/public/modules/app-notifications.js +4 -4
  22. package/lib/public/modules/command-palette.js +11 -22
  23. package/lib/public/modules/context-sources.js +1 -6
  24. package/lib/public/modules/filebrowser.js +25 -13
  25. package/lib/public/modules/mcp-ui.js +2 -2
  26. package/lib/public/modules/notifications.js +22 -1
  27. package/lib/public/modules/playbook.js +6 -6
  28. package/lib/public/modules/project-settings.js +5 -13
  29. package/lib/public/modules/qrcode.js +2 -2
  30. package/lib/public/modules/relative-time.js +27 -0
  31. package/lib/public/modules/scheduler-history.js +1 -5
  32. package/lib/public/modules/server-settings.js +28 -15
  33. package/lib/public/modules/sidebar-projects.js +1 -1
  34. package/lib/public/modules/sidebar-sessions.js +1 -15
  35. package/lib/public/modules/sidebar.js +3 -3
  36. package/lib/public/modules/utils.js +6 -1
  37. package/lib/public/sw.js +24 -4
  38. package/lib/server-auth.js +48 -2
  39. package/lib/server-settings.js +70 -4
  40. package/lib/server.js +269 -15
  41. package/lib/sessions.js +9 -2
  42. package/lib/smtp.js +6 -6
  43. package/lib/users.js +19 -10
  44. package/lib/worktree.js +73 -1
  45. package/lib/yoke/adapters/codex.js +1 -1
  46. package/package.json +1 -1
@@ -13,6 +13,7 @@ import { isHomeHubVisible } from './app-home-hub.js';
13
13
  import { resetTerminals } from './terminal.js';
14
14
  import { closeDmUserPicker } from './sidebar-users.js';
15
15
  import { openDm } from './app-dm.js';
16
+ import { getPaletteVersion } from './command-palette.js';
16
17
 
17
18
  var reconnectTimer = null;
18
19
  var reconnectDelay = 100;
@@ -20,6 +21,20 @@ var connectTimeoutId = null;
20
21
  var connectOverlay = null;
21
22
  var overlayGraceTimer = null;
22
23
 
24
+ // --- Stale-bundle watchdog (lr-e0ec47) ---
25
+ // A foregrounded mobile PWA can be stuck serving a pre-deploy bundle from
26
+ // the service worker's cache (see sw.js network-first/cache-fallback). If
27
+ // that stale bundle predates a WS/message contract change, the reconnect
28
+ // FSM can wedge on "reconnecting" indefinitely even though the server is
29
+ // reachable. Each reconnect attempt compares the server's currently served
30
+ // version (fetched from /info) against the version this client's own WS
31
+ // handshake last reported running (command-palette's cachedVersion, set
32
+ // from the "info" WS message). A version mismatch that survives several
33
+ // consecutive disconnected reconnect attempts means we are not going to
34
+ // self-heal by reconnecting — force a hard reload to fetch the fresh bundle.
35
+ var STALE_VERSION_THRESHOLD = 3;
36
+ var staleVersionStreak = 0;
37
+
23
38
  // Message types that warrant a visible IO blink. Everything else is
24
39
  // background infrastructure traffic (presence, rate-limit accounting,
25
40
  // cursor relay, session list updates, input echo) that does not need
@@ -46,6 +61,17 @@ var _blinkTypes = {
46
61
  export function initConnection() {
47
62
  connectOverlay = document.getElementById("connect-overlay");
48
63
 
64
+ var signinBtn = document.getElementById("connect-overlay-signin-btn");
65
+ if (signinBtn) {
66
+ signinBtn.addEventListener("click", function () {
67
+ // The session is already gone server-side; reloading re-requests "/"
68
+ // which server.js:519 serves as the login page for an unauthed
69
+ // request. No client-side router exists for auth state (see
70
+ // lib/pages.js), so a full reload is the correct navigation here.
71
+ location.reload();
72
+ });
73
+ }
74
+
49
75
  // --- Reactive UI sync for connected/processing state ---
50
76
  store.subscribe(['connected', 'processing'], function (state, prev) {
51
77
  // Status dot (depends on both connected and processing)
@@ -71,6 +97,12 @@ export function initConnection() {
71
97
  var updPill = document.getElementById("update-pill-wrap");
72
98
  if (updPill) updPill.classList.add("hidden");
73
99
  stopLogoAnimation();
100
+ // Reset any lr-de5fcb Surface-1 "session expired" state left over
101
+ // from a prior unauthenticated episode, now that we're connected.
102
+ var signinBtnReset = document.getElementById("connect-overlay-signin-btn");
103
+ if (signinBtnReset) signinBtnReset.classList.add("hidden");
104
+ var msgElReset = document.getElementById("connect-overlay-msg");
105
+ if (msgElReset) msgElReset.textContent = "Reconnecting to server…";
74
106
  } else {
75
107
  if (sendBtn) sendBtn.disabled = true;
76
108
  // Clear any in-progress replay indicator — history_done won't fire on disconnect.
@@ -156,13 +188,104 @@ function onConnected() {
156
188
  }
157
189
  }
158
190
 
191
+ // handleUnauthenticated (lr-de5fcb Surface 1): the reconnect FSM previously
192
+ // treated a 401 identically to a transient disconnect — it kept showing
193
+ // "reconnecting to server" and silently called location.reload() on the
194
+ // next /info poll, which just re-served the login page. The user perceived
195
+ // an endless reconnect loop with no signal that they needed to log back in.
196
+ // This stops the reconnect machinery outright and swaps the overlay to an
197
+ // explicit "session expired" state with a manual sign-in action, instead of
198
+ // auto-reloading (auto-reload here would immediately re-trigger connect(),
199
+ // which would hit /api/ws-ticket 401 again — a tight loop of its own).
200
+ function handleUnauthenticated() {
201
+ cancelReconnect();
202
+ if (connectTimeoutId) { clearTimeout(connectTimeoutId); connectTimeoutId = null; }
203
+ if (overlayGraceTimer) { clearTimeout(overlayGraceTimer); overlayGraceTimer = null; }
204
+ setStatus("disconnected");
205
+ stopLogoAnimation();
206
+ var msgEl = document.getElementById("connect-overlay-msg");
207
+ if (msgEl) msgEl.textContent = "Session expired — sign in again.";
208
+ var signinBtn = document.getElementById("connect-overlay-signin-btn");
209
+ if (signinBtn) signinBtn.classList.remove("hidden");
210
+ if (connectOverlay) connectOverlay.classList.remove("hidden");
211
+ }
212
+
213
+ // Fetch a short-TTL, single-use WS-upgrade ticket (lr-de5fcb). The session
214
+ // cookie is HttpOnly (unreadable by JS), so the client cannot read the raw
215
+ // session token — it must ask the server for a ticket over a normal
216
+ // authenticated HTTP request instead. This request DOES reliably carry the
217
+ // cookie (it's not a script-initiated WebSocket upgrade), which is exactly
218
+ // the mobile-browser gap this ticket exists to route around: mobile
219
+ // browsers don't reliably attach a SameSite=Lax cookie to the WS handshake
220
+ // itself. Returns { ticket } on success, or { unauthenticated: true } on a
221
+ // 401, or { ticket: null } on any other failure (network hiccup — the
222
+ // upgrade will then rely on the cookie alone, same as before this fix).
223
+ function fetchWsTicket() {
224
+ return fetch("/api/ws-ticket", { credentials: "same-origin" })
225
+ .then(function (res) {
226
+ if (res.status === 401) return { unauthenticated: true };
227
+ if (!res.ok) return { ticket: null };
228
+ return res.json().then(function (data) {
229
+ return { ticket: (data && data.ticket) || null };
230
+ }).catch(function () { return { ticket: null }; });
231
+ })
232
+ .catch(function () { return { ticket: null }; });
233
+ }
234
+
235
+ // Milliseconds to wait before re-verifying a single ws-ticket 401 (lr-e5c1fe).
236
+ var UNAUTH_RETRY_BACKOFF_MS = 400;
237
+
238
+ // lr-e5c1fe: a tab woken from background (visibilitychange / OS resume) can
239
+ // fire its first post-wake fetch before the browser has reattached cookies
240
+ // to outgoing requests — server-auth.js's getMultiUserFromReq() is a pure,
241
+ // synchronous cookie-header lookup with no server-side race of its own, so a
242
+ // 401 on /api/ws-ticket while the session cookie IS still valid can only be
243
+ // a client-side cookie-attachment gap on that one fetch, not a real session
244
+ // expiry. Treating a SINGLE such 401 as terminal showed the full-screen
245
+ // "session expired" wall on a session that "Sign in again" (a bare connect()
246
+ // re-run) then proved was still good. Re-verify once, after a short backoff,
247
+ // before declaring the session gone — only two consecutive 401s (auth
248
+ // actually confirmed absent) route to handleUnauthenticated().
159
249
  export function connect() {
160
250
  var ws = getWs();
161
251
  if (ws) { ws.onclose = null; ws.onmessage = null; ws.onerror = null; ws.close(); }
162
252
  if (connectTimeoutId) { clearTimeout(connectTimeoutId); connectTimeoutId = null; }
163
253
 
254
+ fetchWsTicket().then(function (result) {
255
+ if (result.unauthenticated) {
256
+ setTimeout(function () {
257
+ fetchWsTicket().then(function (retryResult) {
258
+ if (retryResult.unauthenticated) {
259
+ // Two consecutive 401s: auth is confirmed gone, not a transient
260
+ // wake-from-background cookie-attachment gap. Route to sign-in
261
+ // instead of opening a socket that would only 401 on the
262
+ // upgrade too — ties into the Surface-1 unauth-vs-unreachable
263
+ // split below.
264
+ handleUnauthenticated();
265
+ return;
266
+ }
267
+ openSocket(retryResult.ticket);
268
+ });
269
+ }, UNAUTH_RETRY_BACKOFF_MS);
270
+ return;
271
+ }
272
+ openSocket(result.ticket);
273
+ });
274
+ }
275
+
276
+ // openSocket does the actual WebSocket construction. Split out from
277
+ // connect() so the ticket fetch (network round-trip) can complete first
278
+ // without duplicating the onopen/onclose/onmessage wiring.
279
+ function openSocket(ticket) {
280
+ // WS URL is derived strictly from window.location — never from the
281
+ // daemon.js:239-243 LAN/share host resolution (which may prefer a
282
+ // 100.x Tailscale address). Pointing the socket at a different origin
283
+ // than the page was served from would re-introduce a cross-origin
284
+ // session mismatch; same-origin is a load-bearing invariant here, not
285
+ // an incidental default (lr-de5fcb / lr-e0ec47 comment #4).
164
286
  var protocol = location.protocol === "https:" ? "wss:" : "ws:";
165
- var newWs = new WebSocket(protocol + "//" + location.host + store.get('wsPath'));
287
+ var url = protocol + "//" + location.host + store.get('wsPath');
288
+ var newWs = ticket ? new WebSocket(url, ["clagentic.auth." + ticket]) : new WebSocket(url);
166
289
  setWs(newWs);
167
290
 
168
291
  // If not connected within 3s, force retry
@@ -176,10 +299,20 @@ export function connect() {
176
299
  }
177
300
  }, 3000);
178
301
 
302
+ // Track whether this socket ever reached onopen. A upgrade rejected with
303
+ // 401 (server.js:781 area — socket.write + socket.destroy, not a clean WS
304
+ // close frame) closes the browser WebSocket WITHOUT ever firing onopen.
305
+ // That is the only client-observable signal that distinguishes "rejected
306
+ // upgrade" from "connected then dropped" — the close event itself carries
307
+ // no HTTP status (lr-de5fcb Surface 1).
308
+ var everOpened = false;
309
+
179
310
  newWs.onopen = function () {
311
+ everOpened = true;
180
312
  if (connectTimeoutId) { clearTimeout(connectTimeoutId); connectTimeoutId = null; }
181
313
  setStatus("connected");
182
314
  reconnectDelay = 100;
315
+ staleVersionStreak = 0;
183
316
  if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
184
317
 
185
318
  // Wrap ws.send to blink LED on outgoing traffic
@@ -204,6 +337,16 @@ export function connect() {
204
337
  // stale — leaving it would cause the *next* successful session_list (on
205
338
  // any project reconnect) to switch to a wrong session.
206
339
  try { sessionStorage.removeItem("pending-hub-session"); } catch (e) {}
340
+
341
+ // A socket that had a valid ticket AND still never opened means the
342
+ // upgrade itself was rejected as unauthenticated (both the cookie and
343
+ // the fresh ticket failed, or the ticket was already consumed by a
344
+ // racing tab) rather than a reachability problem — don't mask this as
345
+ // an endless "reconnecting to server" spinner (lr-de5fcb Surface 1).
346
+ if (!everOpened && ticket) {
347
+ handleUnauthenticated();
348
+ return;
349
+ }
207
350
  scheduleReconnect();
208
351
  };
209
352
 
@@ -214,6 +357,7 @@ export function connect() {
214
357
  if (!store.get('connected')) {
215
358
  setStatus("connected");
216
359
  reconnectDelay = 100;
360
+ staleVersionStreak = 0;
217
361
  if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
218
362
  }
219
363
 
@@ -238,12 +382,51 @@ export function scheduleReconnect() {
238
382
  reconnectTimer = setTimeout(function () {
239
383
  reconnectTimer = null;
240
384
  // Attempt reconnect immediately — don't block on /info preflight.
241
- // Check auth in parallel: if the server returns 401 while we're trying to
242
- // connect, the WS handshake will fail anyway and we reload then.
385
+ // Check auth in parallel: if the server returns 401 while we're trying
386
+ // to connect, route to the explicit unauthenticated state (lr-de5fcb
387
+ // Surface 1) instead of silently reloading into a fresh reconnect loop.
388
+ // lr-e5c1fe: a single 401 here can be the same transient wake-from-
389
+ // background cookie-attachment gap fetchWsTicket() guards against in
390
+ // connect() — re-verify once before treating it as terminal, so this
391
+ // preflight can't independently fire the sign-in wall on a still-valid
392
+ // session out from under connect()'s own retry.
243
393
  fetch("/info").then(function (res) {
244
- if (res.status === 401) { location.reload(); }
394
+ if (res.status === 401) {
395
+ return new Promise(function (resolve) {
396
+ setTimeout(function () {
397
+ fetch("/info").then(function (retryRes) {
398
+ if (retryRes.status === 401) { handleUnauthenticated(); resolve(null); return; }
399
+ resolve(retryRes.ok ? retryRes.json().catch(function () { return null; }) : null);
400
+ }).catch(function () { resolve(null); });
401
+ }, UNAUTH_RETRY_BACKOFF_MS);
402
+ });
403
+ }
404
+ return res.ok ? res.json().catch(function () { return null; }) : null;
405
+ }).then(function (info) {
406
+ if (info) checkStaleVersion(info);
245
407
  }).catch(function () {});
246
408
  connect();
247
409
  }, reconnectDelay);
248
410
  reconnectDelay = Math.min(reconnectDelay * 1.5, 10000);
249
411
  }
412
+
413
+ // Compare the server's currently-served version (from /info) against the
414
+ // version this client's own WS session last reported running. A mismatch
415
+ // that persists across several consecutive disconnected reconnect attempts
416
+ // means the running bundle predates the current deploy and the SW's
417
+ // registration.update() path has not (yet) replaced it — reload rather than
418
+ // keep retrying a connection whose client code may no longer match the
419
+ // server's message contract (lr-e0ec47).
420
+ function checkStaleVersion(info) {
421
+ if (store.get('connected')) { staleVersionStreak = 0; return; }
422
+ var runningVersion = getPaletteVersion();
423
+ var servedVersion = info && info.version;
424
+ if (!runningVersion || !servedVersion || servedVersion === runningVersion) {
425
+ staleVersionStreak = 0;
426
+ return;
427
+ }
428
+ staleVersionStreak++;
429
+ if (staleVersionStreak >= STALE_VERSION_THRESHOLD) {
430
+ location.reload();
431
+ }
432
+ }
@@ -0,0 +1,155 @@
1
+ // app-history-replay.js - history_meta / history_prepend / history_done
2
+ // Extracted from app-messages.js (lr-4e49 Part 2: 185-case switch -> handler
3
+ // registry). This block was called out in the split task as the sharpest
4
+ // ordering risk: history_meta arms sticky-bottom scroll BEFORE the replay
5
+ // batch runs, and history_done re-evaluates / finalizes it AFTER. Both
6
+ // handlers share no local module state with each other (all state lives in
7
+ // `store` or module-level refs in app-rendering.js / pending-navigate.js),
8
+ // so extracting them verbatim preserves the exact sequencing the client
9
+ // already depends on — nothing here changes call order relative to the
10
+ // original switch.
11
+
12
+ import { store } from './store.js';
13
+ import { renderMarkdown, highlightCodeBlocksBatched, renderMermaidBlocks } from './markdown.js';
14
+ import { getPendingNavigate, peekPendingNavigate } from './pending-navigate.js';
15
+ import { armStickyBottom, disarmStickyBottom, scrollToBottom, finalizeAssistantBlock } from './app-rendering.js';
16
+ import { applyDeadSessionTodoCompaction, markAllToolsDone } from './tools.js';
17
+ import { accumulateContext, updateContextPanel, updateUsagePanel, getSessionUsage } from './app-panels.js';
18
+ import { stopUrgentBlink } from './app-favicon.js';
19
+
20
+ var replayLoadingEl = document.getElementById("replay-loading");
21
+
22
+ // updateHistorySentinel is intentionally NOT imported here: app-header.js
23
+ // imports processMessage from app-messages.js, so an app-history-replay.js
24
+ // -> app-header.js import would close an import cycle back through
25
+ // app-messages.js. The caller (app-messages.js, which already imports
26
+ // app-header.js today) supplies it instead.
27
+ export function handleHistoryMeta(msg, updateHistorySentinelFn) {
28
+ store.set({ historyFrom: msg.from, historyTotal: msg.total, replayingHistory: true });
29
+ if (replayLoadingEl) replayLoadingEl.classList.remove("hidden");
30
+ updateHistorySentinelFn();
31
+ // Arm sticky-bottom at the START of replay so the scroll listener's
32
+ // "user scrolled up" detection is suppressed for the entire history
33
+ // append sequence. Without this, scroll events fired during DOM growth
34
+ // can set isUserScrolledUp=true before history_done's arm fires, leaving
35
+ // the user stranded mid-conversation on resume (especially on mobile).
36
+ // Peek without consuming — getPendingNavigate() is the single consumer
37
+ // in the history_done branch below. Calling getPendingNavigate() here
38
+ // would clear the value before history_done can use it.
39
+ var _metaNav = peekPendingNavigate();
40
+ if (!_metaNav || !(_metaNav.toolId || _metaNav.assistantUuid)) {
41
+ armStickyBottom(5000, true); // force: history replay must scroll to bottom
42
+ }
43
+ }
44
+
45
+ export function handleHistoryDone(msg) {
46
+ var messagesEl = document.getElementById("messages");
47
+ store.set({ replayingHistory: false });
48
+ if (replayLoadingEl) replayLoadingEl.classList.add("hidden");
49
+ // Arm sticky-bottom FIRST so the ResizeObserver is watching before the
50
+ // bulk DOM mutations below (syntax highlighting, mermaid, todo
51
+ // compaction) displace the scroll position. Arming after those writes
52
+ // races the browser's layout resolution and can leave the user stranded
53
+ // mid-conversation. The arm is later re-evaluated and potentially
54
+ // replaced by the nav-target branch below; that branch calls
55
+ // scrollToBottom() and does NOT re-arm, so this early arm is harmless.
56
+ var nav = getPendingNavigate();
57
+ var hasNavTarget = nav && (nav.toolId || nav.assistantUuid);
58
+ if (!hasNavTarget) {
59
+ // Scale the quiet window with history depth. A 20-item threshold
60
+ // (old code) gave identical 2000ms to sessions with 21 and 1000
61
+ // items. The scaled formula gives fast disarm for small sessions
62
+ // and up to 3000ms for very large ones (>=500 events), without
63
+ // a hard ceiling that cuts off still-settling content on mobile.
64
+ var historyLen = store.get('historyTotal') || 0;
65
+ var quietMs = Math.min(Math.max(500, Math.round(historyLen * 2.5)), 3000);
66
+ armStickyBottom(quietMs, true); // force: history replay must scroll to bottom
67
+ }
68
+ // Batched syntax highlight + mermaid pass for the entire replayed
69
+ // transcript. Per-message highlights are skipped during replay
70
+ // (see markdown.js). Uses requestIdleCallback batching to avoid
71
+ // blocking the main thread — the old synchronous highlightCodeBlocks()
72
+ // fired hljs on every code block at once, each triggering a
73
+ // ResizeObserver callback that reset the sticky-bottom quiet timer,
74
+ // keeping the scroll pinned and the UI unresponsive for several
75
+ // seconds on large sessions (especially on mobile). The completion
76
+ // callback re-arms once after all blocks are done.
77
+ if (messagesEl) {
78
+ highlightCodeBlocksBatched(messagesEl, function () {
79
+ if (!store.get('processing')) {
80
+ armStickyBottom(500, true); // force: re-pin after all blocks settle
81
+ }
82
+ });
83
+ renderMermaidBlocks(messagesEl);
84
+ // NOTE: The old 300ms setTimeout re-arm is removed. The batched
85
+ // highlight completion callback above replaces it. The 300ms timer
86
+ // was a workaround for Highlight.js deferred work that no longer
87
+ // applies with the idle-callback batching path.
88
+ }
89
+ // Compact dead-session todo widgets (unfinished items will never
90
+ // resolve — the agent isn't coming back) so they don't anchor
91
+ // visual position mid-page on resume.
92
+ if (!store.get('sessionIsProcessing')) {
93
+ applyDeadSessionTodoCompaction();
94
+ }
95
+ // Hide vendor toggle if session has history (vendor already locked)
96
+ var _hTotal = store.get('historyTotal') || 0;
97
+ var _vtw2 = document.getElementById("vendor-toggle-wrap");
98
+ if (_vtw2 && _hTotal > 0) { _vtw2.classList.remove("hidden"); _vtw2.classList.add("locked"); }
99
+ // Restore cached rich context usage BEFORE updateContextPanel runs
100
+ if (msg.contextUsage) {
101
+ store.set({ richContextUsage: msg.contextUsage });
102
+ }
103
+ // Restore accurate context data from the last result in full history.
104
+ // accumulateContext handles context bar fill; accumulateUsage restores the
105
+ // usage panel's context/cost values. Both assign (not sum) so replay
106
+ // accumulation during history messages is correctly overwritten here.
107
+ if (msg.lastUsage || msg.lastModelUsage) {
108
+ accumulateContext(msg.lastCost, msg.lastUsage, msg.lastModelUsage, msg.lastStreamInputTokens);
109
+ }
110
+ // Restore usage panel from the last result in history.
111
+ // output/cacheWrite are cumulative sums that were accumulated during replay above;
112
+ // we keep them. cost and context come from the last result directly.
113
+ if (msg.lastCost != null) {
114
+ var su = getSessionUsage();
115
+ su.cost = msg.lastCost;
116
+ if (msg.lastStreamInputTokens) su.context = msg.lastStreamInputTokens;
117
+ }
118
+ updateContextPanel();
119
+ updateUsagePanel();
120
+ // Render + finalize any incomplete turn from the replayed history
121
+ var _hs = store.snap();
122
+ if (_hs.currentMsgEl && _hs.currentFullText) {
123
+ var replayContentEl = _hs.currentMsgEl.querySelector(".md-content");
124
+ if (replayContentEl) {
125
+ replayContentEl.innerHTML = renderMarkdown(_hs.currentFullText);
126
+ }
127
+ }
128
+ markAllToolsDone();
129
+ finalizeAssistantBlock();
130
+ stopUrgentBlink();
131
+ // Scroll to tool element if navigating from file edit history.
132
+ // nav/hasNavTarget are declared above (early arm block).
133
+ if (hasNavTarget) {
134
+ // Nav target: discard the early sticky-bottom arm and scroll to element.
135
+ disarmStickyBottom();
136
+ scrollToBottom();
137
+ }
138
+ if (hasNavTarget) {
139
+ requestAnimationFrame(function() {
140
+ // Prefer scrolling to the exact tool element
141
+ var target = nav.toolId ? messagesEl.querySelector('[data-tool-id="' + nav.toolId + '"]') : null;
142
+ if (!target && nav.assistantUuid) {
143
+ target = messagesEl.querySelector('[data-uuid="' + nav.assistantUuid + '"]');
144
+ }
145
+ if (target) {
146
+ // Auto-expand parent tool group if collapsed
147
+ var parentGroup = target.closest(".tool-group");
148
+ if (parentGroup) parentGroup.classList.remove("collapsed");
149
+ target.scrollIntoView({ behavior: "smooth", block: "center" });
150
+ target.classList.add("message-blink");
151
+ setTimeout(function() { target.classList.remove("message-blink"); }, 2000);
152
+ }
153
+ });
154
+ }
155
+ }
@@ -3,9 +3,10 @@
3
3
 
4
4
  import { store } from './store.js';
5
5
  import { getWs } from './ws-ref.js';
6
- import { escapeHtml } from './utils.js';
6
+ import { escapeHtml, relativeTime } from './utils.js';
7
7
  import { switchProject, getCachedProjects, renderProjectList } from './app-projects.js';
8
8
  import { renderProjectIcon, projectIconHtml } from './project-icon.js';
9
+ import { getProjectAbbrev } from './sidebar-projects.js';
9
10
  import { openSchedulerToTab } from './scheduler.js';
10
11
  // playbook imports removed (Quick Start section removed from hub)
11
12
  import { exitDmMode } from './app-dm.js';
@@ -237,6 +238,12 @@ function formatScheduleTime(ts) {
237
238
  // renderProjectList() / app-projects.js and rendered as
238
239
  // .icon-strip-project-badge.has-unread / .hub-project-sessions elsewhere).
239
240
  // No separate alert data path — this is a read of the existing cache.
241
+ //
242
+ // This remains the PROJECT-LEVEL aggregate, intentionally — it still backs
243
+ // the Projects-list badge. It is NOT used for the Recent Sessions per-row
244
+ // dot below; that now keys off each session's own sess.unread (lr-0aa7b6),
245
+ // carried end-to-end from lib/server.js's per-session crossProjectUnread
246
+ // restructure through lib/project-loop.js's hub_recent_sessions_list.
240
247
  function projectHasAlert(projectSlug) {
241
248
  if (!projectSlug) return false;
242
249
  var projects = getCachedProjects();
@@ -248,20 +255,6 @@ function projectHasAlert(projectSlug) {
248
255
  return false;
249
256
  }
250
257
 
251
- function formatRelativeTime(ts) {
252
- if (!ts) return "";
253
- var diff = Date.now() - ts;
254
- var m = Math.floor(diff / 60000);
255
- if (m < 1) return "just now";
256
- if (m < 60) return m + "m ago";
257
- var h = Math.floor(m / 60);
258
- if (h < 24) return h + "h ago";
259
- var d = Math.floor(h / 24);
260
- if (d === 1) return "yesterday";
261
- if (d < 7) return d + "d ago";
262
- return Math.floor(d / 7) + "w ago";
263
- }
264
-
265
258
  export function renderHomeHub(projects) {
266
259
  // Greeting + weather tooltip
267
260
  updateGreetingWeather();
@@ -465,29 +458,39 @@ export function handleHubRecentSessions(msg) {
465
458
  sessions.forEach(function (sess) {
466
459
  var item = document.createElement("div");
467
460
  item.className = "hub-recent-item";
468
- // projectIconHtml() routes custom (:slug:) icons to a safe <img> tag and
469
- // emoji to escaped text, replacing the raw escapeHtml(sess.projectIcon)
470
- // which showed ':slug:' as literal text (lr-a6da).
461
+ // projectIconHtml() -> safe <img>/escaped text (lr-a6da). No icon ->
462
+ // getProjectAbbrev() fallback, matching sidebar-projects.js /
463
+ // sidebar-mobile.js, instead of a blank slot (lr-e5faff).
471
464
  var iconHtml = sess.projectIcon
472
465
  ? '<span class="hub-recent-project-icon">' + projectIconHtml(sess.projectIcon) + '</span>'
473
- : '<span class="hub-recent-project-icon hub-recent-project-icon--blank"></span>';
474
- var timeStr = formatRelativeTime(sess.lastActivity);
466
+ : '<span class="hub-recent-project-icon hub-recent-project-icon--abbrev">' +
467
+ escapeHtml(getProjectAbbrev(sess.projectTitle || sess.projectSlug)) + '</span>';
468
+ var timeStr = relativeTime(sess.lastActivity);
475
469
  var agentBadge = sess.agentName
476
470
  ? '<span class="hub-recent-agent">' + escapeHtml(sess.agentName) + '</span>'
477
471
  : '';
478
- var dotClass = "hub-recent-dot" + (sess.isProcessing ? " processing" : "");
479
- // Alert indicator: reuse the same per-project unread count that drives
480
- // the Projects-list badge (icon-strip-project-badge / hub-project-*),
481
- // rather than a new data path. A count won't fit this row, so render a
482
- // plain dot when the row's project has 1+ unresolved (unread) items.
483
- var alertHtml = projectHasAlert(sess.projectSlug)
484
- ? '<span class="hub-recent-alert-dot" title="Unread activity"></span>'
485
- : '';
472
+ // Single left status dot — color precedence LOCKED (andy, lr-0aa7b6):
473
+ // alert(red) > processing(green, pulsing) > live(green) > idle(grey).
474
+ // Alert wins over an active/processing session so the notification is
475
+ // always visible. Previously alert rendered as a SEPARATE right-side dot
476
+ // (.hub-recent-alert-dot); that's removed — alert is now just another
477
+ // color state of the one left dot.
478
+ //
479
+ // Alert state is keyed on THIS session's own unread count (sess.unread,
480
+ // populated server-side per-session — see hub_recent_sessions_list in
481
+ // lib/project-loop.js) — NOT the whole-project alert helper above. That
482
+ // per-project helper would light every sibling row in a notifying
483
+ // project's session list even when only one of them is actually
484
+ // notifying — that was the bug lr-0aa7b6 required fixing, not just
485
+ // documenting.
486
+ var hasAlert = (sess.unread || 0) > 0;
487
+ var dotClass = "hub-recent-dot" +
488
+ (hasAlert ? " alert" : (sess.isProcessing ? " processing" : ""));
489
+ var dotTitle = hasAlert ? "Unread activity" : (sess.isProcessing ? "Active" : "Idle");
486
490
  item.innerHTML =
487
- '<span class="' + dotClass + '"></span>' +
491
+ '<span class="' + dotClass + '" title="' + dotTitle + '"></span>' +
488
492
  iconHtml +
489
493
  '<span class="hub-recent-title">' + escapeHtml(sess.title) + '</span>' +
490
- alertHtml +
491
494
  agentBadge +
492
495
  '<span class="hub-recent-time">' + timeStr + '</span>';
493
496
  item.addEventListener("click", function () {