@clagentic/console 1.12.0-beta.1 → 1.12.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +1 -0
  2. package/bin/cli.js +2 -1
  3. package/lib/build-changes.js +8 -2
  4. package/lib/build-sha.json +2 -2
  5. package/lib/build-update-offer.js +31 -7
  6. package/lib/claude-settings-env.js +142 -0
  7. package/lib/cli/duration.js +27 -0
  8. package/lib/cli/schedule-input-subcommands.js +1 -22
  9. package/lib/cli/session-subcommands.js +38 -7
  10. package/lib/daemon.js +6 -0
  11. package/lib/notification-prefs.js +2 -0
  12. package/lib/notify/core.js +175 -0
  13. package/lib/notify/index.js +31 -0
  14. package/lib/notify/live-prompts.js +36 -0
  15. package/lib/notify/payload.js +63 -0
  16. package/lib/notify/target.js +5 -0
  17. package/lib/notify/type-registry.js +64 -0
  18. package/lib/notify/types.js +20 -0
  19. package/lib/open-sockets.js +27 -0
  20. package/lib/outbound-access.js +74 -0
  21. package/lib/outbound-entry.js +109 -0
  22. package/lib/outbound-ledger.js +306 -0
  23. package/lib/outbound-query.js +153 -0
  24. package/lib/pending-prompts.js +31 -16
  25. package/lib/project-connection.js +40 -1
  26. package/lib/project-filesystem.js +20 -5
  27. package/lib/project-http.js +9 -1
  28. package/lib/project-loop.js +22 -7
  29. package/lib/project-notifications.js +54 -32
  30. package/lib/project-prompt-responses.js +1 -1
  31. package/lib/project-sessions.js +2 -1
  32. package/lib/project.js +15 -1
  33. package/lib/prompt-registry.js +74 -24
  34. package/lib/prompt-reminders.js +38 -33
  35. package/lib/prompt-source.js +43 -8
  36. package/lib/public/app.js +1 -0
  37. package/lib/public/css/diagnostics.css +28 -0
  38. package/lib/public/css/home-hub.css +12 -0
  39. package/lib/public/css/icon-strip.css +9 -0
  40. package/lib/public/css/mobile-nav.css +11 -0
  41. package/lib/public/css/sidebar.css +7 -0
  42. package/lib/public/index.html +3 -0
  43. package/lib/public/modules/activity-state.js +20 -4
  44. package/lib/public/modules/app-connection.js +22 -5
  45. package/lib/public/modules/app-notifications.js +47 -48
  46. package/lib/public/modules/app-projects.js +3 -1
  47. package/lib/public/modules/app-rendering.js +10 -0
  48. package/lib/public/modules/build-update-sessions.js +81 -0
  49. package/lib/public/modules/diagnostics.js +9 -2
  50. package/lib/public/modules/env-shadow-notice.js +34 -0
  51. package/lib/public/modules/notify-client.js +153 -0
  52. package/lib/public/modules/project-settings.js +5 -0
  53. package/lib/public/modules/prompt-state.js +3 -3
  54. package/lib/public/modules/prompts.js +1 -1
  55. package/lib/public/modules/server-settings.js +3 -0
  56. package/lib/public/modules/terminal-links.js +175 -0
  57. package/lib/public/modules/terminal.js +19 -103
  58. package/lib/public/notify-sw-logic.js +300 -0
  59. package/lib/public/notify-target.js +97 -0
  60. package/lib/public/sw.js +15 -68
  61. package/lib/push.js +63 -19
  62. package/lib/runtime-env.js +1 -0
  63. package/lib/sdk-bridge.js +62 -30
  64. package/lib/sdk-message-processor.js +78 -37
  65. package/lib/server.js +34 -2
  66. package/lib/session-directory.js +6 -4
  67. package/lib/session-input-ipc.js +11 -1
  68. package/lib/session-input.js +89 -14
  69. package/lib/session-liveness.js +53 -0
  70. package/lib/session-reclaim.js +37 -2
  71. package/lib/sessions.js +31 -4
  72. package/lib/usage-store.js +29 -7
  73. package/lib/vendor-auth.js +33 -2
  74. package/lib/ws-schema.js +6 -1
  75. package/lib/yoke/adapters/claude-vendor.js +11 -1
  76. package/lib/yoke/adapters/claude.js +7 -0
  77. package/lib/yoke/auth-checks.js +17 -2
  78. package/lib/yoke/index.js +21 -3
  79. package/lib/yoke/provider-credentials.js +24 -0
  80. package/lib/yoke/registry.js +8 -1
  81. package/package.json +2 -2
  82. package/scripts/check-test-count.js +14 -0
@@ -0,0 +1,175 @@
1
+ // Link detection for the console terminal, kept free of DOM and app imports so
2
+ // it can be unit-tested against a fake xterm buffer.
3
+ //
4
+ // xterm's WebLinksAddon only sees one row. This provider rebuilds "logical
5
+ // lines" and detects URLs that span rows in two cases:
6
+ // 1. soft wrap: xterm marked the continuation row isWrapped.
7
+ // 2. hard wrap: a program printed the URL itself across rows, so xterm did
8
+ // not mark isWrapped. Joined only when the row is full to the last column
9
+ // and ends inside a URL, and the next row is nothing but URL text: one
10
+ // whitespace-free token, with only padding after it.
11
+ //
12
+ // Remaining ambiguity: a real newline right after a URL that ends exactly at
13
+ // the last column, followed by a single-token line (for example "Done"), looks
14
+ // the same as a hard wrap and is joined. A following line with more than one
15
+ // word is never joined.
16
+
17
+ var URL_CHAR_CLASS = "[^\\s'\"\\]>)}{]";
18
+ var URL_RE_SOURCE = "https?:\\/\\/" + URL_CHAR_CLASS + "+";
19
+ var URL_AT_ROW_END_RE = new RegExp(URL_RE_SOURCE + "$");
20
+ var URL_CONTINUATION_RE = new RegExp("^" + URL_CHAR_CLASS + "+$");
21
+
22
+ function rowText(buffer, y, trimRight) {
23
+ var line = buffer.getLine(y);
24
+ return line ? line.translateToString(trimRight) : null;
25
+ }
26
+
27
+ // A URL longer than this many rows is cut here: joining stops and the row past
28
+ // the bound is treated as not continued. Far above any sign-in URL, and it
29
+ // keeps every lookup linear in a fixed window instead of in buffer length.
30
+ export var MAX_LINK_ROWS = 64;
31
+
32
+ // Row y fills to the last column and row y+1 is URL text alone, not marked as
33
+ // a soft-wrapped row. Looks at two rows only.
34
+ function hardWrapCandidate(buffer, y, cols) {
35
+ var next = buffer.getLine(y + 1);
36
+ if (!next || next.isWrapped) return false;
37
+ var text = rowText(buffer, y, false);
38
+ if (text === null || text.length < cols) return false;
39
+ var nextText = rowText(buffer, y + 1, true);
40
+ return nextText !== null && URL_CONTINUATION_RE.test(nextText);
41
+ }
42
+
43
+ // hard[i] is true when row lo+i continues onto the next row by a hard wrap.
44
+ // One forward pass: a row qualifies when it ends in a URL, or when it is one
45
+ // full-width token continuing a hard wrap from the row above. The row before
46
+ // lo is assumed not to continue, which is the cut at the bound.
47
+ function hardWrapFlags(buffer, lo, hi, cols) {
48
+ var flags = [];
49
+ var prev = false;
50
+ for (var y = lo; y <= hi; y++) {
51
+ var flag = false;
52
+ if (hardWrapCandidate(buffer, y, cols)) {
53
+ var text = rowText(buffer, y, false);
54
+ var token = text.match(/\S+$/);
55
+ flag = !!token && (URL_AT_ROW_END_RE.test(text) || (token[0].length === cols && prev));
56
+ }
57
+ flags.push(flag);
58
+ prev = flag;
59
+ }
60
+ return flags;
61
+ }
62
+
63
+ function getLogicalLine(buffer, y, cols) {
64
+ var lo = Math.max(0, y - MAX_LINK_ROWS);
65
+ var hi = Math.min(buffer.length - 1, y + MAX_LINK_ROWS);
66
+ var hard = hardWrapFlags(buffer, lo, hi, cols);
67
+
68
+ var startY = y;
69
+ while (startY > lo && y - startY < MAX_LINK_ROWS - 1) {
70
+ var line = buffer.getLine(startY);
71
+ if (!line) break;
72
+ if (!line.isWrapped && !hard[startY - 1 - lo]) break;
73
+ startY--;
74
+ }
75
+
76
+ var endY = startY;
77
+ while (endY < hi && endY - startY < MAX_LINK_ROWS - 1) {
78
+ var next = buffer.getLine(endY + 1);
79
+ if (!next || !(next.isWrapped || hard[endY - lo])) break;
80
+ endY++;
81
+ }
82
+
83
+ var text = "";
84
+ var rowOffsets = []; // { y, startOffset, length }
85
+ for (var row = startY; row <= endY; row++) {
86
+ var t = rowText(buffer, row, row === endY); // trim trailing spaces on the last row only
87
+ if (t === null) break;
88
+ rowOffsets.push({ y: row, startOffset: text.length, length: t.length });
89
+ text += t;
90
+ }
91
+
92
+ return { text: text, startY: startY, endY: endY, rowOffsets: rowOffsets };
93
+ }
94
+
95
+ function offsetToBufferPos(rowOffsets, offset) {
96
+ for (var i = 0; i < rowOffsets.length; i++) {
97
+ var ro = rowOffsets[i];
98
+ if (offset < ro.startOffset + ro.length) {
99
+ return { x: offset - ro.startOffset + 1, y: ro.y + 1 }; // 1-based
100
+ }
101
+ }
102
+ var last = rowOffsets[rowOffsets.length - 1];
103
+ return { x: last.length + 1, y: last.y + 1 };
104
+ }
105
+
106
+ // Every URL in the logical line that crosses a row boundary.
107
+ function findMultiRowUrls(logical) {
108
+ var re = new RegExp(URL_RE_SOURCE, "g");
109
+ var found = [];
110
+ var match;
111
+ while ((match = re.exec(logical.text)) !== null) {
112
+ var start = offsetToBufferPos(logical.rowOffsets, match.index);
113
+ var end = offsetToBufferPos(logical.rowOffsets, match.index + match[0].length - 1);
114
+ if (start.y !== end.y) found.push({ url: match[0], start: start, end: end });
115
+ }
116
+ return found;
117
+ }
118
+
119
+ // opts.onHover(url) / opts.onLeave() let the owner remember the link under
120
+ // the pointer, for a copy-link action.
121
+ export function createMultiLineLinkProvider(xterm, opts) {
122
+ opts = opts || {};
123
+ return {
124
+ provideLinks: function (y, callback) {
125
+ var buffer = xterm.buffer.active;
126
+ var bufferY = y - 1; // provideLinks is 1-based
127
+ var logical = getLogicalLine(buffer, bufferY, xterm.cols);
128
+
129
+ if (logical.startY === logical.endY || bufferY !== logical.startY) {
130
+ callback(undefined);
131
+ return;
132
+ }
133
+
134
+ var links = findMultiRowUrls(logical).map(function (hit) {
135
+ return {
136
+ range: { start: hit.start, end: hit.end },
137
+ text: hit.url,
138
+ activate: function () {
139
+ window.open(hit.url, "_blank", "noopener");
140
+ },
141
+ hover: function () {
142
+ if (opts.onHover) opts.onHover(hit.url);
143
+ },
144
+ leave: function () {
145
+ if (opts.onLeave) opts.onLeave();
146
+ },
147
+ };
148
+ });
149
+
150
+ callback(links.length > 0 ? links : undefined);
151
+ },
152
+ };
153
+ }
154
+
155
+ // getSelection() joins rows with a newline. When the whole selection sits
156
+ // inside one multi-row URL, return the selected part of the URL with the row
157
+ // breaks removed; otherwise return the selection unchanged.
158
+ export function copyTextForSelection(xterm, selection) {
159
+ if (!selection || !/[\r\n]/.test(selection)) return selection;
160
+ var pos = xterm.getSelectionPosition && xterm.getSelectionPosition();
161
+ if (!pos) return selection;
162
+ var buffer = xterm.buffer.active;
163
+ var logical = getLogicalLine(buffer, pos.start.y, xterm.cols);
164
+ if (logical.endY < pos.end.y) return selection;
165
+ var joined = selection.replace(/[\r\n]+/g, "");
166
+ var urls = findMultiRowUrls(logical);
167
+ for (var i = 0; i < urls.length; i++) {
168
+ var hit = urls[i];
169
+ if (pos.start.y >= hit.start.y - 1 && pos.end.y <= hit.end.y - 1 &&
170
+ hit.url.indexOf(joined) !== -1) {
171
+ return joined;
172
+ }
173
+ }
174
+ return selection;
175
+ }
@@ -4,6 +4,7 @@ import { closeFileViewer } from './filebrowser.js';
4
4
  import { copyToClipboard } from './utils.js';
5
5
  import { getTerminalTheme } from './theme.js';
6
6
  import { positionAtPoint } from './popover-position.js';
7
+ import { createMultiLineLinkProvider, copyTextForSelection } from './terminal-links.js';
7
8
 
8
9
  var ctx;
9
10
  var tabs = new Map(); // termId -> { id, title, exited, xterm, fitAddon, bodyEl }
@@ -33,106 +34,6 @@ function disposeTab(tab) {
33
34
  var toolbarBound = false;
34
35
  var termCtxMenu = null;
35
36
 
36
- // --- Multi-line link provider ---
37
- // xterm's WebLinksAddon only detects URLs on a single line.
38
- // This provider reconstructs "logical lines" from wrapped buffer lines
39
- // and detects URLs that span multiple rows.
40
- function createMultiLineLinkProvider(xterm) {
41
- var URL_RE = /https?:\/\/[^\s'"\]>)}{]+/g;
42
-
43
- function getLogicalLine(buffer, y) {
44
- // Walk backward to find the start of the logical line
45
- var startY = y;
46
- while (startY > 0) {
47
- var line = buffer.getLine(startY);
48
- if (!line || !line.isWrapped) break;
49
- startY--;
50
- }
51
-
52
- // Walk forward to collect all wrapped continuation lines
53
- var endY = startY;
54
- var cols = xterm.cols;
55
- while (endY < buffer.length - 1) {
56
- var next = buffer.getLine(endY + 1);
57
- if (!next || !next.isWrapped) break;
58
- endY++;
59
- }
60
-
61
- // Build the full logical line text and track row boundaries
62
- var text = "";
63
- var rowOffsets = []; // { y, startOffset, length }
64
- for (var row = startY; row <= endY; row++) {
65
- var line = buffer.getLine(row);
66
- if (!line) break;
67
- var trimRight = (row === endY); // only trim trailing spaces on last row
68
- var rowText = line.translateToString(trimRight);
69
- rowOffsets.push({ y: row, startOffset: text.length, length: rowText.length });
70
- text += rowText;
71
- }
72
-
73
- return { text: text, startY: startY, endY: endY, rowOffsets: rowOffsets };
74
- }
75
-
76
- function offsetToBufferPos(rowOffsets, offset) {
77
- for (var i = 0; i < rowOffsets.length; i++) {
78
- var ro = rowOffsets[i];
79
- if (offset < ro.startOffset + ro.length) {
80
- return { x: offset - ro.startOffset + 1, y: ro.y + 1 }; // 1-based
81
- }
82
- }
83
- // Past end, clamp to last row
84
- var last = rowOffsets[rowOffsets.length - 1];
85
- return { x: last.length + 1, y: last.y + 1 };
86
- }
87
-
88
- return {
89
- provideLinks: function (y, callback) {
90
- var buffer = xterm.buffer.active;
91
- // y is 1-based in provideLinks
92
- var bufferY = y - 1;
93
- var logical = getLogicalLine(buffer, bufferY);
94
-
95
- // Only process if this logical line spans multiple rows
96
- if (logical.startY === logical.endY) {
97
- callback(undefined);
98
- return;
99
- }
100
-
101
- // Only trigger on the first row of the logical line to avoid duplicates
102
- if (bufferY !== logical.startY) {
103
- callback(undefined);
104
- return;
105
- }
106
-
107
- var links = [];
108
- var match;
109
- URL_RE.lastIndex = 0;
110
- while ((match = URL_RE.exec(logical.text)) !== null) {
111
- var urlStart = match.index;
112
- var urlEnd = match.index + match[0].length - 1;
113
-
114
- var startPos = offsetToBufferPos(logical.rowOffsets, urlStart);
115
- var endPos = offsetToBufferPos(logical.rowOffsets, urlEnd);
116
-
117
- // Only include if the URL actually spans multiple rows
118
- if (startPos.y !== endPos.y) {
119
- (function (url) {
120
- links.push({
121
- range: { start: startPos, end: endPos },
122
- text: url,
123
- activate: function () {
124
- window.open(url, "_blank", "noopener");
125
- },
126
- });
127
- })(match[0]);
128
- }
129
- }
130
-
131
- callback(links.length > 0 ? links : undefined);
132
- },
133
- };
134
- }
135
-
136
37
  // --- Init ---
137
38
  export function initTerminal(_ctx) {
138
39
  ctx = _ctx;
@@ -365,7 +266,10 @@ function createXtermForTab(tab) {
365
266
  }
366
267
 
367
268
  // Custom multi-line link provider: detect URLs that wrap across lines
368
- xterm.registerLinkProvider(createMultiLineLinkProvider(xterm));
269
+ xterm.registerLinkProvider(createMultiLineLinkProvider(xterm, {
270
+ onHover: function (url) { tab._hoverLink = url; },
271
+ onLeave: function () { tab._hoverLink = null; },
272
+ }));
369
273
 
370
274
  // Create a container div for this tab's terminal
371
275
  var bodyEl = document.createElement("div");
@@ -402,7 +306,7 @@ function createXtermForTab(tab) {
402
306
  if (e.type !== "keydown") return true;
403
307
  // Cmd/Ctrl+C: copy selection if any, otherwise send SIGINT
404
308
  if ((e.ctrlKey || e.metaKey) && e.key === "c") {
405
- var sel = xterm.getSelection();
309
+ var sel = copyTextForSelection(xterm, xterm.getSelection());
406
310
  if (sel) {
407
311
  if (navigator.clipboard && navigator.clipboard.writeText) {
408
312
  navigator.clipboard.writeText(sel).catch(function () {});
@@ -820,7 +724,19 @@ function showTermCtxMenu(e, tab) {
820
724
  menu.className = "term-ctx-menu";
821
725
 
822
726
  // Copy selection
823
- var sel = tab.xterm ? tab.xterm.getSelection() : "";
727
+ var sel = tab.xterm ? copyTextForSelection(tab.xterm, tab.xterm.getSelection()) : "";
728
+ if (tab._hoverLink) {
729
+ var hoverUrl = tab._hoverLink;
730
+ var copyLinkItem = document.createElement("button");
731
+ copyLinkItem.className = "term-ctx-item";
732
+ copyLinkItem.innerHTML = iconHtml("link") + " <span>Copy Link</span>";
733
+ copyLinkItem.addEventListener("click", function (ev) {
734
+ ev.stopPropagation();
735
+ closeTermCtxMenu();
736
+ copyToClipboard(hoverUrl);
737
+ });
738
+ menu.appendChild(copyLinkItem);
739
+ }
824
740
  if (sel) {
825
741
  var copySelItem = document.createElement("button");
826
742
  copySelItem.className = "term-ctx-item";
@@ -0,0 +1,300 @@
1
+ // The service worker's notification logic, factored out of sw.js so it runs
2
+ // under test with fake browser objects. A classic script (importScripts in the
3
+ // worker, require in node); it needs notify-target.js loaded first.
4
+ //
5
+ // env: { registration, clients, userAgent, scope, setTimeout }
6
+ (function (root, factory) {
7
+ var target = typeof module === "object" && module.exports ? require("./notify-target.js") : root.NotifyTarget;
8
+ var api = factory(target);
9
+ // Always published on the global too: a module-graph import in a CommonJS
10
+ // host (the tests) evaluates this file as CJS and reads it from there.
11
+ root.NotifySw = api;
12
+ if (typeof module === "object" && module.exports) module.exports = api;
13
+ })(typeof self !== "undefined" ? self : globalThis, function (NotifyTarget) {
14
+ var RESOLVED_LINGER_MS = 4000;
15
+
16
+ function isCore(data) {
17
+ return !!data && data.core === 1;
18
+ }
19
+
20
+ // iOS and desktop Safari revoke a push subscription whose pushes do not each
21
+ // show a notification, so a close there is a visible replacement. Other
22
+ // browsers allow a push that closes a notification and shows nothing.
23
+ function requiresVisible(userAgent) {
24
+ var ua = userAgent || "";
25
+ if (/iPhone|iPad|iPod/.test(ua)) return true;
26
+ return /Safari\//.test(ua) && !/Chrome\/|Chromium\/|Android|Edg\//.test(ua);
27
+ }
28
+
29
+ /** The options a core notification is shown with: all from the payload. */
30
+ function optionsFor(data) {
31
+ return {
32
+ body: data.body || "",
33
+ tag: data.tag,
34
+ data: data,
35
+ requireInteraction: data.requireInteraction === true,
36
+ renotify: data.renotify === true,
37
+ };
38
+ }
39
+
40
+ function showCore(env, data) {
41
+ return env.registration.showNotification(data.title || "Clagentic: Console", optionsFor(data));
42
+ }
43
+
44
+ var markerSeq = 0;
45
+
46
+ function isPlaceholder(n) {
47
+ return !!n && !!n.data && n.data.resolved === true;
48
+ }
49
+
50
+ // Shows the silent notice under a tag and closes it after `lingerMs` (at
51
+ // once for 0). The notice carries a marker unique to this close, and only a
52
+ // notification carrying that marker is closed afterwards: a newer live
53
+ // notification that took the tag in the meantime is left alone.
54
+ function showPlaceholder(env, data, tag, lingerMs) {
55
+ var marker = tag + "#" + Date.now() + "#" + (++markerSeq);
56
+ var wait = env.setTimeout || setTimeout;
57
+ function closeMine() {
58
+ return env.registration.getNotifications({ tag: tag }).then(function (left) {
59
+ left.forEach(function (n) {
60
+ if (n.data && n.data.resolvedMarker === marker) n.close();
61
+ });
62
+ });
63
+ }
64
+ return env.registration.showNotification(data.title || "Clagentic: Console", {
65
+ body: data.body || "",
66
+ tag: tag,
67
+ silent: true,
68
+ requireInteraction: false,
69
+ renotify: false,
70
+ data: { resolved: true, resolvedMarker: marker },
71
+ }).then(function () {
72
+ if (lingerMs <= 0) return closeMine();
73
+ return new Promise(function (done) {
74
+ wait(function () { closeMine().then(done, done); }, lingerMs);
75
+ });
76
+ });
77
+ }
78
+
79
+ // Closes the shown notification under each tag. Where a push must show
80
+ // something (requiresVisible), the shown one is replaced under the same tag
81
+ // by a silent, non-interactive notice that closes itself shortly after. When
82
+ // nothing was shown under any tag (the person already dismissed it), the
83
+ // push still has to show something there, so a single silent notice is shown
84
+ // and closed at once: the least visible thing such a platform allows.
85
+ function closeByTags(env, data) {
86
+ var tags = Array.isArray(data.tags) ? data.tags : [];
87
+ var visible = requiresVisible(env.userAgent);
88
+ return Promise.all(tags.map(function (tag) {
89
+ return env.registration.getNotifications({ tag: tag }).then(function (shown) {
90
+ return { tag: tag, shown: shown.filter(function (n) { return !isPlaceholder(n); }) };
91
+ });
92
+ })).then(function (found) {
93
+ if (!visible) {
94
+ found.forEach(function (f) { f.shown.forEach(function (n) { n.close(); }); });
95
+ return;
96
+ }
97
+ var matched = found.filter(function (f) { return f.shown.length > 0; });
98
+ if (matched.length === 0) {
99
+ return tags.length ? showPlaceholder(env, data, tags[0], 0) : undefined;
100
+ }
101
+ return Promise.all(matched.map(function (f) {
102
+ return showPlaceholder(env, data, f.tag, RESOLVED_LINGER_MS);
103
+ }));
104
+ });
105
+ }
106
+
107
+ // Whether the page's own record still lists the prompt a shown notification
108
+ // names. Only the notifications whose payload says the page can verify them
109
+ // (liveInState) are judged.
110
+ // notifications: the page's banner list (notifications_state).
111
+ // livePrompts: the server's list of prompts awaiting the operator, with
112
+ // the server time it was taken; a notification sent after that is not
113
+ // judged by it, as the prompt may have opened since.
114
+ function isLive(data, notifications, livePrompts) {
115
+ var t = NotifyTarget.makeTarget(data.target);
116
+ if (!t) return true;
117
+ var sessionKey = NotifyTarget.sessionKey(t);
118
+ var banner = (notifications || []).some(function (n) {
119
+ if (n && n.key && n.key === data.tag) return true;
120
+ var meta = (n && n.meta) || {};
121
+ if (data.collapse === "request" && t.requestId) {
122
+ if (meta.requestId === t.requestId) return true;
123
+ return Array.isArray(meta.requestIds) && meta.requestIds.indexOf(t.requestId) !== -1;
124
+ }
125
+ return meta.reminderKey === sessionKey;
126
+ });
127
+ if (banner) return true;
128
+ if (data.collapse !== "request" || !t.requestId || !livePrompts) return false;
129
+ if (typeof data.sentAt !== "number" || data.sentAt >= livePrompts.at) return true;
130
+ return (livePrompts.items || []).some(function (p) {
131
+ return String(p.sessionId) === t.sessionId &&
132
+ (p.requestId === t.requestId || p.toolUseId === t.requestId);
133
+ });
134
+ }
135
+
136
+ /**
137
+ * The same live check for an in-app banner: the banner's notification, in the
138
+ * shape isLive judges a shown push in. A banner the registry does not mark
139
+ * liveInState is not judged and reads as live.
140
+ * @param {object} notif a notification from notifications_state or
141
+ * notification_created.
142
+ * @param {object[]} notifications the page's notifications_state list.
143
+ * @param {?object} livePrompts the live-prompt record of the connection.
144
+ */
145
+ function isBannerLive(notif, notifications, livePrompts) {
146
+ if (!notif || notif.liveInState !== true) return true;
147
+ var meta = notif.meta || {};
148
+ return isLive({
149
+ target: { slug: notif.slug, sessionId: notif.sessionId, requestId: meta.requestId },
150
+ collapse: notif.collapse,
151
+ tag: notif.key,
152
+ sentAt: notif.createdAt,
153
+ }, notifications, livePrompts);
154
+ }
155
+
156
+ /**
157
+ * Closes the shown core notifications whose prompt has ended. The backup for
158
+ * a close push that never arrived. A page never judges another project's
159
+ * notifications: only those whose target is the page's own project.
160
+ * @param {object} registration
161
+ * @param {object[]} notifications the page's notifications_state list.
162
+ * @param {{slug: string, livePrompts: ?object}} scope the page's project
163
+ * slug, and the live-prompt record of its connection.
164
+ * @returns {Promise<number>} how many were closed.
165
+ */
166
+ function reconcileShown(registration, notifications, scope) {
167
+ var slug = scope && typeof scope.slug === "string" && scope.slug ? scope.slug : null;
168
+ if (!slug) return Promise.resolve(0);
169
+ var livePrompts = scope.livePrompts || null;
170
+ return registration.getNotifications().then(function (shown) {
171
+ var closed = 0;
172
+ shown.forEach(function (n) {
173
+ var data = n.data;
174
+ if (!isCore(data) || data.liveInState !== true) return;
175
+ if (!data.target || data.target.slug !== slug) return;
176
+ if (isLive(data, notifications, livePrompts)) return;
177
+ n.close();
178
+ closed++;
179
+ });
180
+ return closed;
181
+ });
182
+ }
183
+
184
+ // Legacy payloads shown even when the app is in the foreground: the ones
185
+ // that wait on the operator. Every other legacy type is suppressed then.
186
+ var LEGACY_ALWAYS_SHOWN = ["permission_request", "permission_reminder", "ask_user"];
187
+
188
+ function isLegacyForeground(type) {
189
+ return LEGACY_ALWAYS_SHOWN.indexOf(type) === -1;
190
+ }
191
+
192
+ // The payloads emitters not yet on the core send, shown as they always were.
193
+ function showLegacy(env, data) {
194
+ var options = {
195
+ body: data.body || "",
196
+ tag: data.tag || "clagentic",
197
+ data: data,
198
+ };
199
+ if (data.type === "permission_request") {
200
+ options.requireInteraction = true;
201
+ options.tag = "perm-" + data.requestId;
202
+ } else if (data.type === "permission_reminder") {
203
+ options.requireInteraction = true;
204
+ options.tag = data.tag || "prompt-reminder";
205
+ options.renotify = true;
206
+ } else if (data.type === "done") {
207
+ options.tag = data.tag || "claude-done";
208
+ } else if (data.type === "ask_user") {
209
+ options.requireInteraction = true;
210
+ options.tag = "claude-ask";
211
+ } else if (data.type === "dm") {
212
+ options.tag = data.tag || "dm";
213
+ }
214
+ return env.clients.matchAll({ type: "window", includeUncontrolled: true }).then(function (list) {
215
+ if (isLegacyForeground(data.type)) {
216
+ for (var i = 0; i < list.length; i++) {
217
+ if (list[i].focused || list[i].visibilityState === "visible") return;
218
+ }
219
+ }
220
+ return env.registration.showNotification(data.title || "Clagentic: Console", options);
221
+ });
222
+ }
223
+
224
+ /**
225
+ * @param {object} env
226
+ * @param {object} data the parsed push payload.
227
+ * @returns {Promise<*>}
228
+ */
229
+ function handlePush(env, data) {
230
+ if (!data || data.type === "test") return Promise.resolve();
231
+ if (isCore(data)) {
232
+ if (data.type === "notify_close") return closeByTags(env, data);
233
+ return showCore(env, data);
234
+ }
235
+ return showLegacy(env, data);
236
+ }
237
+
238
+ function legacyClick(env, data) {
239
+ var baseUrl = env.scope || "/";
240
+ var targetUrl = data.slug ? baseUrl + "p/" + data.slug + "/" : baseUrl;
241
+ return env.clients.matchAll({ type: "window", includeUncontrolled: true }).then(function (list) {
242
+ for (var i = 0; i < list.length; i++) {
243
+ if (list[i].url.indexOf(targetUrl) !== -1) return list[i].focus();
244
+ }
245
+ for (var j = 0; j < list.length; j++) {
246
+ if (list[j].visibilityState !== "hidden") return list[j].focus();
247
+ }
248
+ if (list.length > 0) return list[0].focus();
249
+ return env.clients.openWindow(targetUrl);
250
+ });
251
+ }
252
+
253
+ // Focus a window and hand it the target to route to; open one at the deep
254
+ // link when none exists. A window already on the target's project is
255
+ // preferred, so a tap does not move another project's window.
256
+ function coreClick(env, data) {
257
+ var t = NotifyTarget.makeTarget(data.target);
258
+ var base = env.scope || "/";
259
+ var url = NotifyTarget.urlForTarget(t, base);
260
+ var prefix = t && t.slug ? base + "p/" + t.slug + "/" : null;
261
+ return env.clients.matchAll({ type: "window", includeUncontrolled: true }).then(function (list) {
262
+ var pick = null;
263
+ var i;
264
+ if (prefix) {
265
+ for (i = 0; i < list.length && !pick; i++) {
266
+ if (list[i].url.indexOf(prefix) !== -1) pick = list[i];
267
+ }
268
+ }
269
+ for (i = 0; i < list.length && !pick; i++) {
270
+ if (list[i].visibilityState !== "hidden") pick = list[i];
271
+ }
272
+ if (!pick && list.length > 0) pick = list[0];
273
+ if (!pick) return env.clients.openWindow(url);
274
+ return Promise.resolve(pick.focus()).then(function () {
275
+ pick.postMessage({ type: "notify_route", target: t });
276
+ });
277
+ });
278
+ }
279
+
280
+ /**
281
+ * @param {object} env
282
+ * @param {object} notification the clicked notification (already closed by
283
+ * the caller).
284
+ */
285
+ function handleClick(env, notification) {
286
+ var data = notification.data || {};
287
+ if (data.resolved === true) return Promise.resolve();
288
+ return isCore(data) ? coreClick(env, data) : legacyClick(env, data);
289
+ }
290
+
291
+ return {
292
+ handlePush: handlePush,
293
+ handleClick: handleClick,
294
+ reconcileShown: reconcileShown,
295
+ isLive: isLive,
296
+ isBannerLive: isBannerLive,
297
+ requiresVisible: requiresVisible,
298
+ RESOLVED_LINGER_MS: RESOLVED_LINGER_MS,
299
+ };
300
+ });