@clagentic/console 1.8.0 → 1.9.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 (64) hide show
  1. package/bin/cli.js +12 -1
  2. package/lib/agents.js +13 -3
  3. package/lib/build-sha.json +2 -2
  4. package/lib/cli/ipc-subcommands.js +40 -4
  5. package/lib/daemon.js +25 -1
  6. package/lib/generated/claude-model-catalog.json +180 -0
  7. package/lib/model-catalog.js +202 -0
  8. package/lib/model-families.js +243 -0
  9. package/lib/project-connection.js +30 -5
  10. package/lib/project-loop.js +46 -2
  11. package/lib/project-sessions.js +133 -21
  12. package/lib/project-user-message.js +70 -3
  13. package/lib/project.js +11 -1
  14. package/lib/public/app.js +14 -4
  15. package/lib/public/css/base.css +14 -0
  16. package/lib/public/css/home-hub.css +28 -8
  17. package/lib/public/css/icon-strip.css +17 -0
  18. package/lib/public/css/menus.css +67 -0
  19. package/lib/public/css/messages.css +11 -0
  20. package/lib/public/css/mobile-nav.css +22 -0
  21. package/lib/public/css/server-settings.css +72 -0
  22. package/lib/public/css/sidebar.css +15 -0
  23. package/lib/public/css/title-bar.css +10 -1
  24. package/lib/public/index.html +4 -0
  25. package/lib/public/modules/activity-latch.js +159 -0
  26. package/lib/public/modules/activity-state.js +157 -0
  27. package/lib/public/modules/app-connection.js +10 -4
  28. package/lib/public/modules/app-favicon.js +88 -1
  29. package/lib/public/modules/app-home-hub.js +14 -11
  30. package/lib/public/modules/app-loop-ui.js +90 -2
  31. package/lib/public/modules/app-messages.js +117 -28
  32. package/lib/public/modules/app-panels.js +184 -56
  33. package/lib/public/modules/app-projects.js +28 -8
  34. package/lib/public/modules/app-rate-limit.js +14 -2
  35. package/lib/public/modules/model-families.js +230 -0
  36. package/lib/public/modules/project-settings.js +1 -0
  37. package/lib/public/modules/scheduler.js +5 -0
  38. package/lib/public/modules/server-settings.js +14 -12
  39. package/lib/public/modules/settings-defaults.js +151 -41
  40. package/lib/public/modules/sidebar-mobile.js +32 -22
  41. package/lib/public/modules/sidebar-projects.js +42 -14
  42. package/lib/public/modules/sidebar-sessions.js +168 -48
  43. package/lib/public/modules/tools.js +22 -12
  44. package/lib/sdk-bridge.js +389 -35
  45. package/lib/sdk-message-processor.js +215 -7
  46. package/lib/sdk-skill-discovery.js +46 -6
  47. package/lib/sdk-slash-enrichment.js +5 -2
  48. package/lib/server-hub-sessions.js +70 -0
  49. package/lib/server.js +79 -22
  50. package/lib/session-activity.js +289 -0
  51. package/lib/sessions.js +104 -3
  52. package/lib/smtp.js +10 -1
  53. package/lib/terminal-manager.js +40 -0
  54. package/lib/utils.js +44 -0
  55. package/lib/ws-schema.js +17 -0
  56. package/lib/yoke/adapters/claude-worker.js +6 -2
  57. package/lib/yoke/adapters/claude.js +384 -88
  58. package/lib/yoke/adapters/codex.js +239 -31
  59. package/package.json +2 -2
  60. package/scripts/check-test-count.js +397 -0
  61. package/scripts/generate-model-catalog.js +337 -0
  62. package/scripts/test-file-completion-reporter.js +43 -0
  63. package/lib/model-context-windows.js +0 -65
  64. package/lib/public/modules/model-context-windows.js +0 -62
package/lib/server.js CHANGED
@@ -18,6 +18,7 @@ var { CONFIG_DIR } = require("./config");
18
18
  var { provisionLinuxUser } = require("./os-users");
19
19
  var { detectLite } = require("./lite-detect");
20
20
  var { readCappedBody } = require("./utils");
21
+ var { computeAllProjectSessions } = require("./server-hub-sessions");
21
22
 
22
23
  var https = require("https");
23
24
  var pkg = require("../package.json");
@@ -1148,6 +1149,52 @@ function createServer(opts) {
1148
1149
  broadcastProcessingChange();
1149
1150
  }
1150
1151
 
1152
+ // lr-13c047 (Badge A prune-on-delete): a deleted session's crossProjectUnread
1153
+ // entry previously had no clear path at all — onSessionDone is increment-only
1154
+ // and the only clears were on full project-switch reconnect (below) or the
1155
+ // same-project ws._clayUnread zeroing in switchSession. If the session that
1156
+ // accrued the unread count is deleted before any client ever reconnects to
1157
+ // its project, that count is now permanently unreachable (its key can never
1158
+ // be zeroed by the connect-time prefix clear, since the session no longer
1159
+ // exists to switch to) — a phantom that inflates the Projects-tab badge
1160
+ // forever. Delete the key for every client of every project so the rollup
1161
+ // (getCrossProjectUnreadForSlug) stops counting it on the next broadcast.
1162
+ function onSessionDeleted(sourceSlug, sourceLocalId) {
1163
+ var key = crossUnreadKey(sourceSlug, sourceLocalId);
1164
+ var sawEntry = false;
1165
+ projects.forEach(function (ctx) {
1166
+ ctx.forEachClient(function (ws) {
1167
+ var map = getCrossProjectUnread(ws);
1168
+ if (key in map) {
1169
+ sawEntry = true;
1170
+ delete map[key];
1171
+ }
1172
+ });
1173
+ });
1174
+ if (sawEntry) broadcastProcessingChange();
1175
+ }
1176
+
1177
+ // lr-13c047 (Badge A non-switch clear path): zero every crossProjectUnread
1178
+ // entry for a given project slug, for one client, without requiring that
1179
+ // client to actually connect to (switch into) that project. Wired to a
1180
+ // client-initiated "mark_cross_project_read" WS message (lib/project-sessions.js)
1181
+ // so a user can dismiss the Projects-tab badge for a project they don't want
1182
+ // to open right now — previously the only clear path was the connect-time
1183
+ // prefix zero at :1069-1077 below, which requires a full navigation.
1184
+ function markCrossProjectRead(ws, projSlug) {
1185
+ var map = getCrossProjectUnread(ws);
1186
+ var prefix = projSlug + "::";
1187
+ var keys = Object.keys(map);
1188
+ var cleared = false;
1189
+ for (var i = 0; i < keys.length; i++) {
1190
+ if (keys[i].indexOf(prefix) === 0 && map[keys[i]]) {
1191
+ map[keys[i]] = 0;
1192
+ cleared = true;
1193
+ }
1194
+ }
1195
+ if (cleared) broadcastProcessingChange();
1196
+ }
1197
+
1151
1198
  // --- Debounced broadcast for processing status changes ---
1152
1199
  var processingUpdateTimer = null;
1153
1200
  function broadcastProcessingChange() {
@@ -1240,29 +1287,30 @@ function createServer(opts) {
1240
1287
  // recent-sessions list uses this to gather every project identically —
1241
1288
  // matching the palette's behavior — so the global recency sort is honest
1242
1289
  // and the currently-connected project doesn't dominate the result.
1243
- getAllProjectSessions: function (includeSelf) {
1244
- var allSessions = [];
1245
- projects.forEach(function (pCtx, pSlug) {
1246
- if (!includeSelf && pSlug === slug) return; // skip self unless asked
1247
- var status = pCtx.getStatus();
1248
- if (status.isWorktree) return;
1249
- var pSm = pCtx.getSessionManager();
1250
- if (!pSm) return;
1251
- var projectTitle = status.title || status.project || pSlug;
1252
- var projectIcon = status.icon || null;
1253
- pSm.sessions.forEach(function (s) {
1254
- if (!s.hidden) {
1255
- // Push a shallow copy annotated with project metadata rather than
1256
- // mutating the live session object with transient UI fields.
1257
- allSessions.push(Object.assign({}, s, {
1258
- _projectTitle: projectTitle,
1259
- _projectSlug: pSlug,
1260
- _projectIcon: projectIcon,
1261
- }));
1262
- }
1263
- });
1290
+ //
1291
+ // userId: REQUIRED to filter results to what the viewing user may
1292
+ // actually see. Unlike getProjectList/broadcastProcessingChange (which
1293
+ // the identical onGetProjectAccess + users.canAccessProject gate above
1294
+ // already protects), this function previously took no userId at all
1295
+ // and filtered only on `!s.hidden` -- it structurally could not
1296
+ // enforce per-project access or private-session visibility, leaking
1297
+ // cross-project and private sessions into the Home Hub recent-sessions
1298
+ // list. Fails CLOSED: no userId (or no onGetProjectAccess wiring) means
1299
+ // no sessions are returned. There is no legitimate no-auth caller of
1300
+ // this function -- the WS upgrade handler above rejects any connection
1301
+ // without an authenticated user (wsAuthedUser) with 401 before
1302
+ // ws._clayUser can ever be set, including in single-user/PIN mode
1303
+ // (still a real authenticated user, just one account) -- so failing
1304
+ // closed here never breaks a real deployment mode.
1305
+ getAllProjectSessions: function (includeSelf, userId) {
1306
+ return computeAllProjectSessions({
1307
+ projects: projects,
1308
+ users: users,
1309
+ onGetProjectAccess: onGetProjectAccess,
1310
+ callerSlug: slug,
1311
+ includeSelf: includeSelf,
1312
+ userId: userId,
1264
1313
  });
1265
- return allSessions;
1266
1314
  },
1267
1315
  getHubSchedules: function () {
1268
1316
  var allSchedules = [];
@@ -1329,6 +1377,15 @@ function createServer(opts) {
1329
1377
  onPresenceChange: broadcastPresenceChange,
1330
1378
  onProcessingChanged: broadcastProcessingChange,
1331
1379
  onSessionDone: function (localId) { onSessionDone(slug, localId); },
1380
+ // lr-13c047: prune crossProjectUnread['slug::localId'] for every client
1381
+ // when a session in this project is deleted — see onSessionDeleted's
1382
+ // header above.
1383
+ onSessionDeleted: function (localId) { onSessionDeleted(slug, localId); },
1384
+ // lr-13c047: expose the non-switch "mark read" clear path (see
1385
+ // markCrossProjectRead's header above) so lib/project-sessions.js can
1386
+ // wire a client-initiated mark_cross_project_read WS message without
1387
+ // reaching into server.js internals directly.
1388
+ markCrossProjectRead: function (ws, projSlug) { markCrossProjectRead(ws, projSlug); },
1332
1389
  // lr-0aa7b6: per-session unread lookup for the Home Hub Recent
1333
1390
  // Sessions data path — see getSessionUnread's header above for why
1334
1391
  // this must distinguish "own project" (ws._clayUnread) from
@@ -0,0 +1,289 @@
1
+ // lr-9bcd7b: Server-authoritative activity registry.
2
+ //
3
+ // Problem this replaces: session.isProcessing is written directly at ~26
4
+ // scattered call sites across roughly 8 files (sdk-message-processor.js,
5
+ // sdk-bridge.js, project-sessions.js, and others). One of those sites --
6
+ // the SDK 'result' handler -- clears it unconditionally with no check for
7
+ // a still-running backgrounded Task subagent (lr-255e close comment #8,
8
+ // residual #2). session_list ships isProcessing per session
9
+ // (lib/sessions.js mapSessionForClient) and every session/project/recent
10
+ // picker renders it, so every picker's green dot goes dark the instant a
11
+ // subagent starts, on top of the equivalent in-conversation dots bug.
12
+ //
13
+ // Design: reference-counted token registry, one per session, stored as
14
+ // plain data. isProcessing becomes DERIVED (token count > 0) instead of an
15
+ // independently written boolean. Any subsystem that starts genuine session
16
+ // activity acquires a token; it releases the SAME token on every terminal
17
+ // path (success, error, abort). The derived boolean cannot go stale because
18
+ // of a single missed clear site the way the old boolean could -- as long as
19
+ // acquire/release are balanced, and leak resistance (below) covers the case
20
+ // where they are not.
21
+ //
22
+ // Leak resistance -- four layers, PRIMARY listed first, weakest listed last.
23
+ // A design that trades "dots missing" for "dots stuck on forever" is not an
24
+ // improvement (a stuck dot destroys trust in the signal permanently), so
25
+ // the layers are ordered by how proactively they prevent that outcome:
26
+ //
27
+ // 1. PRIMARY -- generation counter. Each token is stamped with the
28
+ // session's activity generation at acquire time. bumpGeneration(session)
29
+ // (called by the caller on every genuine new-query/turn boundary) makes
30
+ // every token from a prior generation invisible to isSessionActive/
31
+ // getActiveCount immediately, with no timer and no explicit release
32
+ // required. This is the same ownership-guard shape already proved in
33
+ // this codebase for query/session ownership (sdk-bridge.js's
34
+ // `session.queryInstance === myQueryInstance` checks around the
35
+ // processQueryStream finally block) -- a stale reference from an
36
+ // earlier generation is simply outvoted, not manually hunted down.
37
+ // 2. Explicit release on every known terminal path (tool_result,
38
+ // task_notification, turn-boundary block_stop cleanup) -- ordinary,
39
+ // expected cleanup, exercised directly by this module's tests and by
40
+ // the sdk-message-processor wiring.
41
+ // 3. BACKSTOP ONLY -- staleness sweep. sweepStaleTokens(session, maxAgeMs)
42
+ // drops any token older than maxAgeMs regardless of generation. This
43
+ // exists purely to bound the worst case (a token whose owning
44
+ // subsystem died without ever calling release AND without a
45
+ // generation bump happening in between -- e.g. a session that idles
46
+ // forever mid-turn). It is not the primary defense and must never be
47
+ // the ONLY thing keeping the registry honest; layers 1 and 2 are
48
+ // expected to handle the overwhelming majority of releases.
49
+ // 4. Wholesale replacement on reconnect, never merge. hydrateSnapshot()
50
+ // always REPLACES a session's registry outright rather than merging
51
+ // entries -- a reconnecting client must never see a union of stale
52
+ // pre-disconnect tokens and fresh post-reconnect ones.
53
+ //
54
+ // Chattiness mitigation -- mandatory, not optional (see lr-9bcd7b spec).
55
+ // isProcessing changed ~2x/turn under the old boolean; a token registry
56
+ // changes on every tool start/stop and every subagent progress tick, which
57
+ // would be an O(sessions x clients) JSON-serialization broadcast per tool
58
+ // call if naively wired to broadcastSessionList(). The registry itself
59
+ // does NOT broadcast anything -- it is plain data. The caller (sdk-bridge.js/
60
+ // sdk-message-processor.js) is responsible for calling acquireToken/
61
+ // releaseToken and reacting ONLY to the returned `changed` flag, which is
62
+ // true exactly on a 0->1 or 1->0 transition of the derived boolean.
63
+ // Acquiring a second token while the session is already active (count >=1
64
+ // before the call) returns changed:false -- the derived boolean does not
65
+ // move, so the caller must not broadcast. This collapses volume back to
66
+ // roughly the old ~2x/turn rate (only the first acquire and the last
67
+ // release of any turn actually flip the boolean), independent of how many
68
+ // tools/subagents are concurrently active.
69
+
70
+ /**
71
+ * Create a fresh, empty activity registry for a session.
72
+ * @returns {{tokens: object, generation: number}}
73
+ */
74
+ function createRegistry() {
75
+ return {
76
+ // lr-66c118 (fold-in, flagged by BOBBIE on 2/4 and 3/4): tokens is
77
+ // written by bracket assignment (registry.tokens[token] = ...) keyed by
78
+ // SDK/Codex-supplied ids with no prototype guard. Object.create(null)
79
+ // removes the Object.prototype chain so a crafted token id (e.g.
80
+ // "__proto__" or "constructor") cannot collide with an inherited
81
+ // property/method. Session-scoped, no demonstrated exploit — cheap
82
+ // hardening, not a response to a live vulnerability.
83
+ tokens: Object.create(null), // token -> { source, label, startedAt, generation }
84
+ generation: 0,
85
+ };
86
+ }
87
+
88
+ /**
89
+ * Ensure session.activity exists, creating it if this is the first call for
90
+ * this session. Callers should prefer this over reading session.activity
91
+ * directly so a session created before this module existed (or a bare test
92
+ * double) degrades to an empty registry instead of throwing.
93
+ * @param {object} session
94
+ * @returns {{tokens: object, generation: number}}
95
+ */
96
+ function ensureRegistry(session) {
97
+ if (!session.activity) session.activity = createRegistry();
98
+ return session.activity;
99
+ }
100
+
101
+ /**
102
+ * True if the session has at least one live (current-generation) token.
103
+ * This is the DERIVED value that replaces session.isProcessing as a
104
+ * server-side write target -- see the module header for why write sites
105
+ * are being retired in favor of reading this.
106
+ * @param {object} session
107
+ * @returns {boolean}
108
+ */
109
+ function isSessionActive(session) {
110
+ return getActiveCount(session) > 0;
111
+ }
112
+
113
+ /**
114
+ * Count of live (current-generation) tokens. Stale-generation tokens that
115
+ * have not yet been physically swept still don't count -- generation is
116
+ * checked at read time, not just at sweep time, so a generation bump takes
117
+ * effect immediately even before sweepStaleTokens or the next acquire/
118
+ * release physically deletes the entries.
119
+ * @param {object} session
120
+ * @returns {number}
121
+ */
122
+ function getActiveCount(session) {
123
+ var registry = ensureRegistry(session);
124
+ var count = 0;
125
+ for (var token in registry.tokens) {
126
+ if (registry.tokens[token].generation === registry.generation) count++;
127
+ }
128
+ return count;
129
+ }
130
+
131
+ /**
132
+ * Acquire a new activity token for `source` (e.g. "task", "tool",
133
+ * "subagent"). Stamps the token with the session's CURRENT generation, so a
134
+ * token acquired just before a generation bump is immediately treated as
135
+ * stale by every reader without needing its own release call.
136
+ *
137
+ * @param {object} session
138
+ * @param {string} token - caller-chosen unique id (e.g. a tool_use id).
139
+ * Acquiring the same token twice is idempotent (see double-acquire note
140
+ * below) -- the second call refreshes label/startedAt but does not
141
+ * double-count or change `changed`.
142
+ * @param {object} [info] - { source, label }
143
+ * @returns {{changed: boolean, activeCount: number}}
144
+ * changed is true only on a 0->1 transition of isSessionActive -- the
145
+ * mandatory chattiness invariant. Acquiring a second (or further) token
146
+ * while the session is already active returns changed:false.
147
+ */
148
+ function acquireToken(session, token, info) {
149
+ var registry = ensureRegistry(session);
150
+ var wasActive = isSessionActive(session);
151
+ var existed = Object.prototype.hasOwnProperty.call(registry.tokens, token)
152
+ && registry.tokens[token].generation === registry.generation;
153
+ registry.tokens[token] = {
154
+ source: (info && info.source) || "unknown",
155
+ label: (info && info.label) || "",
156
+ startedAt: existed ? registry.tokens[token].startedAt : Date.now(),
157
+ generation: registry.generation,
158
+ };
159
+ var nowActive = true; // acquiring always leaves at least one live token
160
+ return { changed: !wasActive && nowActive, activeCount: getActiveCount(session) };
161
+ }
162
+
163
+ /**
164
+ * Release a token. Idempotent -- releasing an already-released or
165
+ * never-acquired token is a no-op (returns changed:false), never an error.
166
+ * This matters because multiple terminal paths can race to release the
167
+ * same logical unit of work (e.g. tool_result AND a later task_notification
168
+ * for the same Task tool id) -- see sdk-message-processor.js's existing
169
+ * lr-9d4b ownership-cleanup pattern, which this mirrors.
170
+ *
171
+ * @param {object} session
172
+ * @param {string} token
173
+ * @returns {{changed: boolean, activeCount: number}}
174
+ * changed is true only on a 1->0 transition of isSessionActive.
175
+ */
176
+ function releaseToken(session, token) {
177
+ var registry = ensureRegistry(session);
178
+ var wasActive = isSessionActive(session);
179
+ delete registry.tokens[token];
180
+ var nowActive = isSessionActive(session);
181
+ return { changed: wasActive && !nowActive, activeCount: getActiveCount(session) };
182
+ }
183
+
184
+ /**
185
+ * PRIMARY leak-resistance layer. Bump the session's activity generation --
186
+ * every token acquired before this call becomes invisible to
187
+ * isSessionActive/getActiveCount immediately, with no explicit release
188
+ * needed. Callers should invoke this at genuine new-query/turn-start
189
+ * boundaries (the same boundary sdk-bridge.js already treats as
190
+ * "isNewQuery" / resets activeTaskToolIds for) so a subagent or tool that
191
+ * died silently mid-turn cannot hold the indicator on forever into an
192
+ * unrelated later turn.
193
+ *
194
+ * This reuses the ownership-guard SHAPE already proved in this codebase at
195
+ * sdk-bridge.js's `session.queryInstance === myQueryInstance` checks (a
196
+ * stale reference is outvoted by identity/generation comparison, not
197
+ * tracked down and manually cleared) -- see lr-8355.
198
+ *
199
+ * @param {object} session
200
+ * @returns {{changed: boolean, activeCount: number}}
201
+ * changed is true if this bump caused a transition from active to
202
+ * inactive (i.e. every live token was stale-generation and got dropped).
203
+ */
204
+ function bumpGeneration(session) {
205
+ var registry = ensureRegistry(session);
206
+ var wasActive = isSessionActive(session);
207
+ registry.generation++;
208
+ // Physically drop stale entries now rather than waiting for the next
209
+ // sweep -- keeps registry.tokens from growing unboundedly across a very
210
+ // long-lived session with many turns.
211
+ for (var token in registry.tokens) {
212
+ if (registry.tokens[token].generation !== registry.generation) {
213
+ delete registry.tokens[token];
214
+ }
215
+ }
216
+ var nowActive = isSessionActive(session);
217
+ return { changed: wasActive && !nowActive, activeCount: getActiveCount(session) };
218
+ }
219
+
220
+ /**
221
+ * BACKSTOP ONLY leak-resistance layer -- see module header. Drops any token
222
+ * older than maxAgeMs regardless of generation. Never call this as the
223
+ * primary mechanism for clearing activity; it exists solely to bound the
224
+ * worst case where a subsystem died without releasing AND no generation
225
+ * bump has happened since (e.g. a session idling forever mid-turn with no
226
+ * new query started).
227
+ *
228
+ * @param {object} session
229
+ * @param {number} maxAgeMs
230
+ * @returns {{changed: boolean, activeCount: number, swept: number}}
231
+ */
232
+ function sweepStaleTokens(session, maxAgeMs) {
233
+ var registry = ensureRegistry(session);
234
+ var wasActive = isSessionActive(session);
235
+ var now = Date.now();
236
+ var swept = 0;
237
+ for (var token in registry.tokens) {
238
+ if (now - registry.tokens[token].startedAt > maxAgeMs) {
239
+ delete registry.tokens[token];
240
+ swept++;
241
+ }
242
+ }
243
+ var nowActive = isSessionActive(session);
244
+ return { changed: wasActive && !nowActive, activeCount: getActiveCount(session), swept: swept };
245
+ }
246
+
247
+ /**
248
+ * Wholesale-replace a session's registry (used on reconnect hydration) --
249
+ * NEVER merge with whatever the client last saw. See module header layer 4.
250
+ * @param {object} session
251
+ * @param {{tokens: object, generation: number}} [snapshot] - defaults to a
252
+ * fresh empty registry when omitted, matching "reconnect clears activity
253
+ * unless the caller has a live snapshot to restore".
254
+ */
255
+ function replaceRegistry(session, snapshot) {
256
+ session.activity = snapshot || createRegistry();
257
+ }
258
+
259
+ /**
260
+ * Detailed per-source breakdown of currently-live tokens, for scoping to
261
+ * the viewing client only (ws._clayActiveSession-style filtering) rather
262
+ * than broadcasting to every connected client -- see lr-9bcd7b spec's
263
+ * chattiness mitigation #3.
264
+ * @param {object} session
265
+ * @returns {Array<{token: string, source: string, label: string, startedAt: number}>}
266
+ */
267
+ function listActiveSources(session) {
268
+ var registry = ensureRegistry(session);
269
+ var out = [];
270
+ for (var token in registry.tokens) {
271
+ var entry = registry.tokens[token];
272
+ if (entry.generation !== registry.generation) continue;
273
+ out.push({ token: token, source: entry.source, label: entry.label, startedAt: entry.startedAt });
274
+ }
275
+ return out;
276
+ }
277
+
278
+ module.exports = {
279
+ createRegistry: createRegistry,
280
+ ensureRegistry: ensureRegistry,
281
+ isSessionActive: isSessionActive,
282
+ getActiveCount: getActiveCount,
283
+ acquireToken: acquireToken,
284
+ releaseToken: releaseToken,
285
+ bumpGeneration: bumpGeneration,
286
+ sweepStaleTokens: sweepStaleTokens,
287
+ replaceRegistry: replaceRegistry,
288
+ listActiveSources: listActiveSources,
289
+ };
package/lib/sessions.js CHANGED
@@ -19,6 +19,42 @@ var { isVisibleHistoryEvent } = require("./history-visibility");
19
19
  var HISTORY_INMEM_MAX_DEFAULT = 1000;
20
20
  var HISTORY_INMEM_TRIM_TO_DEFAULT = 800;
21
21
 
22
+ // lr-041af8: single source of truth for "what model should THIS session's
23
+ // clients see right now" — a session's own persisted/live choice always
24
+ // wins, falling back to the project/global default (sm.currentModel) only
25
+ // when the session has never picked one of its own (e.g. brand new, or a
26
+ // pre-lr-db0437 session file with no persisted model). This is the same
27
+ // precedence every per-session config_state sender already used ad hoc
28
+ // (project-sessions.js's switch_session/set_model targeted replies); lifted
29
+ // out here so the connect/hydration path and every other sender can share
30
+ // it instead of re-deriving it (and risking a third divergence — see
31
+ // lr-db0437, which fixed the WRITE side of this same shared-mutable-state
32
+ // class but never enumerated the SENDERS, which is what lr-041af8 fixes).
33
+ function effectiveSessionModel(session, sm) {
34
+ if (session && session.model) return session.model;
35
+ return (sm && sm.currentModel) || "";
36
+ }
37
+
38
+ // Message types whose client-side handler writes the global client-local
39
+ // 'processing'/'sessionIsProcessing' edge latch (app-messages.js's status/
40
+ // done/auth_required handlers). Stamping localId at the shared send choke
41
+ // points (doSendToSession/doSendAndRecord below, and project.js's own
42
+ // sendToSession/sendToSessionOthers which reuse this same list) means every
43
+ // one of the ~15 status/done/auth_required send sites across sessions.js/
44
+ // project.js/project-loop.js/sdk-bridge.js gets session-scoping for free,
45
+ // mirroring the existing scheduled_message_queued/sent localId pattern
46
+ // (project.js), without widening this to every message type — most types
47
+ // are already inherently session-scoped by their own handler logic and
48
+ // don't need it.
49
+ var ACTIVITY_LATCH_TYPES = { status: true, done: true, auth_required: true };
50
+
51
+ function stampActivityLocalId(session, obj) {
52
+ if (ACTIVITY_LATCH_TYPES[obj.type] && obj.localId === undefined) {
53
+ obj.localId = (session && session.localId !== undefined) ? session.localId : session;
54
+ }
55
+ return obj;
56
+ }
57
+
22
58
  function createSessionManager(opts) {
23
59
  var cwd = opts.cwd;
24
60
  var send = opts.send; // function(obj) - broadcast to all clients
@@ -26,6 +62,14 @@ function createSessionManager(opts) {
26
62
  var sendEach = opts.sendEach || null; // function(fn) - call fn(ws) for each connected client
27
63
  var sendAndRecord = null; // set after init via setSendAndRecord
28
64
  var onSessionDone = opts.onSessionDone || function () {};
65
+ // lr-13c047: fired whenever a session is permanently removed (single or
66
+ // bulk delete) so the server's cross-project unread map (keyed
67
+ // "slug::localId", lib/server.js) can prune the entry for this session
68
+ // instead of leaking it forever — the "prune-on-session-delete" half of
69
+ // Badge A's fix. No-op default keeps this opt-in for callers that don't
70
+ // wire cross-project unread tracking (e.g. tests constructing a bare
71
+ // SessionManager).
72
+ var onSessionDeleted = opts.onSessionDeleted || function () {};
29
73
 
30
74
  // daemon.json knob `historyInMemMax` (lr-2ea2a7): operators may override the
31
75
  // in-heap tail cap. TRIM_TO is derived as 80% of the configured max so the
@@ -83,6 +127,12 @@ function createSessionManager(opts) {
83
127
  if (session.lastRewindUuid) metaObj.lastRewindUuid = session.lastRewindUuid;
84
128
  if (session.agentName) metaObj.agentName = session.agentName;
85
129
  if (session.loop) metaObj.loop = session.loop;
130
+ // lr-db0437: persist the session's own model choice so it survives a
131
+ // daemon restart / resume. Without this, session.model only ever lived
132
+ // in memory — a restart silently reset every session back to whatever
133
+ // the project/global default happened to be, indistinguishable from the
134
+ // user never having picked a model at all.
135
+ if (session.model) metaObj.model = session.model;
86
136
  // Persist per-session "allow for session" tool grants (lr-8b2e) so they
87
137
  // survive daemon restart / resume-by-cliSessionId rehydration instead of
88
138
  // silently re-prompting. Only written when non-empty — grants that were
@@ -100,6 +150,22 @@ function createSessionManager(opts) {
100
150
  metaObj.pendingAutoResume = true;
101
151
  if (session.pendingAutoResumeReason) metaObj.pendingAutoResumeReason = session.pendingAutoResumeReason;
102
152
  }
153
+ // lr-62157d: durable auto-title state. Without this, titleAutoGenerated
154
+ // and titleManuallySet lived in memory only — every daemon restart reset
155
+ // both to false, so the "already auto-titled" / "user renamed it" guards
156
+ // at sdk-message-processor.js and sdk-bridge.js were guarding against
157
+ // state that could never actually be true after a restart. turnCount is
158
+ // persisted alongside them because the turn-threshold gate (see the
159
+ // '>=' fix at sdk-message-processor.js) depends on it surviving too —
160
+ // a restarted session that lost its turn count would silently miss the
161
+ // auto-title window forever instead of catching up on a later turn.
162
+ // titleProvisional marks a title set from the raw first-message
163
+ // truncation (project-user-message.js) so autoGenerateTitle knows it is
164
+ // safe to overwrite even though the flags above look "not yet set".
165
+ if (session.titleAutoGenerated) metaObj.titleAutoGenerated = true;
166
+ if (session.titleManuallySet) metaObj.titleManuallySet = true;
167
+ if (session.titleProvisional) metaObj.titleProvisional = true;
168
+ if (typeof session.turnCount === "number" && session.turnCount > 0) metaObj.turnCount = session.turnCount;
103
169
  return JSON.stringify(metaObj);
104
170
  }
105
171
 
@@ -679,6 +745,10 @@ function createSessionManager(opts) {
679
745
  if (m.vendor) session.vendor = m.vendor;
680
746
  if (m.agentName) session.agentName = m.agentName;
681
747
  if (m.loop) session.loop = m.loop;
748
+ // lr-db0437: restore the session's own model choice across a daemon
749
+ // restart — see buildMetaLine's write side above for why this must
750
+ // persist (session.model, not the project/global default).
751
+ if (m.model) session.model = m.model;
682
752
  if (m.ownerId) session.ownerId = m.ownerId;
683
753
  session.sessionVisibility = m.sessionVisibility || "shared";
684
754
  session.bookmarked = !!m.bookmarked;
@@ -689,6 +759,14 @@ function createSessionManager(opts) {
689
759
  session.pendingAutoResume = true;
690
760
  session.pendingAutoResumeReason = m.pendingAutoResumeReason || null;
691
761
  }
762
+ // lr-62157d: restore auto-title state across a daemon restart — see
763
+ // buildMetaLine's write side for why this must persist. Without this,
764
+ // the guards at sdk-message-processor.js/sdk-bridge.js always saw
765
+ // false/0 after a restart no matter what actually happened before it.
766
+ session.titleAutoGenerated = !!m.titleAutoGenerated;
767
+ session.titleManuallySet = !!m.titleManuallySet;
768
+ session.titleProvisional = !!m.titleProvisional;
769
+ session.turnCount = typeof m.turnCount === "number" ? m.turnCount : 0;
692
770
  sessions.set(localId, session);
693
771
  }
694
772
  }
@@ -1036,7 +1114,11 @@ function createSessionManager(opts) {
1036
1114
  var _capsByVendor = capabilitiesByVendor || {};
1037
1115
  var _sessionVendor = session.vendor || defaultVendor || "claude";
1038
1116
  var _vendorCaps = _capsByVendor[_sessionVendor] || {};
1039
- _send({ type: "session_switched", id: localId, cliSessionId: session.cliSessionId || null, loop: session.loop || null, vendor: session.vendor || null, hasHistory: (session._historyLoaded ? session.history.length > 0 : !!session.cliSessionId), capabilities: _vendorCaps, isProcessing: !!session.isProcessing, agentName: session.agentName || null });
1117
+ // lr-041af8: carry the session's own effective model on the wire so a
1118
+ // client hydrating from session_switched alone (no separate config_state
1119
+ // round-trip needed) never has to fall back to guessing the shared
1120
+ // project/global default — see effectiveSessionModel() above.
1121
+ _send({ type: "session_switched", id: localId, cliSessionId: session.cliSessionId || null, loop: session.loop || null, vendor: session.vendor || null, model: effectiveSessionModel(session, _instance), hasHistory: (session._historyLoaded ? session.history.length > 0 : !!session.cliSessionId), capabilities: _vendorCaps, isProcessing: !!session.isProcessing, agentName: session.agentName || null });
1040
1122
  // Send vendor-specific slash commands
1041
1123
  var _vendorCmds = slashCommandsByVendor[_sessionVendor] || slashCommands || [];
1042
1124
  _send({ type: "slash_commands", commands: _vendorCmds, vendor: _sessionVendor });
@@ -1122,6 +1204,7 @@ function createSessionManager(opts) {
1122
1204
 
1123
1205
  sessions.delete(localId);
1124
1206
  broadcastSessionDeleted(localId);
1207
+ onSessionDeleted(localId);
1125
1208
 
1126
1209
  if (activeSessionId === localId) {
1127
1210
  var remaining = [...sessions.keys()];
@@ -1164,6 +1247,7 @@ function createSessionManager(opts) {
1164
1247
  try { fs.unlinkSync(sessionFilePath(session.cliSessionId)); } catch(e) {}
1165
1248
  }
1166
1249
  sessions.delete(localId);
1250
+ onSessionDeleted(localId);
1167
1251
  }
1168
1252
 
1169
1253
  function deleteSessionsBulk(localIds, targetWs) {
@@ -1200,6 +1284,7 @@ function createSessionManager(opts) {
1200
1284
  }
1201
1285
 
1202
1286
  function doSendToSession(session, obj) {
1287
+ stampActivityLocalId(session, obj);
1203
1288
  // Send to active clients without recording to history/disk (ephemeral data)
1204
1289
  if (sendEach) {
1205
1290
  var data = JSON.stringify(obj);
@@ -1214,6 +1299,7 @@ function createSessionManager(opts) {
1214
1299
  }
1215
1300
 
1216
1301
  function doSendAndRecord(session, obj) {
1302
+ stampActivityLocalId(session, obj);
1217
1303
  // Stamp every recorded message so history replay preserves original times
1218
1304
  if (!obj._ts) obj._ts = Date.now();
1219
1305
  // If history has not been loaded from disk yet, do not trigger a load just
@@ -1530,7 +1616,15 @@ function createSessionManager(opts) {
1530
1616
  }).catch(function() {});
1531
1617
  }
1532
1618
 
1533
- return {
1619
+ // lr-041af8: captured once so internal functions (e.g. switchSession, which
1620
+ // may be invoked either as sm.switchSession(...) or directly by another
1621
+ // internal function like createSession — `this` is not reliably bound in
1622
+ // the latter case) can read ad hoc properties external callers set directly
1623
+ // on the returned instance (sm.currentModel, sm.modelsByVendor, etc.) that
1624
+ // were never declared as closure variables in this file.
1625
+ var _instance;
1626
+
1627
+ _instance = {
1534
1628
  get activeSessionId() { return activeSessionId; },
1535
1629
  get nextLocalId() { return nextLocalId; },
1536
1630
  // slashCommands and slashCommandsByVendor store {name, desc, type}[] (lr-1c7f).
@@ -1706,6 +1800,12 @@ function createSessionManager(opts) {
1706
1800
  return { ok: true };
1707
1801
  },
1708
1802
  permissionRequestIndex: permissionRequestIndex,
1803
+ // lr-041af8: exposed on the instance too (in addition to the module
1804
+ // export) so every existing `sm.<method>` call-site convention in
1805
+ // project-sessions.js / project-connection.js can call
1806
+ // `sm.effectiveSessionModel(session)` without importing this module
1807
+ // separately.
1808
+ effectiveSessionModel: function (session) { return effectiveSessionModel(session, _instance); },
1709
1809
  // Remove the process-level exit listener registered above.
1710
1810
  // Must be called when the project owning this session manager is destroyed
1711
1811
  // so listeners do not accumulate across project open/close cycles (lr-daca).
@@ -1713,6 +1813,7 @@ function createSessionManager(opts) {
1713
1813
  process.removeListener("exit", _onProcessExit);
1714
1814
  },
1715
1815
  };
1816
+ return _instance;
1716
1817
  }
1717
1818
 
1718
- module.exports = { createSessionManager };
1819
+ module.exports = { createSessionManager, effectiveSessionModel, stampActivityLocalId };
package/lib/smtp.js CHANGED
@@ -183,7 +183,15 @@ function sendInviteEmail(email, inviteUrl, inviterName) {
183
183
 
184
184
  // --- Cleanup expired OTPs ---
185
185
 
186
- setInterval(function () {
186
+ // lr-795882: unref()'d — matches the equivalent ws-ticket sweep in
187
+ // server-auth.js (wsTicketSweepInterval). This is a housekeeping sweep, not
188
+ // something that should keep the process alive on its own; leaving it
189
+ // ref'd meant every test that required this module (or re-required it after
190
+ // busting require.cache, as test/ws-ticket-auth-lr-de5fcb.test.js's
191
+ // makeAuth() helper does once per test) left a real, permanently-running
192
+ // setInterval handle on the event loop, blocking `node --test` from ever
193
+ // reaching idle without --test-force-exit.
194
+ var _otpCleanupInterval = setInterval(function () {
187
195
  var now = Date.now();
188
196
  var keys = Object.keys(otpStore);
189
197
  for (var i = 0; i < keys.length; i++) {
@@ -192,6 +200,7 @@ setInterval(function () {
192
200
  }
193
201
  }
194
202
  }, 60000);
203
+ if (_otpCleanupInterval.unref) _otpCleanupInterval.unref();
195
204
 
196
205
  module.exports = {
197
206
  getSmtpConfig: getSmtpConfig,