claude-code-session-manager 0.138.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.
- package/.claude-plugin/marketplace.json +1 -1
- package/README.md +339 -82
- package/dist/assets/{AppSettings-CgDhqrsU.js → AppSettings-CUfWY9vN.js} +2 -2
- package/dist/assets/History-DDnqaLyw.js +2 -0
- package/dist/assets/HomeClaudeConfig-CGD2Onjv.js +3 -0
- package/dist/assets/{Panel-CeDiyuNn.js → Panel-Csyd9HbD.js} +1 -1
- package/dist/assets/ProjectClaudeConfig-C-jlYpC_.js +26 -0
- package/dist/assets/{Scheduler-CkhTvG7C.js → Scheduler-NLs08fx7.js} +9 -9
- package/dist/assets/{SkillReferenceGraph-CFMK8NJh.js → SkillReferenceGraph-DcscPXAG.js} +1 -1
- package/dist/assets/Skills-BpGRKOcY.js +67 -0
- package/dist/assets/{TiptapBody-D1kTj-tn.js → TiptapBody-DSU3769X.js} +60 -54
- package/dist/assets/ViewTabs-C0PRZx4_.js +1 -0
- package/dist/assets/{VoiceButton-CZeyPM31.js → VoiceButton-D2rMurNg.js} +1 -1
- package/dist/assets/{historyTotals-B00l64Jw.js → historyTotals-TcIQs2sh.js} +1 -1
- package/dist/assets/{index-62tyjEQB.css → index-BCySPdtU.css} +1 -1
- package/dist/assets/{index-CgCxpunJ.js → index-C-d0DCre.js} +523 -515
- package/dist/index.html +2 -2
- package/dist-web/app.css +1 -1
- package/dist-web/app.js +469 -450
- package/package.json +13 -5
- package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
- package/plugins/session-manager-dev/skills/builder/SKILL.md +12 -4
- package/plugins/session-manager-dev/skills/builder/scripts/publish-preflight.cjs +255 -0
- package/plugins/session-manager-dev/skills/develop/SKILL.md +12 -5
- package/scripts/README.md +1 -0
- package/scripts/scheduler-mcp-server.cjs +161 -18
- package/src/main/build-info.json +4 -4
- package/src/main/chatRunner.cjs +2 -2
- package/src/main/exchanges.cjs +70 -5
- package/src/main/historyAggregator.cjs +84 -58
- package/src/main/historyDashboard.cjs +18 -13
- package/src/main/index.cjs +22 -2
- package/src/main/ipcSchemas.cjs +122 -5
- package/src/main/lib/claude/effectiveModelInfo.cjs +2 -2
- package/src/main/lib/claude/modelPricing.cjs +148 -0
- package/src/main/lib/epic/epicAdminRoutes.cjs +101 -0
- package/src/main/lib/epic/epicJobReceipt.cjs +87 -0
- package/src/main/lib/epic/epicOutsideRead.cjs +306 -0
- package/src/main/lib/epic/epicOutsideState.cjs +233 -0
- package/src/main/lib/epic/epicSettle.cjs +1 -1
- package/src/main/lib/epic/epicStateWatcher.cjs +157 -0
- package/src/main/lib/epic/externalRef.cjs +37 -0
- package/src/main/lib/epic/externalRefIndex.cjs +136 -0
- package/src/main/lib/epic/restorableSessions.cjs +151 -17
- package/src/main/lib/epic/transcriptUsage.cjs +197 -0
- package/src/main/lib/externalContract.cjs +111 -0
- package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +121 -4
- package/src/main/lib/feedback-remote/crossProjectReply.cjs +83 -1
- package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -6
- package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +50 -8
- package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +218 -4
- package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +19 -3
- package/src/main/lib/feedback-remote/feedbackImages.cjs +171 -0
- package/src/main/lib/feedback-remote/localAdminHttp.cjs +11 -10
- package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +120 -2
- package/src/main/lib/feedback-remote/needsYouAdminRoutes.cjs +133 -0
- package/src/main/lib/feedback-remote/needsYouIpc.cjs +50 -0
- package/src/main/lib/feedback-remote/needsYouStore.cjs +281 -0
- package/src/main/lib/historyRollup.cjs +32 -5
- package/src/main/lib/mcpToolCatalog.cjs +111 -14
- package/src/main/lib/persona-macro/agentAdminRoutes.cjs +121 -0
- package/src/main/lib/promptSessionSchema.cjs +4 -0
- package/src/main/lib/remoteTranscriptTail.cjs +32 -1
- package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
- package/src/main/lib/telemetry/auditEvents.cjs +176 -0
- package/src/main/lib/telemetry/eventsAdminRoutes.cjs +45 -0
- package/src/main/loopEfficiencyHandlers.cjs +1 -1
- package/src/main/scheduler.cjs +29 -0
- package/src/main/templates/PRD_AUTHORING.md +1 -0
- package/src/main/transcripts.cjs +62 -7
- package/src/main/webRemote.cjs +122 -18
- package/src/preload/api.d.ts +71 -8
- package/src/preload/apiSurface.cjs +7 -0
- package/src/preload/apiSurface.json +408 -83
- package/src/preload/index.cjs +15 -3
- package/dist/assets/AgentLibrary-C1d_D7uQ.js +0 -2
- package/dist/assets/Button-Bk23rEnZ.js +0 -1
- package/dist/assets/DocumentEditorPane-BqY5Nq6W.js +0 -1
- package/dist/assets/Extensions-CXem-uwI.js +0 -2
- package/dist/assets/History-BwO3coo4.js +0 -2
- package/dist/assets/Library-BDV69fSe.js +0 -32
- package/dist/assets/ListDetail-CD-Fm6mh.js +0 -1
- package/dist/assets/ProjectClaudeConfig-NjdKdwe8.js +0 -25
- package/dist/assets/ProvenanceBadge-Bu8NmI_R.js +0 -1
- package/dist/assets/Settings-COT34hBF.js +0 -2
- package/dist/assets/Skills-BgexoUkQ.js +0 -29
- package/dist/assets/SourceChip-BXjcdeb1.js +0 -1
- package/dist/assets/SystemPrompt-CeeH3EeW.js +0 -1
- package/dist/assets/Toggle-CENi19iK.js +0 -1
- package/dist/assets/ViewTabs-DDBb0x96.js +0 -1
- package/dist/assets/claude-settings-schema-COigsajx.js +0 -3
|
@@ -33,8 +33,8 @@
|
|
|
33
33
|
* `onChanged()` exactly once so the Sessions HOT KEYS strip updates live,
|
|
34
34
|
* matching the IPC handlers in index.cjs.
|
|
35
35
|
*
|
|
36
|
-
* POST /admin/macros/run {cwd, id, inputs?, effort?}
|
|
37
|
-
* -> { ok, epicId, alreadyRunning }
|
|
36
|
+
* POST /admin/macros/run {cwd, id, inputs?, effort?, externalRef?}
|
|
37
|
+
* -> { ok, epicId, alreadyRunning, externalRef? }
|
|
38
38
|
* Starts a saved macro from a script (e.g. a systemd timer) through the
|
|
39
39
|
* renderer's press path (deps.startExternalNewSession: same persona, tag, AIM
|
|
40
40
|
* prompt and source.macroId, so autoStartTargets apply). Refused (400, no
|
|
@@ -43,6 +43,10 @@
|
|
|
43
43
|
* = the macro's defaults overlaid by `inputs`. While that macro's Epic is
|
|
44
44
|
* still running in the cwd it returns that Epic (alreadyRunning:true) instead
|
|
45
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).
|
|
46
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>"}'
|
|
47
51
|
*/
|
|
48
52
|
'use strict';
|
|
@@ -54,6 +58,8 @@ const { appendAuditEvent } = require('../telemetry/auditLog.cjs');
|
|
|
54
58
|
const { findHumanPromptContaining } = require('./humanPromptLedger.cjs');
|
|
55
59
|
const { readActiveIndex } = require('../epic/epicMint.cjs');
|
|
56
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');
|
|
57
63
|
|
|
58
64
|
const EVERY_PROJECT_RE = /(^|[^a-z0-9])(every|all|each)\s+(of\s+)?(my\s+|the\s+|our\s+)?projects?($|[^a-z0-9])/;
|
|
59
65
|
|
|
@@ -344,12 +350,19 @@ function runHandler(deps, libOpts) {
|
|
|
344
350
|
if (effort !== undefined && !PRD_EFFORT_LEVELS.includes(effort)) {
|
|
345
351
|
return bad(`effort must be one of: ${PRD_EFFORT_LEVELS.join(', ')}`);
|
|
346
352
|
}
|
|
353
|
+
const ref = normalizeExternalRef(body.externalRef);
|
|
354
|
+
if (!ref.ok) return bad(ref.error);
|
|
347
355
|
const rendered = macroLibrary.renderMacroPrompt(macro.prompt, macro.inputs, {
|
|
348
356
|
...macroLibrary.defaultMacroValues(macro.inputs),
|
|
349
357
|
...(body.inputs || {}),
|
|
350
358
|
});
|
|
351
359
|
if (!rendered.ok) return bad(rendered.error);
|
|
352
360
|
|
|
361
|
+
if (ref.value !== undefined) {
|
|
362
|
+
await runWithExternalRef({ deps, res, cwd, macro, prompt: rendered.prompt, effort, externalRef: ref.value });
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
|
|
353
366
|
const key = `${cwd}\u0000${id}`;
|
|
354
367
|
const pending = inProgressRuns.get(key);
|
|
355
368
|
if (pending) {
|
|
@@ -410,6 +423,111 @@ function runHandler(deps, libOpts) {
|
|
|
410
423
|
};
|
|
411
424
|
}
|
|
412
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
|
+
|
|
413
531
|
/**
|
|
414
532
|
* @param {{ onChanged?: () => void, startExternalNewSession?: (p: object) => Promise<any>,
|
|
415
533
|
* isTabBusy?: (tabId: string) => boolean, listPersonas?: () => Promise<Array<{name: string}>> }} deps
|
|
@@ -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 };
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* needsYouStore.cjs — machine-level store of "Needs you" items: questions an
|
|
5
|
+
* outside app on this machine needs the owner to decide, so they can show in
|
|
6
|
+
* the Dashboard's Needs you list instead of one inbox per app.
|
|
7
|
+
*
|
|
8
|
+
* File: schedulerHome()/needs-you.json = { version: 1, items }.
|
|
9
|
+
* Writes are atomic (writeJsonAtomic) and serialized through one queue.
|
|
10
|
+
* A missing or corrupt file reads as empty; a corrupt file is set aside as
|
|
11
|
+
* `needs-you.json.corrupt-<ms>` at the next write. Answered or withdrawn items
|
|
12
|
+
* older than 14 days are dropped at the next write.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const fsp = require('node:fs/promises');
|
|
16
|
+
const { z } = require('zod');
|
|
17
|
+
const { writeJsonAtomic } = require('../util/atomicFs.cjs');
|
|
18
|
+
const { needsYouPath } = require('../scheduler/schedulerPaths.cjs');
|
|
19
|
+
const { normalizeExternalRef } = require('../epic/externalRef.cjs');
|
|
20
|
+
|
|
21
|
+
const STORE_VERSION = 1;
|
|
22
|
+
const MAX_OPEN_PER_APP = 10;
|
|
23
|
+
const MAX_OPEN_TOTAL = 50;
|
|
24
|
+
const RETENTION_MS = 14 * 24 * 60 * 60 * 1000;
|
|
25
|
+
const STATUSES = /** @type {const} */ (['open', 'answered', 'withdrawn']);
|
|
26
|
+
|
|
27
|
+
const AppSchema = z.string().regex(/^[A-Za-z0-9._-]{1,40}$/, 'app must be 1 to 40 letters, digits, . _ or -');
|
|
28
|
+
|
|
29
|
+
/** Runs a value through normalizeExternalRef; `required` refuses absent values. */
|
|
30
|
+
function refSchema(label, required) {
|
|
31
|
+
return z.unknown().transform((v, ctx) => {
|
|
32
|
+
if (required && (v === undefined || v === null)) {
|
|
33
|
+
ctx.addIssue({ code: z.ZodIssueCode.custom, message: `${label} is required.` });
|
|
34
|
+
return z.NEVER;
|
|
35
|
+
}
|
|
36
|
+
const r = normalizeExternalRef(v);
|
|
37
|
+
if (!r.ok) {
|
|
38
|
+
ctx.addIssue({ code: z.ZodIssueCode.custom, message: r.error.replace(/^externalRef/, label) });
|
|
39
|
+
return z.NEVER;
|
|
40
|
+
}
|
|
41
|
+
return r.value;
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const TitleSchema = z.string().min(1).max(200).refine((s) => !/[\r\n]/.test(s), 'title must be one line');
|
|
46
|
+
const WhySchema = z.string().max(1000);
|
|
47
|
+
const LinkSchema = z.string().max(2000).regex(/^https?:\/\//, 'link must start with http:// or https://');
|
|
48
|
+
const OptionsSchema = z.array(z.string().min(1).max(80)).min(2).max(5)
|
|
49
|
+
.refine((opts) => new Set(opts).size === opts.length, 'options must be distinct');
|
|
50
|
+
|
|
51
|
+
const NeedsYouPostSchema = z.object({
|
|
52
|
+
app: AppSchema,
|
|
53
|
+
id: refSchema('id', true),
|
|
54
|
+
title: TitleSchema,
|
|
55
|
+
why: WhySchema.optional(),
|
|
56
|
+
link: LinkSchema.optional(),
|
|
57
|
+
options: OptionsSchema.optional(),
|
|
58
|
+
externalRef: refSchema('externalRef', false),
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
const KeySchema = z.object({ app: AppSchema, id: refSchema('id', true) });
|
|
62
|
+
|
|
63
|
+
const StoredItemSchema = z.object({
|
|
64
|
+
app: AppSchema,
|
|
65
|
+
id: z.string().min(1),
|
|
66
|
+
title: TitleSchema,
|
|
67
|
+
why: z.string(),
|
|
68
|
+
link: LinkSchema.nullable(),
|
|
69
|
+
options: OptionsSchema.nullable(),
|
|
70
|
+
externalRef: z.string().nullable(),
|
|
71
|
+
status: z.enum(STATUSES),
|
|
72
|
+
answer: z.string().nullable(),
|
|
73
|
+
createdAt: z.string(),
|
|
74
|
+
updatedAt: z.string(),
|
|
75
|
+
answeredAt: z.string().nullable(),
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
/** @typedef {z.infer<typeof StoredItemSchema>} NeedsYouItem */
|
|
79
|
+
|
|
80
|
+
// --- serialized writes ------------------------------------------------------
|
|
81
|
+
|
|
82
|
+
let writeChain = Promise.resolve();
|
|
83
|
+
/** @template T @param {() => Promise<T>} fn @returns {Promise<T>} */
|
|
84
|
+
function serialize(fn) {
|
|
85
|
+
const run = writeChain.then(fn, fn);
|
|
86
|
+
writeChain = run.then(() => undefined, () => undefined);
|
|
87
|
+
return run;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// --- read / write -----------------------------------------------------------
|
|
91
|
+
|
|
92
|
+
/** Returns { state: 'missing'|'corrupt'|'unreadable'|'ok', items }. Never throws. */
|
|
93
|
+
async function readStore(filePath) {
|
|
94
|
+
let text;
|
|
95
|
+
try {
|
|
96
|
+
text = await fsp.readFile(filePath, 'utf8');
|
|
97
|
+
} catch (err) {
|
|
98
|
+
if (err && err.code === 'ENOENT') return { state: 'missing', items: [] };
|
|
99
|
+
console.warn(`[needsYouStore] cannot read ${filePath}:`, err && err.message);
|
|
100
|
+
return { state: 'unreadable', items: [] };
|
|
101
|
+
}
|
|
102
|
+
let raw;
|
|
103
|
+
try {
|
|
104
|
+
raw = JSON.parse(text);
|
|
105
|
+
} catch {
|
|
106
|
+
return { state: 'corrupt', items: [] };
|
|
107
|
+
}
|
|
108
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return { state: 'corrupt', items: [] };
|
|
109
|
+
const list = Array.isArray(raw.items) ? raw.items : [];
|
|
110
|
+
const items = [];
|
|
111
|
+
const seen = new Set();
|
|
112
|
+
let dropped = 0;
|
|
113
|
+
for (const entry of list) {
|
|
114
|
+
const r = StoredItemSchema.safeParse(entry);
|
|
115
|
+
const key = r.success ? `${r.data.app}\u0000${r.data.id}` : '';
|
|
116
|
+
if (r.success && !seen.has(key)) {
|
|
117
|
+
seen.add(key);
|
|
118
|
+
items.push(r.data);
|
|
119
|
+
} else {
|
|
120
|
+
dropped++;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (dropped > 0) console.warn(`[needsYouStore] dropped ${dropped} invalid item(s) from ${filePath}`);
|
|
124
|
+
return { state: 'ok', items };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Load for a write. MUST run inside serialize. Sets a corrupt file aside. */
|
|
128
|
+
async function loadForWrite(filePath) {
|
|
129
|
+
const cur = await readStore(filePath);
|
|
130
|
+
if (cur.state === 'unreadable') throw new Error(`needs-you store is unreadable: ${filePath}`);
|
|
131
|
+
if (cur.state === 'corrupt') {
|
|
132
|
+
const quarantine = `${filePath}.corrupt-${Date.now()}`;
|
|
133
|
+
await fsp.rename(filePath, quarantine);
|
|
134
|
+
console.warn(`[needsYouStore] ${filePath} is unparseable; preserved as ${quarantine}`);
|
|
135
|
+
}
|
|
136
|
+
return cur.items;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function prune(items, nowMs) {
|
|
140
|
+
return items.filter((it) => {
|
|
141
|
+
if (it.status === 'open') return true;
|
|
142
|
+
const closedAt = Date.parse(it.answeredAt || it.updatedAt);
|
|
143
|
+
return !(Number.isFinite(closedAt) && nowMs - closedAt > RETENTION_MS);
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function writeStore(filePath, items) {
|
|
148
|
+
await writeJsonAtomic(filePath, { version: STORE_VERSION, items: prune(items, Date.now()) });
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function limitError(message) {
|
|
152
|
+
const err = /** @type {Error & { code: string }} */ (new Error(message));
|
|
153
|
+
err.code = 'NEEDS_YOU_LIMIT';
|
|
154
|
+
return err;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// --- public API ---------------------------------------------------------------
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* @param {{ app?: string, status?: string }} [filter]
|
|
161
|
+
* @returns {Promise<NeedsYouItem[]>}
|
|
162
|
+
*/
|
|
163
|
+
async function listNeedsYou(filter = {}) {
|
|
164
|
+
const { app, status } = filter || {};
|
|
165
|
+
const { items } = await readStore(needsYouPath());
|
|
166
|
+
return items.filter((it) => (app === undefined || it.app === app) && (status === undefined || it.status === status));
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** The caller fields a post may set on an open item. */
|
|
170
|
+
function callerKey(item) {
|
|
171
|
+
return JSON.stringify([item.title, item.why, item.link, item.options, item.externalRef]);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Create an open item, or replace title/why/link/options/externalRef of an
|
|
176
|
+
* existing open item with the same app + id (a left-out field is cleared).
|
|
177
|
+
* A closed item is returned unchanged. `changed` is decided inside the write
|
|
178
|
+
* queue: true on create or when a stored field differs; an identical re-post
|
|
179
|
+
* writes nothing and keeps updatedAt.
|
|
180
|
+
* @param {unknown} input
|
|
181
|
+
* @returns {Promise<{ item: NeedsYouItem, created: boolean, changed: boolean }>}
|
|
182
|
+
*/
|
|
183
|
+
async function postNeedsYou(input) {
|
|
184
|
+
const data = NeedsYouPostSchema.parse(input);
|
|
185
|
+
const filePath = needsYouPath();
|
|
186
|
+
return serialize(async () => {
|
|
187
|
+
const items = await loadForWrite(filePath);
|
|
188
|
+
const now = new Date().toISOString();
|
|
189
|
+
const existing = items.find((it) => it.app === data.app && it.id === data.id);
|
|
190
|
+
if (existing) {
|
|
191
|
+
if (existing.status !== 'open') return { item: existing, created: false, changed: false };
|
|
192
|
+
const before = callerKey(existing);
|
|
193
|
+
existing.title = data.title;
|
|
194
|
+
existing.why = data.why ?? '';
|
|
195
|
+
existing.link = data.link ?? null;
|
|
196
|
+
existing.options = data.options ?? null;
|
|
197
|
+
existing.externalRef = data.externalRef ?? null;
|
|
198
|
+
if (callerKey(existing) === before) return { item: existing, created: false, changed: false };
|
|
199
|
+
existing.updatedAt = now;
|
|
200
|
+
await writeStore(filePath, items);
|
|
201
|
+
return { item: existing, created: false, changed: true };
|
|
202
|
+
}
|
|
203
|
+
const open = items.filter((it) => it.status === 'open');
|
|
204
|
+
if (open.filter((it) => it.app === data.app).length >= MAX_OPEN_PER_APP) {
|
|
205
|
+
throw limitError(`${data.app} already has ${MAX_OPEN_PER_APP} open Needs you items.`);
|
|
206
|
+
}
|
|
207
|
+
if (open.length >= MAX_OPEN_TOTAL) {
|
|
208
|
+
throw limitError(`There are already ${MAX_OPEN_TOTAL} open Needs you items.`);
|
|
209
|
+
}
|
|
210
|
+
/** @type {NeedsYouItem} */
|
|
211
|
+
const item = {
|
|
212
|
+
app: data.app,
|
|
213
|
+
id: /** @type {string} */ (data.id),
|
|
214
|
+
title: data.title,
|
|
215
|
+
why: data.why ?? '',
|
|
216
|
+
link: data.link ?? null,
|
|
217
|
+
options: data.options ?? null,
|
|
218
|
+
externalRef: data.externalRef ?? null,
|
|
219
|
+
status: 'open',
|
|
220
|
+
answer: null,
|
|
221
|
+
createdAt: now,
|
|
222
|
+
updatedAt: now,
|
|
223
|
+
answeredAt: null,
|
|
224
|
+
};
|
|
225
|
+
items.push(item);
|
|
226
|
+
await writeStore(filePath, items);
|
|
227
|
+
return { item, created: true, changed: true };
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Apply `mutate` to the open item app+id; returns it, or null when none / mutate refuses. */
|
|
232
|
+
async function updateOpen(app, id, mutate) {
|
|
233
|
+
const key = KeySchema.parse({ app, id });
|
|
234
|
+
const filePath = needsYouPath();
|
|
235
|
+
return serialize(async () => {
|
|
236
|
+
const items = await loadForWrite(filePath);
|
|
237
|
+
const item = items.find((it) => it.app === key.app && it.id === key.id);
|
|
238
|
+
if (!item || item.status !== 'open') return null;
|
|
239
|
+
const now = new Date().toISOString();
|
|
240
|
+
if (!mutate(item, now)) return null;
|
|
241
|
+
item.updatedAt = now;
|
|
242
|
+
await writeStore(filePath, items);
|
|
243
|
+
return item;
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* @param {{ app: string, id: string }} args
|
|
249
|
+
* @returns {Promise<NeedsYouItem | null>}
|
|
250
|
+
*/
|
|
251
|
+
async function withdrawNeedsYou({ app, id }) {
|
|
252
|
+
return updateOpen(app, id, (item) => {
|
|
253
|
+
item.status = 'withdrawn';
|
|
254
|
+
return true;
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* @param {{ app: string, id: string, answer: string }} args
|
|
260
|
+
* @returns {Promise<NeedsYouItem | null>}
|
|
261
|
+
*/
|
|
262
|
+
async function answerNeedsYou({ app, id, answer }) {
|
|
263
|
+
return updateOpen(app, id, (item, now) => {
|
|
264
|
+
if (!item.options || typeof answer !== 'string' || !item.options.includes(answer)) return false;
|
|
265
|
+
item.status = 'answered';
|
|
266
|
+
item.answer = answer;
|
|
267
|
+
item.answeredAt = now;
|
|
268
|
+
return true;
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
module.exports = {
|
|
273
|
+
NeedsYouPostSchema,
|
|
274
|
+
listNeedsYou,
|
|
275
|
+
postNeedsYou,
|
|
276
|
+
withdrawNeedsYou,
|
|
277
|
+
answerNeedsYou,
|
|
278
|
+
MAX_OPEN_PER_APP,
|
|
279
|
+
MAX_OPEN_TOTAL,
|
|
280
|
+
RETENTION_MS,
|
|
281
|
+
};
|