@clagentic/console 1.9.0-beta.1 → 1.9.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/bin/cli.js +23 -1
  2. package/lib/agents.js +13 -3
  3. package/lib/build-sha.json +2 -2
  4. package/lib/cli/ipc-subcommands.js +84 -4
  5. package/lib/daemon.js +111 -7
  6. package/lib/effective-protocol.js +82 -0
  7. package/lib/project-connection.js +21 -8
  8. package/lib/project-filesystem.js +4 -4
  9. package/lib/project-http.js +4 -4
  10. package/lib/project-loop.js +49 -5
  11. package/lib/project-sessions.js +166 -68
  12. package/lib/project-user-mention.js +7 -7
  13. package/lib/project-user-message.js +81 -14
  14. package/lib/project.js +28 -22
  15. package/lib/public/app.js +18 -4
  16. package/lib/public/css/base.css +14 -0
  17. package/lib/public/css/filebrowser.css +6 -0
  18. package/lib/public/css/home-hub.css +28 -8
  19. package/lib/public/css/icon-strip.css +17 -0
  20. package/lib/public/css/messages.css +11 -0
  21. package/lib/public/css/mobile-nav.css +22 -0
  22. package/lib/public/css/server-settings.css +9 -0
  23. package/lib/public/css/sidebar.css +15 -0
  24. package/lib/public/css/title-bar.css +10 -1
  25. package/lib/public/index.html +9 -2
  26. package/lib/public/modules/activity-latch.js +45 -0
  27. package/lib/public/modules/activity-state.js +195 -0
  28. package/lib/public/modules/app-connection.js +31 -6
  29. package/lib/public/modules/app-favicon.js +75 -1
  30. package/lib/public/modules/app-home-hub.js +14 -11
  31. package/lib/public/modules/app-loop-ui.js +86 -2
  32. package/lib/public/modules/app-messages.js +178 -54
  33. package/lib/public/modules/app-panels.js +91 -32
  34. package/lib/public/modules/app-projects.js +46 -9
  35. package/lib/public/modules/app-rate-limit.js +13 -1
  36. package/lib/public/modules/server-settings.js +256 -21
  37. package/lib/public/modules/sidebar-mobile.js +32 -22
  38. package/lib/public/modules/sidebar-projects.js +42 -14
  39. package/lib/public/modules/sidebar-sessions.js +168 -48
  40. package/lib/public/modules/theme.js +2 -2
  41. package/lib/public/modules/tools.js +11 -39
  42. package/lib/sdk-bridge.js +375 -33
  43. package/lib/sdk-message-processor.js +98 -15
  44. package/lib/sdk-skill-discovery.js +46 -6
  45. package/lib/sdk-slash-enrichment.js +5 -2
  46. package/lib/server-dm.js +5 -5
  47. package/lib/server-hub-sessions.js +70 -0
  48. package/lib/server.js +78 -43
  49. package/lib/session-activity.js +9 -2
  50. package/lib/sessions.js +64 -18
  51. package/lib/smtp.js +10 -1
  52. package/lib/terminal-manager.js +6 -6
  53. package/lib/ws-schema.js +16 -0
  54. package/lib/yoke/adapters/claude.js +7 -1
  55. package/lib/yoke/adapters/codex.js +219 -31
  56. package/package.json +2 -2
  57. package/scripts/check-test-count.js +397 -0
  58. package/scripts/test-file-completion-reporter.js +43 -0
  59. package/scripts/verify-installed-build.js +242 -15
  60. package/lib/model-context-windows.js +0 -74
  61. package/lib/public/modules/model-context-windows.js +0 -71
@@ -23,6 +23,9 @@ function attachMessageProcessor(ctx) {
23
23
  var mergeSkills = ctx.mergeSkills;
24
24
  var discoverSkillsWithMeta = ctx.discoverSkillsWithMeta;
25
25
  var mergeSkillsWithMeta = ctx.mergeSkillsWithMeta;
26
+ // lr-3ccc78 — resolves the session owner's home on a shared multi-user
27
+ // daemon; returns null (falls back to REAL_HOME) in single-user mode.
28
+ var resolveSessionHome = ctx.resolveSessionHome || function () { return null; };
26
29
  // Allows callers (and tests) to inject a mock; falls back to the real implementation.
27
30
  var discoverWorkflowsFn = ctx.discoverWorkflows || discoverWorkflows;
28
31
 
@@ -67,9 +70,11 @@ function attachMessageProcessor(ctx) {
67
70
  // turn-wide isProcessing=true covering ordinary tool activity implicitly --
68
71
  // acquiring an explicit token here is how Codex activity becomes visible to
69
72
  // the derived isProcessing/picker-dot path at all. Gated on
70
- // session.vendor === "codex" so Claude's existing behavior (which already
71
- // has turn-wide isProcessing coverage for ordinary tools, and only acquires
72
- // a token for backgrounded Task tools) is completely unchanged by this.
73
+ // session.vendor === "codex" so this stays independent of Claude's own
74
+ // widened acquisition below (lr-6e20f7, block_stop) -- the two vendors
75
+ // acquire tokens through different yokeType branches (tool_start here vs.
76
+ // block_stop for Claude) and neither path double-acquires the other's
77
+ // tokens.
73
78
  //
74
79
  // Release happens on tool_result (per-token, matching Claude's tool_result
75
80
  // release) OR at the turn's result event, which releases EVERY still-live
@@ -253,13 +258,16 @@ function attachMessageProcessor(ctx) {
253
258
 
254
259
  // Cache slash_commands and model from CLI init message
255
260
  if (parsed.yokeType === "init") {
256
- var fsSkills = discoverSkillDirs();
261
+ // lr-3ccc78 — resolve THIS session's owner's home so skill discovery
262
+ // isn't the daemon's REAL_HOME for every user on a shared daemon.
263
+ var _initHome = resolveSessionHome(session);
264
+ var fsSkills = discoverSkillDirs(_initHome);
257
265
  sm.skillNames = mergeSkills(parsed.skills, fsSkills);
258
266
  sm.workflowMeta = discoverWorkflowsFn(cwd);
259
267
  // Enriched skill metadata (lr-7d8d) — stored alongside skillNames for consumers
260
268
  // that need description and type without breaking existing skillNames callers.
261
269
  if (typeof discoverSkillsWithMeta === "function" && typeof mergeSkillsWithMeta === "function") {
262
- var fsSkillsMeta = discoverSkillsWithMeta(cwd);
270
+ var fsSkillsMeta = discoverSkillsWithMeta(cwd, _initHome);
263
271
  sm.skillMeta = mergeSkillsWithMeta(parsed.skills, fsSkillsMeta);
264
272
  }
265
273
  if (parsed.slashCommands) {
@@ -269,6 +277,7 @@ function attachMessageProcessor(ctx) {
269
277
  discoverSkillsWithMeta: typeof discoverSkillsWithMeta === "function" ? discoverSkillsWithMeta : undefined,
270
278
  mergeSkillsWithMeta: typeof mergeSkillsWithMeta === "function" ? mergeSkillsWithMeta : undefined,
271
279
  discoverWorkflows: discoverWorkflowsFn,
280
+ homeOverride: _initHome,
272
281
  };
273
282
  var combined = buildEnrichedSlashCommands(parsed.slashCommands, cwd, _enrichFns);
274
283
  sm.slashCommands = combined;
@@ -438,14 +447,23 @@ function attachMessageProcessor(ctx) {
438
447
  try { input = JSON.parse(block.inputJson); } catch (e) {}
439
448
  sendAndRecord(session, { type: "tool_executing", id: block.id, name: block.name, input: input });
440
449
 
450
+ // lr-6e20f7: acquire an activity token for EVERY Claude tool_use
451
+ // block, not only Task. Claude has turn-wide isProcessing coverage
452
+ // for ordinary tools (see the module-header comment), which is
453
+ // sufficient for the LOCAL viewing client's own turn-in-flight
454
+ // signal (store.processing) but not for the SERVER-side registry
455
+ // that drives every OTHER client's picker/sidebar dot — that
456
+ // registry previously only saw a live token for a backgrounded
457
+ // Task, so a plain Bash/Read/Edit call was invisible to it. Released
458
+ // at the same block below (whichever tool ends up there) OR at the
459
+ // 'message' handler's tool_result content-array scan below
460
+ // (releaseActivity is idempotent either way).
461
+ acquireActivity(session, block.id, { source: "tool", label: input.description || block.name || "" });
462
+
441
463
  // Track active Task tools for sub-agent done detection
442
464
  if (block.name === "Task") {
443
465
  if (!session.activeTaskToolIds) session.activeTaskToolIds = {};
444
466
  session.activeTaskToolIds[block.id] = true;
445
- // lr-9bcd7b: acquire an activity token for the lifetime of this
446
- // backgrounded Task — released at the tool_result / task_notification
447
- // drain paths below (whichever fires first for this same block.id).
448
- acquireActivity(session, block.id, { source: "task", label: input.description || "" });
449
467
  }
450
468
 
451
469
  if (pushModule && block.name === "AskUserQuestion" && input.questions) {
@@ -523,10 +541,15 @@ function attachMessageProcessor(ctx) {
523
541
  });
524
542
  delete session.activeTaskToolIds[block.tool_use_id];
525
543
  }
526
- // lr-9bcd7b: release the activity token acquired at block_stop for
527
- // this tool id, unconditionally -- NOT gated on activeTaskToolIds
528
- // still containing the entry. The 'result' handler's pre-existing
529
- // lr-9d4b cleanup (retainPreservedTaskBookkeeping) already trims
544
+ // lr-9bcd7b (widened lr-6e20f7): release the activity token
545
+ // acquired at block_stop for this tool id, unconditionally --
546
+ // NOT gated on activeTaskToolIds still containing the entry.
547
+ // This covers every tool now (lr-6e20f7 widened acquisition
548
+ // beyond Task), not only backgrounded Task tools -- the
549
+ // Task-specific bookkeeping above (activeTaskToolIds,
550
+ // subagent_done) is unrelated to this release and unaffected by
551
+ // the widening. The 'result' handler's pre-existing lr-9d4b
552
+ // cleanup (retainPreservedTaskBookkeeping) already trims
530
553
  // activeTaskToolIds down to only Task ids with a preserved
531
554
  // permission on EVERY result, so a Task with no pending permission
532
555
  // of its own has its activeTaskToolIds entry deleted before this
@@ -759,8 +782,14 @@ function attachMessageProcessor(ctx) {
759
782
  session.streamedText = false;
760
783
  sm.broadcastSessionList();
761
784
 
762
- // Auto-generate title after N turns (skip if loop or already auto-generated)
763
- if (session.turnCount === AUTO_TITLE_TURN_THRESHOLD
785
+ // Auto-generate title after N turns (skip if loop or already auto-generated).
786
+ // lr-62157d: '===' -> '>=' so a session that skips past the exact
787
+ // threshold turn (early return, error path, non-result terminal event,
788
+ // or a turnCount that was never persisted before this fix) still gets
789
+ // titled on a later turn instead of being permanently disqualified.
790
+ // Idempotence comes from !session.titleAutoGenerated, which is now
791
+ // durable (see sessions.js buildMetaLine/loadSessions).
792
+ if (session.turnCount >= AUTO_TITLE_TURN_THRESHOLD
764
793
  && !session.titleAutoGenerated
765
794
  && !session.titleManuallySet
766
795
  && !session.loop
@@ -768,6 +797,46 @@ function attachMessageProcessor(ctx) {
768
797
  try { onAutoTitle(session); } catch (e) {
769
798
  console.error("[auto-title] onAutoTitle threw:", e.message || e);
770
799
  }
800
+ } else {
801
+ // lr-efdab6 (DRUMMER decision, comment #1): the taken branch above
802
+ // already logs on every path (sdk-bridge.js [auto-title] sites) — but
803
+ // logging existed on NOTHING that recorded the gate NOT firing, so
804
+ // silence read identically for "ran fine and logged nothing notable",
805
+ // "never invoked", and "invoked and died before the first log". That
806
+ // ambiguity is exactly what let lr-62157d's dead auto-title feature
807
+ // survive ~3 months / ~160 sessions undetected. This branch makes the
808
+ // negative case unambiguous: every turn where the gate evaluates
809
+ // false gets exactly one line naming why.
810
+ //
811
+ // already_auto_generated is the expected steady-state reason for the
812
+ // overwhelming majority of turns in a mature session (fires every
813
+ // turn after the session's title is set) and is logged at a lower
814
+ // level (console.debug) so a normal journald view isn't dominated by
815
+ // it; every other reason is diagnostic of a gate that should be
816
+ // firing but isn't, and stays at console.log so it is visible by
817
+ // default. Nothing here transmits session content — only flags/counts.
818
+ var _autoTitleReason;
819
+ if (!onAutoTitle) {
820
+ _autoTitleReason = "no_callback";
821
+ } else if (session.loop) {
822
+ _autoTitleReason = "loop_running";
823
+ } else if (session.titleManuallySet) {
824
+ _autoTitleReason = "manually_set";
825
+ } else if (session.titleAutoGenerated) {
826
+ _autoTitleReason = "already_auto_generated";
827
+ } else if (session.turnCount < AUTO_TITLE_TURN_THRESHOLD) {
828
+ _autoTitleReason = "turn_threshold_not_met";
829
+ } else {
830
+ _autoTitleReason = "unknown";
831
+ }
832
+ var _autoTitleLogFn = (_autoTitleReason === "already_auto_generated") ? console.debug : console.log;
833
+ _autoTitleLogFn(
834
+ "[auto-title] gate did not fire: reason=" + _autoTitleReason
835
+ + " turnCount=" + session.turnCount
836
+ + " titleAutoGenerated=" + !!session.titleAutoGenerated
837
+ + " titleManuallySet=" + !!session.titleManuallySet
838
+ + " loop=" + !!session.loop
839
+ );
771
840
  }
772
841
 
773
842
  if (onTurnDone) {
@@ -779,6 +848,20 @@ function attachMessageProcessor(ctx) {
779
848
  sendAndRecord(session, { type: "compacting", active: true });
780
849
  } else if (session.compacting) {
781
850
  sendAndRecord(session, { type: "compacting", active: false });
851
+ // lr-3af675: compaction just finished (session.compacting true ->
852
+ // this transition). Re-read vendor-reported usage now instead of
853
+ // leaving the context meter pinned at its pre-compact figure until
854
+ // the next turn's 'result' event — the provider has already
855
+ // self-corrected its own usage accounting at this point, we just
856
+ // never asked. Fire-and-forget, same pattern as the 'result' handler.
857
+ if (session.queryInstance && typeof session.queryInstance.getContextUsage === "function") {
858
+ session.queryInstance.getContextUsage().then(function(ctxUsage) {
859
+ session.lastContextUsage = ctxUsage;
860
+ sendToSession(session, { type: "context_usage", data: ctxUsage });
861
+ }).catch(function(e) {
862
+ console.error("[sdk-bridge] post-compaction getContextUsage failed (non-fatal):", e.message || e);
863
+ });
864
+ }
782
865
  }
783
866
  session.compacting = parsed.status === "compacting";
784
867
 
@@ -1,6 +1,29 @@
1
1
  var fs = require("fs");
2
2
  var path = require("path");
3
3
 
4
+ // Two-stage containment check mirroring project.js's safePath: a directory
5
+ // entry name from readdirSync can be a symlink, so a lexical path.resolve
6
+ // check alone (entry.name embedded in a path string that lexically stays
7
+ // under base) is NOT sufficient — the subsequent fs.accessSync/readFileSync
8
+ // on SKILL.md follows the symlink at read time, escaping base entirely.
9
+ // Stage 1 (lexical) rejects a literal ".." style escape before any syscall.
10
+ // Stage 2 (fs.realpathSync) resolves the symlink and re-checks containment
11
+ // against the REAL target, which is the check that actually defeats a
12
+ // symlinked directory entry pointing outside base. Returns the resolved
13
+ // real path on success, or null if entry escapes base or doesn't exist.
14
+ function resolveContainedSkillDir(base, entryName) {
15
+ var resolvedBase = path.resolve(base);
16
+ var lexical = path.resolve(resolvedBase, entryName);
17
+ if (lexical !== resolvedBase && lexical.indexOf(resolvedBase + path.sep) !== 0) return null;
18
+ try {
19
+ var real = fs.realpathSync(lexical);
20
+ if (real !== resolvedBase && real.indexOf(resolvedBase + path.sep) !== 0) return null;
21
+ return real;
22
+ } catch (e) {
23
+ return null;
24
+ }
25
+ }
26
+
4
27
  // Split shell command on operators (&&, ||, ;, |) while respecting quotes
5
28
  // and parentheses. Returns array of command segments.
6
29
  function splitShellSegments(cmd) {
@@ -197,9 +220,16 @@ function extractSkillDescription(skillDir) {
197
220
  // skill directories. Reads every SKILL.md to extract a description.
198
221
  // Project skills override global skills with the same name (global → project
199
222
  // discovery order, last-write wins).
200
- function discoverSkillsWithMeta(cwd) {
223
+ //
224
+ // homeOverride: optional. On a shared multi-user daemon, the caller resolves
225
+ // the SESSION OWNER's home (os-users.getLinuxUserHome(linuxUser)) and passes
226
+ // it here so the global skills dir is the invoking user's own ~/.claude/skills,
227
+ // not the daemon process's REAL_HOME (lr-3ccc78). Falls back to REAL_HOME when
228
+ // absent — the single-user / no-OS-isolation case, unchanged behavior.
229
+ function discoverSkillsWithMeta(cwd, homeOverride) {
230
+ var globalHome = homeOverride || require("./config").REAL_HOME;
201
231
  var dirs = [
202
- path.join(require("./config").REAL_HOME, ".claude", "skills"),
232
+ path.join(globalHome, ".claude", "skills"),
203
233
  path.join(cwd, ".claude", "skills"),
204
234
  ];
205
235
  // Ordered map so project skills override global skills
@@ -215,7 +245,8 @@ function discoverSkillsWithMeta(cwd) {
215
245
  for (var i = 0; i < entries.length; i++) {
216
246
  var entry = entries[i];
217
247
  if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
218
- var skillDir = path.join(base, entry.name);
248
+ var skillDir = resolveContainedSkillDir(base, entry.name);
249
+ if (!skillDir) continue;
219
250
  var skillMdPath = path.join(skillDir, "SKILL.md");
220
251
  try {
221
252
  fs.accessSync(skillMdPath, fs.constants.R_OK);
@@ -271,10 +302,14 @@ function mergeSkillsWithMeta(sdkSkillNames, fsSkillsWithMeta) {
271
302
  function attachSkillDiscovery(ctx) {
272
303
  var cwd = ctx.cwd;
273
304
 
274
- function discoverSkillDirs() {
305
+ // homeOverride: optional per-call override (see discoverSkillsWithMeta
306
+ // above) so a caller can resolve the session owner's home instead of the
307
+ // daemon's REAL_HOME on a shared multi-user daemon (lr-3ccc78).
308
+ function discoverSkillDirs(homeOverride) {
275
309
  var skills = {};
310
+ var globalHome = homeOverride || require("./config").REAL_HOME;
276
311
  var dirs = [
277
- path.join(require("./config").REAL_HOME, ".claude", "skills"),
312
+ path.join(globalHome, ".claude", "skills"),
278
313
  path.join(cwd, ".claude", "skills"),
279
314
  ];
280
315
  for (var d = 0; d < dirs.length; d++) {
@@ -288,7 +323,8 @@ function attachSkillDiscovery(ctx) {
288
323
  for (var i = 0; i < entries.length; i++) {
289
324
  var entry = entries[i];
290
325
  if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
291
- var skillDir = path.join(base, entry.name);
326
+ var skillDir = resolveContainedSkillDir(base, entry.name);
327
+ if (!skillDir) continue;
292
328
  var skillMd = path.join(skillDir, "SKILL.md");
293
329
  try {
294
330
  fs.accessSync(skillMd, fs.constants.R_OK);
@@ -326,4 +362,8 @@ module.exports = {
326
362
  extractSkillDescription: extractSkillDescription,
327
363
  discoverSkillsWithMeta: discoverSkillsWithMeta,
328
364
  mergeSkillsWithMeta: mergeSkillsWithMeta,
365
+ // Exported so other skill-discovery consumers (yoke/adapters/codex.js)
366
+ // reuse the same two-stage (lexical + realpath) containment check instead
367
+ // of approximating it — see the function's own doc comment.
368
+ resolveContainedSkillDir: resolveContainedSkillDir,
329
369
  };
@@ -12,7 +12,9 @@ var _defaultDiscoverWorkflows = require('./sdk-workflow-discovery').discoverWork
12
12
  //
13
13
  // The optional third argument `fns` allows callers to inject alternative
14
14
  // discovery functions — used by sdk-message-processor.js to pass its
15
- // context-injected mocks so tests remain hermetic.
15
+ // context-injected mocks so tests remain hermetic. `fns.homeOverride`
16
+ // (lr-3ccc78) is forwarded to discoverSkillsWithMeta as the global skills
17
+ // home for a shared multi-user daemon — see that function's own doc comment.
16
18
  //
17
19
  // Both discovery calls are wrapped in try/catch so a missing .claude directory
18
20
  // on disk never prevents slash commands from reaching the frontend.
@@ -20,9 +22,10 @@ function buildEnrichedSlashCommands(cliSlashCommands, cwd, fns) {
20
22
  var discoverSkillsWithMeta = (fns && fns.discoverSkillsWithMeta) || _defaultDiscoverSkillsWithMeta;
21
23
  var mergeSkillsWithMeta = (fns && fns.mergeSkillsWithMeta) || _defaultMergeSkillsWithMeta;
22
24
  var discoverWorkflows = (fns && fns.discoverWorkflows) || _defaultDiscoverWorkflows;
25
+ var homeOverride = (fns && fns.homeOverride) || null;
23
26
 
24
27
  var fsSkillsMeta = [];
25
- try { fsSkillsMeta = discoverSkillsWithMeta(cwd); } catch (e) {}
28
+ try { fsSkillsMeta = discoverSkillsWithMeta(cwd, homeOverride); } catch (e) {}
26
29
  var skillMeta = [];
27
30
  try { skillMeta = mergeSkillsWithMeta([], fsSkillsMeta); } catch (e) {}
28
31
 
package/lib/server-dm.js CHANGED
@@ -15,8 +15,8 @@ function attachDm(ctx) {
15
15
  var pushModule = ctx.pushModule;
16
16
 
17
17
  function handleMessage(ws, msg) {
18
- if (!ws._clayUser) return false;
19
- var userId = ws._clayUser.id;
18
+ if (!ws._clagenticUser) return false;
19
+ var userId = ws._clagenticUser.id;
20
20
 
21
21
  if (msg.type === "dm_list") {
22
22
  var dmList = dm.getDmList(userId);
@@ -76,7 +76,7 @@ function attachDm(ctx) {
76
76
  projects.forEach(function (ctx) {
77
77
  ctx.forEachClient(function (otherWs) {
78
78
  if (otherWs === ws) return;
79
- if (!otherWs._clayUser || otherWs._clayUser.id !== targetId) return;
79
+ if (!otherWs._clagenticUser || otherWs._clagenticUser.id !== targetId) return;
80
80
  if (otherWs.readyState !== 1) return;
81
81
  otherWs.send(JSON.stringify({ type: "dm_typing", dmKey: dmKey, userId: userId, typing: !!msg.typing }));
82
82
  });
@@ -101,13 +101,13 @@ function attachDm(ctx) {
101
101
  projects.forEach(function (ctx) {
102
102
  ctx.forEachClient(function (otherWs) {
103
103
  if (otherWs === ws) return;
104
- if (!otherWs._clayUser || otherWs._clayUser.id !== targetId) return;
104
+ if (!otherWs._clagenticUser || otherWs._clagenticUser.id !== targetId) return;
105
105
  if (otherWs.readyState !== 1) return;
106
106
  otherWs.send(JSON.stringify({ type: "dm_message", dmKey: msg.dmKey, message: message }));
107
107
  });
108
108
  });
109
109
  // Send push notification to target user
110
- var senderName = ws._clayUser ? (ws._clayUser.displayName || ws._clayUser.username || "Someone") : "Someone";
110
+ var senderName = ws._clagenticUser ? (ws._clagenticUser.displayName || ws._clagenticUser.username || "Someone") : "Someone";
111
111
  var preview = (msg.text || "").substring(0, 140);
112
112
  if (pushModule && pushModule.sendPushToUser) {
113
113
  pushModule.sendPushToUser(targetId, {
@@ -0,0 +1,70 @@
1
+ // Extracted from lib/server.js's addProject() closure (lr-c4da07 rework) so
2
+ // the Home Hub recent-sessions access filter is directly unit-testable
3
+ // against real code, not a test-file reimplementation of its loop shape.
4
+ // lib/server.js's getAllProjectSessions is now a thin call into
5
+ // computeAllProjectSessions below; both production and test code call this
6
+ // same function.
7
+
8
+ // Gathers every session across every project the given user may access,
9
+ // annotated with project metadata, for the Home Hub recent-sessions list.
10
+ //
11
+ // userId: REQUIRED to filter results to what the viewing user may actually
12
+ // see. Fails CLOSED: no userId (or no onGetProjectAccess) means no sessions
13
+ // are returned. There is no legitimate no-auth caller of this function --
14
+ // the WS upgrade handler in lib/server.js rejects any connection without an
15
+ // authenticated user with 401 before ws._clagenticUser can ever be set, including
16
+ // in single-user/PIN mode (still a real authenticated user, just one
17
+ // account) -- so failing closed here never breaks a real deployment mode.
18
+ //
19
+ // deps:
20
+ // projects Map<slug, projectCtx> (or anything with .forEach(fn(ctx, slug)))
21
+ // users the users module (canAccessProject / canAccessSession)
22
+ // onGetProjectAccess function(slug) -> access object | {error} | falsy
23
+ // callerSlug the connecting project's own slug (for includeSelf skip)
24
+ // includeSelf when true, callerSlug's own sessions are included too
25
+ // userId the viewing user's id, or null/undefined to fail closed
26
+ function computeAllProjectSessions(deps) {
27
+ var projects = deps.projects;
28
+ var users = deps.users;
29
+ var onGetProjectAccess = deps.onGetProjectAccess;
30
+ var callerSlug = deps.callerSlug;
31
+ var includeSelf = deps.includeSelf;
32
+ var userId = deps.userId;
33
+
34
+ var allSessions = [];
35
+ if (!userId || !onGetProjectAccess) return allSessions;
36
+
37
+ projects.forEach(function (pCtx, pSlug) {
38
+ if (!includeSelf && pSlug === callerSlug) return; // skip self unless asked
39
+ var status = pCtx.getStatus();
40
+ if (status.isWorktree) return;
41
+ var pSm = pCtx.getSessionManager();
42
+ if (!pSm) return;
43
+ // Resolve per-project access ONCE per project (hoisted out of the
44
+ // per-session inner loop below, not re-resolved per session) and skip
45
+ // the whole project up front if the user cannot access it at all --
46
+ // avoids an O(projects * sessions) repeated-resolution pattern for a
47
+ // value that does not vary per session.
48
+ var access = onGetProjectAccess(pSlug);
49
+ if (!access || access.error) return;
50
+ if (!users.canAccessProject(userId, access)) return;
51
+ var projectTitle = status.title || status.project || pSlug;
52
+ var projectIcon = status.icon || null;
53
+ pSm.sessions.forEach(function (s) {
54
+ if (!s.hidden && users.canAccessSession(userId, s, access)) {
55
+ // Push a shallow copy annotated with project metadata rather than
56
+ // mutating the live session object with transient UI fields.
57
+ allSessions.push(Object.assign({}, s, {
58
+ _projectTitle: projectTitle,
59
+ _projectSlug: pSlug,
60
+ _projectIcon: projectIcon,
61
+ }));
62
+ }
63
+ });
64
+ });
65
+ return allSessions;
66
+ }
67
+
68
+ module.exports = {
69
+ computeAllProjectSessions: computeAllProjectSessions,
70
+ };