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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +18 -0
  2. package/lib/daemon.js +94 -0
  3. package/lib/history-visibility.js +113 -0
  4. package/lib/project-sessions.js +51 -2
  5. package/lib/public/css/base.css +18 -0
  6. package/lib/public/css/diagnostics.css +99 -11
  7. package/lib/public/css/icon-strip.css +201 -0
  8. package/lib/public/css/menus.css +2 -2
  9. package/lib/public/css/mobile-nav.css +24 -0
  10. package/lib/public/css/server-settings.css +100 -0
  11. package/lib/public/index.html +17 -1
  12. package/lib/public/modules/app-header.js +72 -17
  13. package/lib/public/modules/app-home-hub.js +31 -7
  14. package/lib/public/modules/app-messages.js +5 -0
  15. package/lib/public/modules/app-notifications.js +5 -1
  16. package/lib/public/modules/app-projects.js +10 -5
  17. package/lib/public/modules/command-palette.js +16 -5
  18. package/lib/public/modules/custom-icons-settings.js +399 -0
  19. package/lib/public/modules/custom-icons.js +114 -0
  20. package/lib/public/modules/diagnostic-format.js +18 -2
  21. package/lib/public/modules/diagnostics.js +159 -8
  22. package/lib/public/modules/emoji-picker.js +274 -6
  23. package/lib/public/modules/history-visibility.js +98 -0
  24. package/lib/public/modules/popover-position.js +192 -0
  25. package/lib/public/modules/project-icon.js +113 -0
  26. package/lib/public/modules/project-settings.js +2 -2
  27. package/lib/public/modules/project-switcher.js +2 -1
  28. package/lib/public/modules/scheduler-config.js +5 -8
  29. package/lib/public/modules/scheduler.js +5 -6
  30. package/lib/public/modules/server-settings.js +6 -0
  31. package/lib/public/modules/sidebar-mobile.js +4 -6
  32. package/lib/public/modules/sidebar-projects.js +35 -90
  33. package/lib/public/modules/sidebar-sessions.js +6 -20
  34. package/lib/public/modules/sticky-notes.js +4 -4
  35. package/lib/public/modules/terminal.js +5 -12
  36. package/lib/sdk-bridge.js +59 -19
  37. package/lib/sdk-message-processor.js +58 -3
  38. package/lib/sdk-permission-ownership.js +85 -0
  39. package/lib/server-settings.js +221 -1
  40. package/lib/server.js +2 -0
  41. package/lib/sessions.js +77 -10
  42. package/lib/settings-preflight.js +52 -16
  43. package/lib/utils.js +23 -0
  44. package/lib/ws-schema.js +2 -0
  45. package/lib/yoke/adapters/diagnostic-patterns.js +25 -0
  46. package/package.json +2 -1
@@ -1,6 +1,27 @@
1
1
  var fs = require("fs");
2
2
  var path = require("path");
3
3
  var audit = require("./audit");
4
+ var projectModule = require("./project");
5
+
6
+ // Validate a custom-emoji slug: lowercase alphanumeric, hyphen, underscore, 1-64 chars.
7
+ // Must pass BEFORE any filesystem operation (structurally excludes . and /).
8
+ var SLUG_RE = /^[a-z0-9_-]{1,64}$/;
9
+
10
+ // Content-type → file extension map for custom emoji uploads.
11
+ var CUSTOM_EMOJI_EXT = {
12
+ "image/jpeg": "jpg",
13
+ "image/png": "png",
14
+ "image/gif": "gif",
15
+ "image/webp": "webp",
16
+ };
17
+
18
+ // Extension → Content-Type for serving.
19
+ var CUSTOM_EMOJI_CT = {
20
+ jpg: "image/jpeg",
21
+ png: "image/png",
22
+ gif: "image/gif",
23
+ webp: "image/webp",
24
+ };
4
25
 
5
26
  function attachSettings(ctx) {
6
27
  var users = ctx.users;
@@ -150,6 +171,7 @@ function attachSettings(ctx) {
150
171
  res.writeHead(200, {
151
172
  "Content-Type": ctMap[ext] || "application/octet-stream",
152
173
  "Cache-Control": "public, max-age=31536000, immutable",
174
+ "X-Content-Type-Options": "nosniff",
153
175
  });
154
176
  res.end(fs.readFileSync(path.join(avatarDir, match)));
155
177
  return true;
@@ -389,11 +411,209 @@ function attachSettings(ctx) {
389
411
  return true;
390
412
  }
391
413
 
414
+ // -----------------------------------------------------------------------
415
+ // Custom emoji routes — /api/custom-emoji[/:slug]
416
+ // Storage: CONFIG_DIR/custom-emoji/{slug}.{ext}
417
+ // Global shared namespace (not per-user).
418
+ // -----------------------------------------------------------------------
419
+
420
+ var customEmojiDir = path.join(CONFIG_DIR, "custom-emoji");
421
+
422
+ // GET /api/custom-emoji — list all uploads [{slug, url, size, ext, contentType}]
423
+ // size/ext/contentType are additive (lr-d1d9) — existing consumers that only
424
+ // read {slug, url} are unaffected.
425
+ if (req.method === "GET" && fullUrl === "/api/custom-emoji") {
426
+ var list = [];
427
+ try {
428
+ var emojiFiles = fs.readdirSync(customEmojiDir);
429
+ for (var lfi = 0; lfi < emojiFiles.length; lfi++) {
430
+ var lf = emojiFiles[lfi];
431
+ var lfExt = path.extname(lf).slice(1);
432
+ if (!CUSTOM_EMOJI_CT[lfExt]) continue;
433
+ var lfSlug = path.basename(lf, "." + lfExt);
434
+ if (!SLUG_RE.test(lfSlug)) continue;
435
+ var lfEntry = { slug: lfSlug, url: "/api/custom-emoji/" + lfSlug, ext: lfExt, contentType: CUSTOM_EMOJI_CT[lfExt] };
436
+ try { lfEntry.size = fs.statSync(path.join(customEmojiDir, lf)).size; } catch (e) { /* stat failed — omit size */ }
437
+ list.push(lfEntry);
438
+ }
439
+ } catch (e) { /* dir absent → empty list */ }
440
+ res.writeHead(200, { "Content-Type": "application/json" });
441
+ res.end(JSON.stringify(list));
442
+ return true;
443
+ }
444
+
445
+ // POST /api/custom-emoji/:slug — upload a new custom emoji image
446
+ if (req.method === "POST" && fullUrl.startsWith("/api/custom-emoji/")) {
447
+ var postSlug = fullUrl.slice("/api/custom-emoji/".length).split("?")[0];
448
+
449
+ // Auth gate
450
+ var muPost = getMultiUserFromReq(req);
451
+ if (!muPost) {
452
+ res.writeHead(401, { "Content-Type": "application/json" });
453
+ res.end('{"error":"unauthorized"}');
454
+ return true;
455
+ }
456
+
457
+ // Validate slug before any filesystem use
458
+ if (!SLUG_RE.test(postSlug)) {
459
+ res.writeHead(400, { "Content-Type": "application/json" });
460
+ res.end('{"error":"Invalid slug"}');
461
+ return true;
462
+ }
463
+
464
+ var postChunks = [];
465
+ var postSize = 0;
466
+ var postMaxSize = 512 * 1024; // 512 KB
467
+ req.on("data", function (chunk) {
468
+ postSize += chunk.length;
469
+ if (postSize <= postMaxSize) postChunks.push(chunk);
470
+ });
471
+ req.on("end", function () {
472
+ if (postSize > postMaxSize) {
473
+ res.writeHead(413, { "Content-Type": "application/json" });
474
+ res.end('{"error":"File too large (max 512 KB)"}');
475
+ return;
476
+ }
477
+ var raw = Buffer.concat(postChunks);
478
+
479
+ // Magic-byte type detection — reuse same pattern as avatar handler
480
+ var ct = null;
481
+ if (raw[0] === 0xFF && raw[1] === 0xD8) ct = "image/jpeg";
482
+ else if (raw[0] === 0x89 && raw[1] === 0x50) ct = "image/png";
483
+ else if (raw[0] === 0x47 && raw[1] === 0x49) ct = "image/gif";
484
+ else if (raw[0] === 0x52 && raw[1] === 0x49) ct = "image/webp";
485
+
486
+ if (!ct) {
487
+ res.writeHead(400, { "Content-Type": "application/json" });
488
+ res.end('{"error":"Unsupported image format"}');
489
+ return;
490
+ }
491
+
492
+ var ext = CUSTOM_EMOJI_EXT[ct];
493
+ try { fs.mkdirSync(customEmojiDir, { recursive: true }); } catch (e) {}
494
+
495
+ // Build + validate the target path (defense-in-depth — slug already
496
+ // validated by SLUG_RE but guard against path.resolve surprises).
497
+ // safePath requires the file to exist, so we use a pre-write resolve check.
498
+ var candidatePath = path.join(customEmojiDir, postSlug + "." + ext);
499
+ var resolvedCandidate = path.resolve(customEmojiDir, postSlug + "." + ext);
500
+ if (!resolvedCandidate.startsWith(customEmojiDir + path.sep)) {
501
+ res.writeHead(400, { "Content-Type": "application/json" });
502
+ res.end('{"error":"Invalid path"}');
503
+ return;
504
+ }
505
+
506
+ // Remove any existing file for this slug (different ext)
507
+ try {
508
+ var existingAll = fs.readdirSync(customEmojiDir);
509
+ for (var ri = 0; ri < existingAll.length; ri++) {
510
+ var rf = existingAll[ri];
511
+ var rfExt = path.extname(rf).slice(1);
512
+ if (!CUSTOM_EMOJI_CT[rfExt]) continue;
513
+ if (path.basename(rf, "." + rfExt) === postSlug) {
514
+ fs.unlinkSync(path.join(customEmojiDir, rf));
515
+ }
516
+ }
517
+ } catch (e) {}
518
+
519
+ fs.writeFileSync(candidatePath, raw);
520
+ try { fs.chmodSync(candidatePath, 0o644); } catch (e) {}
521
+
522
+ res.writeHead(200, { "Content-Type": "application/json" });
523
+ res.end(JSON.stringify({ ok: true, slug: postSlug, url: "/api/custom-emoji/" + postSlug }));
524
+ });
525
+ return true;
526
+ }
527
+
528
+ // GET /api/custom-emoji/:slug — serve the image for a slug
529
+ if (req.method === "GET" && fullUrl.startsWith("/api/custom-emoji/")) {
530
+ var getSlug = fullUrl.slice("/api/custom-emoji/".length).split("?")[0];
531
+
532
+ if (!SLUG_RE.test(getSlug)) {
533
+ res.writeHead(404, { "Content-Type": "application/json" });
534
+ res.end('{"error":"not found"}');
535
+ return true;
536
+ }
537
+
538
+ try {
539
+ var getFiles = fs.readdirSync(customEmojiDir);
540
+ var getMatch = null;
541
+ for (var gfi = 0; gfi < getFiles.length; gfi++) {
542
+ var gf = getFiles[gfi];
543
+ var gfExt = path.extname(gf).slice(1);
544
+ if (!CUSTOM_EMOJI_CT[gfExt]) continue;
545
+ // Exact-basename match (NOT startsWith — prevents prefix collisions)
546
+ if (path.basename(gf, "." + gfExt) === getSlug) {
547
+ getMatch = gf;
548
+ break;
549
+ }
550
+ }
551
+ if (getMatch) {
552
+ var matchExt = path.extname(getMatch).slice(1);
553
+ var matchPath = path.join(customEmojiDir, getMatch);
554
+ // Defense-in-depth: verify resolved path stays within customEmojiDir
555
+ var safeMatchPath = projectModule.safePath(customEmojiDir, getMatch);
556
+ if (!safeMatchPath) {
557
+ res.writeHead(404, { "Content-Type": "application/json" });
558
+ res.end('{"error":"not found"}');
559
+ return true;
560
+ }
561
+ res.writeHead(200, {
562
+ "Content-Type": CUSTOM_EMOJI_CT[matchExt] || "application/octet-stream",
563
+ "Cache-Control": "public, max-age=31536000, immutable",
564
+ "X-Content-Type-Options": "nosniff",
565
+ });
566
+ res.end(fs.readFileSync(matchPath));
567
+ return true;
568
+ }
569
+ } catch (e) {}
570
+
571
+ res.writeHead(404, { "Content-Type": "application/json" });
572
+ res.end('{"error":"not found"}');
573
+ return true;
574
+ }
575
+
576
+ // DELETE /api/custom-emoji/:slug — remove an uploaded emoji
577
+ if (req.method === "DELETE" && fullUrl.startsWith("/api/custom-emoji/")) {
578
+ var delSlug = fullUrl.slice("/api/custom-emoji/".length).split("?")[0];
579
+
580
+ // Auth gate
581
+ var muDel = getMultiUserFromReq(req);
582
+ if (!muDel) {
583
+ res.writeHead(401, { "Content-Type": "application/json" });
584
+ res.end('{"error":"unauthorized"}');
585
+ return true;
586
+ }
587
+
588
+ if (!SLUG_RE.test(delSlug)) {
589
+ res.writeHead(400, { "Content-Type": "application/json" });
590
+ res.end('{"error":"Invalid slug"}');
591
+ return true;
592
+ }
593
+
594
+ try {
595
+ var delFiles = fs.readdirSync(customEmojiDir);
596
+ for (var dfi = 0; dfi < delFiles.length; dfi++) {
597
+ var df = delFiles[dfi];
598
+ var dfExt = path.extname(df).slice(1);
599
+ if (!CUSTOM_EMOJI_CT[dfExt]) continue;
600
+ if (path.basename(df, "." + dfExt) === delSlug) {
601
+ var safeDelPath = projectModule.safePath(customEmojiDir, df);
602
+ if (safeDelPath) fs.unlinkSync(safeDelPath);
603
+ }
604
+ }
605
+ } catch (e) {}
606
+
607
+ res.writeHead(200, { "Content-Type": "application/json" });
608
+ res.end('{"ok":true}');
609
+ return true;
610
+ }
611
+
392
612
  return false;
393
613
  }
394
614
 
395
615
  return { handleRequest: handleRequest };
396
616
  }
397
617
 
398
- module.exports = { attachSettings: attachSettings };
618
+ module.exports = { attachSettings: attachSettings, SLUG_RE: SLUG_RE, CUSTOM_EMOJI_CT: CUSTOM_EMOJI_CT };
399
619
 
package/lib/server.js CHANGED
@@ -153,6 +153,7 @@ function createServer(opts) {
153
153
  var onSetProjectFolder = opts.onSetProjectFolder || null;
154
154
  var onRenameProjectFolder = opts.onRenameProjectFolder || null;
155
155
  var onSetFolderIcon = opts.onSetFolderIcon || null;
156
+ var onRenameCustomIcon = opts.onRenameCustomIcon || null;
156
157
  var getFolderMeta = opts.getFolderMeta || function () { return {}; };
157
158
  var onProjectOwnerChanged = opts.onProjectOwnerChanged || null;
158
159
  var onGetServerDefaultEffort = opts.onGetServerDefaultEffort || null;
@@ -1076,6 +1077,7 @@ function createServer(opts) {
1076
1077
  onSetProjectFolder: onSetProjectFolder,
1077
1078
  onRenameProjectFolder: onRenameProjectFolder,
1078
1079
  onSetFolderIcon: onSetFolderIcon,
1080
+ onRenameCustomIcon: onRenameCustomIcon,
1079
1081
  onProjectOwnerChanged: onProjectOwnerChanged,
1080
1082
  onGetServerDefaultEffort: onGetServerDefaultEffort,
1081
1083
  onSetServerDefaultEffort: onSetServerDefaultEffort,
package/lib/sessions.js CHANGED
@@ -4,6 +4,7 @@ var config = require("./config");
4
4
  var utils = require("./utils");
5
5
  var users = require("./users");
6
6
  var { CODEX_DEFAULTS } = require("./codex-defaults");
7
+ var { isVisibleHistoryEvent } = require("./history-visibility");
7
8
 
8
9
  function createSessionManager(opts) {
9
10
  var cwd = opts.cwd;
@@ -64,6 +65,13 @@ function createSessionManager(opts) {
64
65
  if (session.lastRewindUuid) metaObj.lastRewindUuid = session.lastRewindUuid;
65
66
  if (session.agentName) metaObj.agentName = session.agentName;
66
67
  if (session.loop) metaObj.loop = session.loop;
68
+ // Persist per-session "allow for session" tool grants (lr-8b2e) so they
69
+ // survive daemon restart / resume-by-cliSessionId rehydration instead of
70
+ // silently re-prompting. Only written when non-empty — grants that were
71
+ // never given must stay absent, not round-trip as {}.
72
+ if (session.allowedTools && Object.keys(session.allowedTools).length > 0) {
73
+ metaObj.allowedTools = session.allowedTools;
74
+ }
67
75
  var meta = JSON.stringify(metaObj);
68
76
  var lines = [meta];
69
77
  for (var i = 0; i < session.history.length; i++) {
@@ -285,6 +293,12 @@ function createSessionManager(opts) {
285
293
  sentToolResults: {},
286
294
  pendingPermissions: {},
287
295
  pendingAskUser: {},
296
+ // Hydrate previously-granted "allow for session" tool decisions from
297
+ // durable state (lr-8b2e); default to {} only when none was saved so
298
+ // grants that were never given remain empty, not re-prompted.
299
+ // Sanitized (lr-8b2e hardening) so a malformed/injected persisted
300
+ // record cannot silently auto-approve a tool.
301
+ allowedTools: utils.sanitizeAllowedTools(m.allowedTools),
288
302
  isProcessing: false,
289
303
  title: m.title || "",
290
304
  createdAt: m.createdAt || Date.now(),
@@ -462,6 +476,14 @@ function createSessionManager(opts) {
462
476
  // scroll-up via the existing pagination path.
463
477
  var HISTORY_PAGE_SIZE = 100;
464
478
 
479
+ // Hard cap on how many additional turn-boundary steps a page window may be
480
+ // extended backward by when searching for visible content (lr-c24b). Each
481
+ // step is itself bounded by HISTORY_PAGE_SIZE (see findTurnBoundary), so the
482
+ // total worst-case scan is MAX_VISIBILITY_EXTENSIONS * HISTORY_PAGE_SIZE —
483
+ // bounded, not unbounded (codex engrams 2026-05-27/29 flagged unbounded
484
+ // backward scans as a structural trap for this exact pagination path).
485
+ var MAX_VISIBILITY_EXTENSIONS = 5;
486
+
465
487
  // Scan backward from the END of history (hard-capped at HISTORY_PAGE_SIZE) to
466
488
  // find the most recent user_message. This ensures the initial replay window
467
489
  // always starts at a clean turn boundary rather than mid-stream, regardless of
@@ -490,6 +512,34 @@ function createSessionManager(opts) {
490
512
  return targetIndex;
491
513
  }
492
514
 
515
+ // Returns true when history[from..to) contains at least one event that
516
+ // app-messages.js will render as a new visible message (lr-c24b). A page
517
+ // window can otherwise land entirely on invisible-yield events (todo/task
518
+ // bookkeeping, hidden plan tools, state events, thinking deltas) and render
519
+ // zero bubbles even though it advanced historyFrom.
520
+ function sliceHasVisibleEvent(history, from, to) {
521
+ for (var i = from; i < to; i++) {
522
+ if (isVisibleHistoryEvent(history[i])) return true;
523
+ }
524
+ return false;
525
+ }
526
+
527
+ // Extend a turn-boundary-aligned page window backward, one turn boundary at
528
+ // a time, until the slice [from, to) contains at least one visibly-rendering
529
+ // event or from reaches 0 — capped at MAX_VISIBILITY_EXTENSIONS additional
530
+ // steps so the scan stays bounded even for pathological all-invisible runs.
531
+ // `to` never changes; only `from` moves backward.
532
+ function extendWindowForVisibility(history, from, to) {
533
+ var steps = 0;
534
+ while (from > 0 && !sliceHasVisibleEvent(history, from, to) && steps < MAX_VISIBILITY_EXTENSIONS) {
535
+ var next = findTurnBoundary(history, from - 1);
536
+ if (next >= from) break; // no further progress possible — avoid an infinite loop
537
+ from = next;
538
+ steps++;
539
+ }
540
+ return from;
541
+ }
542
+
493
543
  function replayHistory(session, fromIndex, targetWs, transform) {
494
544
  // Ensure history is in memory before replaying.
495
545
  loadSessionHistory(session);
@@ -506,6 +556,11 @@ function createSessionManager(opts) {
506
556
  var hardFloor = Math.max(0, total - HISTORY_PAGE_SIZE);
507
557
  var lastTurn = findLastTurnStart(session.history);
508
558
  fromIndex = Math.max(hardFloor, lastTurn);
559
+ // Same yield guarantee as load_more_history (lr-c24b): a turn
560
+ // dominated by invisible-yield events (todo/task bookkeeping, hidden
561
+ // plan tools, thinking deltas) can otherwise replay zero visible
562
+ // bubbles on initial resume.
563
+ fromIndex = extendWindowForVisibility(session.history, fromIndex, total);
509
564
  }
510
565
  }
511
566
 
@@ -553,18 +608,25 @@ function createSessionManager(opts) {
553
608
  // (same rules as getVisibleSessions / server-palette). Internal callers
554
609
  // (targetWs=null) bypass this gate — they operate on already-validated session
555
610
  // references.
611
+ //
612
+ // No-auth / single-user connections have _clayUser === null (set by
613
+ // project-connection.js:92 as wsUser || null). In that deployment there is
614
+ // no user identity to check — the connection is the implicit owner. We skip
615
+ // the gate entirely for null users so that _clayActiveSession is still
616
+ // bound below, keeping the live-broadcast filter (doSendAndRecord /
617
+ // doSendToSession) in sync. Authenticated users who lack access are still
618
+ // rejected by canAccessSession. (regression introduced by dca60a7, lr-690b)
556
619
  if (targetWs) {
557
620
  var requestingUser = targetWs._clayUser || null;
558
- if (!requestingUser) {
559
- if (sendTo) sendTo(targetWs, { type: "error", error: "Access denied" });
560
- return;
561
- }
562
- // Use { visibility: "public" } so canAccessProject passes and the
563
- // session-level ownership/visibility rules do the real work.
564
- if (!users.canAccessSession(requestingUser.id, session, { visibility: "public" })) {
565
- if (sendTo) sendTo(targetWs, { type: "error", error: "Access denied" });
566
- return;
621
+ if (requestingUser) {
622
+ // Use { visibility: "public" } so canAccessProject passes and the
623
+ // session-level ownership/visibility rules do the real work.
624
+ if (!users.canAccessSession(requestingUser.id, session, { visibility: "public" })) {
625
+ if (sendTo) sendTo(targetWs, { type: "error", error: "Access denied" });
626
+ return;
627
+ }
567
628
  }
629
+ // null requestingUser = no-auth deployment; fall through to bind _clayActiveSession.
568
630
  }
569
631
 
570
632
  activeSessionId = localId;
@@ -819,7 +881,11 @@ function createSessionManager(opts) {
819
881
  sentToolResults: {},
820
882
  pendingPermissions: {},
821
883
  pendingAskUser: {},
822
- allowedTools: {},
884
+ // Hydrate previously-granted "allow for session" tool decisions from
885
+ // durable state (lr-8b2e); default to {} only when none was saved.
886
+ // Sanitized (lr-8b2e hardening) so a malformed/injected persisted
887
+ // record cannot silently auto-approve a tool.
888
+ allowedTools: utils.sanitizeAllowedTools(opts && opts.allowedTools),
823
889
  isProcessing: false,
824
890
  title: title,
825
891
  createdAt: Date.now(),
@@ -1086,6 +1152,7 @@ function createSessionManager(opts) {
1086
1152
  sendToSession: doSendToSession,
1087
1153
  findTurnBoundary: findTurnBoundary,
1088
1154
  findLastTurnStart: findLastTurnStart,
1155
+ extendWindowForVisibility: extendWindowForVisibility,
1089
1156
  replayHistory: replayHistory,
1090
1157
  searchSessions: searchSessions,
1091
1158
  searchSessionContent: searchSessionContent,
@@ -5,12 +5,19 @@
5
5
  // without relying on CLI stderr pattern matching.
6
6
  //
7
7
  // Public surface:
8
- // validateSettingsObject(obj, filePath) — pure: settings obj → diagnostic[]
9
- // runPreflight(opts) — IO: reads files, validates, returns diagnostic[]
10
- // VALID_HOOK_EVENTS — exported for tests
8
+ // validateSettingsObject(obj, filePath, scope) — pure: settings obj → diagnostic[]
9
+ // runPreflight(opts) — IO: reads files, validates, returns diagnostic[]
10
+ // VALID_HOOK_EVENTS — exported for tests
11
11
  //
12
12
  // Diagnostic shape (conforms to validateDiagnosticEvent from YOKE interface):
13
- // { type: 'diagnostic', severity, source: 'preflight', message }
13
+ // { type: 'diagnostic', severity, source: 'preflight', scope?: 'user'|'project', message }
14
+ //
15
+ // scope (lr-7e22) distinguishes which settings file a diagnostic came from —
16
+ // runPreflight checks both ~/.claude/settings.json (scope:'user') and
17
+ // <projectDir>/.claude/settings.json (scope:'project') independently, so a
18
+ // single unknown hook key can legitimately produce one diagnostic per file.
19
+ // The render layer (diagnostic-format.js) uses scope to keep those visually
20
+ // distinct instead of both showing an identical "Preflight" source label.
14
21
 
15
22
  "use strict";
16
23
 
@@ -21,20 +28,27 @@ var os = require("os");
21
28
  // ---------------------------------------------------------------------------
22
29
  // Hook event allowlist
23
30
  //
24
- // SOURCE: This list was derived from the Claude Code CLI documentation and SDK
25
- // source as of 2026-06-30 (claude@1.x). The hooks.AgentTeams case (the
31
+ // SOURCE: Verified live against the Claude Code hooks documentation
32
+ // (https://code.claude.com/docs/en/hooks, hook lifecycle table) as of
33
+ // 2026-07-01, cross-checked via web search. The hooks.AgentTeams case (the
26
34
  // motivating screenshot for this stage) is a real example of an unknown key
27
35
  // that surfaces as a silent no-op in the CLI but clutters the warnings stream.
36
+ // The 8 events added under lr-7e22 (PreCompact, PostCompact, SessionStart,
37
+ // UserPromptSubmit, PermissionRequest, TaskCreated, TeammateIdle,
38
+ // TaskCompleted) were confirmed present in that same table — they are not an
39
+ // exhaustive list of all documented events (the docs list ~30 total as of
40
+ // this sync), only the ones observed in the field that needed verification.
28
41
  //
29
42
  // IMPORTANT: This list is the ONLY place the valid hook events are defined in
30
43
  // the Console codebase. Do not duplicate it elsewhere — drift between copies
31
44
  // is exactly the parity bug we are fixing.
32
45
  //
33
46
  // TODO(lr-1a26): Sync this list whenever the Claude Code CLI releases new hook
34
- // event types. The authoritative upstream is the CLI's hook documentation or
35
- // source (search for "hook" + "event" in the @anthropic-ai/claude-code package).
36
- // Consider scripting a CI check against the installed CLI version's known events
37
- // if the CLI exposes a machine-readable list in a future release.
47
+ // event types. The authoritative upstream is the CLI's hook documentation
48
+ // (https://code.claude.com/docs/en/hooks) or source (search for "hook" +
49
+ // "event" in the @anthropic-ai/claude-code package). Consider scripting a CI
50
+ // check against the installed CLI version's known events if the CLI exposes
51
+ // a machine-readable list in a future release.
38
52
  // ---------------------------------------------------------------------------
39
53
  var VALID_HOOK_EVENTS = [
40
54
  "PreToolUse",
@@ -42,6 +56,15 @@ var VALID_HOOK_EVENTS = [
42
56
  "Notification",
43
57
  "Stop",
44
58
  "SubagentStop",
59
+ // lr-7e22: verified 2026-07-01 against code.claude.com/docs/en/hooks
60
+ "PreCompact",
61
+ "PostCompact",
62
+ "SessionStart",
63
+ "UserPromptSubmit",
64
+ "PermissionRequest",
65
+ "TaskCreated",
66
+ "TeammateIdle",
67
+ "TaskCompleted",
45
68
  ];
46
69
 
47
70
  // ---------------------------------------------------------------------------
@@ -55,9 +78,13 @@ var VALID_HOOK_EVENTS = [
55
78
  *
56
79
  * @param {object} obj - Parsed settings JSON (any shape; we check what we know)
57
80
  * @param {string} filePath - Path string used only in diagnostic messages
58
- * @returns {Array<{type,severity,source,message}>} Diagnostics (empty = no issues)
81
+ * @param {string} [scope] - 'user' | 'project', attached to each diagnostic so the
82
+ * render layer can distinguish which settings file a
83
+ * warning came from (lr-7e22). Omitted when the caller
84
+ * has no file-scope context (e.g. direct unit tests).
85
+ * @returns {Array<{type,severity,source,scope,message}>} Diagnostics (empty = no issues)
59
86
  */
60
- function validateSettingsObject(obj, filePath) {
87
+ function validateSettingsObject(obj, filePath, scope) {
61
88
  var diagnostics = [];
62
89
  var label = filePath || "settings.json";
63
90
 
@@ -75,6 +102,7 @@ function validateSettingsObject(obj, filePath) {
75
102
  type: "diagnostic",
76
103
  severity: "warning",
77
104
  source: "preflight",
105
+ scope: scope || undefined,
78
106
  message: label + ": 'hooks' field is not an object — expected { EventName: [...] }.",
79
107
  });
80
108
  } else {
@@ -86,6 +114,7 @@ function validateSettingsObject(obj, filePath) {
86
114
  type: "diagnostic",
87
115
  severity: "warning",
88
116
  source: "preflight",
117
+ scope: scope || undefined,
89
118
  message: label + ": unknown hook event '" + key + "'. Valid events: " + VALID_HOOK_EVENTS.join(", ") + ". This hook will be silently ignored by the CLI.",
90
119
  });
91
120
  }
@@ -112,9 +141,14 @@ function validateSettingsObject(obj, filePath) {
112
141
  * per the non-blocking preflight contract.
113
142
  *
114
143
  * @param {string} filePath - Absolute path to settings.json
144
+ * @param {string} [scope] - 'user' | 'project', attached to each diagnostic (lr-7e22)
145
+ * so multiple legitimate warnings across files render as
146
+ * visibly distinct entries instead of stacking as apparent
147
+ * duplicates. Optional — omitted when the caller has no
148
+ * file-scope context.
115
149
  * @returns {Array<object>} diagnostics
116
150
  */
117
- function validateSettingsFile(filePath) {
151
+ function validateSettingsFile(filePath, scope) {
118
152
  var diagnostics = [];
119
153
 
120
154
  // Missing file → nothing to validate. Not an error.
@@ -128,6 +162,7 @@ function validateSettingsFile(filePath) {
128
162
  type: "diagnostic",
129
163
  severity: "info",
130
164
  source: "preflight",
165
+ scope: scope || undefined,
131
166
  message: filePath + ": could not read settings file (" + e.code + " — " + (e.message || String(e)) + ").",
132
167
  });
133
168
  return diagnostics;
@@ -142,13 +177,14 @@ function validateSettingsFile(filePath) {
142
177
  type: "diagnostic",
143
178
  severity: "error",
144
179
  source: "preflight",
180
+ scope: scope || undefined,
145
181
  message: filePath + ": settings.json is not valid JSON — " + (e.message || String(e)) + ".",
146
182
  });
147
183
  return diagnostics;
148
184
  }
149
185
 
150
186
  // (b) Structural validation
151
- var structural = validateSettingsObject(obj, filePath);
187
+ var structural = validateSettingsObject(obj, filePath, scope);
152
188
  for (var i = 0; i < structural.length; i++) {
153
189
  diagnostics.push(structural[i]);
154
190
  }
@@ -186,7 +222,7 @@ function runPreflight(opts) {
186
222
 
187
223
  // User global: ~/.claude/settings.json
188
224
  var userSettingsPath = path.join(userHome, ".claude", "settings.json");
189
- var userDiags = validateSettingsFile(userSettingsPath);
225
+ var userDiags = validateSettingsFile(userSettingsPath, "user");
190
226
  for (var i = 0; i < userDiags.length; i++) {
191
227
  diagnostics.push(userDiags[i]);
192
228
  }
@@ -195,7 +231,7 @@ function runPreflight(opts) {
195
231
  var projectDir = opts.projectDir;
196
232
  if (projectDir && typeof projectDir === "string" && projectDir.length > 0) {
197
233
  var projectSettingsPath = path.join(projectDir, ".claude", "settings.json");
198
- var projectDiags = validateSettingsFile(projectSettingsPath);
234
+ var projectDiags = validateSettingsFile(projectSettingsPath, "project");
199
235
  for (var j = 0; j < projectDiags.length; j++) {
200
236
  diagnostics.push(projectDiags[j]);
201
237
  }
package/lib/utils.js CHANGED
@@ -57,8 +57,31 @@ function resolveEncodedFile(baseDir, cwd, ext) {
57
57
  });
58
58
  }
59
59
 
60
+ /**
61
+ * Sanitize a persisted `allowedTools` map before hydrating it into a live
62
+ * session (lr-8b2e). The value originates from a durable .jsonl meta record
63
+ * that shares its trust boundary with other session-file fields, but an
64
+ * un-validated shape would let a crafted record (e.g. {"Bash": "yes"} or a
65
+ * non-object) auto-approve a tool with no operator click at the
66
+ * handleCanUseTool check (lib/sdk-bridge.js:691).
67
+ *
68
+ * Keeps only entries whose key is a string and whose value is strictly
69
+ * boolean `true`; drops everything else. A non-object input (including
70
+ * null/undefined/arrays) yields {} rather than throwing.
71
+ */
72
+ function sanitizeAllowedTools(value) {
73
+ var out = {};
74
+ if (!value || typeof value !== "object" || Array.isArray(value)) return out;
75
+ for (var key in value) {
76
+ if (!Object.prototype.hasOwnProperty.call(value, key)) continue;
77
+ if (typeof key === "string" && value[key] === true) out[key] = true;
78
+ }
79
+ return out;
80
+ }
81
+
60
82
  module.exports = {
61
83
  encodeCwd: encodeCwd,
62
84
  resolveEncodedDir: resolveEncodedDir,
63
85
  resolveEncodedFile: resolveEncodedFile,
86
+ sanitizeAllowedTools: sanitizeAllowedTools,
64
87
  };
package/lib/ws-schema.js CHANGED
@@ -270,6 +270,8 @@ var schema = {
270
270
  "rename_project_folder_result": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "Rename folder result" },
271
271
  "set_folder_icon": { direction: "c2s", handler: "lib/project-sessions.js", description: "Set or clear the emoji icon for a named folder" },
272
272
  "set_folder_icon_result": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "Set folder icon result" },
273
+ "rename_custom_icon": { direction: "c2s", handler: "lib/project-sessions.js", description: "Rename a custom-icon upload (oldSlug -> newSlug), rewriting all project/folder references atomically" },
274
+ "rename_custom_icon_result": { direction: "s2c", handler: "lib/public/modules/custom-icons-settings.js", description: "Custom icon rename result" },
273
275
  "transfer_project_owner": { direction: "c2s", handler: "lib/project-sessions.js", description: "Transfer project ownership to another user" },
274
276
  "project_owner_changed": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "Project ownership was transferred" },
275
277
  "projects_updated": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "Broadcast: project list changed" },
@@ -11,6 +11,18 @@
11
11
 
12
12
  var validateDiagnosticEvent = require("../interface").validateDiagnosticEvent;
13
13
 
14
+ // VALID_HOOK_EVENTS (lr-e901): the CLI's own "Unknown hook event: X" stderr
15
+ // line is matched generically below (source:'hook') without knowing whether
16
+ // the Console's allowlist actually considers X unknown. settings-preflight.js
17
+ // is the single source of truth for that allowlist (see its header comment —
18
+ // "the ONLY place the valid hook events are defined"). Reuse it here instead
19
+ // of re-deriving a second copy, so a hook event added to the allowlist stops
20
+ // producing a false "unknown hook" toast from BOTH emission paths at once.
21
+ var VALID_HOOK_EVENTS = require("../../settings-preflight").VALID_HOOK_EVENTS;
22
+
23
+ // Matches the hook event name out of a CLI "Unknown hook event: <Name>" line.
24
+ var UNKNOWN_HOOK_EVENT_RE = /^Unknown hook event:\s*(\S+)/;
25
+
14
26
  // ---------------------------------------------------------------------------
15
27
  // Pattern table
16
28
  // ---------------------------------------------------------------------------
@@ -91,6 +103,19 @@ function parseDiagnosticLine(rawLine) {
91
103
  for (var i = 0; i < PATTERNS.length; i++) {
92
104
  var pattern = PATTERNS[i];
93
105
  if (matches(line, pattern)) {
106
+ // lr-e901: reconcile the CLI-stderr "Unknown hook event" path against
107
+ // the Console's own VALID_HOOK_EVENTS allowlist (settings-preflight.js).
108
+ // The CLI's stderr message reflects the *installed CLI version's*
109
+ // knowledge of hook events, which can lag the allowlist verified here
110
+ // (see settings-preflight.js header, lr-7e22). When the named event IS
111
+ // in VALID_HOOK_EVENTS, treat this as a stale/false CLI warning and
112
+ // suppress it rather than surfacing a contradictory toast — do not
113
+ // widen the allowlist to "fix" this, the allowlist is already correct.
114
+ var hookMatch = pattern.source === "hook" && UNKNOWN_HOOK_EVENT_RE.exec(line);
115
+ if (hookMatch && VALID_HOOK_EVENTS.indexOf(hookMatch[1]) !== -1) {
116
+ return null;
117
+ }
118
+
94
119
  var event = {
95
120
  type: "diagnostic",
96
121
  severity: pattern.severity,