claude-code-session-manager 0.137.0 → 0.139.0

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 (101) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +339 -82
  3. package/dist/assets/{AppSettings-l7NTc0yu.js → AppSettings-CUfWY9vN.js} +2 -2
  4. package/dist/assets/History-DDnqaLyw.js +2 -0
  5. package/dist/assets/HomeClaudeConfig-CGD2Onjv.js +3 -0
  6. package/dist/assets/{Panel-BuInRmA0.js → Panel-Csyd9HbD.js} +1 -1
  7. package/dist/assets/ProjectClaudeConfig-C-jlYpC_.js +26 -0
  8. package/dist/assets/{Scheduler-B7sn2mUw.js → Scheduler-NLs08fx7.js} +9 -9
  9. package/dist/assets/{SkillReferenceGraph-DwV0Ueyc.js → SkillReferenceGraph-DcscPXAG.js} +1 -1
  10. package/dist/assets/Skills-BpGRKOcY.js +67 -0
  11. package/dist/assets/{TiptapBody-Bl8hDhhS.js → TiptapBody-DSU3769X.js} +60 -54
  12. package/dist/assets/ViewTabs-C0PRZx4_.js +1 -0
  13. package/dist/assets/{VoiceButton-DJx-jY4r.js → VoiceButton-D2rMurNg.js} +1 -1
  14. package/dist/assets/{historyTotals-Cgjm5q24.js → historyTotals-TcIQs2sh.js} +1 -1
  15. package/dist/assets/{index-62tyjEQB.css → index-BCySPdtU.css} +1 -1
  16. package/dist/assets/index-C-d0DCre.js +3124 -0
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +471 -452
  20. package/package.json +13 -5
  21. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  22. package/plugins/session-manager-dev/skills/builder/SKILL.md +12 -4
  23. package/plugins/session-manager-dev/skills/builder/scripts/publish-preflight.cjs +255 -0
  24. package/plugins/session-manager-dev/skills/develop/SKILL.md +12 -5
  25. package/scripts/README.md +1 -0
  26. package/scripts/scheduler-mcp-server.cjs +161 -18
  27. package/src/main/build-info.json +4 -4
  28. package/src/main/chatRunner.cjs +53 -2
  29. package/src/main/exchanges.cjs +70 -5
  30. package/src/main/historyAggregator.cjs +84 -58
  31. package/src/main/historyDashboard.cjs +18 -13
  32. package/src/main/index.cjs +35 -9
  33. package/src/main/ipcSchemas.cjs +133 -5
  34. package/src/main/lib/claude/effectiveModelInfo.cjs +2 -2
  35. package/src/main/lib/claude/modelPricing.cjs +148 -0
  36. package/src/main/lib/demo-video-kit/checks.cjs +16 -0
  37. package/src/main/lib/epic/epicAdminRoutes.cjs +101 -0
  38. package/src/main/lib/epic/epicAttachments.cjs +143 -0
  39. package/src/main/lib/epic/epicJobReceipt.cjs +87 -0
  40. package/src/main/lib/epic/epicMint.cjs +4 -0
  41. package/src/main/lib/epic/epicOutsideRead.cjs +306 -0
  42. package/src/main/lib/epic/epicOutsideState.cjs +233 -0
  43. package/src/main/lib/epic/epicSettle.cjs +1 -1
  44. package/src/main/lib/epic/epicStateWatcher.cjs +157 -0
  45. package/src/main/lib/epic/externalRef.cjs +37 -0
  46. package/src/main/lib/epic/externalRefIndex.cjs +136 -0
  47. package/src/main/lib/epic/restorableSessions.cjs +151 -17
  48. package/src/main/lib/epic/transcriptUsage.cjs +197 -0
  49. package/src/main/lib/externalContract.cjs +111 -0
  50. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +121 -4
  51. package/src/main/lib/feedback-remote/crossProjectReply.cjs +83 -1
  52. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -6
  53. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +50 -8
  54. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +218 -4
  55. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +19 -3
  56. package/src/main/lib/feedback-remote/feedbackImages.cjs +171 -0
  57. package/src/main/lib/feedback-remote/localAdminHttp.cjs +11 -10
  58. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +287 -1
  59. package/src/main/lib/feedback-remote/needsYouAdminRoutes.cjs +133 -0
  60. package/src/main/lib/feedback-remote/needsYouIpc.cjs +50 -0
  61. package/src/main/lib/feedback-remote/needsYouStore.cjs +281 -0
  62. package/src/main/lib/feedback-remote/remoteFrameAssembler.cjs +113 -0
  63. package/src/main/lib/historyRollup.cjs +32 -5
  64. package/src/main/lib/mcpToolCatalog.cjs +111 -14
  65. package/src/main/lib/persona-macro/agentAdminRoutes.cjs +121 -0
  66. package/src/main/lib/persona-macro/macroLibrary.cjs +7 -0
  67. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  68. package/src/main/lib/process/bootStdioGuard.cjs +32 -0
  69. package/src/main/lib/process/stdioGuard.cjs +115 -0
  70. package/src/main/lib/promptSessionSchema.cjs +4 -0
  71. package/src/main/lib/remoteTranscriptTail.cjs +32 -1
  72. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  73. package/src/main/lib/telemetry/auditEvents.cjs +176 -0
  74. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +45 -0
  75. package/src/main/loopEfficiencyHandlers.cjs +1 -1
  76. package/src/main/scheduler.cjs +29 -0
  77. package/src/main/templates/PRD_AUTHORING.md +1 -0
  78. package/src/main/transcripts.cjs +62 -7
  79. package/src/main/webRemote.cjs +122 -18
  80. package/src/preload/api.d.ts +98 -9
  81. package/src/preload/apiSurface.cjs +7 -0
  82. package/src/preload/apiSurface.json +415 -83
  83. package/src/preload/index.cjs +17 -3
  84. package/src/seed/agents/demo-video-builder.md +10 -7
  85. package/dist/assets/AgentLibrary-DV0DTZDC.js +0 -2
  86. package/dist/assets/Button-Cmfkgjfa.js +0 -1
  87. package/dist/assets/DocumentEditorPane-MTljV-Uw.js +0 -1
  88. package/dist/assets/Extensions-Cc1Q_8id.js +0 -2
  89. package/dist/assets/History-CFo-1DHo.js +0 -2
  90. package/dist/assets/Library-C_ibFiOx.js +0 -32
  91. package/dist/assets/ListDetail-ByULG209.js +0 -1
  92. package/dist/assets/ProjectClaudeConfig-yqqVtHY7.js +0 -25
  93. package/dist/assets/ProvenanceBadge-CJvnQReI.js +0 -1
  94. package/dist/assets/Settings-DRRSJksU.js +0 -2
  95. package/dist/assets/Skills-DVYHA9gV.js +0 -29
  96. package/dist/assets/SourceChip-DfJ5_5rV.js +0 -1
  97. package/dist/assets/SystemPrompt-f11wGllK.js +0 -1
  98. package/dist/assets/Toggle-DaxeFDFp.js +0 -1
  99. package/dist/assets/ViewTabs-DRtgFKRw.js +0 -1
  100. package/dist/assets/claude-settings-schema-COigsajx.js +0 -3
  101. package/dist/assets/index-iQ6pdyuS.js +0 -3116
@@ -32,6 +32,22 @@
32
32
  * Every successful save appends one `admin_macro_save` audit event and calls
33
33
  * `onChanged()` exactly once so the Sessions HOT KEYS strip updates live,
34
34
  * matching the IPC handlers in index.cjs.
35
+ *
36
+ * POST /admin/macros/run {cwd, id, inputs?, effort?, externalRef?}
37
+ * -> { ok, epicId, alreadyRunning, externalRef? }
38
+ * Starts a saved macro from a script (e.g. a systemd timer) through the
39
+ * renderer's press path (deps.startExternalNewSession: same persona, tag, AIM
40
+ * prompt and source.macroId, so autoStartTargets apply). Refused (400, no
41
+ * launch) unless a human ticked 'Can be started by a script' (scriptStart)
42
+ * on a visible, non-builtin, non-job macro whose persona is listed. {{inputs}}
43
+ * = the macro's defaults overlaid by `inputs`. While that macro's Epic is
44
+ * still running in the cwd it returns that Epic (alreadyRunning:true) instead
45
+ * of a second start. A launch failure is a 503 with no audit event.
46
+ * externalRef (normalizeExternalRef; invalid = 400), e.g. a date, starts the
47
+ * macro at most once per ref: it rides in the payload, is recorded in
48
+ * externalRefIndex and audited; a repeat with the same cwd + ref answers
49
+ * { existing: true } with that Epic (409 if another producer/macro owns the ref).
50
+ * curl -s -X POST "http://127.0.0.1:$(jq -r .port ~/.claude/session-manager/admin-api.json)/admin/macros/run" -H "Authorization: Bearer $(jq -r .token ~/.claude/session-manager/admin-api.json)" -H 'Content-Type: application/json' -d '{"cwd":"/abs/project","id":"<macro-id>"}'
35
51
  */
36
52
  'use strict';
37
53
 
@@ -40,6 +56,10 @@ const { resolveCwd } = require('./projectHomeAdminRoutes.cjs');
40
56
  const macroLibrary = require('../persona-macro/macroLibrary.cjs');
41
57
  const { appendAuditEvent } = require('../telemetry/auditLog.cjs');
42
58
  const { findHumanPromptContaining } = require('./humanPromptLedger.cjs');
59
+ const { readActiveIndex } = require('../epic/epicMint.cjs');
60
+ const { PRD_EFFORT_LEVELS } = require('../prd/prdFrontmatter.cjs');
61
+ const { normalizeExternalRef } = require('../epic/externalRef.cjs');
62
+ const { findEpicByExternalRef, recordExternalRef, withExternalRefLock } = require('../epic/externalRefIndex.cjs');
43
63
 
44
64
  const EVERY_PROJECT_RE = /(^|[^a-z0-9])(every|all|each)\s+(of\s+)?(my\s+|the\s+|our\s+)?projects?($|[^a-z0-9])/;
45
65
 
@@ -250,11 +270,277 @@ function deleteHandler(onChanged, libOpts) {
250
270
  };
251
271
  }
252
272
 
253
- function registerAdminRoute(adminHttp, { onChanged } = {}, opts = {}) {
273
+ const RUN_INPUT_MAX_KEYS = 20;
274
+ const RUN_INPUT_MAX_LEN = 2000;
275
+ const RECENT_START_MS = 60_000;
276
+ const OPEN_STATUSES = new Set(['proposed', 'active']);
277
+ /** `${cwd}\u0000${id}` -> { epicId, at } — starts made by this route. */
278
+ const recentRuns = new Map();
279
+ /** `${cwd}\u0000${id}` -> Promise<{ok, epicId?}> — runs still awaiting the renderer. */
280
+ const inProgressRuns = new Map();
281
+
282
+ const SCRIPT_START_HINT = "the human can tick 'Can be started by a script' in the macro editor";
283
+
284
+ /** The open Epic this macro is already running in `cwd`, or null. */
285
+ function findRunningEpic(cwd, id, isTabBusy) {
286
+ const index = readActiveIndex(cwd);
287
+ for (const epic of Object.values(index.sessions)) {
288
+ if (!epic || typeof epic !== 'object' || !OPEN_STATUSES.has(epic.status)) continue;
289
+ const src = epic.source;
290
+ if (!src || src.producer !== 'new-epic-ui' || src.macroId !== id) continue;
291
+ if (typeof epic.id === 'string' && isTabBusy(epic.id)) return epic.id;
292
+ }
293
+ const key = `${cwd}\u0000${id}`;
294
+ const recent = recentRuns.get(key);
295
+ if (recent && Date.now() - recent.at < RECENT_START_MS) {
296
+ const entry = index.sessions[recent.epicId];
297
+ // Not in the index yet = just minted and still being persisted: open.
298
+ const open = entry ? OPEN_STATUSES.has(entry.status) : !index.tombstones[recent.epicId];
299
+ if (open) return recent.epicId;
300
+ } else if (recent) {
301
+ recentRuns.delete(key);
302
+ }
303
+ return null;
304
+ }
305
+
306
+ /** Returns an error string, or null when `inputs` is acceptable for `macro`. */
307
+ function validateRunInputs(inputs, macro) {
308
+ if (inputs === undefined) return null;
309
+ if (inputs === null || typeof inputs !== 'object' || Array.isArray(inputs)) return 'inputs must be an object';
310
+ const keys = Object.keys(inputs);
311
+ if (keys.length > RUN_INPUT_MAX_KEYS) return `inputs: at most ${RUN_INPUT_MAX_KEYS} keys`;
312
+ const declared = new Set((macro.inputs || []).map((i) => i.name));
313
+ for (const k of keys) {
314
+ if (!declared.has(k)) return `inputs: ${k} is not an input of macro ${macro.id}`;
315
+ const v = inputs[k];
316
+ if (typeof v !== 'string') return `inputs: ${k} must be a string`;
317
+ if (v.length > RUN_INPUT_MAX_LEN) return `inputs: ${k} is longer than ${RUN_INPUT_MAX_LEN} characters`;
318
+ }
319
+ return null;
320
+ }
321
+
322
+ function runHandler(deps, libOpts) {
323
+ const listPersonas = deps.listPersonas || ((...a) => require('../../agentLibrary.cjs').listPersonas(...a));
324
+ return async (req, res) => {
325
+ const body = await readJsonBody(req, res);
326
+ if (!body) return;
327
+ const resolved = resolveCwd(body.cwd);
328
+ if (!resolved.ok) {
329
+ sendJson(res, resolved.status, { ok: false, error: resolved.error });
330
+ return;
331
+ }
332
+ const cwd = resolved.cwd;
333
+ const bad = (error) => sendJson(res, 400, { ok: false, error });
334
+ const id = body.id;
335
+ if (typeof id !== 'string' || !id) return bad('id is required');
336
+ if (id.startsWith('builtin-')) return bad('built-in macros cannot be started through this route');
337
+ const macros = await macroLibrary.listMacros(libOpts);
338
+ const macro = macros.find((m) => m.id === id);
339
+ if (!macro) return bad(`macro not found: ${id}`);
340
+ if (!macroLibrary.macroVisibleIn(macro, cwd)) return bad(`macro ${id} is not visible to ${cwd}`);
341
+ if (macro.job) return bad(`macro ${id} runs a job, not a session; it cannot be started through this route`);
342
+ if (macro.scriptStart !== true) {
343
+ return bad(`macro ${id} is not marked 'Can be started by a script'; ${SCRIPT_START_HINT}`);
344
+ }
345
+ const personas = await listPersonas();
346
+ if (!personas.some((a) => a.name === macro.agentName)) return bad(`unknown agent: ${macro.agentName}`);
347
+ const inputsError = validateRunInputs(body.inputs, macro);
348
+ if (inputsError) return bad(inputsError);
349
+ const effort = body.effort;
350
+ if (effort !== undefined && !PRD_EFFORT_LEVELS.includes(effort)) {
351
+ return bad(`effort must be one of: ${PRD_EFFORT_LEVELS.join(', ')}`);
352
+ }
353
+ const ref = normalizeExternalRef(body.externalRef);
354
+ if (!ref.ok) return bad(ref.error);
355
+ const rendered = macroLibrary.renderMacroPrompt(macro.prompt, macro.inputs, {
356
+ ...macroLibrary.defaultMacroValues(macro.inputs),
357
+ ...(body.inputs || {}),
358
+ });
359
+ if (!rendered.ok) return bad(rendered.error);
360
+
361
+ if (ref.value !== undefined) {
362
+ await runWithExternalRef({ deps, res, cwd, macro, prompt: rendered.prompt, effort, externalRef: ref.value });
363
+ return;
364
+ }
365
+
366
+ const key = `${cwd}\u0000${id}`;
367
+ const pending = inProgressRuns.get(key);
368
+ if (pending) {
369
+ const first = await pending;
370
+ if (first.ok) {
371
+ sendJson(res, 200, { ok: true, epicId: first.epicId, alreadyRunning: true });
372
+ } else {
373
+ sendJson(res, 503, { ok: false, error: first.error || 'launch failed' });
374
+ }
375
+ return;
376
+ }
377
+ const running = findRunningEpic(cwd, id, deps.isTabBusy || (() => false));
378
+ if (running) {
379
+ sendJson(res, 200, { ok: true, epicId: running, alreadyRunning: true });
380
+ return;
381
+ }
382
+
383
+ const payload = {
384
+ cwd,
385
+ agentName: macro.agentName,
386
+ tag: macro.tag,
387
+ title: macro.label,
388
+ prompt: rendered.prompt,
389
+ macroId: macro.id,
390
+ via: 'script',
391
+ ...(effort !== undefined ? { effort } : {}),
392
+ };
393
+ const launch = (async () => {
394
+ try {
395
+ return await deps.startExternalNewSession(payload);
396
+ } catch (e) {
397
+ return { ok: false, reason: 'launch-failed', error: e?.message ?? 'launch failed' };
398
+ }
399
+ })();
400
+ inProgressRuns.set(key, launch);
401
+ let result;
402
+ try {
403
+ result = await launch;
404
+ if (result && result.ok) recentRuns.set(key, { epicId: result.epicId, at: Date.now() });
405
+ } finally {
406
+ inProgressRuns.delete(key);
407
+ }
408
+ if (!result || !result.ok) {
409
+ const error = result?.reason === 'timeout'
410
+ ? 'timed out waiting for the window; the session may still start, check the Sessions queue before retrying'
411
+ : result?.error || 'launch failed';
412
+ sendJson(res, 503, { ok: false, error });
413
+ return;
414
+ }
415
+ appendAuditEvent('admin_macro_run', {
416
+ route: '/admin/macros/run',
417
+ cwd,
418
+ macroId: macro.id,
419
+ epicId: result.epicId,
420
+ alreadyRunning: false,
421
+ });
422
+ sendJson(res, 200, { ok: true, epicId: result.epicId, alreadyRunning: false });
423
+ };
424
+ }
425
+
426
+ /** 503 error text for a failed startExternalNewSession result. */
427
+ function launchFailureError(result) {
428
+ return result?.reason === 'timeout'
429
+ ? 'timed out waiting for the window; the session may still start, check the Sessions queue before retrying'
430
+ : result?.error || 'launch failed';
431
+ }
432
+
433
+ /**
434
+ * The externalRef branch of /admin/macros/run. The lookup, launch and record
435
+ * run inside withExternalRefLock, so concurrent calls with the same
436
+ * (cwd, externalRef) share one launch. The macro-wide findRunningEpic shortcut
437
+ * is skipped: a new ref is a new run even while another run is busy.
438
+ */
439
+ async function runWithExternalRef({ deps, res, cwd, macro, prompt, effort, externalRef }) {
440
+ const isTabBusy = deps.isTabBusy || (() => false);
441
+ const existingAnswer = (epicId) => sendJson(res, 200, {
442
+ ok: true, epicId, existing: true, alreadyRunning: !!isTabBusy(epicId), externalRef,
443
+ });
444
+ await withExternalRefLock({ cwd, externalRef }, async () => {
445
+ const key = `${cwd}\u0000${macro.id}\u0000${externalRef}`;
446
+ const pending = inProgressRuns.get(key);
447
+ if (pending) {
448
+ const first = await pending;
449
+ if (first.ok) existingAnswer(first.epicId);
450
+ else sendJson(res, 503, { ok: false, error: first.error || 'launch failed' });
451
+ return;
452
+ }
453
+ const found = await findEpicByExternalRef({ cwd, externalRef });
454
+ if (found) {
455
+ if (found.producer !== 'new-epic-ui' || found.macroId !== macro.id) {
456
+ sendJson(res, 409, {
457
+ ok: false,
458
+ error: `externalRef ${externalRef} already names Epic ${found.epicId}, started by ${found.producer || 'an unknown producer'}${found.macroId ? ` for macro ${found.macroId}` : ''}, not by macro ${macro.id}`,
459
+ epicId: found.epicId,
460
+ externalRef,
461
+ });
462
+ return;
463
+ }
464
+ existingAnswer(found.epicId);
465
+ return;
466
+ }
467
+ const recent = recentRuns.get(key);
468
+ if (recent && Date.now() - recent.at < RECENT_START_MS) {
469
+ existingAnswer(recent.epicId);
470
+ return;
471
+ } else if (recent) {
472
+ recentRuns.delete(key);
473
+ }
474
+
475
+ const payload = {
476
+ cwd,
477
+ agentName: macro.agentName,
478
+ tag: macro.tag,
479
+ title: macro.label,
480
+ prompt,
481
+ macroId: macro.id,
482
+ via: 'script',
483
+ externalRef,
484
+ ...(effort !== undefined ? { effort } : {}),
485
+ };
486
+ const launch = (async () => {
487
+ try {
488
+ return await deps.startExternalNewSession(payload);
489
+ } catch (e) {
490
+ return { ok: false, reason: 'launch-failed', error: e?.message ?? 'launch failed' };
491
+ }
492
+ })();
493
+ inProgressRuns.set(key, launch);
494
+ let result;
495
+ try {
496
+ result = await launch;
497
+ if (result && result.ok) recentRuns.set(key, { epicId: result.epicId, at: Date.now() });
498
+ } finally {
499
+ inProgressRuns.delete(key);
500
+ }
501
+ if (!result || !result.ok) {
502
+ sendJson(res, 503, { ok: false, error: launchFailureError(result) });
503
+ return;
504
+ }
505
+ // The session already started; a failed write is retried once, then
506
+ // reported as externalRefRecorded: false (the open-session scan in
507
+ // findEpicByExternalRef still finds it while it is open).
508
+ // Required lazily: crossProjectFeedback.cjs is a heavy module this file
509
+ // otherwise never loads.
510
+ const { recordExternalRefWithRetry } = require('./crossProjectFeedback.cjs');
511
+ const recorded = await recordExternalRefWithRetry(
512
+ deps.recordExternalRef || recordExternalRef,
513
+ { cwd, externalRef, epicId: result.epicId, producer: 'new-epic-ui', macroId: macro.id },
514
+ '[macroAdminRoutes]',
515
+ );
516
+ appendAuditEvent('admin_macro_run', {
517
+ route: '/admin/macros/run',
518
+ cwd,
519
+ macroId: macro.id,
520
+ epicId: result.epicId,
521
+ alreadyRunning: false,
522
+ externalRef,
523
+ });
524
+ sendJson(res, 200, {
525
+ ok: true, epicId: result.epicId, alreadyRunning: false, externalRef,
526
+ ...(recorded ? {} : { externalRefRecorded: false }),
527
+ });
528
+ });
529
+ }
530
+
531
+ /**
532
+ * @param {{ onChanged?: () => void, startExternalNewSession?: (p: object) => Promise<any>,
533
+ * isTabBusy?: (tabId: string) => boolean, listPersonas?: () => Promise<Array<{name: string}>> }} deps
534
+ */
535
+ function registerAdminRoute(adminHttp, deps = {}, opts = {}) {
536
+ const { onChanged } = deps;
254
537
  const libOpts = opts.filePath ? { filePath: opts.filePath } : undefined;
255
538
  adminHttp.registerRoute('GET', '/admin/macros', listHandler(onChanged, libOpts));
256
539
  adminHttp.registerRoute('POST', '/admin/macros/save', saveHandler(onChanged, libOpts));
257
540
  adminHttp.registerRoute('POST', '/admin/macros/delete', deleteHandler(onChanged, libOpts));
541
+ if (typeof deps.startExternalNewSession === 'function') {
542
+ adminHttp.registerRoute('POST', '/admin/macros/run', runHandler(deps, libOpts));
543
+ }
258
544
  }
259
545
 
260
546
  module.exports = {
@@ -0,0 +1,133 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * needsYouAdminRoutes.cjs — loopback admin HTTP routes so an outside app on
5
+ * this machine can put a "Needs you" item in front of the owner, take it back,
6
+ * and list its items, through needsYouStore.cjs:
7
+ * POST /admin/needs-you {app, id, title, why?, link?, options?, externalRef?}
8
+ * -> 200 { ok, item, created, changed } | 400 | 429 (item limit)
9
+ * POST /admin/needs-you/withdraw {app, id} -> 200 { ok, item } | 404 { ok:false, error:'not found' }
10
+ * GET /admin/needs-you?app=&status= -> 200 { ok, items }
11
+ *
12
+ * A post the store reports as `changed` (decided inside its write queue)
13
+ * appends one `needs_you_posted` audit row and calls deps.onChanged once; a
14
+ * post that changed nothing (an identical re-post, or an item already
15
+ * answered/withdrawn) writes no row and does not call it. A withdrawal
16
+ * appends `needs_you_withdrawn` and calls onChanged once.
17
+ * Answering is the human's, in the app — no route here.
18
+ */
19
+
20
+ const { readBody, sendJson } = require('./localAdminHttp.cjs');
21
+ const needsYouStore = require('./needsYouStore.cjs');
22
+ const { appendAuditEvent } = require('../telemetry/auditLog.cjs');
23
+
24
+ const STATUSES = ['open', 'answered', 'withdrawn'];
25
+
26
+ /** Read + parse a JSON object body; on failure sends the 400 and returns null. */
27
+ async function readJsonBody(req, res) {
28
+ let raw;
29
+ try {
30
+ raw = await readBody(req);
31
+ } catch (e) {
32
+ sendJson(res, 400, { ok: false, error: `request body rejected: ${e?.message ?? 'unreadable'}` });
33
+ return null;
34
+ }
35
+ let body;
36
+ try {
37
+ body = raw ? JSON.parse(raw) : {};
38
+ } catch {
39
+ sendJson(res, 400, { ok: false, error: 'invalid JSON body' });
40
+ return null;
41
+ }
42
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) {
43
+ sendJson(res, 400, { ok: false, error: 'invalid JSON body' });
44
+ return null;
45
+ }
46
+ return body;
47
+ }
48
+
49
+ function firstIssue(e, fallback) {
50
+ return e?.issues?.[0]?.message ?? e?.message ?? fallback;
51
+ }
52
+
53
+ function postHandler(onChanged) {
54
+ return async (req, res) => {
55
+ const body = await readJsonBody(req, res);
56
+ if (!body) return;
57
+ let result;
58
+ try {
59
+ result = await needsYouStore.postNeedsYou(body);
60
+ } catch (e) {
61
+ if (e?.code === 'NEEDS_YOU_LIMIT') {
62
+ sendJson(res, 429, { ok: false, error: e.message });
63
+ return;
64
+ }
65
+ if (Array.isArray(e?.issues)) {
66
+ sendJson(res, 400, { ok: false, error: firstIssue(e, 'invalid payload') });
67
+ return;
68
+ }
69
+ sendJson(res, 500, { ok: false, error: e?.message ?? 'post failed' });
70
+ return;
71
+ }
72
+ const { item, created, changed } = result;
73
+ if (changed) {
74
+ appendAuditEvent('needs_you_posted', {
75
+ route: '/admin/needs-you',
76
+ app: item.app,
77
+ id: item.id,
78
+ externalRef: item.externalRef,
79
+ created,
80
+ });
81
+ if (onChanged) onChanged();
82
+ }
83
+ sendJson(res, 200, { ok: true, item, created, changed });
84
+ };
85
+ }
86
+
87
+ function withdrawHandler(onChanged) {
88
+ return async (req, res) => {
89
+ const body = await readJsonBody(req, res);
90
+ if (!body) return;
91
+ let item;
92
+ try {
93
+ item = await needsYouStore.withdrawNeedsYou({ app: body.app, id: body.id });
94
+ } catch (e) {
95
+ if (Array.isArray(e?.issues)) {
96
+ sendJson(res, 400, { ok: false, error: firstIssue(e, 'invalid payload') });
97
+ return;
98
+ }
99
+ sendJson(res, 500, { ok: false, error: e?.message ?? 'withdraw failed' });
100
+ return;
101
+ }
102
+ if (!item) {
103
+ sendJson(res, 404, { ok: false, error: 'not found' });
104
+ return;
105
+ }
106
+ appendAuditEvent('needs_you_withdrawn', { route: '/admin/needs-you/withdraw', app: item.app, id: item.id });
107
+ if (onChanged) onChanged();
108
+ sendJson(res, 200, { ok: true, item });
109
+ };
110
+ }
111
+
112
+ function listHandler() {
113
+ return async (_req, res, query) => {
114
+ const app = query.get('app') || undefined;
115
+ const status = query.get('status') || undefined;
116
+ if (status !== undefined && !STATUSES.includes(status)) {
117
+ sendJson(res, 400, { ok: false, error: `status must be one of ${STATUSES.join(', ')}` });
118
+ return;
119
+ }
120
+ const items = await needsYouStore.listNeedsYou({ app, status });
121
+ sendJson(res, 200, { ok: true, items });
122
+ };
123
+ }
124
+
125
+ /** @param {{ onChanged?: () => void }} deps */
126
+ function registerAdminRoute(adminHttp, deps = {}) {
127
+ const { onChanged } = deps;
128
+ adminHttp.registerRoute('GET', '/admin/needs-you', listHandler());
129
+ adminHttp.registerRoute('POST', '/admin/needs-you', postHandler(onChanged));
130
+ adminHttp.registerRoute('POST', '/admin/needs-you/withdraw', withdrawHandler(onChanged));
131
+ }
132
+
133
+ module.exports = { registerAdminRoute };
@@ -0,0 +1,50 @@
1
+ // @ts-check
2
+ 'use strict';
3
+
4
+ /**
5
+ * needsYouIpc.cjs — renderer-facing IPC for the Dashboard's "Needs you" list,
6
+ * over needsYouStore.cjs:
7
+ * needsYou:list (no payload) -> { ok: true, items } (open items only)
8
+ * needsYou:answer { app, id, answer } -> { ok: true, item } | { ok: false, error }
9
+ *
10
+ * A successful answer appends one `needs_you_answered` audit row (app, id,
11
+ * answer, and the item's externalRef when it has one) so the outside app that
12
+ * posted the item can read the decision, then calls onChanged once. When the
13
+ * store refuses (no open item, or the answer is not one of its options) the
14
+ * handler returns an error in words and writes nothing.
15
+ */
16
+
17
+ const needsYouStore = require('./needsYouStore.cjs');
18
+ const { appendAuditEvent } = require('../telemetry/auditLog.cjs');
19
+
20
+ /**
21
+ * @param {{ ipcMain?: any, onChanged?: () => void }} [deps]
22
+ */
23
+ function registerNeedsYouIpc(deps = {}) {
24
+ const ipcMain = deps.ipcMain || require('electron').ipcMain;
25
+ const { onChanged } = deps;
26
+ const { schemas: s, validated: v } = require('../../ipcSchemas.cjs');
27
+
28
+ ipcMain.handle('needsYou:list', v(s.needsYouList, async () => {
29
+ const items = await needsYouStore.listNeedsYou({ status: 'open' });
30
+ return { ok: true, items };
31
+ }));
32
+
33
+ ipcMain.handle('needsYou:answer', v(s.needsYouAnswer, async ({ app, id, answer }) => {
34
+ const item = await needsYouStore.answerNeedsYou({ app, id, answer });
35
+ if (!item) {
36
+ return {
37
+ ok: false,
38
+ error: `There is no open question "${id}" from ${app} with the option "${answer}". It may already be answered or withdrawn.`,
39
+ };
40
+ }
41
+ /** @type {Record<string, unknown>} */
42
+ const row = { app: item.app, id: item.id, answer: item.answer };
43
+ if (item.externalRef) row.externalRef = item.externalRef;
44
+ appendAuditEvent('needs_you_answered', row);
45
+ if (onChanged) onChanged();
46
+ return { ok: true, item };
47
+ }));
48
+ }
49
+
50
+ module.exports = { registerNeedsYouIpc };