@clagentic/console 1.7.0-beta.1 → 1.7.1-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.
@@ -0,0 +1,4 @@
1
+ {
2
+ "sha": "c9d70891483d21fe59b0e73e3bed2fad1a443cb9",
3
+ "writtenAt": "2026-07-16T12:31:21.232Z"
4
+ }
package/lib/daemon.js CHANGED
@@ -564,12 +564,21 @@ var relay = createServer({
564
564
  for (var pi = 0; pi < config.projects.length; pi++) {
565
565
  if (config.projects[pi].slug === wtParent) { parentProject = config.projects[pi]; break; }
566
566
  }
567
- if (parentProject) {
568
- var rmResult = removeWorktree(parentProject.path, wtDirName);
569
- if (!rmResult.ok) {
570
- console.log("[daemon] Failed to remove worktree:", slug, rmResult.error);
571
- return { ok: false, error: rmResult.error };
572
- }
567
+ if (!parentProject) {
568
+ // Parent project is gone from config (removed/renamed) — we cannot
569
+ // resolve the worktree's on-disk path, so `git worktree remove` never
570
+ // runs and the checkout stays on disk. Surface this as a failure
571
+ // instead of silently reporting success (lr-fc2818): previously this
572
+ // branch fell through to relay.removeProject/unregisterWorktreeSlug
573
+ // and returned {ok:true}, unregistering the slug while leaving the
574
+ // worktree directory and branch behind with no way to retry from the UI.
575
+ console.log("[daemon] Cannot remove worktree, parent project not found:", slug);
576
+ return { ok: false, error: "Parent project not found; worktree left on disk. Remove it manually with 'git worktree remove'." };
577
+ }
578
+ var rmResult = removeWorktree(parentProject.path, wtDirName);
579
+ if (!rmResult.ok) {
580
+ console.log("[daemon] Failed to remove worktree:", slug, rmResult.error);
581
+ return { ok: false, error: rmResult.error };
573
582
  }
574
583
  relay.removeProject(slug);
575
584
  unregisterWorktreeSlug(wtParent, slug);
@@ -111,6 +111,15 @@ function shedMemory(opts) {
111
111
 
112
112
  var sessionsTrimmed = 0;
113
113
  var sessionsEvicted = 0;
114
+ // lr-f36626: sessions force-evicted while carrying a live registered
115
+ // background child (session.activeTaskToolIds non-empty at eviction time).
116
+ // forceEvictToLimit only ever unloads in-heap history for these — it never
117
+ // closes queryInstance, so the child itself is never killed — but the
118
+ // operator still needs to know pressure reached as far as a live dispatch,
119
+ // per lr-f36626's "never a silent orphan" requirement. Each entry carries
120
+ // the project's send()/sendAndRecord so the per-session notification below
121
+ // can run after the loop, once beforeBytes/afterBytes are both known.
122
+ var liveChildReclaims = [];
114
123
 
115
124
  for (var pi = 0; pi < projects.length; pi++) {
116
125
  var proj = projects[pi];
@@ -135,10 +144,21 @@ function shedMemory(opts) {
135
144
  try {
136
145
  // 2. Force-evict beyond the normal LRU limit down to a pressure limit,
137
146
  // still skipping the active session (forceEvictToLimit's own
138
- // invariant, shared with the routine LRU path).
147
+ // invariant, shared with the routine LRU path). Live-child sessions
148
+ // are only reached as a last resort within forceEvictToLimit itself
149
+ // (pass 2) — see its header in lib/sessions.js.
139
150
  if (typeof sm.forceEvictToLimit === 'function' && typeof sm.LRU_HISTORY_LIMIT === 'number') {
140
151
  var pressureLimit = Math.max(1, Math.floor(sm.LRU_HISTORY_LIMIT * PRESSURE_LRU_FRACTION));
141
- sessionsEvicted += sm.forceEvictToLimit(pressureLimit);
152
+ var evictResult = sm.forceEvictToLimit(pressureLimit);
153
+ sessionsEvicted += evictResult.evicted;
154
+ for (var rci = 0; rci < evictResult.reclaimedLiveChild.length; rci++) {
155
+ liveChildReclaims.push({
156
+ session: evictResult.reclaimedLiveChild[rci],
157
+ sm: sm,
158
+ send: proj.send,
159
+ slug: proj.slug,
160
+ });
161
+ }
142
162
  }
143
163
  } catch (e) {
144
164
  // Same isolation as above — one project's failure does not block others.
@@ -169,6 +189,7 @@ function shedMemory(opts) {
169
189
  sessionsTrimmed: sessionsTrimmed,
170
190
  sessionsEvicted: sessionsEvicted,
171
191
  cachesDropped: cachesDropped,
192
+ liveChildReclaimed: liveChildReclaims.length,
172
193
  };
173
194
 
174
195
  _log(Object.assign({
@@ -179,6 +200,9 @@ function shedMemory(opts) {
179
200
  // 4. UI diagnostic — session-independent, project-scoped broadcast (same
180
201
  // delivery path as settings-preflight's diagnostics: plain send(), not
181
202
  // sendAndRecord, since this has no session to attach to and is ephemeral).
203
+ // Fires for every shedding pass, live-child reclaim or not — this is the
204
+ // routine "memory pressure occurred" signal, distinct from the per-session
205
+ // reclaim notification below.
182
206
  var deltaBytes = beforeBytes - afterBytes;
183
207
  var diagnostic = {
184
208
  type: 'diagnostic',
@@ -196,6 +220,61 @@ function shedMemory(opts) {
196
220
  }
197
221
  }
198
222
 
223
+ // 5. lr-f36626: per-session notification + durable AUTO-RESUME marker for
224
+ // every session force-evicted while a live background child was
225
+ // registered. This is the ONLY reap-adjacent path allowed to reclaim a
226
+ // live-child session (the idle reaper in sdk-bridge.js now refuses to —
227
+ // see the lastActivityAt bump on subagent stream events in
228
+ // sdk-message-processor.js), and per spec it must never do so silently:
229
+ // - session.pendingAutoResume=true is a durable flag (persisted via
230
+ // sm.saveSessionFile) so a later reconnect / session-list read can
231
+ // drive a console-initiated AUTO-RESUME of that session — the "durable
232
+ // checkpoint" is the on-disk session file itself (source of truth is
233
+ // already disk per lr-2ea2a7; this eviction never touched it) plus
234
+ // this marker recording WHY a resume is expected.
235
+ // - Diagnostics panel: same broadcast diagnostic path as step 4, one
236
+ // entry per reclaimed session, source 'memory-reclaim' so it reads
237
+ // distinctly from the routine pressure diagnostic above.
238
+ // - Inline red chat marker: sendAndRecord'd into the affected session's
239
+ // own history via the existing type:"error" -> addSystemMessage(...,
240
+ // true) render path (sys-msg.error) — zero new frontend code, and it
241
+ // replays correctly on reconnect like any other history entry.
242
+ for (var li = 0; li < liveChildReclaims.length; li++) {
243
+ var reclaim = liveChildReclaims[li];
244
+ var rSession = reclaim.session;
245
+ if (!rSession) continue;
246
+ try {
247
+ rSession.pendingAutoResume = true;
248
+ rSession.pendingAutoResumeReason = 'memory_pressure_reclaim';
249
+ if (reclaim.sm && typeof reclaim.sm.saveSessionFile === 'function') {
250
+ reclaim.sm.saveSessionFile(rSession);
251
+ }
252
+ } catch (e) {
253
+ // Marker persistence failing must not block the notification below —
254
+ // the operator still needs to see the reclaim happened.
255
+ }
256
+
257
+ var reclaimMessage = 'Memory pressure reclaimed this session while a background task was still running. '
258
+ + 'It will auto-resume; if it does not, resume it manually.';
259
+
260
+ if (reclaim.send) {
261
+ try {
262
+ reclaim.send({
263
+ type: 'diagnostic',
264
+ severity: 'warning',
265
+ source: 'memory-reclaim',
266
+ message: (reclaim.slug ? '[' + reclaim.slug + '] ' : '') + reclaimMessage,
267
+ });
268
+ } catch (e) { /* one client's send failure must not block others */ }
269
+ }
270
+
271
+ if (reclaim.sm && typeof reclaim.sm.sendAndRecord === 'function') {
272
+ try {
273
+ reclaim.sm.sendAndRecord(rSession, { type: 'error', text: reclaimMessage });
274
+ } catch (e) { /* inline marker failing must not block the rest of the pass */ }
275
+ }
276
+ }
277
+
199
278
  return summary;
200
279
  }
201
280
 
@@ -196,6 +196,19 @@ function attachConnection(ctx) {
196
196
  active.ownerId = wsUser.id;
197
197
  sm.saveSessionFile(active);
198
198
  }
199
+ // lr-f36626: console-driven AUTO-RESUME for a session that was force-
200
+ // evicted under memory pressure while it had a live background child
201
+ // (see lib/memory-shed.js's liveChildReclaims handling). The eviction
202
+ // itself never killed queryInstance — the child kept running — so
203
+ // "resume" here means: this is the first console reconnect since the
204
+ // reclaim, the durable checkpoint (the on-disk session file, already
205
+ // reloaded by loadSessionHistory above) is what the operator sees, and
206
+ // the flag is cleared so this fires exactly once, not on every
207
+ // subsequent reconnect to the same session.
208
+ if (active.pendingAutoResume) {
209
+ active.pendingAutoResume = false;
210
+ sm.saveSessionFile(active);
211
+ }
199
212
  // lr-2ea2a7: hasHistory uses the ABSOLUTE count (_historyBaseIndex +
200
213
  // heap length), not the raw heap length — with a bounded tail-loaded
201
214
  // session the heap length alone is still correct here (a session with
@@ -1441,6 +1441,10 @@ function attachLoop(ctx) {
1441
1441
  for (var di = 0; di < sessionIds.length; di++) {
1442
1442
  sm.deleteSessionQuiet(sessionIds[di]);
1443
1443
  }
1444
+ // lr-0827ba (PEACHES follow-up): notify clients of exactly which
1445
+ // sessions were deleted so per-session client state (rate-limit-state.js)
1446
+ // can be pruned instead of leaking a background timer forever.
1447
+ if (sessionIds.length > 0) sm.broadcastSessionDeleted(sessionIds);
1444
1448
  loopRegistry.remove(loopIdToDel);
1445
1449
  sm.broadcastSessionList();
1446
1450
  return true;
@@ -1538,10 +1538,16 @@ function attachSessions(ctx) {
1538
1538
  moveAllSchedulesToProject(removeSlug, msg.moveTasksTo);
1539
1539
  }
1540
1540
  if (typeof opts.onRemoveProject === "function") {
1541
- // Send result before removing so the WS is still open
1542
- sendTo(ws, { type: "remove_project_result", ok: true, slug: removeSlug });
1541
+ // onRemoveProject is synchronous (git worktree remove runs via
1542
+ // execFileSync) — call it first and forward its actual result.
1543
+ // Previously this sent {ok:true} unconditionally before calling
1544
+ // onRemoveProject, so a real failure (e.g. dirty/locked worktree
1545
+ // returned by removeWorktree) was silently discarded: the client
1546
+ // was told removal succeeded while the worktree stayed on disk
1547
+ // (lr-fc2818).
1543
1548
  var removeUserId = ws._clayUser ? ws._clayUser.id : null;
1544
- opts.onRemoveProject(removeSlug, removeUserId);
1549
+ var removeResult = opts.onRemoveProject(removeSlug, removeUserId) || {};
1550
+ sendTo(ws, { type: "remove_project_result", ok: removeResult.ok !== false, slug: removeSlug, error: removeResult.error });
1545
1551
  } else {
1546
1552
  sendTo(ws, { type: "remove_project_result", ok: false, error: "Not supported" });
1547
1553
  }
package/lib/project.js CHANGED
@@ -689,6 +689,7 @@ function createProjectContext(opts) {
689
689
  text: text,
690
690
  resetsAt: sendsAt,
691
691
  scheduledAt: Date.now(),
692
+ localId: session.localId,
692
693
  };
693
694
  sm.sendAndRecord(session, schedEntry);
694
695
  session.scheduledMessage = {
@@ -698,7 +699,7 @@ function createProjectContext(opts) {
698
699
  session.scheduledMessage = null;
699
700
  if (session.destroying) return;
700
701
  console.log("[project] Scheduled message firing for session " + session.localId);
701
- sm.sendAndRecord(session, { type: "scheduled_message_sent" });
702
+ sm.sendAndRecord(session, { type: "scheduled_message_sent", localId: session.localId });
702
703
  var schedUserMsg = { type: "user_message", text: text, _ts: Date.now() };
703
704
  // lr-2ea2a7: routes through the shared history-cap helper (see grep-guard test).
704
705
  sm.recordHistoryEntry(session, schedUserMsg, true);
@@ -719,7 +720,7 @@ function createProjectContext(opts) {
719
720
  clearTimeout(session.scheduledMessage.timer);
720
721
  session.scheduledMessage = null;
721
722
  session.rateLimitAutoContinuePending = false;
722
- sm.sendAndRecord(session, { type: "scheduled_message_cancelled" });
723
+ sm.sendAndRecord(session, { type: "scheduled_message_cancelled", localId: session.localId });
723
724
  }
724
725
  }
725
726
 
@@ -251,11 +251,19 @@
251
251
  border-radius: 10px;
252
252
  box-shadow: 0 4px 20px rgba(var(--shadow-rgb), 0.3);
253
253
  min-width: 280px;
254
- max-width: 400px;
254
+ /* lr-fab390: the container is right:8px from the viewport edge, so the
255
+ box's available width is capped at (100vw - 16px) — clamp max-width to
256
+ whichever is smaller than the 400px intent so the box can never be
257
+ pushed past the right edge on a narrow/zoomed desktop viewport. The
258
+ min-width:280px floor is unchanged; it still fits down to ~296px
259
+ viewports, matching the mobile breakpoint below which the container
260
+ itself switches to a full-width layout. */
261
+ max-width: min(400px, calc(100vw - 16px));
255
262
  padding: 10px 14px;
256
263
  display: flex;
257
264
  flex-direction: column;
258
265
  gap: 4px;
266
+ box-sizing: border-box;
259
267
  }
260
268
  .toast-diagnostic.visible {
261
269
  opacity: 1;
@@ -324,6 +332,11 @@
324
332
  font-size: 12.5px;
325
333
  color: var(--text-secondary);
326
334
  line-height: 1.5;
335
+ /* lr-fab390: mirrors the mobile overflow-wrap:anywhere fix (lr-4ef618,
336
+ below) — word-break:break-word alone does not break long unbreakable
337
+ tokens (hook event names, absolute paths), letting them force the
338
+ flex child's intrinsic width past the container's right edge. */
339
+ overflow-wrap: anywhere;
327
340
  word-break: break-word;
328
341
  }
329
342
 
@@ -497,6 +497,16 @@
497
497
  text-align: center;
498
498
  flex-shrink: 0;
499
499
  }
500
+ /* Per-project alert indicator — same red used by .icon-strip-project-badge
501
+ (unread badge). A count wouldn't fit this row, so a plain dot is enough
502
+ to show WHERE the alert is coming from. */
503
+ .hub-recent-alert-dot {
504
+ width: 6px;
505
+ height: 6px;
506
+ border-radius: 50%;
507
+ flex-shrink: 0;
508
+ background: #e74c3c;
509
+ }
500
510
  .hub-recent-project-icon--blank {
501
511
  width: 20px;
502
512
  height: 20px;
@@ -232,6 +232,22 @@ function formatScheduleTime(ts) {
232
232
  return DAY_NAMES[d.getDay()] + " " + timeStr;
233
233
  }
234
234
 
235
+ // Looks up whether a project has unresolved alerts, using the SAME source
236
+ // that drives the Projects-list unread badge (proj.unread, populated in
237
+ // renderProjectList() / app-projects.js and rendered as
238
+ // .icon-strip-project-badge.has-unread / .hub-project-sessions elsewhere).
239
+ // No separate alert data path — this is a read of the existing cache.
240
+ function projectHasAlert(projectSlug) {
241
+ if (!projectSlug) return false;
242
+ var projects = getCachedProjects();
243
+ for (var i = 0; i < projects.length; i++) {
244
+ if (projects[i].slug === projectSlug) {
245
+ return (projects[i].unread || 0) > 0;
246
+ }
247
+ }
248
+ return false;
249
+ }
250
+
235
251
  function formatRelativeTime(ts) {
236
252
  if (!ts) return "";
237
253
  var diff = Date.now() - ts;
@@ -460,10 +476,18 @@ export function handleHubRecentSessions(msg) {
460
476
  ? '<span class="hub-recent-agent">' + escapeHtml(sess.agentName) + '</span>'
461
477
  : '';
462
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
+ : '';
463
486
  item.innerHTML =
464
487
  '<span class="' + dotClass + '"></span>' +
465
488
  iconHtml +
466
489
  '<span class="hub-recent-title">' + escapeHtml(sess.title) + '</span>' +
490
+ alertHtml +
467
491
  agentBadge +
468
492
  '<span class="hub-recent-time">' + timeStr + '</span>';
469
493
  item.addEventListener("click", function () {
@@ -44,7 +44,7 @@ import { updateProjectList, resetClientState, showUpdateAvailable, handleRemoveP
44
44
  import { updateHistorySentinel, prependOlderHistory } from './app-header.js';
45
45
  import { hideHomeHub, handleHubSchedules, handleHubRecentSessions } from './app-home-hub.js';
46
46
  import { openDm, enterDmMode, exitDmMode, appendDmMessage, showDmTypingIndicator } from './app-dm.js';
47
- import { handleRateLimitEvent, updateRateLimitUsage, addScheduledMessageBubble, removeScheduledMessageBubble, handleFastModeState } from './app-rate-limit.js';
47
+ import { handleRateLimitEvent, updateRateLimitUsage, addScheduledMessageBubble, removeScheduledMessageBubble, clearScheduledMessage, handleFastModeState, restoreRateLimitStateForSession, forgetSessionRateLimitState } from './app-rate-limit.js';
48
48
  import { handleRemoteCursorMove, handleRemoteCursorLeave, handleRemoteSelection, clearRemoteCursors } from './app-cursors.js';
49
49
  import { showLoopBanner, updateLoopBanner, updateLoopInputVisibility, updateLoopPendingBanner, showRalphApprovalBar, updateRalphApprovalStatus, openRalphPreviewModal, showExecModal, updateExecModalStatus } from './app-loop-ui.js';
50
50
  import { handleSkillInstallWs } from './app-skills-install.js';
@@ -435,6 +435,18 @@ export function processMessage(msg) {
435
435
  if (!store.get('dmMode')) handleInputSync(msg.text);
436
436
  break;
437
437
 
438
+ case "session_deleted":
439
+ // lr-0827ba (PEACHES follow-up): a session was actually deleted (not
440
+ // merely switched away from) — prune its per-session rate-limit /
441
+ // scheduled-message arming state, canceling any background reset
442
+ // timer, instead of leaking it forever. session_list alone never
443
+ // told the client WHICH id(s) disappeared, so nothing could target
444
+ // this cleanup before this message existed.
445
+ (msg.ids || []).forEach(function (deletedId) {
446
+ forgetSessionRateLimitState(deletedId);
447
+ });
448
+ break;
449
+
438
450
  case "session_list":
439
451
  renderSessionList(msg.sessions || []);
440
452
  handlePaletteSessionSwitch();
@@ -558,6 +570,11 @@ export function processMessage(msg) {
558
570
  // Session presence is now tracked server-side (user-presence.json)
559
571
  clearRemoteCursors();
560
572
  resetClientState();
573
+ // lr-0827ba: redraw the incoming session's own armed rate-limit /
574
+ // scheduled-message state (arming happens per-session in the
575
+ // background regardless of focus — see rate-limit-state.js) instead
576
+ // of relying on chat-history replay to happen to repaint it.
577
+ restoreRateLimitStateForSession(store.get('activeSessionId'));
561
578
 
562
579
  updateLoopInputVisibility(msg.loop);
563
580
  // Restore input area visibility (may have been hidden by auth_required)
@@ -964,19 +981,23 @@ export function processMessage(msg) {
964
981
  break;
965
982
 
966
983
  case "scheduled_message_queued":
967
- addScheduledMessageBubble(msg.text, msg.resetsAt);
968
- setScheduleBtnDisabled(true);
984
+ // lr-0827ba: msg.localId identifies the session this schedule
985
+ // actually belongs to — may not be the currently focused session.
986
+ addScheduledMessageBubble(msg.text, msg.resetsAt, msg.localId);
987
+ if (msg.localId == null || msg.localId === store.get('activeSessionId')) setScheduleBtnDisabled(true);
969
988
  break;
970
989
 
971
990
  case "scheduled_message_sent":
972
- removeScheduledMessageBubble();
973
- setScheduleBtnDisabled(false);
974
- setStatus("processing");
991
+ clearScheduledMessage(msg.localId);
992
+ if (msg.localId == null || msg.localId === store.get('activeSessionId')) {
993
+ setScheduleBtnDisabled(false);
994
+ setStatus("processing");
995
+ }
975
996
  break;
976
997
 
977
998
  case "scheduled_message_cancelled":
978
- removeScheduledMessageBubble();
979
- setScheduleBtnDisabled(false);
999
+ clearScheduledMessage(msg.localId);
1000
+ if (msg.localId == null || msg.localId === store.get('activeSessionId')) setScheduleBtnDisabled(false);
980
1001
  break;
981
1002
 
982
1003
  case "auto_continue_scheduled":
@@ -6,22 +6,37 @@ import { store } from './store.js';
6
6
  import { getWs } from './ws-ref.js';
7
7
  import { addToMessages, scrollToBottom } from './app-rendering.js';
8
8
  import { userAvatarUrl } from './avatar.js';
9
- import { setScheduleDelayMs, clearScheduleDelay } from './input.js';
9
+ import { clearScheduleDelay, setScheduleDelayForSession, clearScheduleDelayForSession, restoreScheduleDelayUi } from './input.js';
10
10
  import { isSonnetModel, isOpusModel } from './settings-defaults.js';
11
+ import {
12
+ getRateLimitResetsAt, setRateLimitResetsAt,
13
+ getRateLimitResetTimer, setRateLimitResetTimer,
14
+ getRateLimitResetState,
15
+ setScheduledMsg, clearScheduledMsg, getScheduledMsg,
16
+ clearSession as clearSessionRateLimitState,
17
+ } from './rate-limit-state.js';
11
18
 
12
19
  // --- Module-owned state ---
20
+ // lr-0827ba: rateLimitResetsAt / rateLimitResetTimer / rateLimitResetState /
21
+ // the scheduled-message bubble text are now owned per-session by
22
+ // rate-limit-state.js (see imports above) — arming one project's rate-limit
23
+ // auto-schedule no longer clobbers another project's armed state. The
24
+ // variables below remain module-scoped because they are references to the
25
+ // single visible DOM element/timer for whichever session is currently
26
+ // focused; they get rebuilt/rebound whenever the focused session changes.
13
27
  var rateLimitCountdownTimer = null;
14
28
  var rateLimitIndicatorEl = null;
15
- var rateLimitResetsAt = null;
16
- var rateLimitResetTimer = null;
17
29
  var rateLimitUsageEl = null;
18
- var rateLimitResetState = {};
19
30
  var rateLimitTickTimer = null;
20
31
  var _rateLimitUsageLastHtml = null; // guard against redundant innerHTML + refreshIcons()
21
32
  var scheduledMsgEl = null;
22
33
  var scheduledCountdownTimer = null;
23
34
  var fastModeIndicatorEl = null;
24
35
 
36
+ function currentSessionId() {
37
+ return store.get('activeSessionId');
38
+ }
39
+
25
40
  // --- Internal helpers ---
26
41
 
27
42
  function getVendorUsageMeta(vendor) {
@@ -158,11 +173,12 @@ function tickRateLimitUsage() {
158
173
  if (!rateLimitUsageEl) return;
159
174
  var parts = [];
160
175
  var types = ["five_hour", "seven_day", "seven_day_opus", "seven_day_sonnet"];
176
+ var resetState = getRateLimitResetState(currentSessionId());
161
177
  for (var i = 0; i < types.length; i++) {
162
- var entry = rateLimitResetState[types[i]];
178
+ var entry = resetState[types[i]];
163
179
  if (!entry || !entry.resetsAt) continue;
164
180
  var timeStr = formatResetTime(entry.resetsAt);
165
- if (!timeStr) { delete rateLimitResetState[types[i]]; continue; }
181
+ if (!timeStr) { delete resetState[types[i]]; continue; }
166
182
  parts.push(rateLimitTypeShortLabel(types[i]) + " resets " + timeStr);
167
183
  }
168
184
  var newHtml;
@@ -201,18 +217,31 @@ export function handleRateLimitEvent(msg) {
201
217
  var typeLabel = rateLimitTypeLabel(msg.rateLimitType);
202
218
  var popoverText = "";
203
219
 
220
+ // lr-0827ba: the event's own session (server-stamped localId) is the one
221
+ // that gets its schedule armed, NOT necessarily the currently-focused
222
+ // session — a rate limit hit in a background session must still arm that
223
+ // session's auto-schedule and keep its reset timer running, exactly like
224
+ // server-side session.scheduledMessage already does. Fall back to the
225
+ // active session for events from servers/replays that predate the localId
226
+ // stamp (older recorded history entries).
227
+ var eventSessionId = msg.localId != null ? msg.localId : currentSessionId();
228
+ var isActiveSession = eventSessionId === currentSessionId();
229
+
204
230
  if (isRejected && msg.resetsAt) {
205
231
  // Check if already expired (history replay) — skip popover
206
232
  if (msg.resetsAt < Date.now()) {
207
- updateRateLimitIndicator(msg);
233
+ if (isActiveSession) updateRateLimitIndicator(msg);
208
234
  return;
209
235
  }
210
- popoverText = typeLabel + " limit exceeded";
211
- updateRateLimitIndicator(msg);
212
- startRateLimitCountdown(null, msg.resetsAt, null);
213
- // Track rate limit reset time
214
- rateLimitResetsAt = msg.resetsAt;
215
- if (rateLimitResetTimer) clearTimeout(rateLimitResetTimer);
236
+ if (isActiveSession) {
237
+ popoverText = typeLabel + " limit exceeded";
238
+ updateRateLimitIndicator(msg);
239
+ startRateLimitCountdown(null, msg.resetsAt, null);
240
+ }
241
+ // Track rate limit reset time for the event's own session.
242
+ setRateLimitResetsAt(eventSessionId, msg.resetsAt);
243
+ var existingTimer = getRateLimitResetTimer(eventSessionId);
244
+ if (existingTimer) clearTimeout(existingTimer);
216
245
  // Auto-switch input to schedule mode: any message typed will be queued for after reset.
217
246
  // Model-aware: a seven_day_sonnet rejection should not schedule when the user is on Opus
218
247
  // (and vice-versa), since those messages would send fine against the other model's quota.
@@ -235,20 +264,21 @@ export function handleRateLimitEvent(msg) {
235
264
  }
236
265
  }
237
266
  if (shouldSchedule) {
238
- setScheduleDelayMs(delayUntilReset + 60000); // +1min buffer after reset
267
+ setScheduleDelayForSession(eventSessionId, delayUntilReset + 60000); // +1min buffer after reset
239
268
  }
240
269
  }
241
270
  // Only arm the reset timer when we actually entered schedule mode; otherwise we'd
242
271
  // clear unrelated scheduled state on reset.
243
272
  if (shouldSchedule) {
244
- rateLimitResetTimer = setTimeout(function () {
245
- rateLimitResetsAt = null;
246
- rateLimitResetTimer = null;
247
- // Clear schedule mode when rate limit resets
248
- clearScheduleDelay();
249
- }, msg.resetsAt - Date.now() + 1000);
273
+ setRateLimitResetTimer(eventSessionId, setTimeout(function () {
274
+ setRateLimitResetsAt(eventSessionId, null);
275
+ setRateLimitResetTimer(eventSessionId, null);
276
+ // Clear schedule mode when rate limit resets — for the event's own
277
+ // session, whether or not it's the one currently focused.
278
+ clearScheduleDelayForSession(eventSessionId);
279
+ }, msg.resetsAt - Date.now() + 1000));
250
280
  }
251
- } else {
281
+ } else if (isActiveSession) {
252
282
  var pct = msg.utilization ? Math.round(msg.utilization * 100) : null;
253
283
  popoverText = typeLabel + " warning" + (pct ? " (" + pct + "% used)" : "");
254
284
  updateRateLimitIndicator(msg);
@@ -258,9 +288,19 @@ export function handleRateLimitEvent(msg) {
258
288
  }
259
289
 
260
290
  export function updateRateLimitUsage(msg) {
291
+ // lr-0827ba: rate_limit_usage is a project-wide broadcast (account-wide
292
+ // usage, not session content), but only repaint the top-bar widget when
293
+ // the event belongs to the session currently in view, so a background
294
+ // session's usage tick doesn't visibly flicker the widget for whatever
295
+ // session the user is actually looking at. Reset-time bookkeeping itself
296
+ // is still tracked per-session (via rate-limit-state.js) so switching back
297
+ // into that session redraws with its own latest data.
298
+ var eventSessionId = msg.localId != null ? msg.localId : currentSessionId();
299
+ var resetState = getRateLimitResetState(eventSessionId);
261
300
  if (msg.rateLimitType && msg.resetsAt) {
262
- rateLimitResetState[msg.rateLimitType] = { resetsAt: msg.resetsAt, status: msg.status };
301
+ resetState[msg.rateLimitType] = { resetsAt: msg.resetsAt, status: msg.status };
263
302
  }
303
+ if (eventSessionId !== currentSessionId()) return;
264
304
 
265
305
  var topBarActions = document.querySelector("#top-bar .top-bar-actions");
266
306
  if (!topBarActions) return;
@@ -279,7 +319,7 @@ export function updateRateLimitUsage(msg) {
279
319
  var parts = [];
280
320
  var types = ["five_hour", "seven_day", "seven_day_opus", "seven_day_sonnet"];
281
321
  for (var i = 0; i < types.length; i++) {
282
- var entry = rateLimitResetState[types[i]];
322
+ var entry = resetState[types[i]];
283
323
  if (!entry || !entry.resetsAt) continue;
284
324
  var timeStr = formatResetTime(entry.resetsAt);
285
325
  if (!timeStr) continue;
@@ -313,7 +353,17 @@ export function updateRateLimitUsage(msg) {
313
353
  }
314
354
  }
315
355
 
316
- export function addScheduledMessageBubble(text, resetsAt) {
356
+ // lr-0827ba: msg carries the server-stamped localId of the session the
357
+ // scheduled message actually belongs to. Persist the queued text/resetsAt
358
+ // for that session regardless of focus (so switching back in later can
359
+ // redraw it), but only render the visible bubble into the DOM when the
360
+ // event's session is the one currently in view — otherwise a background
361
+ // project's scheduled message would render into whatever session's message
362
+ // list happens to be on screen.
363
+ export function addScheduledMessageBubble(text, resetsAt, sessionId) {
364
+ var targetSessionId = sessionId != null ? sessionId : currentSessionId();
365
+ setScheduledMsg(targetSessionId, text, resetsAt);
366
+ if (targetSessionId !== currentSessionId()) return;
317
367
  removeScheduledMessageBubble();
318
368
  var isChannel = document.body.classList.contains("wide-view");
319
369
  var wrap = document.createElement("div");
@@ -475,6 +525,10 @@ export function addScheduledMessageBubble(text, resetsAt) {
475
525
  scheduledCountdownTimer = setInterval(updateCountdown, 1000);
476
526
  }
477
527
 
528
+ // Clears the visible DOM bubble/countdown only — does not touch the
529
+ // per-session persisted state. Used internally when re-rendering the bubble
530
+ // for the same session (addScheduledMessageBubble) and by
531
+ // clearScheduledMessage() below.
478
532
  export function removeScheduledMessageBubble() {
479
533
  if (scheduledMsgEl) {
480
534
  scheduledMsgEl.remove();
@@ -486,6 +540,16 @@ export function removeScheduledMessageBubble() {
486
540
  }
487
541
  }
488
542
 
543
+ // lr-0827ba: clears both the persisted per-session scheduled-message state
544
+ // and (if that session is currently focused) the visible bubble. sessionId
545
+ // defaults to the currently active session for existing call sites that
546
+ // don't yet carry a server-stamped localId (older history entries).
547
+ export function clearScheduledMessage(sessionId) {
548
+ var targetSessionId = sessionId != null ? sessionId : currentSessionId();
549
+ clearScheduledMsg(targetSessionId);
550
+ if (targetSessionId === currentSessionId()) removeScheduledMessageBubble();
551
+ }
552
+
489
553
  export function handleFastModeState(state) {
490
554
  var statusArea = document.querySelector(".title-bar-content .status");
491
555
  if (!statusArea) return;
@@ -515,15 +579,52 @@ export function handleFastModeState(state) {
515
579
 
516
580
  export function getScheduledMsgEl() { return scheduledMsgEl; }
517
581
 
582
+ // lr-0827ba: this used to also null out the bare module-scoped
583
+ // rateLimitResetsAt/rateLimitResetTimer/rateLimitResetState variables —
584
+ // which meant switching projects silently canceled the OUTGOING session's
585
+ // rate-limit reset timer and armed schedule, exactly the bug this task
586
+ // fixes. Reset timers and armed state are per-session now (rate-limit-state.js)
587
+ // and must keep running in the background regardless of focus, mirroring
588
+ // server-side session.scheduledMessage. This function now only tears down
589
+ // the visible DOM/UI-timer for whichever session was previously focused —
590
+ // it does not touch any session's persisted arming state. Callers switching
591
+ // into a different session must call restoreRateLimitStateForSession() for
592
+ // the new session afterward to redraw its own state (see app-messages.js
593
+ // session_switched handler).
518
594
  export function resetRateLimitState() {
519
595
  clearRateLimitIndicator();
520
596
  if (rateLimitCountdownTimer) { clearInterval(rateLimitCountdownTimer); rateLimitCountdownTimer = null; }
521
597
  if (rateLimitTickTimer) { clearInterval(rateLimitTickTimer); rateLimitTickTimer = null; }
522
- if (rateLimitResetTimer) { clearTimeout(rateLimitResetTimer); rateLimitResetTimer = null; }
523
- rateLimitResetsAt = null;
524
- rateLimitResetState = {};
525
598
  // Remove the usage link element entirely so it is rebuilt fresh for the new
526
599
  // project (correct vendor href, correct reset times).
527
600
  if (rateLimitUsageEl) { rateLimitUsageEl.remove(); rateLimitUsageEl = null; }
528
601
  if (fastModeIndicatorEl) { fastModeIndicatorEl.remove(); fastModeIndicatorEl = null; }
602
+ removeScheduledMessageBubble();
603
+ }
604
+
605
+ // Called when a session is actually destroyed/removed (not merely
606
+ // unfocused) so its background reset timer is canceled and its entry is
607
+ // dropped instead of leaking forever. Wired from app-messages.js's
608
+ // session_deleted handler (server-stamped ids from lib/sessions.js'
609
+ // broadcastSessionDeleted, lr-0827ba PEACHES follow-up).
610
+ export function forgetSessionRateLimitState(sessionId) {
611
+ clearSessionRateLimitState(sessionId);
612
+ }
613
+
614
+ // lr-0827ba: "redraw on switch-in" — restores the newly-focused session's
615
+ // already-armed indicator/schedule-button/scheduled-message-bubble state
616
+ // instead of relying on the unreliable chat-history-replay side effect that
617
+ // happened to repaint these before. Call after resetRateLimitState() once
618
+ // the new session is focused (store.activeSessionId already updated).
619
+ export function restoreRateLimitStateForSession(sessionId) {
620
+ restoreScheduleDelayUi();
621
+ var resetsAt = getRateLimitResetsAt(sessionId);
622
+ if (resetsAt && resetsAt > Date.now()) {
623
+ updateRateLimitIndicator({ status: "rejected", resetsAt: resetsAt });
624
+ startRateLimitCountdown(null, resetsAt, null);
625
+ }
626
+ var queued = getScheduledMsg(sessionId);
627
+ if (queued && queued.resetsAt > Date.now()) {
628
+ addScheduledMessageBubble(queued.text, queued.resetsAt, sessionId);
629
+ }
529
630
  }