@clagentic/console 1.5.0 → 1.6.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 (66) hide show
  1. package/README.md +23 -4
  2. package/bin/cli.js +15 -82
  3. package/lib/agents-favorites.js +21 -6
  4. package/lib/config.js +1 -1
  5. package/lib/daemon.js +153 -22
  6. package/lib/drain.js +213 -0
  7. package/lib/lite-detect.js +6 -5
  8. package/lib/loop-handoff.js +282 -0
  9. package/lib/mcp-local.js +18 -2
  10. package/lib/memory-limits.js +436 -0
  11. package/lib/model-context-windows.js +65 -0
  12. package/lib/project-loop.js +31 -3
  13. package/lib/project-sessions.js +26 -0
  14. package/lib/project-team.js +4 -1
  15. package/lib/project.js +8 -0
  16. package/lib/public/app.js +4 -0
  17. package/lib/public/css/base.css +18 -0
  18. package/lib/public/css/diagnostics.css +279 -0
  19. package/lib/public/css/icon-strip.css +201 -0
  20. package/lib/public/css/menus.css +2 -2
  21. package/lib/public/css/mobile-nav.css +24 -0
  22. package/lib/public/css/server-settings.css +100 -0
  23. package/lib/public/index.html +26 -0
  24. package/lib/public/modules/app-header.js +4 -7
  25. package/lib/public/modules/app-home-hub.js +31 -7
  26. package/lib/public/modules/app-messages.js +13 -0
  27. package/lib/public/modules/app-notifications.js +5 -1
  28. package/lib/public/modules/app-panels.js +11 -21
  29. package/lib/public/modules/app-projects.js +10 -5
  30. package/lib/public/modules/command-palette.js +16 -5
  31. package/lib/public/modules/custom-icons-settings.js +399 -0
  32. package/lib/public/modules/custom-icons.js +114 -0
  33. package/lib/public/modules/diagnostic-format.js +34 -0
  34. package/lib/public/modules/diagnostics.js +297 -0
  35. package/lib/public/modules/emoji-picker.js +253 -6
  36. package/lib/public/modules/model-context-windows.js +62 -0
  37. package/lib/public/modules/popover-position.js +192 -0
  38. package/lib/public/modules/project-icon.js +113 -0
  39. package/lib/public/modules/project-settings.js +2 -2
  40. package/lib/public/modules/project-switcher.js +2 -1
  41. package/lib/public/modules/scheduler-config.js +5 -8
  42. package/lib/public/modules/scheduler.js +5 -6
  43. package/lib/public/modules/server-settings.js +6 -0
  44. package/lib/public/modules/sidebar-mobile.js +4 -6
  45. package/lib/public/modules/sidebar-projects.js +35 -90
  46. package/lib/public/modules/sidebar-sessions.js +6 -20
  47. package/lib/public/modules/sticky-notes.js +4 -4
  48. package/lib/public/modules/terminal.js +5 -12
  49. package/lib/public/style.css +1 -0
  50. package/lib/sdk-bridge.js +75 -10
  51. package/lib/sdk-message-processor.js +12 -0
  52. package/lib/sdk-worker.js +4 -1
  53. package/lib/server-settings.js +221 -1
  54. package/lib/server.js +30 -1
  55. package/lib/sessions.js +27 -11
  56. package/lib/settings-preflight.js +212 -0
  57. package/lib/ws-schema.js +2 -0
  58. package/lib/yoke/adapters/claude-worker.js +14 -2
  59. package/lib/yoke/adapters/claude.js +16 -0
  60. package/lib/yoke/adapters/diagnostic-patterns.js +120 -0
  61. package/lib/yoke/index.js +4 -0
  62. package/lib/yoke/interface.js +99 -0
  63. package/package.json +2 -1
  64. package/scripts/postinstall.js +41 -0
  65. package/lib/certs/fullchain.pem +0 -47
  66. package/lib/certs/privkey.pem +0 -5
@@ -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;
@@ -365,7 +366,7 @@ function createServer(opts) {
365
366
  return;
366
367
  }
367
368
 
368
- // PWA install guide (builtin cert mode, no CA step needed)
369
+ // PWA install guide
369
370
  if (fullUrl === "/pwa" && req.method === "GET") {
370
371
  var host = req.headers.host || "localhost";
371
372
  var hostname = host.split(":")[0];
@@ -732,6 +733,14 @@ function createServer(opts) {
732
733
  });
733
734
  }
734
735
 
736
+ // --- Drain state (lr-6b30) ---
737
+ // Injected by daemon.js via setDrain() after the drain controller is created.
738
+ var _drainController = null;
739
+
740
+ function setDrain(drainController) {
741
+ _drainController = drainController;
742
+ }
743
+
735
744
  // --- WebSocket ---
736
745
  var wss = new WebSocketServer({ noServer: true });
737
746
 
@@ -771,6 +780,23 @@ function createServer(opts) {
771
780
  return;
772
781
  }
773
782
 
783
+ // Drain gate (lr-6b30): reject new sessions while draining so in-flight
784
+ // sessions can complete before the daemon exits.
785
+ if (_drainController && _drainController.isDraining()) {
786
+ socket.write(
787
+ "HTTP/1.1 503 Service Unavailable\r\n" +
788
+ "Content-Type: application/json\r\n" +
789
+ "Connection: close\r\n" +
790
+ "\r\n"
791
+ );
792
+ socket.end(JSON.stringify({
793
+ type: "error",
794
+ code: "server_draining",
795
+ message: "Server is draining for restart. Please reconnect in a moment.",
796
+ }));
797
+ return;
798
+ }
799
+
774
800
  // Extract slug from WS URL: /p/{slug}/ws
775
801
  var wsSlug = extractSlug(req.url);
776
802
  if (!wsSlug) {
@@ -1051,6 +1077,7 @@ function createServer(opts) {
1051
1077
  onSetProjectFolder: onSetProjectFolder,
1052
1078
  onRenameProjectFolder: onRenameProjectFolder,
1053
1079
  onSetFolderIcon: onSetFolderIcon,
1080
+ onRenameCustomIcon: onRenameCustomIcon,
1054
1081
  onProjectOwnerChanged: onProjectOwnerChanged,
1055
1082
  onGetServerDefaultEffort: onGetServerDefaultEffort,
1056
1083
  onSetServerDefaultEffort: onSetServerDefaultEffort,
@@ -1410,6 +1437,8 @@ function createServer(opts) {
1410
1437
  forEachProject: forEachProject,
1411
1438
  destroyProject: removeProject,
1412
1439
  destroyAll: destroyAll,
1440
+ // Drain controller injection (lr-6b30).
1441
+ setDrain: setDrain,
1413
1442
  };
1414
1443
  }
1415
1444
 
package/lib/sessions.js CHANGED
@@ -313,11 +313,14 @@ function createSessionManager(opts) {
313
313
 
314
314
  // Drain all write buffers synchronously on process exit to prevent trailing
315
315
  // event loss when the daemon shuts down cleanly.
316
- process.on("exit", function() {
316
+ // Named so it can be deregistered via sm.destroy() when the project is torn
317
+ // down — avoids accumulating one listener per project open (lr-daca).
318
+ function _onProcessExit() {
317
319
  sessions.forEach(function(session) {
318
320
  flushSessionBuffer(session);
319
321
  });
320
- });
322
+ }
323
+ process.on("exit", _onProcessExit);
321
324
 
322
325
  function getActiveSession() {
323
326
  return sessions.get(activeSessionId) || null;
@@ -550,18 +553,25 @@ function createSessionManager(opts) {
550
553
  // (same rules as getVisibleSessions / server-palette). Internal callers
551
554
  // (targetWs=null) bypass this gate — they operate on already-validated session
552
555
  // references.
556
+ //
557
+ // No-auth / single-user connections have _clayUser === null (set by
558
+ // project-connection.js:92 as wsUser || null). In that deployment there is
559
+ // no user identity to check — the connection is the implicit owner. We skip
560
+ // the gate entirely for null users so that _clayActiveSession is still
561
+ // bound below, keeping the live-broadcast filter (doSendAndRecord /
562
+ // doSendToSession) in sync. Authenticated users who lack access are still
563
+ // rejected by canAccessSession. (regression introduced by dca60a7, lr-690b)
553
564
  if (targetWs) {
554
565
  var requestingUser = targetWs._clayUser || null;
555
- if (!requestingUser) {
556
- if (sendTo) sendTo(targetWs, { type: "error", error: "Access denied" });
557
- return;
558
- }
559
- // Use { visibility: "public" } so canAccessProject passes and the
560
- // session-level ownership/visibility rules do the real work.
561
- if (!users.canAccessSession(requestingUser.id, session, { visibility: "public" })) {
562
- if (sendTo) sendTo(targetWs, { type: "error", error: "Access denied" });
563
- return;
566
+ if (requestingUser) {
567
+ // Use { visibility: "public" } so canAccessProject passes and the
568
+ // session-level ownership/visibility rules do the real work.
569
+ if (!users.canAccessSession(requestingUser.id, session, { visibility: "public" })) {
570
+ if (sendTo) sendTo(targetWs, { type: "error", error: "Access denied" });
571
+ return;
572
+ }
564
573
  }
574
+ // null requestingUser = no-auth deployment; fall through to bind _clayActiveSession.
565
575
  }
566
576
 
567
577
  activeSessionId = localId;
@@ -1163,6 +1173,12 @@ function createSessionManager(opts) {
1163
1173
  return { ok: true };
1164
1174
  },
1165
1175
  permissionRequestIndex: permissionRequestIndex,
1176
+ // Remove the process-level exit listener registered above.
1177
+ // Must be called when the project owning this session manager is destroyed
1178
+ // so listeners do not accumulate across project open/close cycles (lr-daca).
1179
+ destroy: function() {
1180
+ process.removeListener("exit", _onProcessExit);
1181
+ },
1166
1182
  };
1167
1183
  }
1168
1184
 
@@ -0,0 +1,212 @@
1
+ // settings-preflight.js — Console-side settings.json preflight validator.
2
+ //
3
+ // Part of epic lr-1a52 stage 5/5 (lr-1a26): deterministic, version-independent
4
+ // preflight that validates ~/.claude/settings.json and project .claude/settings.json
5
+ // without relying on CLI stderr pattern matching.
6
+ //
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
11
+ //
12
+ // Diagnostic shape (conforms to validateDiagnosticEvent from YOKE interface):
13
+ // { type: 'diagnostic', severity, source: 'preflight', message }
14
+
15
+ "use strict";
16
+
17
+ var fs = require("fs");
18
+ var path = require("path");
19
+ var os = require("os");
20
+
21
+ // ---------------------------------------------------------------------------
22
+ // Hook event allowlist
23
+ //
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
26
+ // motivating screenshot for this stage) is a real example of an unknown key
27
+ // that surfaces as a silent no-op in the CLI but clutters the warnings stream.
28
+ //
29
+ // IMPORTANT: This list is the ONLY place the valid hook events are defined in
30
+ // the Console codebase. Do not duplicate it elsewhere — drift between copies
31
+ // is exactly the parity bug we are fixing.
32
+ //
33
+ // 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.
38
+ // ---------------------------------------------------------------------------
39
+ var VALID_HOOK_EVENTS = [
40
+ "PreToolUse",
41
+ "PostToolUse",
42
+ "Notification",
43
+ "Stop",
44
+ "SubagentStop",
45
+ ];
46
+
47
+ // ---------------------------------------------------------------------------
48
+ // Pure validator
49
+ // ---------------------------------------------------------------------------
50
+
51
+ /**
52
+ * Validate a parsed settings object for known structural problems.
53
+ *
54
+ * Pure function — no IO, no side effects. Suitable for unit testing.
55
+ *
56
+ * @param {object} obj - Parsed settings JSON (any shape; we check what we know)
57
+ * @param {string} filePath - Path string used only in diagnostic messages
58
+ * @returns {Array<{type,severity,source,message}>} Diagnostics (empty = no issues)
59
+ */
60
+ function validateSettingsObject(obj, filePath) {
61
+ var diagnostics = [];
62
+ var label = filePath || "settings.json";
63
+
64
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
65
+ // Nothing meaningful to validate — caller should have caught this at parse time
66
+ return diagnostics;
67
+ }
68
+
69
+ // (b) Known-hook-event allowlist check.
70
+ // The hooks field is expected to be an object whose keys are hook event names.
71
+ // Unknown keys silently no-op in the CLI but should warn operators.
72
+ if (obj.hooks !== null && obj.hooks !== undefined) {
73
+ if (typeof obj.hooks !== "object" || Array.isArray(obj.hooks)) {
74
+ diagnostics.push({
75
+ type: "diagnostic",
76
+ severity: "warning",
77
+ source: "preflight",
78
+ message: label + ": 'hooks' field is not an object — expected { EventName: [...] }.",
79
+ });
80
+ } else {
81
+ var hookKeys = Object.keys(obj.hooks);
82
+ for (var i = 0; i < hookKeys.length; i++) {
83
+ var key = hookKeys[i];
84
+ if (VALID_HOOK_EVENTS.indexOf(key) === -1) {
85
+ diagnostics.push({
86
+ type: "diagnostic",
87
+ severity: "warning",
88
+ source: "preflight",
89
+ message: label + ": unknown hook event '" + key + "'. Valid events: " + VALID_HOOK_EVENTS.join(", ") + ". This hook will be silently ignored by the CLI.",
90
+ });
91
+ }
92
+ }
93
+ }
94
+ }
95
+
96
+ return diagnostics;
97
+ }
98
+
99
+ // ---------------------------------------------------------------------------
100
+ // IO layer
101
+ // ---------------------------------------------------------------------------
102
+
103
+ /**
104
+ * Validate a single settings.json file.
105
+ *
106
+ * Returns an array of diagnostic objects:
107
+ * - Empty array → file absent, or file is clean (silence is success)
108
+ * - error entry → file exists but failed JSON.parse
109
+ * - warning entries → file parsed but has structural problems
110
+ *
111
+ * Never throws — all errors are surfaced as diagnostics or swallowed
112
+ * per the non-blocking preflight contract.
113
+ *
114
+ * @param {string} filePath - Absolute path to settings.json
115
+ * @returns {Array<object>} diagnostics
116
+ */
117
+ function validateSettingsFile(filePath) {
118
+ var diagnostics = [];
119
+
120
+ // Missing file → nothing to validate. Not an error.
121
+ var raw;
122
+ try {
123
+ raw = fs.readFileSync(filePath, "utf8");
124
+ } catch (e) {
125
+ if (e.code === "ENOENT") return diagnostics;
126
+ // Unreadable file (permissions etc.) → low-severity, not user-facing error
127
+ diagnostics.push({
128
+ type: "diagnostic",
129
+ severity: "info",
130
+ source: "preflight",
131
+ message: filePath + ": could not read settings file (" + e.code + " — " + (e.message || String(e)) + ").",
132
+ });
133
+ return diagnostics;
134
+ }
135
+
136
+ // (a) JSON parse check
137
+ var obj;
138
+ try {
139
+ obj = JSON.parse(raw);
140
+ } catch (e) {
141
+ diagnostics.push({
142
+ type: "diagnostic",
143
+ severity: "error",
144
+ source: "preflight",
145
+ message: filePath + ": settings.json is not valid JSON — " + (e.message || String(e)) + ".",
146
+ });
147
+ return diagnostics;
148
+ }
149
+
150
+ // (b) Structural validation
151
+ var structural = validateSettingsObject(obj, filePath);
152
+ for (var i = 0; i < structural.length; i++) {
153
+ diagnostics.push(structural[i]);
154
+ }
155
+
156
+ return diagnostics;
157
+ }
158
+
159
+ /**
160
+ * Run the full preflight check against both user and project settings files.
161
+ *
162
+ * @param {object} opts
163
+ * @param {string} [opts.userHome] - Home directory to find ~/.claude/settings.json.
164
+ * Resolved via REAL_HOME from config.js when absent.
165
+ * @param {string} [opts.projectDir] - Project working directory to find .claude/settings.json.
166
+ * When absent (or empty), project settings are skipped.
167
+ * @returns {Array<object>} All diagnostics across both files (empty = all clean)
168
+ */
169
+ function runPreflight(opts) {
170
+ opts = opts || {};
171
+
172
+ var diagnostics = [];
173
+
174
+ // Resolve the user home from config.js (honours SUDO_USER resolution),
175
+ // falling back to os.homedir() if the module is unavailable.
176
+ // The REAL_HOME constant in config.js is already resolved on module load —
177
+ // reading it here is free (no IO, no side effect).
178
+ var userHome = opts.userHome;
179
+ if (!userHome) {
180
+ try {
181
+ userHome = require("./config").REAL_HOME;
182
+ } catch (e) {
183
+ userHome = os.homedir();
184
+ }
185
+ }
186
+
187
+ // User global: ~/.claude/settings.json
188
+ var userSettingsPath = path.join(userHome, ".claude", "settings.json");
189
+ var userDiags = validateSettingsFile(userSettingsPath);
190
+ for (var i = 0; i < userDiags.length; i++) {
191
+ diagnostics.push(userDiags[i]);
192
+ }
193
+
194
+ // Project-local: <projectDir>/.claude/settings.json (optional)
195
+ var projectDir = opts.projectDir;
196
+ if (projectDir && typeof projectDir === "string" && projectDir.length > 0) {
197
+ var projectSettingsPath = path.join(projectDir, ".claude", "settings.json");
198
+ var projectDiags = validateSettingsFile(projectSettingsPath);
199
+ for (var j = 0; j < projectDiags.length; j++) {
200
+ diagnostics.push(projectDiags[j]);
201
+ }
202
+ }
203
+
204
+ return diagnostics;
205
+ }
206
+
207
+ module.exports = {
208
+ VALID_HOOK_EVENTS: VALID_HOOK_EVENTS,
209
+ validateSettingsObject: validateSettingsObject,
210
+ validateSettingsFile: validateSettingsFile,
211
+ runPreflight: runPreflight,
212
+ };
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" },
@@ -18,6 +18,7 @@ var crypto = require("crypto");
18
18
  var path = require("path");
19
19
  var fs = require("fs");
20
20
  var os = require("os");
21
+ var parseDiagnosticLine = require("./diagnostic-patterns").parseDiagnosticLine;
21
22
 
22
23
  var socketPath = process.argv[2];
23
24
  if (!socketPath) {
@@ -463,13 +464,24 @@ async function handleQueryStart(msg) {
463
464
  });
464
465
  // Track the child so cleanup() can terminate it on worker shutdown.
465
466
  _claudeChildProcess = cp;
466
- // Capture ALL CLI stderr
467
+ // Capture ALL CLI stderr. Known diagnostic lines are also emitted as
468
+ // 'diagnostic' YOKE events (stage 2/5, lr-28ee) so they can be routed to
469
+ // the Console UI. The raw [CLI-STDERR] log is always kept regardless.
467
470
  if (cp.stderr) {
468
471
  cp.stderr.on("data", function(chunk) {
469
472
  var lines = chunk.toString().split("\n");
470
473
  for (var li = 0; li < lines.length; li++) {
471
474
  var line = lines[li].trim();
472
- if (line) console.log("[CLI-STDERR] " + line.substring(0, 500));
475
+ if (!line) continue;
476
+ console.log("[CLI-STDERR] " + line.substring(0, 500));
477
+ var diag = parseDiagnosticLine(line);
478
+ if (diag) {
479
+ // Emit as sdk_event so the existing IPC path (createWorkerQueryHandle
480
+ // → flattenEvent) carries it through unchanged. flattenEvent will
481
+ // tag it yokeType:"unknown"/rawType:"diagnostic" until stage 3/5
482
+ // (lr-0868) adds the explicit branch in flattenEvent().
483
+ sendToDaemon({ type: "sdk_event", event: diag });
484
+ }
473
485
  }
474
486
  });
475
487
  }
@@ -259,6 +259,19 @@ function flattenEvent(raw) {
259
259
  return raw;
260
260
  }
261
261
 
262
+ // --- diagnostic events (stage 2/5, lr-28ee / stage 3/5, lr-0868) ---
263
+ // Emitted by claude-worker.js via sdk_event when parseDiagnosticLine matches
264
+ // a CLI stderr line. Shape: { type:'diagnostic', severity, source, message }.
265
+ // Must NOT fall through to the unknown catch-all — the processor routes on
266
+ // yokeType:'diagnostic' to produce a distinct frontend message (not 'error').
267
+ if (raw.type === "diagnostic") {
268
+ base.yokeType = "diagnostic";
269
+ base.severity = raw.severity;
270
+ base.source = raw.source;
271
+ base.message = raw.message;
272
+ return base;
273
+ }
274
+
262
275
  // --- fallback: unknown event type ---
263
276
  base.yokeType = "unknown";
264
277
  base.rawType = raw.type;
@@ -1600,5 +1613,8 @@ module.exports = {
1600
1613
  createClaudeAdapter: createClaudeAdapter,
1601
1614
  createMessageQueue: createMessageQueue,
1602
1615
  _test_handleWorkerEarlyExit: _test_handleWorkerEarlyExit,
1616
+ // Test seam for hop-A diagnostic routing (lr-0868): allows test/diagnostic-routing-lr-0868.test.js
1617
+ // to call flattenEvent directly without spawning a worker process.
1618
+ _test_flattenEvent: flattenEvent,
1603
1619
  };
1604
1620