@clagentic/console 1.6.0-beta.1 → 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.
Files changed (46) hide show
  1. package/README.md +18 -0
  2. package/lib/daemon.js +94 -0
  3. package/lib/history-visibility.js +113 -0
  4. package/lib/project-sessions.js +51 -2
  5. package/lib/public/css/base.css +18 -0
  6. package/lib/public/css/diagnostics.css +99 -11
  7. package/lib/public/css/icon-strip.css +201 -0
  8. package/lib/public/css/menus.css +2 -2
  9. package/lib/public/css/mobile-nav.css +24 -0
  10. package/lib/public/css/server-settings.css +100 -0
  11. package/lib/public/index.html +17 -1
  12. package/lib/public/modules/app-header.js +72 -17
  13. package/lib/public/modules/app-home-hub.js +31 -7
  14. package/lib/public/modules/app-messages.js +5 -0
  15. package/lib/public/modules/app-notifications.js +5 -1
  16. package/lib/public/modules/app-projects.js +10 -5
  17. package/lib/public/modules/command-palette.js +16 -5
  18. package/lib/public/modules/custom-icons-settings.js +399 -0
  19. package/lib/public/modules/custom-icons.js +114 -0
  20. package/lib/public/modules/diagnostic-format.js +18 -2
  21. package/lib/public/modules/diagnostics.js +159 -8
  22. package/lib/public/modules/emoji-picker.js +274 -6
  23. package/lib/public/modules/history-visibility.js +98 -0
  24. package/lib/public/modules/popover-position.js +192 -0
  25. package/lib/public/modules/project-icon.js +113 -0
  26. package/lib/public/modules/project-settings.js +2 -2
  27. package/lib/public/modules/project-switcher.js +2 -1
  28. package/lib/public/modules/scheduler-config.js +5 -8
  29. package/lib/public/modules/scheduler.js +5 -6
  30. package/lib/public/modules/server-settings.js +6 -0
  31. package/lib/public/modules/sidebar-mobile.js +4 -6
  32. package/lib/public/modules/sidebar-projects.js +35 -90
  33. package/lib/public/modules/sidebar-sessions.js +6 -20
  34. package/lib/public/modules/sticky-notes.js +4 -4
  35. package/lib/public/modules/terminal.js +5 -12
  36. package/lib/sdk-bridge.js +59 -19
  37. package/lib/sdk-message-processor.js +58 -3
  38. package/lib/sdk-permission-ownership.js +85 -0
  39. package/lib/server-settings.js +221 -1
  40. package/lib/server.js +2 -0
  41. package/lib/sessions.js +77 -10
  42. package/lib/settings-preflight.js +52 -16
  43. package/lib/utils.js +23 -0
  44. package/lib/ws-schema.js +2 -0
  45. package/lib/yoke/adapters/diagnostic-patterns.js +25 -0
  46. package/package.json +2 -1
@@ -7,6 +7,8 @@ import { openProjectSettings } from './project-settings.js';
7
7
  import { triggerShare } from './qrcode.js';
8
8
  import { parseEmojis } from './markdown.js';
9
9
  import { buildEmojiPicker } from './emoji-picker.js';
10
+ import { renderProjectIcon, projectIconHtml } from './project-icon.js';
11
+ import { positionPopover } from './popover-position.js';
10
12
  import { store } from './store.js';
11
13
  import { getWs } from './ws-ref.js';
12
14
  import { closeSidebar } from './sidebar.js';
@@ -190,18 +192,8 @@ function showProjectAccessPopover(anchorEl, slug) {
190
192
  projectAccessPopover = popover;
191
193
 
192
194
  requestAnimationFrame(function () {
193
- var rect = anchorEl.getBoundingClientRect();
194
- popover.style.position = "fixed";
195
- popover.style.left = (rect.right + 8) + "px";
196
- popover.style.top = rect.top + "px";
195
+ positionPopover(popover, anchorEl, { placement: "right", gap: 8 });
197
196
  popover.style.zIndex = "9999";
198
- var popRect = popover.getBoundingClientRect();
199
- if (popRect.right > window.innerWidth - 8) {
200
- popover.style.left = (rect.left - popRect.width - 8) + "px";
201
- }
202
- if (popRect.bottom > window.innerHeight - 8) {
203
- popover.style.top = (window.innerHeight - popRect.height - 8) + "px";
204
- }
205
197
  });
206
198
 
207
199
  setTimeout(function () {
@@ -380,17 +372,7 @@ function showIconCtxMenu(anchorEl, slug, name) {
380
372
  refreshIcons();
381
373
 
382
374
  requestAnimationFrame(function () {
383
- var rect = anchorEl.getBoundingClientRect();
384
- menu.style.position = "fixed";
385
- menu.style.left = (rect.right + 6) + "px";
386
- menu.style.top = rect.top + "px";
387
- var menuRect = menu.getBoundingClientRect();
388
- if (menuRect.right > window.innerWidth - 8) {
389
- menu.style.left = (rect.left - menuRect.width - 6) + "px";
390
- }
391
- if (menuRect.bottom > window.innerHeight - 8) {
392
- menu.style.top = (window.innerHeight - menuRect.height - 8) + "px";
393
- }
375
+ positionPopover(menu, anchorEl, { placement: "right" });
394
376
  });
395
377
  }
396
378
 
@@ -599,27 +581,24 @@ function showProjectCtxMenu(anchorEl, slug, name, icon, position) {
599
581
  refreshIcons();
600
582
 
601
583
  requestAnimationFrame(function () {
602
- var rect = anchorEl.getBoundingClientRect();
603
- menu.style.position = "fixed";
604
- if (position === "below") {
605
- menu.style.left = rect.left + "px";
606
- menu.style.top = (rect.bottom + 4) + "px";
607
- } else {
608
- menu.style.left = (rect.right + 6) + "px";
609
- menu.style.top = rect.top + "px";
610
- }
611
- var menuRect = menu.getBoundingClientRect();
612
- if (menuRect.right > window.innerWidth - 8) {
613
- menu.style.left = (rect.left - menuRect.width - 6) + "px";
614
- }
615
- if (menuRect.bottom > window.innerHeight - 8) {
616
- menu.style.top = (window.innerHeight - menuRect.height - 8) + "px";
617
- }
584
+ // "below" kept its original 4px gap; "right" keeps the shared default (6px).
585
+ positionPopover(menu, anchorEl, position === "below" ? { placement: "below", gap: 4 } : { placement: "right" });
618
586
  });
619
587
  }
620
588
 
621
589
  // --- Emoji picker ---
622
590
 
591
+ // Position an emoji-picker popover relative to an anchor element, keeping it
592
+ // fully on-screen. Delegates to the shared viewport-clamp util (lr-a10a,
593
+ // generalized from the original lr-149e fix here): desktop is
594
+ // anchor-relative (right of the anchor, flipped left + four-edge clamped);
595
+ // mobile centers the picker in the viewport and clamps both axes — this is
596
+ // what icon-strip.css's mobile block expects (it no longer sets left/right
597
+ // itself, so there is nothing for these inline styles to fight).
598
+ function positionEmojiPicker(picker, anchorEl) {
599
+ positionPopover(picker, anchorEl, { placement: "right" });
600
+ }
601
+
623
602
  function closeEmojiPicker() {
624
603
  if (emojiPickerEl) {
625
604
  emojiPickerEl.remove();
@@ -649,16 +628,7 @@ function showEmojiPicker(slug, anchorEl) {
649
628
  emojiPickerEl = picker;
650
629
 
651
630
  requestAnimationFrame(function () {
652
- var rect = anchorEl.getBoundingClientRect();
653
- picker.style.left = (rect.right + 6) + "px";
654
- picker.style.top = rect.top + "px";
655
- var pRect = picker.getBoundingClientRect();
656
- if (pRect.right > window.innerWidth - 8) {
657
- picker.style.left = (rect.left - pRect.width - 6) + "px";
658
- }
659
- if (pRect.bottom > window.innerHeight - 8) {
660
- picker.style.top = (window.innerHeight - pRect.height - 8) + "px";
661
- }
631
+ positionEmojiPicker(picker, anchorEl);
662
632
  });
663
633
  }
664
634
 
@@ -685,16 +655,7 @@ function showFolderEmojiPicker(folderName, anchorEl) {
685
655
  emojiPickerEl = picker;
686
656
 
687
657
  requestAnimationFrame(function () {
688
- var rect = anchorEl.getBoundingClientRect();
689
- picker.style.left = (rect.right + 6) + "px";
690
- picker.style.top = rect.top + "px";
691
- var pRect = picker.getBoundingClientRect();
692
- if (pRect.right > window.innerWidth - 8) {
693
- picker.style.left = (rect.left - pRect.width - 6) + "px";
694
- }
695
- if (pRect.bottom > window.innerHeight - 8) {
696
- picker.style.top = (window.innerHeight - pRect.height - 8) + "px";
697
- }
658
+ positionEmojiPicker(picker, anchorEl);
698
659
  });
699
660
  }
700
661
 
@@ -753,17 +714,7 @@ function showFolderCtxMenu(anchorEl, folderName) {
753
714
  refreshIcons();
754
715
 
755
716
  requestAnimationFrame(function () {
756
- var rect = anchorEl.getBoundingClientRect();
757
- menu.style.position = "fixed";
758
- menu.style.left = (rect.right + 6) + "px";
759
- menu.style.top = rect.top + "px";
760
- var menuRect = menu.getBoundingClientRect();
761
- if (menuRect.right > window.innerWidth - 8) {
762
- menu.style.left = (rect.left - menuRect.width - 6) + "px";
763
- }
764
- if (menuRect.bottom > window.innerHeight - 8) {
765
- menu.style.top = (window.innerHeight - menuRect.height - 8) + "px";
766
- }
717
+ positionPopover(menu, anchorEl, { placement: "right" });
767
718
  });
768
719
  }
769
720
 
@@ -778,7 +729,11 @@ function showMoveFolderMenu(anchorEl, slug, folders, position) {
778
729
  var item = document.createElement("button");
779
730
  item.className = "project-ctx-item";
780
731
  var fmeta2 = cachedFolderMeta[fn] || {};
781
- var ficon = fmeta2.icon ? ('<span style="margin-right:4px">' + fmeta2.icon + '</span>') : (iconHtml("folder") + " ");
732
+ // LOCKED SCOPE (Andy, lr-a6da): folder icons support custom :slug: images
733
+ // at parity with project icons. projectIconHtml() routes custom icons to
734
+ // a safe <img> tag and emoji to escaped text; the prior raw fmeta2.icon
735
+ // interpolation showed ':slug:' as literal text.
736
+ var ficon = fmeta2.icon ? ('<span style="margin-right:4px">' + projectIconHtml(fmeta2.icon) + '</span>') : (iconHtml("folder") + " ");
782
737
  item.innerHTML = ficon + "<span>" + escapeHtml(fn) + "</span>";
783
738
  item.addEventListener("click", function (e) {
784
739
  e.stopPropagation();
@@ -797,18 +752,8 @@ function showMoveFolderMenu(anchorEl, slug, folders, position) {
797
752
  refreshIcons();
798
753
 
799
754
  requestAnimationFrame(function () {
800
- var rect = anchorEl.getBoundingClientRect();
801
- menu.style.position = "fixed";
802
- if (position === "below") {
803
- menu.style.left = rect.left + "px";
804
- menu.style.top = (rect.bottom + 4) + "px";
805
- } else {
806
- menu.style.left = (rect.right + 6) + "px";
807
- menu.style.top = rect.top + "px";
808
- }
809
- var menuRect = menu.getBoundingClientRect();
810
- if (menuRect.right > window.innerWidth - 8) menu.style.left = (rect.left - menuRect.width - 6) + "px";
811
- if (menuRect.bottom > window.innerHeight - 8) menu.style.top = (window.innerHeight - menuRect.height - 8) + "px";
755
+ // "below" kept its original 4px gap; "right" keeps the shared default (6px).
756
+ positionPopover(menu, anchorEl, position === "below" ? { placement: "below", gap: 4 } : { placement: "right" });
812
757
  });
813
758
  }
814
759
 
@@ -1353,8 +1298,7 @@ function createIconItem(p, currentSlug) {
1353
1298
  if (p.icon) {
1354
1299
  var emojiSpan = document.createElement("span");
1355
1300
  emojiSpan.className = "project-emoji";
1356
- emojiSpan.textContent = p.icon;
1357
- parseEmojis(emojiSpan);
1301
+ renderProjectIcon(p.icon, emojiSpan, parseEmojis);
1358
1302
  el.appendChild(emojiSpan);
1359
1303
  } else {
1360
1304
  el.appendChild(document.createTextNode(getProjectAbbrev(p.name)));
@@ -1635,10 +1579,13 @@ function renderUserFolder(unit, wtByParent, currentSlug, currentDmUserId) {
1635
1579
  var iconBox = document.createElement("span");
1636
1580
  iconBox.className = "icon-strip-folder-icon-box";
1637
1581
  if (fmeta.icon) {
1638
- // Emoji fills the box — render as plain text, no parseEmojis needed
1582
+ // LOCKED SCOPE (Andy, lr-a6da): folder icons support custom :slug: images
1583
+ // at parity with project icons. renderProjectIcon() routes custom icons to
1584
+ // <img> and emoji to text; the prior plain textContent assignment showed
1585
+ // ':slug:' as literal text.
1639
1586
  var emojiSpan = document.createElement("span");
1640
1587
  emojiSpan.className = "icon-strip-folder-emoji-main";
1641
- emojiSpan.textContent = fmeta.icon;
1588
+ renderProjectIcon(fmeta.icon, emojiSpan, parseEmojis);
1642
1589
  iconBox.appendChild(emojiSpan);
1643
1590
  } else {
1644
1591
  // Fallback: folder SVG icon
@@ -1861,8 +1808,7 @@ function renderWorktreeGroup(p, worktrees, currentSlug, currentDmUserId) {
1861
1808
  if (wt.icon) {
1862
1809
  var wtEmoji = document.createElement("span");
1863
1810
  wtEmoji.className = "wt-branch-abbrev project-emoji";
1864
- wtEmoji.textContent = wt.icon;
1865
- parseEmojis(wtEmoji);
1811
+ renderProjectIcon(wt.icon, wtEmoji, parseEmojis);
1866
1812
  wtEl.appendChild(wtEmoji);
1867
1813
  } else {
1868
1814
  var abbrev = document.createElement("span");
@@ -1998,8 +1944,7 @@ function createMobileProjectItem(p, currentSlug, isWorktree) {
1998
1944
  var abbrev = document.createElement("span");
1999
1945
  abbrev.className = "mobile-project-abbrev";
2000
1946
  if (p.icon) {
2001
- abbrev.textContent = p.icon;
2002
- parseEmojis(abbrev);
1947
+ renderProjectIcon(p.icon, abbrev, parseEmojis);
2003
1948
  } else {
2004
1949
  abbrev.textContent = getProjectAbbrev(p.name);
2005
1950
  }
@@ -14,6 +14,7 @@ import { getUpcomingSchedules } from './scheduler.js';
14
14
  import { refreshMobileChatSheet } from './sidebar-mobile.js';
15
15
  import { openAgentPicker, openAgentPickerForPreferred } from './agent-picker.js';
16
16
  import { getCachedProjects } from './app-projects.js';
17
+ import { positionPopover } from './popover-position.js';
17
18
 
18
19
 
19
20
  // --- Session state ---
@@ -682,18 +683,11 @@ function showSessionCtxMenu(anchorBtn, sessionId, title, cliSid, sessionData) {
682
683
  sessionCtxMenu = menu;
683
684
  refreshIcons();
684
685
 
685
- // Position: fixed relative to the anchor button
686
+ // Position: fixed relative to the anchor button, right-edge aligned,
687
+ // flip-then-clamp on all four edges (lr-a10a: the prior bottom-flip-only
688
+ // logic could leave the flipped menu with top < 0 on a short viewport).
686
689
  requestAnimationFrame(function () {
687
- var btnRect = anchorBtn.getBoundingClientRect();
688
- menu.style.position = "fixed";
689
- menu.style.top = (btnRect.bottom + 2) + "px";
690
- menu.style.right = (window.innerWidth - btnRect.right) + "px";
691
- menu.style.left = "auto";
692
- // If menu overflows below viewport, flip up
693
- var menuRect = menu.getBoundingClientRect();
694
- if (menuRect.bottom > window.innerHeight - 8) {
695
- menu.style.top = (btnRect.top - menuRect.height - 2) + "px";
696
- }
690
+ positionPopover(menu, anchorBtn, { placement: "below-right-aligned", gap: 2 });
697
691
  });
698
692
  }
699
693
 
@@ -737,15 +731,7 @@ function showLoopCtxMenu(anchorBtn, loopId, loopName, childCount) {
737
731
  refreshIcons();
738
732
 
739
733
  requestAnimationFrame(function () {
740
- var btnRect = anchorBtn.getBoundingClientRect();
741
- menu.style.position = "fixed";
742
- menu.style.top = (btnRect.bottom + 2) + "px";
743
- menu.style.right = (window.innerWidth - btnRect.right) + "px";
744
- menu.style.left = "auto";
745
- var menuRect = menu.getBoundingClientRect();
746
- if (menuRect.bottom > window.innerHeight - 8) {
747
- menu.style.top = (btnRect.top - menuRect.height - 2) + "px";
748
- }
734
+ positionPopover(menu, anchorBtn, { placement: "below-right-aligned", gap: 2 });
749
735
  });
750
736
  }
751
737
 
@@ -1,5 +1,6 @@
1
1
  import { refreshIcons, iconHtml } from './icons.js';
2
2
  import { pushOverlayState, popOverlayState } from './overlay-history.js';
3
+ import { positionPopover } from './popover-position.js';
3
4
 
4
5
  var ctx;
5
6
  var notes = new Map(); // id -> { data, el }
@@ -835,10 +836,9 @@ function showColorPicker(anchor, noteEl, noteId) {
835
836
  document.body.appendChild(picker);
836
837
  colorPickerEl = picker;
837
838
 
838
- // Position relative to anchor
839
- var rect = anchor.getBoundingClientRect();
840
- picker.style.left = rect.left + "px";
841
- picker.style.top = (rect.bottom + 4) + "px";
839
+ // Position relative to anchor, clamped to the viewport on all four edges
840
+ // (lr-a10a: this popover previously had no clamp at all).
841
+ positionPopover(picker, anchor, { placement: "below", gap: 4 });
842
842
 
843
843
  // Close on outside click
844
844
  setTimeout(function () {
@@ -3,6 +3,7 @@ import { closeSidebar } from './sidebar.js';
3
3
  import { closeFileViewer } from './filebrowser.js';
4
4
  import { copyToClipboard } from './utils.js';
5
5
  import { getTerminalTheme } from './theme.js';
6
+ import { positionAtPoint } from './popover-position.js';
6
7
 
7
8
  var ctx;
8
9
  var tabs = new Map(); // termId -> { id, title, exited, xterm, fitAddon, bodyEl }
@@ -877,19 +878,11 @@ function showTermCtxMenu(e, tab) {
877
878
  });
878
879
  menu.appendChild(clearItem);
879
880
 
880
- // Position at mouse cursor
881
- menu.style.left = e.clientX + "px";
882
- menu.style.top = e.clientY + "px";
881
+ // Position at mouse cursor, clamped to viewport on all four edges
882
+ // (lr-a10a: mobile's synthetic contextmenu can fire from a low/edge
883
+ // touch point, so a right/bottom-only clamp isn't enough).
883
884
  document.body.appendChild(menu);
884
-
885
- // Clamp to viewport
886
- var rect = menu.getBoundingClientRect();
887
- if (rect.right > window.innerWidth) {
888
- menu.style.left = (window.innerWidth - rect.width - 4) + "px";
889
- }
890
- if (rect.bottom > window.innerHeight) {
891
- menu.style.top = (window.innerHeight - rect.height - 4) + "px";
892
- }
885
+ positionAtPoint(menu, { x: e.clientX, y: e.clientY });
893
886
 
894
887
  termCtxMenu = menu;
895
888
  refreshIcons();
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;
@@ -0,0 +1,85 @@
1
+ // lr-9d4b: Shared keep-vs-clear decision for session.pendingPermissions /
2
+ // activeTaskToolIds / taskIdMap at turn-boundary cleanup sites.
3
+ //
4
+ // Two call sites reset this same state at the end of a turn:
5
+ // - sdk-message-processor.js: the 'result' message handler
6
+ // - sdk-bridge.js: processQueryStream's finally block (normal, non-
7
+ // superseded completion)
8
+ // Both used to unconditionally wipe session.pendingPermissions, which
9
+ // destroys a backgrounded sub-agent's still-open permission resolver if the
10
+ // sub-agent's own tool call (e.g. Bash) is still awaiting the operator's
11
+ // approval when the parent turn ends. The permission card stays on the UI,
12
+ // but the resolver is gone, so the sub-agent's canUseTool Promise (no
13
+ // timeout on the in-process path) hangs forever (lr-9d4b root cause).
14
+ //
15
+ // This module computes which entries are owned by a still-active
16
+ // backgrounded sub-agent (via session.subagentToolOwners, recorded in
17
+ // processSubagentMessage) so both cleanup sites can preserve them instead of
18
+ // wiping them, mirroring the existing _keepAskUser preservation pattern for
19
+ // session.pendingAskUser (mcp-mode entries survive the same cleanup sites).
20
+
21
+ /**
22
+ * Partition session.pendingPermissions into entries to keep (owned by a
23
+ * still-active backgrounded sub-agent) vs. the rest (top-level, or a
24
+ * sub-agent whose owning Task has already finished) — the latter are
25
+ * cleared exactly as before.
26
+ *
27
+ * @param {object} session - session object with pendingPermissions,
28
+ * subagentToolOwners, activeTaskToolIds.
29
+ * @returns {{keptPermissions: object, preservedTaskIds: object}}
30
+ * keptPermissions: requestId -> pending entry, to become the new
31
+ * session.pendingPermissions.
32
+ * preservedTaskIds: Task tool-use id -> true, for the caller to also keep
33
+ * the corresponding activeTaskToolIds/taskIdMap entries (the sub-agent's
34
+ * bookkeeping must survive alongside its pending permission).
35
+ */
36
+ function partitionSubagentOwnedPermissions(session) {
37
+ var keptPermissions = {};
38
+ var pendingPermissions = session.pendingPermissions || {};
39
+ var subagentToolOwners = session.subagentToolOwners || {};
40
+ var activeTaskToolIds = session.activeTaskToolIds || {};
41
+
42
+ var permissionIds = Object.keys(pendingPermissions);
43
+ for (var i = 0; i < permissionIds.length; i++) {
44
+ var pid = permissionIds[i];
45
+ var pentry = pendingPermissions[pid];
46
+ var owningTaskId = pentry && pentry.toolUseId ? subagentToolOwners[pentry.toolUseId] : null;
47
+ if (owningTaskId && activeTaskToolIds[owningTaskId]) {
48
+ keptPermissions[pid] = pentry;
49
+ }
50
+ }
51
+
52
+ var preservedTaskIds = {};
53
+ for (var kpid in keptPermissions) {
54
+ var kpTaskId = subagentToolOwners[keptPermissions[kpid].toolUseId];
55
+ preservedTaskIds[kpTaskId] = true;
56
+ }
57
+
58
+ return { keptPermissions: keptPermissions, preservedTaskIds: preservedTaskIds };
59
+ }
60
+
61
+ /**
62
+ * Apply the partition result to activeTaskToolIds/taskIdMap, keeping only
63
+ * entries for Task ids whose permission was just preserved.
64
+ *
65
+ * @param {object} session
66
+ * @param {object} preservedTaskIds - from partitionSubagentOwnedPermissions.
67
+ */
68
+ function retainPreservedTaskBookkeeping(session, preservedTaskIds) {
69
+ var nextActiveTaskToolIds = {};
70
+ for (var atk in (session.activeTaskToolIds || {})) {
71
+ if (preservedTaskIds[atk]) nextActiveTaskToolIds[atk] = session.activeTaskToolIds[atk];
72
+ }
73
+ session.activeTaskToolIds = nextActiveTaskToolIds;
74
+
75
+ var nextTaskIdMap = {};
76
+ for (var tik in (session.taskIdMap || {})) {
77
+ if (preservedTaskIds[tik]) nextTaskIdMap[tik] = session.taskIdMap[tik];
78
+ }
79
+ session.taskIdMap = nextTaskIdMap;
80
+ }
81
+
82
+ module.exports = {
83
+ partitionSubagentOwnedPermissions: partitionSubagentOwnedPermissions,
84
+ retainPreservedTaskBookkeeping: retainPreservedTaskBookkeeping,
85
+ };