@clagentic/console 1.11.0 → 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 (99) hide show
  1. package/README.md +1 -0
  2. package/bin/cli.js +14 -2
  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/arg-validation.js +1 -1
  8. package/lib/cli/duration.js +27 -0
  9. package/lib/cli/ipc-subcommands.js +26 -0
  10. package/lib/cli/schedule-input-subcommands.js +1 -22
  11. package/lib/cli/session-subcommands.js +38 -7
  12. package/lib/daemon.js +26 -0
  13. package/lib/notification-prefs.js +257 -0
  14. package/lib/notify/core.js +175 -0
  15. package/lib/notify/index.js +31 -0
  16. package/lib/notify/live-prompts.js +36 -0
  17. package/lib/notify/payload.js +63 -0
  18. package/lib/notify/target.js +5 -0
  19. package/lib/notify/type-registry.js +64 -0
  20. package/lib/notify/types.js +20 -0
  21. package/lib/open-sockets.js +27 -0
  22. package/lib/outbound-access.js +74 -0
  23. package/lib/outbound-entry.js +109 -0
  24. package/lib/outbound-ledger.js +306 -0
  25. package/lib/outbound-query.js +153 -0
  26. package/lib/pending-prompts.js +31 -16
  27. package/lib/project-connection.js +40 -1
  28. package/lib/project-filesystem.js +20 -5
  29. package/lib/project-http.js +9 -1
  30. package/lib/project-loop.js +25 -13
  31. package/lib/project-notifications.js +206 -42
  32. package/lib/project-prompt-responses.js +1 -1
  33. package/lib/project-sessions.js +30 -1
  34. package/lib/project.js +15 -1
  35. package/lib/prompt-registry.js +92 -24
  36. package/lib/prompt-reminders.js +282 -0
  37. package/lib/prompt-source.js +43 -8
  38. package/lib/public/app.js +1 -0
  39. package/lib/public/css/diagnostics.css +28 -0
  40. package/lib/public/css/home-hub.css +12 -0
  41. package/lib/public/css/icon-strip.css +9 -0
  42. package/lib/public/css/input.css +93 -0
  43. package/lib/public/css/menus.css +22 -0
  44. package/lib/public/css/mobile-nav.css +11 -0
  45. package/lib/public/css/server-settings.css +24 -0
  46. package/lib/public/css/sidebar.css +24 -0
  47. package/lib/public/index.html +6 -0
  48. package/lib/public/modules/activity-state.js +20 -4
  49. package/lib/public/modules/app-connection.js +22 -5
  50. package/lib/public/modules/app-header.js +2 -0
  51. package/lib/public/modules/app-messages.js +6 -2
  52. package/lib/public/modules/app-notifications.js +65 -40
  53. package/lib/public/modules/app-projects.js +3 -1
  54. package/lib/public/modules/app-rate-limit.js +12 -6
  55. package/lib/public/modules/app-rendering.js +26 -3
  56. package/lib/public/modules/build-update-sessions.js +81 -0
  57. package/lib/public/modules/collapsible-text.js +77 -0
  58. package/lib/public/modules/diagnostics.js +9 -2
  59. package/lib/public/modules/env-shadow-notice.js +34 -0
  60. package/lib/public/modules/keep-alive.js +66 -0
  61. package/lib/public/modules/notification-prefs.js +151 -0
  62. package/lib/public/modules/notify-client.js +153 -0
  63. package/lib/public/modules/project-settings.js +5 -0
  64. package/lib/public/modules/prompt-reminders-setting.js +13 -0
  65. package/lib/public/modules/prompt-state.js +3 -3
  66. package/lib/public/modules/prompts.js +1 -1
  67. package/lib/public/modules/server-settings.js +3 -0
  68. package/lib/public/modules/sidebar-mobile.js +8 -0
  69. package/lib/public/modules/sidebar-sessions.js +27 -0
  70. package/lib/public/modules/terminal-links.js +175 -0
  71. package/lib/public/modules/terminal.js +19 -103
  72. package/lib/public/notify-sw-logic.js +300 -0
  73. package/lib/public/notify-target.js +97 -0
  74. package/lib/public/sw.js +15 -62
  75. package/lib/push-audience.js +84 -0
  76. package/lib/push.js +87 -20
  77. package/lib/runtime-env.js +1 -0
  78. package/lib/sdk-bridge.js +83 -36
  79. package/lib/sdk-message-processor.js +148 -49
  80. package/lib/sender-ref.js +3 -0
  81. package/lib/server.js +80 -4
  82. package/lib/session-directory.js +6 -4
  83. package/lib/session-input-ipc.js +11 -1
  84. package/lib/session-input.js +95 -14
  85. package/lib/session-liveness.js +53 -0
  86. package/lib/session-reclaim.js +37 -2
  87. package/lib/sessions.js +58 -4
  88. package/lib/usage-store.js +403 -0
  89. package/lib/vendor-auth.js +33 -2
  90. package/lib/ws-schema.js +13 -2
  91. package/lib/yoke/adapters/claude-vendor.js +11 -1
  92. package/lib/yoke/adapters/claude.js +17 -0
  93. package/lib/yoke/adapters/codex.js +5 -1
  94. package/lib/yoke/auth-checks.js +17 -2
  95. package/lib/yoke/index.js +21 -3
  96. package/lib/yoke/provider-credentials.js +24 -0
  97. package/lib/yoke/registry.js +8 -1
  98. package/package.json +2 -2
  99. package/scripts/check-test-count.js +14 -0
@@ -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
+ });
@@ -0,0 +1,97 @@
1
+ // The notification target model, shared by the server notification core
2
+ // (lib/notify/), the service worker (importScripts) and the page's ES modules
3
+ // (side-effect import, then read from globalThis). A classic script with no
4
+ // import/export so all three can load it.
5
+ //
6
+ // A target names where a notification's action lives: the project (slug), the
7
+ // console session (sessionId) and, where there is one, the prompt (requestId).
8
+ // Session ids restart in every project, so a target without its slug is
9
+ // ambiguous: the slug is always part of its identity.
10
+ (function (root, factory) {
11
+ var api = factory();
12
+ // Always published on the global too: a module-graph import in a CommonJS
13
+ // host (the tests) evaluates this file as CJS and reads it from there.
14
+ root.NotifyTarget = api;
15
+ if (typeof module === "object" && module.exports) module.exports = api;
16
+ })(typeof self !== "undefined" ? self : globalThis, function () {
17
+ var SLUG_RE = /^[a-z0-9_-]+$/;
18
+
19
+ // An id is a string or a number; anything else (an object from a hostile or
20
+ // broken message) names nothing, and is never coerced to text.
21
+ function present(v) {
22
+ return (typeof v === "string" && v !== "") || typeof v === "number";
23
+ }
24
+
25
+ /**
26
+ * @param {{slug: ?string, sessionId: ?(number|string), requestId: ?string}} t
27
+ * @returns {{slug: ?string, sessionId: ?string, requestId: ?string}|null}
28
+ * a normalised target, or null when the input names no valid target. An id
29
+ * is carried as a string; a slug that is not a plain project slug is
30
+ * refused, since it ends up in a URL path.
31
+ */
32
+ function makeTarget(t) {
33
+ if (!t || typeof t !== "object") return null;
34
+ var slug = present(t.slug) ? String(t.slug) : null;
35
+ if (slug !== null && !SLUG_RE.test(slug)) return null;
36
+ return {
37
+ slug: slug,
38
+ sessionId: present(t.sessionId) ? String(t.sessionId) : null,
39
+ requestId: present(t.requestId) ? String(t.requestId) : null,
40
+ };
41
+ }
42
+
43
+ /** The one identity behind collapse, close and route: slug:sessionId[:requestId]. */
44
+ function targetKey(t) {
45
+ var n = makeTarget(t);
46
+ if (!n) return "";
47
+ var key = (n.slug || "") + ":" + (n.sessionId || "");
48
+ return n.requestId ? key + ":" + n.requestId : key;
49
+ }
50
+
51
+ /** The session-level identity (no request): slug:sessionId. */
52
+ function sessionKey(t) {
53
+ var n = makeTarget(t);
54
+ return n ? (n.slug || "") + ":" + (n.sessionId || "") : "";
55
+ }
56
+
57
+ /**
58
+ * The deep link that opens a target: <base>p/<slug>/?session=<id>[&request=<id>].
59
+ * A target with no slug (a system notice) opens the base page.
60
+ * @param {object} target
61
+ * @param {string} [base] the app root with a trailing slash; "/" by default.
62
+ */
63
+ function urlForTarget(target, base) {
64
+ var n = makeTarget(target);
65
+ var root = base || "/";
66
+ if (root.charAt(root.length - 1) !== "/") root += "/";
67
+ if (!n || !n.slug) return root;
68
+ var url = root + "p/" + n.slug + "/";
69
+ var q = [];
70
+ if (n.sessionId) q.push("session=" + encodeURIComponent(n.sessionId));
71
+ if (n.requestId) q.push("request=" + encodeURIComponent(n.requestId));
72
+ return q.length ? url + "?" + q.join("&") : url;
73
+ }
74
+
75
+ /**
76
+ * Reads a deep link's query. The slug comes from the path the page was
77
+ * served on, so only the session and the request are in the query.
78
+ * @param {string} search location.search
79
+ * @returns {{sessionId: string, requestId: ?string}|null}
80
+ */
81
+ function parseDeepLink(search) {
82
+ if (typeof search !== "string" || !search) return null;
83
+ var params = new URLSearchParams(search);
84
+ var session = params.get("session");
85
+ if (!session || !/^[0-9]+$/.test(session)) return null;
86
+ var request = params.get("request");
87
+ return { sessionId: session, requestId: request || null };
88
+ }
89
+
90
+ return {
91
+ makeTarget: makeTarget,
92
+ targetKey: targetKey,
93
+ sessionKey: sessionKey,
94
+ urlForTarget: urlForTarget,
95
+ parseDeepLink: parseDeepLink,
96
+ };
97
+ });
package/lib/public/sw.js CHANGED
@@ -115,75 +115,28 @@ self.addEventListener("fetch", function (event) {
115
115
 
116
116
  // --- Push notifications ---
117
117
 
118
+ // The show, close and tap logic lives in notify-sw-logic.js so it can be tested
119
+ // without a browser; this file only wires it to the worker's events.
120
+ importScripts("/notify-target.js", "/notify-sw-logic.js");
121
+
122
+ function notifyEnv() {
123
+ return {
124
+ registration: self.registration,
125
+ clients: self.clients,
126
+ userAgent: self.navigator ? self.navigator.userAgent : "",
127
+ scope: self.registration.scope || "/",
128
+ };
129
+ }
130
+
118
131
  self.addEventListener("push", function (event) {
119
132
  var data = {};
120
133
  try { data = event.data.json(); } catch (e) { return; }
121
-
122
- // Silent validation push, do not show notification
123
- if (data.type === "test") return;
124
-
125
- var options = {
126
- body: data.body || "",
127
- tag: data.tag || "clagentic",
128
- data: data,
129
- };
130
-
131
- if (data.type === "permission_request") {
132
- options.requireInteraction = true;
133
- options.tag = "perm-" + data.requestId;
134
- } else if (data.type === "done") {
135
- options.tag = data.tag || "claude-done";
136
- } else if (data.type === "ask_user") {
137
- options.requireInteraction = true;
138
- options.tag = "claude-ask";
139
- } else if (data.type === "error") {
140
- options.requireInteraction = true;
141
- options.tag = "claude-error";
142
- } else if (data.type === "dm") {
143
- options.tag = data.tag || "dm";
144
- }
145
-
146
- event.waitUntil(
147
- self.clients.matchAll({ type: "window", includeUncontrolled: true }).then(function (clientList) {
148
- // Always show permission requests, questions, and errors
149
- // Only suppress "done" notifications when app is in foreground
150
- if (data.type !== "permission_request" && data.type !== "ask_user" && data.type !== "error") {
151
- for (var i = 0; i < clientList.length; i++) {
152
- if (clientList[i].focused || clientList[i].visibilityState === "visible") return;
153
- }
154
- }
155
- return self.registration.showNotification(data.title || "Clagentic: Console", options);
156
- }).catch(function () {})
157
- );
134
+ event.waitUntil(NotifySw.handlePush(notifyEnv(), data).catch(function () {}));
158
135
  });
159
136
 
160
137
  // --- Notification click ---
161
138
 
162
139
  self.addEventListener("notificationclick", function (event) {
163
- var data = event.notification.data || {};
164
140
  event.notification.close();
165
-
166
- // Build target URL from slug so we open the correct project
167
- var baseUrl = self.registration.scope || "/";
168
- var targetUrl = data.slug ? baseUrl + "p/" + data.slug + "/" : baseUrl;
169
-
170
- event.waitUntil(
171
- self.clients.matchAll({ type: "window", includeUncontrolled: true }).then(function (clientList) {
172
- // Prefer a client already on the correct project
173
- for (var i = 0; i < clientList.length; i++) {
174
- if (clientList[i].url.indexOf(targetUrl) !== -1) {
175
- return clientList[i].focus();
176
- }
177
- }
178
- // Fall back to any visible client
179
- for (var i = 0; i < clientList.length; i++) {
180
- if (clientList[i].visibilityState !== "hidden") {
181
- return clientList[i].focus();
182
- }
183
- }
184
- if (clientList.length > 0) return clientList[0].focus();
185
- return self.clients.openWindow(targetUrl);
186
- })
187
- );
141
+ event.waitUntil(NotifySw.handleClick(notifyEnv(), event.notification));
188
142
  });
189
-