@clagentic/console 1.6.0-beta.2 → 1.6.0-beta.3

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.
@@ -12,20 +12,61 @@
12
12
  // initDiagnostics() — call once on page load (wires up panel button)
13
13
  // addDiagnostic(msg) — call from processMessage case 'diagnostic'
14
14
  // formatDiagnosticSource(source) — pure helper, exported for tests
15
+ //
16
+ // Dismiss / clear-all (parity with app-notifications.js banner dismiss +
17
+ // clear-all, see initAppNotifications/dismissNotif/clearAllBanners there):
18
+ // diagnostics are client-side-only session state — there is no backend
19
+ // message type or persistence for them (unlike notifications, which round-
20
+ // trip a notification_dismiss/_dismiss_all message over the websocket).
21
+ // Dismissing here only ever mutates the in-memory `diagnostics` array and
22
+ // the DOM; a dismissed diagnostic can legitimately reappear if the next
23
+ // settings-preflight run re-emits the same underlying condition — that is
24
+ // expected and not a bug in this module.
15
25
 
16
26
  import { iconHtml, refreshIcons } from './icons.js';
17
27
  import { formatDiagnosticSource as _formatSource } from './diagnostic-format.js';
18
28
 
19
29
  // --- Module state ---
20
- var diagnostics = []; // [{severity, source, message, actionable, ts}]
30
+ var diagnostics = []; // [{id, severity, source, message, actionable, ts}]
21
31
  var panelEl = null;
22
32
  var panelListEl = null;
23
33
  var panelToggleBtn = null;
24
34
  var panelBadgeEl = null;
35
+ var clearAllBtn = null;
36
+
37
+ // Stable per-entry identity so a specific rendered item can be located and
38
+ // removed on dismiss. The array otherwise carries no unique key.
39
+ var _nextDiagnosticId = 1;
25
40
 
26
41
  // Severity priority (higher = more prominent).
27
42
  var SEVERITY_ORDER = { error: 2, warning: 1, info: 0 };
28
43
 
44
+ // lr-e901: dedup window for repeated/duplicate diagnostics. Two independent
45
+ // emitters (CLI-stderr capture + deterministic settings-preflight runPreflight())
46
+ // can legitimately produce a diagnostic for the same underlying condition -
47
+ // addDiagnostic() had no dedup, so both were pushed and both toasted. Identity
48
+ // is (source, scope, message): scope is included because runPreflight()
49
+ // intentionally emits one diagnostic per settings file (user vs project,
50
+ // lr-7e22) - those are distinct conditions and must NOT be deduped together.
51
+ var DEDUP_WINDOW_MS = 5000;
52
+ var _recentDiagnosticKeys = Object.create(null); // key -> last-seen timestamp (ms)
53
+
54
+ function _diagnosticKey(msg) {
55
+ return (msg.source || "") + "|" + (msg.scope || "") + "|" + (msg.message || "");
56
+ }
57
+
58
+ /**
59
+ * True when an equivalent diagnostic (same source+scope+message) was already
60
+ * recorded within DEDUP_WINDOW_MS. Also prunes the key's prior timestamp so
61
+ * the map does not grow unbounded across a long session.
62
+ */
63
+ function _isDuplicateDiagnostic(msg, now) {
64
+ var key = _diagnosticKey(msg);
65
+ var last = _recentDiagnosticKeys[key];
66
+ _recentDiagnosticKeys[key] = now;
67
+ return typeof last === "number" && (now - last) < DEDUP_WINDOW_MS;
68
+ }
69
+
29
70
  // ============================================================
30
71
  // Init
31
72
  // ============================================================
@@ -35,6 +76,7 @@ export function initDiagnostics() {
35
76
  panelListEl = document.getElementById("diagnostics-panel-list");
36
77
  panelToggleBtn = document.getElementById("diagnostics-panel-btn");
37
78
  panelBadgeEl = document.getElementById("diagnostics-panel-badge");
79
+ clearAllBtn = panelEl ? panelEl.querySelector(".diagnostics-panel-clear-all") : null;
38
80
 
39
81
  if (!panelEl || !panelListEl || !panelToggleBtn) return;
40
82
 
@@ -54,6 +96,14 @@ export function initDiagnostics() {
54
96
  });
55
97
  }
56
98
 
99
+ // Clear-all button (parity with app-notifications.js clearAllBanners()).
100
+ if (clearAllBtn) {
101
+ clearAllBtn.addEventListener("click", function () {
102
+ clearAllDiagnostics();
103
+ if (closeBtn) closeBtn.focus();
104
+ });
105
+ }
106
+
57
107
  // Toggle button in the topbar.
58
108
  panelToggleBtn.addEventListener("click", function () {
59
109
  if (panelEl.classList.contains("hidden")) {
@@ -86,12 +136,20 @@ export function initDiagnostics() {
86
136
  // ============================================================
87
137
 
88
138
  export function addDiagnostic(msg) {
139
+ var now = Date.now();
140
+
141
+ // lr-e901: same condition can arrive via two independent emitters (CLI-stderr
142
+ // capture + deterministic preflight) - collapse to a single visible entry.
143
+ if (_isDuplicateDiagnostic(msg, now)) return;
144
+
89
145
  var entry = {
90
146
  severity: msg.severity || "info",
91
147
  source: msg.source || "",
148
+ scope: msg.scope || "",
92
149
  message: msg.message || "",
93
150
  actionable: msg.actionable || null,
94
- ts: Date.now(),
151
+ ts: now,
152
+ id: _nextDiagnosticId++,
95
153
  };
96
154
  diagnostics.push(entry);
97
155
 
@@ -116,6 +174,23 @@ export { formatDiagnosticSource } from './diagnostic-format.js';
116
174
  // Toast
117
175
  // ============================================================
118
176
 
177
+ // lr-e901: fixed top-right corner stack (see diagnostics.css
178
+ // #diagnostic-toast-container) so concurrent diagnostic toasts stack via
179
+ // normal flex flow instead of piling on top of each other at a single fixed
180
+ // position over the input box.
181
+ var toastContainerEl = null;
182
+
183
+ function _getToastContainer() {
184
+ if (toastContainerEl && toastContainerEl.isConnected) return toastContainerEl;
185
+ toastContainerEl = document.getElementById("diagnostic-toast-container");
186
+ if (!toastContainerEl) {
187
+ toastContainerEl = document.createElement("div");
188
+ toastContainerEl.id = "diagnostic-toast-container";
189
+ document.body.appendChild(toastContainerEl);
190
+ }
191
+ return toastContainerEl;
192
+ }
193
+
119
194
  function _showDiagnosticToast(entry) {
120
195
  var el = document.createElement("div");
121
196
  // Use a dedicated class so diagnostics are visually distinct from error messages.
@@ -132,7 +207,7 @@ function _showDiagnosticToast(entry) {
132
207
 
133
208
  var sourceEl = document.createElement("span");
134
209
  sourceEl.className = "toast-diagnostic-source";
135
- sourceEl.textContent = _formatSource(entry.source);
210
+ sourceEl.textContent = _formatSource(entry.source, entry.scope);
136
211
 
137
212
  var dismissBtn = document.createElement("button");
138
213
  dismissBtn.className = "toast-diagnostic-dismiss";
@@ -155,7 +230,7 @@ function _showDiagnosticToast(entry) {
155
230
  el.appendChild(msgEl);
156
231
  el.appendChild(hintEl);
157
232
 
158
- document.body.appendChild(el);
233
+ _getToastContainer().appendChild(el);
159
234
  refreshIcons();
160
235
 
161
236
  // Animate in.
@@ -216,11 +291,11 @@ function _appendEntry(entry) {
216
291
  if (!panelListEl) return;
217
292
 
218
293
  // Remove the empty-state placeholder if present.
219
- var emptyEl = panelListEl.querySelector(".diagnostics-empty");
220
- if (emptyEl) emptyEl.parentNode.removeChild(emptyEl);
294
+ _removeEmptyPlaceholder();
221
295
 
222
296
  var item = document.createElement("div");
223
297
  item.className = "diagnostics-item diagnostics-item-" + entry.severity;
298
+ item.setAttribute("data-diag-id", String(entry.id));
224
299
 
225
300
  // Icon strip: severity pill.
226
301
  var meta = document.createElement("div");
@@ -233,10 +308,19 @@ function _appendEntry(entry) {
233
308
 
234
309
  var srcEl = document.createElement("span");
235
310
  srcEl.className = "diagnostics-source";
236
- srcEl.textContent = _formatSource(entry.source);
311
+ srcEl.textContent = _formatSource(entry.source, entry.scope);
312
+
313
+ var dismissBtn = document.createElement("button");
314
+ dismissBtn.className = "diagnostics-item-dismiss";
315
+ dismissBtn.setAttribute("aria-label", "Dismiss this diagnostic");
316
+ dismissBtn.innerHTML = iconHtml("x");
317
+ dismissBtn.addEventListener("click", function () {
318
+ dismissDiagnostic(entry.id);
319
+ });
237
320
 
238
321
  meta.appendChild(sevEl);
239
322
  meta.appendChild(srcEl);
323
+ meta.appendChild(dismissBtn);
240
324
 
241
325
  var msgEl = document.createElement("div");
242
326
  msgEl.className = "diagnostics-message";
@@ -261,15 +345,72 @@ function _appendEntry(entry) {
261
345
  actionEl.appendChild(fixIcon);
262
346
  actionEl.appendChild(fixText);
263
347
  item.appendChild(actionEl);
264
- refreshIcons();
265
348
  }
266
349
 
267
350
  panelListEl.appendChild(item);
351
+ refreshIcons();
268
352
 
269
353
  // Scroll the panel to the newest entry.
270
354
  panelListEl.scrollTop = panelListEl.scrollHeight;
271
355
  }
272
356
 
357
+ // ============================================================
358
+ // Dismiss / clear-all (client-side only — see module header note)
359
+ // ============================================================
360
+
361
+ function _removeEmptyPlaceholder() {
362
+ if (!panelListEl) return;
363
+ var emptyEl = panelListEl.querySelector(".diagnostics-empty");
364
+ if (emptyEl) emptyEl.parentNode.removeChild(emptyEl);
365
+ }
366
+
367
+ // Restore the empty-state placeholder that _appendEntry removes on first
368
+ // append. Mirrors the markup baked into index.html so a fresh page load and
369
+ // a fully-cleared panel render identically.
370
+ function _restoreEmptyPlaceholder() {
371
+ if (!panelListEl) return;
372
+ if (panelListEl.querySelector(".diagnostics-empty")) return;
373
+ var emptyEl = document.createElement("div");
374
+ emptyEl.className = "diagnostics-empty";
375
+ emptyEl.textContent = "No diagnostics this session.";
376
+ panelListEl.appendChild(emptyEl);
377
+ }
378
+
379
+ /**
380
+ * Remove a single diagnostic by id from both the in-memory array and the
381
+ * rendered panel list, then refresh the badge. No-op if the id is unknown
382
+ * (e.g. a stale dismiss click racing a clear-all).
383
+ */
384
+ function dismissDiagnostic(id) {
385
+ var idx = -1;
386
+ for (var i = 0; i < diagnostics.length; i++) {
387
+ if (diagnostics[i].id === id) { idx = i; break; }
388
+ }
389
+ if (idx === -1) return;
390
+ diagnostics.splice(idx, 1);
391
+
392
+ if (panelListEl) {
393
+ var itemEl = panelListEl.querySelector('[data-diag-id="' + id + '"]');
394
+ if (itemEl && itemEl.parentNode) itemEl.parentNode.removeChild(itemEl);
395
+ }
396
+
397
+ if (diagnostics.length === 0) _restoreEmptyPlaceholder();
398
+ _updateBadge();
399
+ }
400
+
401
+ /**
402
+ * Empty the diagnostics array and panel list, restore the empty-state
403
+ * placeholder, and hide the badge. Parity with clearAllBanners() in
404
+ * app-notifications.js, minus the websocket round-trip — diagnostics have
405
+ * no server-side dismiss contract (see module header note).
406
+ */
407
+ function clearAllDiagnostics() {
408
+ diagnostics = [];
409
+ if (panelListEl) panelListEl.innerHTML = "";
410
+ _restoreEmptyPlaceholder();
411
+ _updateBadge();
412
+ }
413
+
273
414
  // ============================================================
274
415
  // Badge
275
416
  // ============================================================
@@ -249,12 +249,24 @@ export function buildEmojiPicker(opts) {
249
249
  }
250
250
 
251
251
  function doUpload() {
252
- if (!pendingFile) return;
252
+ // Both early returns below used to be silent — the control (rendered
253
+ // by showSlugConfirm) is only reachable once a file is already
254
+ // selected, but a defensive check that fires with zero user feedback
255
+ // is indistinguishable from the picker doing nothing at all. Surface
256
+ // both via the same toast used for server-side upload failures (line
257
+ // ~285) so "nothing happened" never happens silently again.
258
+ if (!pendingFile) {
259
+ showToast("Couldn't add custom emoji", "warn");
260
+ return;
261
+ }
253
262
  var slug = slugInput.value.trim().toLowerCase()
254
263
  .replace(/[^a-z0-9_-]+/g, "-")
255
264
  .replace(/^-+|-+$/g, "")
256
265
  .slice(0, 64);
257
- if (!slug || !/^[a-z0-9_-]{1,64}$/.test(slug)) return;
266
+ if (!slug || !/^[a-z0-9_-]{1,64}$/.test(slug)) {
267
+ showToast("Enter a valid name", "warn");
268
+ return;
269
+ }
258
270
 
259
271
  // Check for duplicate in the already-fetched list
260
272
  var existing = customList || [];
@@ -274,9 +286,14 @@ export function buildEmojiPicker(opts) {
274
286
  showToast(result.error || "Upload failed", "warn");
275
287
  return;
276
288
  }
277
- // Refresh the custom grid after upload
289
+ // Refresh the custom grid after upload. buildCustomPanel() already
290
+ // repaints the grid it just (re)built via its own fresh
291
+ // renderCustomGrid closure (see below) — calling the outer
292
+ // renderCustomGrid here re-renders the ORPHANED grid captured by
293
+ // this closure at the time doUpload's panel was built, which is
294
+ // detached from the DOM the moment buildCustomPanel() runs again.
278
295
  customList = null;
279
- fetchCustomList(function () { buildCustomPanel(); renderCustomGrid(); });
296
+ fetchCustomList(function () { buildCustomPanel(); });
280
297
  });
281
298
  }
282
299
 
@@ -352,8 +369,12 @@ export function buildEmojiPicker(opts) {
352
369
  delBtn.addEventListener("click", function (e) {
353
370
  e.stopPropagation();
354
371
  deleteCustomIcon(entry.slug).then(function () {
372
+ // Same stale-closure hazard as the upload success path above:
373
+ // buildCustomPanel() already repaints via its own fresh
374
+ // renderCustomGrid; the closure captured here is orphaned
375
+ // once buildCustomPanel() rebuilds the panel.
355
376
  customList = null;
356
- fetchCustomList(function () { buildCustomPanel(); renderCustomGrid(); });
377
+ fetchCustomList(function () { buildCustomPanel(); });
357
378
  });
358
379
  });
359
380
  tile.appendChild(delBtn);
@@ -0,0 +1,98 @@
1
+ /**
2
+ * history-visibility.js — shared source of truth for classifying a recorded
3
+ * history event as "renders a visible message" vs. an invisible-yield event.
4
+ * (lr-c24b)
5
+ *
6
+ * This is the ES module (browser) copy, used by app-header.js's
7
+ * prependOlderHistory / updateHistorySentinel to decide whether a prepended
8
+ * page surfaced any visible content. The CJS backend copy lives at
9
+ * lib/history-visibility.js. A test (test/history-visibility-parity.test.js)
10
+ * asserts both copies produce identical classifications so they cannot
11
+ * silently drift.
12
+ *
13
+ * When adding a new WS message type: check whether processMessage() in
14
+ * app-messages.js inserts a new visible element for it, then update BOTH
15
+ * this file and lib/history-visibility.js accordingly. The parity test will
16
+ * fail if they disagree.
17
+ */
18
+
19
+ // Tool names that render as hidden bookkeeping widgets (todo/task list state,
20
+ // plan-mode banners) — mirrors TODO_TOOLS / PLAN_MODE_TOOLS in tools.js and
21
+ // the tool_start branch in app-messages.js.
22
+ export var HIDDEN_TOOL_NAMES = {
23
+ TodoWrite: 1,
24
+ TaskCreate: 1,
25
+ TaskUpdate: 1,
26
+ TaskList: 1,
27
+ TaskGet: 1,
28
+ EnterPlanMode: 1,
29
+ ExitPlanMode: 1,
30
+ ask_user_questions: 1,
31
+ };
32
+
33
+ // Event types that never render a new visible message/bubble on their own —
34
+ // they update existing UI state (status text, badges, panels) or are pure
35
+ // internal bookkeeping. Matches the case branches in app-messages.js that
36
+ // call a state setter / no-op rather than a DOM-inserting render helper.
37
+ export var INVISIBLE_TYPES = {
38
+ message_uuid: 1,
39
+ session_id: 1,
40
+ status: 1,
41
+ compacting: 1,
42
+ thinking_start: 1,
43
+ thinking_delta: 1,
44
+ thinking_stop: 1,
45
+ ask_user_answered: 1,
46
+ permission_request: 1,
47
+ permission_request_pending: 1,
48
+ permission_cancel: 1,
49
+ permission_resolved: 1,
50
+ elicitation_request: 1,
51
+ elicitation_resolved: 1,
52
+ context_usage: 1,
53
+ fast_mode_state: 1,
54
+ rate_limit: 1,
55
+ rate_limit_usage: 1,
56
+ subagent_activity: 1,
57
+ subagent_tool: 1,
58
+ subagent_done: 1,
59
+ task_started: 1,
60
+ task_progress: 1,
61
+ task_updated: 1,
62
+ done: 1,
63
+ digest_checkpoint: 1,
64
+ };
65
+
66
+ // Event types whose visibility depends on the tool name carried in the event.
67
+ var TOOL_NAME_TYPES = {
68
+ tool_start: 1,
69
+ tool_executing: 1,
70
+ };
71
+
72
+ /**
73
+ * Returns true when `entry` (a single session.history[] item / WS message)
74
+ * causes app-messages.js's processMessage() to insert a new visible element
75
+ * into the message list. Returns false for state-only or hidden-bookkeeping
76
+ * events — the invisible-yield set that can dominate a raw-event-count page.
77
+ *
78
+ * entry is intentionally treated defensively: unknown/missing type defaults
79
+ * to visible (safe default — never under-counts and can't create a new
80
+ * zero-visible page shape that this module wasn't already guarding against).
81
+ */
82
+ export function isVisibleHistoryEvent(entry) {
83
+ if (!entry || typeof entry.type !== "string") return true;
84
+ var type = entry.type;
85
+
86
+ if (INVISIBLE_TYPES[type]) return false;
87
+
88
+ if (TOOL_NAME_TYPES[type]) {
89
+ return !HIDDEN_TOOL_NAMES[entry.name];
90
+ }
91
+
92
+ // tool_result carries only an id (no name) — it updates an existing tool
93
+ // card rather than inserting a new one, so it is never itself the reason
94
+ // a page becomes visible.
95
+ if (type === "tool_result") return false;
96
+
97
+ return true;
98
+ }
package/lib/sdk-bridge.js CHANGED
@@ -13,6 +13,7 @@ var { discoverWorkflows } = require("./sdk-workflow-discovery");
13
13
  var { buildEnrichedSlashCommands } = require("./sdk-slash-enrichment");
14
14
  var { KNOWN_CONTEXT_WINDOWS: _BACKEND_KNOWN_CONTEXT_WINDOWS, resolveModelContextWindow } = require("./model-context-windows");
15
15
  var { runPreflight } = require("./settings-preflight");
16
+ var { partitionSubagentOwnedPermissions, retainPreservedTaskBookkeeping } = require("./sdk-permission-ownership");
16
17
 
17
18
  // --- lr-29f9: Global concurrent-session ceiling ---
18
19
  // Counts queries that are actively running (startQuery entered, processQueryStream
@@ -693,6 +694,16 @@ function createSDKBridge(opts) {
693
694
  }
694
695
 
695
696
  // Regular tool permission request: send to client and wait
697
+ // TODO(lr-9d4b): unlike the worker path's canUseTool (claude-worker.js:315,
698
+ // 30s auto-deny), this in-process path has no timeout, so an orphaned
699
+ // resolver (e.g. one whose owning session/sub-agent tracking bug is not
700
+ // yet known) wedges the turn forever instead of failing closed. Deferred
701
+ // out of this PR: a uniform timeout here would also auto-deny normal
702
+ // foreground human-review latency for every non-sub-agent permission
703
+ // request in the in-process path, which is a broader behavior change than
704
+ // this hang-fix should bundle silently. Needs a design pass (e.g. scope
705
+ // the timeout to sub-agent-owned entries only, or make it operator-
706
+ // configurable) rather than copying the worker's blanket 30s.
696
707
  return new Promise(function(resolve) {
697
708
  var requestId = crypto.randomUUID();
698
709
  sm.permissionRequestIndex[requestId] = session.localId;
@@ -1019,26 +1030,55 @@ function createSDKBridge(opts) {
1019
1030
  console.log("[sdk-bridge] Live query count: " + _activeLiveCount + "/" + MAX_CONCURRENT_SESSIONS + " (session " + session.localId + " done)");
1020
1031
  }
1021
1032
  session.taskStopRequested = false;
1022
- session.pendingPermissions = {};
1023
- // Preserve MCP-mode AskUserQuestion entries across turn boundaries.
1024
- // The MCP path is intentionally stateless: ask_user returns immediately
1025
- // ("card posted, end your turn") and the answer arrives as a new
1026
- // user_message on the next turn. Those entries MUST survive this finally
1027
- // block so ask_user_response can find the toolId and inject the answer.
1028
- // canUseTool-mode entries hold an open SDK callback that dies with the
1029
- // query anyway, so those are correctly cleared here.
1030
- var _keepAskUser = {};
1031
- for (var _tid in session.pendingAskUser) {
1032
- var _pau = session.pendingAskUser[_tid];
1033
- if (_pau && _pau.mode === "mcp") _keepAskUser[_tid] = _pau;
1033
+ // lr-8355: A rewind (or any other replacement) may have already started
1034
+ // a NEW query on this session while this stream's for-await is still
1035
+ // unwinding (e.g. rewind_execute nulls session.queryInstance, then the
1036
+ // user immediately sends a message, starting a fresh query). If that
1037
+ // happened, session.queryInstance now points at the newer query's
1038
+ // instance, not ours. Resetting pendingPermissions/pendingAskUser/
1039
+ // pendingElicitations/isProcessing here would wipe the NEW query's
1040
+ // in-flight state out from under it (approval clicks silently ignored,
1041
+ // turn hangs forever) and flip isProcessing=false while the new query
1042
+ // is still live. Only run the reset when we still own the session
1043
+ // (queryInstance is unchanged or has already been nulled by our own
1044
+ // completion path above) — never when a newer query has taken over.
1045
+ if (session.queryInstance === myQueryInstance || session.queryInstance === null) {
1046
+ // lr-9d4b: This finally block runs on EVERY ordinary (non-superseded)
1047
+ // turn completion — including the common case where a backgrounded
1048
+ // sub-agent's own permission request (e.g. Bash) is still awaiting
1049
+ // the operator's click when the parent turn ends normally. This is a
1050
+ // second wipe of pendingPermissions on the SAME turn as the 'result'
1051
+ // message's own reset (sdk-message-processor.js), microseconds later
1052
+ // once the for-await loop drains. Unconditionally clearing here would
1053
+ // re-orphan the resolver the result handler just preserved. Use the
1054
+ // same shared keep-decision as that handler (see
1055
+ // lib/sdk-permission-ownership.js) rather than duplicating it.
1056
+ var _perm9d4b = partitionSubagentOwnedPermissions(session);
1057
+ session.pendingPermissions = _perm9d4b.keptPermissions;
1058
+ // Preserve MCP-mode AskUserQuestion entries across turn boundaries.
1059
+ // The MCP path is intentionally stateless: ask_user returns immediately
1060
+ // ("card posted, end your turn") and the answer arrives as a new
1061
+ // user_message on the next turn. Those entries MUST survive this finally
1062
+ // block so ask_user_response can find the toolId and inject the answer.
1063
+ // canUseTool-mode entries hold an open SDK callback that dies with the
1064
+ // query anyway, so those are correctly cleared here.
1065
+ var _keepAskUser = {};
1066
+ for (var _tid in session.pendingAskUser) {
1067
+ var _pau = session.pendingAskUser[_tid];
1068
+ if (_pau && _pau.mode === "mcp") _keepAskUser[_tid] = _pau;
1069
+ }
1070
+ session.pendingAskUser = _keepAskUser;
1071
+ session.pendingElicitations = {};
1072
+ // lr-9d4b: keep activeTaskToolIds/taskIdMap bookkeeping in sync with
1073
+ // whichever Task ids just had a permission preserved above — mirrors
1074
+ // the same reconciliation the 'result' handler performs.
1075
+ retainPreservedTaskBookkeeping(session, _perm9d4b.preservedTaskIds);
1076
+
1077
+ // Auto-continue on rate limit (scheduler sessions, or user setting)
1078
+ // Mark session as done processing so the late rate_limit_event handler
1079
+ // can detect the race condition and schedule auto-continue itself.
1080
+ session.isProcessing = false;
1034
1081
  }
1035
- session.pendingAskUser = _keepAskUser;
1036
- session.pendingElicitations = {};
1037
-
1038
- // Auto-continue on rate limit (scheduler sessions, or user setting)
1039
- // Mark session as done processing so the late rate_limit_event handler
1040
- // can detect the race condition and schedule auto-continue itself.
1041
- session.isProcessing = false;
1042
1082
 
1043
1083
  var didScheduleAutoContinue = false;
1044
1084
  var acEnabled = session.onQueryComplete || (typeof opts.getAutoContinueSetting === "function" && opts.getAutoContinueSetting(session));
@@ -1,6 +1,7 @@
1
1
  var usersModule = require("./users");
2
2
  var { discoverWorkflows } = require("./sdk-workflow-discovery");
3
3
  var { buildEnrichedSlashCommands } = require("./sdk-slash-enrichment");
4
+ var { partitionSubagentOwnedPermissions, retainPreservedTaskBookkeeping } = require("./sdk-permission-ownership");
4
5
 
5
6
  function attachMessageProcessor(ctx) {
6
7
  var sm = ctx.sm;
@@ -84,6 +85,12 @@ function attachMessageProcessor(ctx) {
84
85
  for (var i = 0; i < content.length; i++) {
85
86
  var block = content[i];
86
87
  if (block.type === "tool_use") {
88
+ // lr-9d4b: Record which backgrounded Task (parentId) owns this tool
89
+ // call's id so the parent turn's 'result' handler can tell a
90
+ // sub-agent-owned pendingPermissions entry apart from an orphaned one
91
+ // before it wipes the map (see sdk-message-processor.js result branch).
92
+ if (!session.subagentToolOwners) session.subagentToolOwners = {};
93
+ session.subagentToolOwners[block.id] = parentId;
87
94
  var activityText = toolActivityTextForSubagent(block.name, block.input);
88
95
  sendAndRecord(session, {
89
96
  type: "subagent_tool",
@@ -433,7 +440,23 @@ function attachMessageProcessor(ctx) {
433
440
  } else if (parsed.yokeType === "result") {
434
441
  session.blocks = {};
435
442
  session.sentToolResults = {};
436
- session.pendingPermissions = {};
443
+ // lr-9d4b: Preserve pendingPermissions entries owned by a backgrounded
444
+ // sub-agent that is still running when the PARENT turn's 'result' arrives.
445
+ // A Task tool launched an async sub-agent whose own Bash/etc permission
446
+ // request is still awaiting the operator's click; that resolver lives in
447
+ // this same session.pendingPermissions map (keyed by requestId) but is
448
+ // unrelated to the parent turn that just ended. Wiping it unconditionally
449
+ // orphans the resolver — the permission card stays on the UI, but the
450
+ // operator's later permission_response finds nothing to resolve and the
451
+ // sub-agent's canUseTool Promise hangs forever (lr-9d4b root cause).
452
+ // Shared with sdk-bridge.js's processQueryStream finally block, which
453
+ // performs the same reset on normal (non-superseded) turn completion —
454
+ // see lib/sdk-permission-ownership.js for the single source of truth.
455
+ // This MUST run before activeTaskToolIds/taskIdMap are reset below, since
456
+ // that is the ownership information this decision depends on. Mirrors the
457
+ // _keepAskUser preservation pattern for pendingAskUser directly below.
458
+ var _perm9d4b = partitionSubagentOwnedPermissions(session);
459
+ session.pendingPermissions = _perm9d4b.keptPermissions;
437
460
  session.pendingElicitations = {};
438
461
  // Record ask_user_answered for any leftover pending questions so replay pairs correctly.
439
462
  // EXCEPTION: "mcp" mode entries are stateless — the tool returned immediately and the
@@ -452,8 +475,12 @@ function attachMessageProcessor(ctx) {
452
475
  sendAndRecord(session, { type: "ask_user_answered", toolId: lid });
453
476
  }
454
477
  session.pendingAskUser = keptAskUser;
455
- session.activeTaskToolIds = {};
456
- session.taskIdMap = {};
478
+ // Only clear activeTaskToolIds/taskIdMap entries for Task ids we did NOT
479
+ // just preserve a permission for above — a still-active backgrounded
480
+ // sub-agent's bookkeeping must survive alongside its pending permission,
481
+ // otherwise a second permission from the same sub-agent (or subagent_done
482
+ // delivery) has nothing to correlate against.
483
+ retainPreservedTaskBookkeeping(session, _perm9d4b.preservedTaskIds);
457
484
  // Only clear rateLimitResetsAt on genuine success (non-zero cost).
458
485
  // When rate-limited, the SDK sends result with zero cost right after
459
486
  // rate_limit_event; clearing here would prevent auto-continue scheduling.
@@ -685,6 +712,34 @@ function attachMessageProcessor(ctx) {
685
712
  }
686
713
  }
687
714
  }
715
+ // lr-9d4b: the sub-agent is done — release any tool-ownership records
716
+ // for tool ids it registered, so they don't linger as orphaned entries.
717
+ // EXCEPTION: do not prune a tool id that still has a live
718
+ // pendingPermissions entry pointing at it. task_notification can arrive
719
+ // while the sub-agent's own permission request (e.g. its last Bash
720
+ // call) is still awaiting the operator's click, or a permission can
721
+ // arrive in the brief window right after. Pruning ownership here would
722
+ // make that entry look like an orphaned top-level permission to the
723
+ // 'result' handler / processQueryStream finally block, which would
724
+ // then clear it and re-orphan the resolver — the same hang via a
725
+ // different timing path. Defer cleanup for those tool ids until the
726
+ // permission itself is resolved (project-sessions.js's permission_response
727
+ // handler deletes the pendingPermissions entry; the ownership record is
728
+ // harmless to leave a little longer since it is keyed by tool-use id,
729
+ // not by Task, and simply becomes inert once no pendingPermissions
730
+ // entry references it).
731
+ if (parentId && session.subagentToolOwners) {
732
+ var liveOwnedToolIds = {};
733
+ for (var lpk in (session.pendingPermissions || {})) {
734
+ var lpEntry = session.pendingPermissions[lpk];
735
+ if (lpEntry && lpEntry.toolUseId) liveOwnedToolIds[lpEntry.toolUseId] = true;
736
+ }
737
+ for (var stk in session.subagentToolOwners) {
738
+ if (session.subagentToolOwners[stk] === parentId && !liveOwnedToolIds[stk]) {
739
+ delete session.subagentToolOwners[stk];
740
+ }
741
+ }
742
+ }
688
743
 
689
744
  } else if (parsed.yokeType === "rate_limit") {
690
745
  var info = parsed.rateLimitInfo;