claude-code-session-manager 0.138.0 → 0.140.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 +352 -79
- package/dist/assets/AppSettings-CMFEM68R.js +2 -0
- package/dist/assets/History--JwsFnbn.js +2 -0
- package/dist/assets/HomeClaudeConfig-ijEXs--3.js +3 -0
- package/dist/assets/{Panel-CeDiyuNn.js → Panel-CALyU0pe.js} +1 -1
- package/dist/assets/ProjectClaudeConfig-sdlA-fUb.js +26 -0
- package/dist/assets/Scheduler-YT3j8SUa.js +16 -0
- package/dist/assets/{SkillReferenceGraph-CFMK8NJh.js → SkillReferenceGraph-CxAuwhNN.js} +1 -1
- package/dist/assets/Skills-DtRzghn5.js +67 -0
- package/dist/assets/{TiptapBody-D1kTj-tn.js → TiptapBody-DApeu7x8.js} +60 -54
- package/dist/assets/ViewTabs-B7qLXRAH.js +1 -0
- package/dist/assets/{VoiceButton-CZeyPM31.js → VoiceButton-DtStfv1H.js} +1 -1
- package/dist/assets/{historyTotals-B00l64Jw.js → historyTotals-ydfnwepc.js} +1 -1
- package/dist/assets/index-CtxruO1L.js +3121 -0
- package/dist/assets/{index-62tyjEQB.css → index-DKXdXfka.css} +1 -1
- package/dist/index.html +2 -2
- package/dist-web/app.css +1 -1
- package/dist-web/app.js +467 -451
- package/package.json +17 -6
- package/plugins/AGENTS.md +60 -0
- package/plugins/CLAUDE.md +1 -60
- 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 +36 -22
- package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +5 -4
- package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +4 -2
- package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +16 -12
- package/plugins/session-manager-dev/skills/maintaining-md-network/migrate-to-agents-md.md +15 -0
- package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +50 -2
- package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +10 -10
- package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +117 -112
- package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdDuplicates.cjs +182 -0
- package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdLinks.cjs +340 -0
- package/scripts/README.md +2 -0
- package/scripts/hooks/guard-tool-risk.cjs +91 -0
- package/scripts/hooks/lib/guard-tool-risk-policy.cjs +217 -0
- package/scripts/ops-sweep.cjs +53 -23
- package/scripts/scheduler-mcp-server.cjs +360 -35
- package/src/main/build-info.json +4 -4
- package/src/main/chatRunner.cjs +2 -2
- package/src/main/config.cjs +112 -8
- package/src/main/docEdit.cjs +6 -1
- package/src/main/exchanges.cjs +70 -5
- package/src/main/files.cjs +7 -27
- package/src/main/health.cjs +48 -15
- package/src/main/historyAggregator.cjs +172 -63
- package/src/main/historyDashboard.cjs +87 -17
- package/src/main/index.cjs +78 -4
- package/src/main/ipcSchemas.cjs +233 -20
- package/src/main/lib/AGENTS.md +54 -0
- package/src/main/lib/CLAUDE.md +1 -54
- package/src/main/lib/agent-cli/adapters/codex.cjs +5 -2
- package/src/main/lib/agent-cli/agentCliIpc.cjs +18 -2
- package/src/main/lib/agent-cli/agentCliSessionStore.cjs +1 -0
- package/src/main/lib/agent-cli/agentCliTurn.cjs +20 -2
- package/src/main/lib/agent-cli/geminiContextDefaults.cjs +94 -0
- package/src/main/lib/claude/effectiveModelInfo.cjs +92 -22
- package/src/main/lib/claude/jobSandboxPolicy.cjs +202 -0
- package/src/main/lib/claude/modelPricing.cjs +148 -0
- package/src/main/lib/claude/personaToolScope.cjs +12 -6
- package/src/main/lib/claude/rateLimitDetect.cjs +13 -2
- package/src/main/lib/claude/runClaudeP.cjs +6 -1
- package/src/main/lib/claude/toolRiskIpc.cjs +177 -0
- package/src/main/lib/claude/toolRiskMarks.cjs +373 -0
- package/src/main/lib/demo-video-kit/seedKit.cjs +27 -6
- package/src/main/lib/ephemeralCwd.cjs +37 -2
- package/src/main/lib/epic/delegationReadiness.cjs +42 -9
- package/src/main/lib/epic/epicAdminRoutes.cjs +121 -0
- package/src/main/lib/epic/epicJobReceipt.cjs +87 -0
- package/src/main/lib/epic/epicOutsideRead.cjs +423 -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/epicSweepValidator.cjs +7 -2
- package/src/main/lib/epic/epicValidationHook.cjs +24 -4
- package/src/main/lib/epic/externalRef.cjs +37 -0
- package/src/main/lib/epic/externalRefIndex.cjs +136 -0
- package/src/main/lib/epic/guardSpawnSettings.cjs +57 -1
- package/src/main/lib/epic/restorableSessions.cjs +151 -17
- package/src/main/lib/epic/transcriptUsage.cjs +197 -0
- package/src/main/lib/externalContract.cjs +137 -0
- package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +176 -5
- package/src/main/lib/feedback-remote/crossProjectReply.cjs +186 -9
- 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 +167 -21
- 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 +285 -0
- package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +98 -1
- package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +5 -0
- package/src/main/lib/git/branchSweep.cjs +209 -4
- package/src/main/lib/git/gitWorktree.cjs +41 -5
- package/src/main/lib/guardShims.cjs +1 -1
- package/src/main/lib/historyRollup.cjs +58 -5
- package/src/main/lib/insideHome.cjs +27 -1
- package/src/main/lib/mcpToolCatalog.cjs +232 -25
- package/src/main/lib/mdDocCensus.cjs +59 -78
- package/src/main/lib/mdDocRefs.cjs +71 -93
- package/src/main/lib/mdNetworkScan.cjs +245 -250
- package/src/main/lib/mdReviewRecord.cjs +22 -9
- package/src/main/lib/memoryMdNetwork.cjs +5 -12
- package/src/main/lib/opsOwnership.cjs +18 -2
- package/src/main/lib/opsRetentionSettings.cjs +28 -4
- package/src/main/lib/persona-macro/agentAdminRoutes.cjs +121 -0
- package/src/main/lib/persona-macro/macroJobDispatch.cjs +90 -20
- package/src/main/lib/persona-macro/macroJobIpc.cjs +144 -46
- package/src/main/lib/persona-macro/macroJobStatus.cjs +87 -9
- package/src/main/lib/persona-macro/macroLibrary.cjs +95 -5
- package/src/main/lib/persona-macro/personaImportHealth.cjs +78 -17
- package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +96 -0
- package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
- package/src/main/lib/prd/depSlugResolve.cjs +104 -4
- package/src/main/lib/prd/prdAdminRoutes.cjs +35 -2
- package/src/main/lib/prd/prdCreate.cjs +351 -23
- package/src/main/lib/prd/prdDisposition.cjs +11 -2
- package/src/main/lib/prd/prdFrontmatter.cjs +96 -3
- package/src/main/lib/process/loginItem.cjs +171 -0
- package/src/main/lib/process/loginItemPlan.cjs +193 -0
- package/src/main/lib/project-pages/playerBridge.cjs +4 -0
- package/src/main/lib/project-pages/videoReview.cjs +268 -0
- package/src/main/lib/project-pages/videoReviewIpc.cjs +229 -0
- package/src/main/lib/promptSessionSchema.cjs +4 -0
- package/src/main/lib/remoteTranscriptTail.cjs +32 -1
- package/src/main/lib/scheduler/cpuSample.cjs +131 -4
- package/src/main/lib/scheduler/fixPlanSlug.cjs +4 -3
- package/src/main/lib/scheduler/loadGate.cjs +24 -6
- package/src/main/lib/scheduler/planRecordHarvest.cjs +108 -0
- package/src/main/lib/scheduler/planRecordRetention.cjs +144 -0
- package/src/main/lib/scheduler/queueStore.cjs +7 -0
- package/src/main/lib/scheduler/rcaReport.cjs +21 -1
- package/src/main/lib/scheduler/reaperHelpers.cjs +35 -5
- package/src/main/lib/scheduler/runLogRetention.cjs +104 -3
- package/src/main/lib/scheduler/scheduleJobSchema.cjs +3 -0
- package/src/main/lib/scheduler/schedulerBatch.cjs +25 -48
- package/src/main/lib/scheduler/schedulerPaths.cjs +12 -0
- package/src/main/lib/scheduler/sessionSlots.cjs +176 -21
- package/src/main/lib/scheduler/validationQuality.cjs +282 -0
- package/src/main/lib/scheduler/validatorVerdictSchema.cjs +254 -0
- package/src/main/lib/tasks/taskAdminRoutes.cjs +641 -0
- package/src/main/lib/tasks/taskIpc.cjs +80 -0
- package/src/main/lib/tasks/taskLedger.cjs +502 -0
- package/src/main/lib/tasks/taskRun.cjs +313 -0
- package/src/main/lib/tasks/taskSwitch.cjs +120 -0
- package/src/main/lib/telemetry/auditEvents.cjs +176 -0
- package/src/main/lib/telemetry/eventsAdminRoutes.cjs +45 -0
- package/src/main/loginItemIpc.cjs +35 -0
- package/src/main/loopEfficiencyHandlers.cjs +11 -2
- package/src/main/projectPages.cjs +6 -15
- package/src/main/promptSessionEvents.cjs +9 -1
- package/src/main/queueOps.cjs +260 -3
- package/src/main/runVerify.cjs +53 -25
- package/src/main/scheduler/AGENTS.md +26 -0
- package/src/main/scheduler/CLAUDE.md +1 -26
- package/src/main/scheduler/budget.cjs +239 -9
- package/src/main/scheduler/cancelDependents.cjs +154 -0
- package/src/main/scheduler/prdParser.cjs +4 -1
- package/src/main/scheduler/starvation.cjs +20 -18
- package/src/main/scheduler.cjs +774 -64
- package/src/main/supervisor.cjs +5 -1
- package/src/main/templates/PRD_AUTHORING.md +7 -1
- package/src/main/transcripts.cjs +62 -7
- package/src/main/validationQualityHandlers.cjs +199 -0
- package/src/main/webRemote.cjs +132 -20
- package/src/preload/api.d.ts +434 -28
- package/src/preload/apiSurface.cjs +7 -0
- package/src/preload/apiSurface.json +485 -81
- package/src/preload/index.cjs +38 -5
- package/src/seed/agents/validator.md +19 -8
- package/dist/assets/AgentLibrary-C1d_D7uQ.js +0 -2
- package/dist/assets/AppSettings-CgDhqrsU.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/Scheduler-CkhTvG7C.js +0 -16
- 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
- package/dist/assets/index-CgCxpunJ.js +0 -3116
package/src/main/supervisor.cjs
CHANGED
|
@@ -18,6 +18,7 @@ const { spawn, execFileSync } = require('node:child_process');
|
|
|
18
18
|
const { ipcMain } = require('electron');
|
|
19
19
|
const { resolveClaudeBin, claudeSpawnTarget } = require('./lib/claude/claudeBin.cjs');
|
|
20
20
|
const { headlessPermissionArgs, ensureCliCapsProbed } = require('./lib/claude/claudeCliCaps.cjs');
|
|
21
|
+
const { buildJobSandboxSettings } = require('./lib/claude/jobSandboxPolicy.cjs');
|
|
21
22
|
const { withProcRole } = require('./lib/process/cleanEnv.cjs');
|
|
22
23
|
const { feedChildStdin } = require('./lib/process/childStdin.cjs');
|
|
23
24
|
const schedulerPaths = require('./lib/scheduler/schedulerPaths.cjs');
|
|
@@ -247,13 +248,16 @@ async function runProbe(claudeBin, prompt) {
|
|
|
247
248
|
let child;
|
|
248
249
|
try {
|
|
249
250
|
const target = claudeSpawnTarget('aux', 'supervisor', claudeBin);
|
|
251
|
+
// No spawn cwd is set, so the child inherits process.cwd() — the sandbox roots there.
|
|
252
|
+
const sandboxDir = process.cwd();
|
|
253
|
+
const sandbox = buildJobSandboxSettings({ agentType: 'aux', worktreeDir: sandboxDir, projectRoot: sandboxDir, homeDir: os.homedir(), tmpDir: os.tmpdir(), deps: { available: false, missing: [] } });
|
|
250
254
|
child = spawn(target.command, [
|
|
251
255
|
'-p',
|
|
252
256
|
'--model', 'claude-haiku-5-5',
|
|
253
257
|
'--no-session-persistence',
|
|
254
258
|
'--output-format', 'json',
|
|
255
259
|
'--max-budget-usd', '0.50',
|
|
256
|
-
|
|
260
|
+
...sandbox.argv,
|
|
257
261
|
...headlessPermissionArgs(),
|
|
258
262
|
'--strict-mcp-config',
|
|
259
263
|
'--allowedTools', 'Bash',
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
<!-- PRD_AUTHORING.md
|
|
1
|
+
<!-- PRD_AUTHORING.md v23 -->
|
|
2
2
|
# PRD Authoring Guide — Scheduler Safety Rules
|
|
3
3
|
|
|
4
4
|
Rule: every PRD you queue follows the rules below.
|
|
@@ -75,6 +75,11 @@ Rule: every PRD needs these fields.
|
|
|
75
75
|
|
|
76
76
|
`planId` is written by the API, never by you. It groups PRDs into the plan (wave) they belong to: an `append` PRD, or one with an explicit `dependsOn`, inherits the `planId` of the PRD it attaches behind; a fresh PRD mints a new one. The Scheduler groups a plan card as a validate PRD (slug `validate-*`) plus everything it depends on, titled by that PRD's title.
|
|
77
77
|
|
|
78
|
+
Records: a validate PRD's record, and the ship/deploy record of a release or deploy PRD, is written to `session-manager-operations/plan-records/<epic-id>/<slug>.md` — machine-local runtime state the scheduler copies to the main checkout and prunes `planRecordsDays` after the Epic completes. A record is never committed and never force-added (`git add -f`); don't list it in `# Files` or a commit step. Why: records used to be committed under `reviews/validation/`, and they piled up in every project with no cleanup.
|
|
79
|
+
|
|
80
|
+
Rule: a PRD that must call a tool marked `irreversible`, `money` or `public` names it in `riskTools` on `scheduler_create_prd` (at most 20 rules, the marks' syntax, e.g. `["Bash(npm publish:*)"]`). Name only what the work needs; a Task can never be cleared.
|
|
81
|
+
Why: the headless job's guard-tool-risk hook refuses an uncleared marked tool. Marks, lookup order and limits: Session Manager's `session-manager-operations/architecture/tool-risk.md`.
|
|
82
|
+
|
|
78
83
|
Artifact-only PRDs (`deliverable: artifact` + `artifactPaths: [...]`) — use this ONLY when every deliverable is a file the repo deliberately git-excludes, so "no commit" is the correct outcome, not a miss.
|
|
79
84
|
1. Every artifact path is listed in `artifactPaths` and is relative, never `..`.
|
|
80
85
|
2. Each file must be non-empty and written during the run window — the verifier stat-checks it on disk.
|
|
@@ -223,6 +228,7 @@ Before queueing a new PRD, verify each of these:
|
|
|
223
228
|
- [ ] **Every command bounded:** every test/build/deploy command is wrapped in `timeout` (typecheck/unit 300s, e2e 120s, `curl --max-time 15`).
|
|
224
229
|
- [ ] **§2 No bonus work:** the AC list is the only source of work.
|
|
225
230
|
- [ ] **§3 Verify, don't poll:** every deploy/migration step is followed by a test command that exits 1 on failure; the AC test command ran green once before you declare done.
|
|
231
|
+
- [ ] **Traceable criteria:** every criterion must be checkable after the run from the tree, a commit, or a read-only probe (registry, API, file); run-time steps such as printing probe output or a value seen mid-run belong in the run report, not in a criterion. Why: the 2026-11-21 release fix plan (3240) had process claims as criteria, and its validator could not verify them.
|
|
226
232
|
- [ ] **§4 Bounded generators:** any search/seed loop has an explicit max and surfaces failure on exhaustion.
|
|
227
233
|
- [ ] **§5 Frontmatter:** `title`, `cwd` (exists on this machine); `estimateMinutes` omitted (optional); `dependsOn` used for ordering, not `parallelGroup`.
|
|
228
234
|
- [ ] **§6 Gate and files:** `gate` follows every rule in §6 (or is `["none"]` alone); `files` is 1–50 repo-relative paths, no overlap with a concurrent PRD.
|
package/src/main/transcripts.cjs
CHANGED
|
@@ -473,11 +473,21 @@ const MAX_USAGE_FILE_BYTES = 64 * 1024 * 1024;
|
|
|
473
473
|
/** Max distinct transcripts whose running totals stay cached. */
|
|
474
474
|
const USAGE_CACHE_MAX = 200;
|
|
475
475
|
|
|
476
|
+
/** How many recent message ids a cache entry remembers for de-dup across tail reads. */
|
|
477
|
+
const USAGE_RECENT_IDS_MAX = 64;
|
|
478
|
+
|
|
476
479
|
/**
|
|
477
|
-
* LRU<filePath, { ino, size, mtimeMs, readOffset, usage }>. `readOffset`
|
|
478
|
-
* byte just past the last complete (newline-terminated) line already
|
|
479
|
-
* the next call only parses [readOffset, size).
|
|
480
|
-
*
|
|
480
|
+
* LRU<filePath, { ino, size, mtimeMs, readOffset, usage, recentIds, newestId }>. `readOffset`
|
|
481
|
+
* is the byte just past the last complete (newline-terminated) line already
|
|
482
|
+
* summed, so the next call only parses [readOffset, size). `recentIds` is an
|
|
483
|
+
* array of [message.id, { inputTokens, outputTokens }] (oldest first, at most
|
|
484
|
+
* USAGE_RECENT_IDS_MAX) — the values already counted for that id, so a message
|
|
485
|
+
* whose lines straddle two reads is still counted once. `newestId` is the
|
|
486
|
+
* message.id of the newest counted call (null if it had none), so a later line
|
|
487
|
+
* of that call can raise `usage.lastContext` while a late repeat of an older
|
|
488
|
+
* id cannot. `usage` = { inputTokens, outputTokens, lastContext, calls }:
|
|
489
|
+
* lastContext is input + cache-read + cache-creation tokens of the newest
|
|
490
|
+
* counted call (null before any), calls the number of counted calls.
|
|
481
491
|
*/
|
|
482
492
|
const usageCache = new LRUCache(USAGE_CACHE_MAX);
|
|
483
493
|
|
|
@@ -510,6 +520,12 @@ async function usageForOne(filePath) {
|
|
|
510
520
|
const start = canTail ? cached.readOffset : 0;
|
|
511
521
|
let inputTokens = canTail ? cached.usage.inputTokens : 0;
|
|
512
522
|
let outputTokens = canTail ? cached.usage.outputTokens : 0;
|
|
523
|
+
let calls = canTail ? cached.usage.calls : 0;
|
|
524
|
+
let lastContext = canTail ? cached.usage.lastContext : null;
|
|
525
|
+
// message.id of the newest counted call (null when that call had no id).
|
|
526
|
+
let newestId = canTail ? cached.newestId : null;
|
|
527
|
+
/** @type {Map<string, { inputTokens: number, outputTokens: number, context: number }>} */
|
|
528
|
+
const recent = new Map(canTail && cached.recentIds ? cached.recentIds : []);
|
|
513
529
|
const want = stat.size - start;
|
|
514
530
|
let buf = Buffer.alloc(0);
|
|
515
531
|
if (want > 0) {
|
|
@@ -545,17 +561,56 @@ async function usageForOne(filePath) {
|
|
|
545
561
|
for (const ev of events) {
|
|
546
562
|
if (ev.kind !== 'usage') continue;
|
|
547
563
|
const u = ev.data || {};
|
|
548
|
-
|
|
549
|
-
|
|
564
|
+
const inTok = u.input_tokens ?? u.inputTokens ?? 0;
|
|
565
|
+
const outTok = u.output_tokens ?? u.outputTokens ?? 0;
|
|
566
|
+
const ctx =
|
|
567
|
+
inTok +
|
|
568
|
+
(u.cache_read_input_tokens ?? u.cacheReadInputTokens ?? 0) +
|
|
569
|
+
(u.cache_creation_input_tokens ?? u.cacheCreationInputTokens ?? 0);
|
|
570
|
+
// One API message's usage is repeated on each of its transcript lines:
|
|
571
|
+
// count a message.id once, keeping the larger value of each field.
|
|
572
|
+
const id = obj?.message?.id;
|
|
573
|
+
if (typeof id !== 'string' || !id) {
|
|
574
|
+
inputTokens += inTok;
|
|
575
|
+
outputTokens += outTok;
|
|
576
|
+
calls += 1;
|
|
577
|
+
lastContext = ctx;
|
|
578
|
+
newestId = null;
|
|
579
|
+
continue;
|
|
580
|
+
}
|
|
581
|
+
const prev = recent.get(id);
|
|
582
|
+
if (prev) {
|
|
583
|
+
const nextIn = Math.max(prev.inputTokens, inTok);
|
|
584
|
+
const nextOut = Math.max(prev.outputTokens, outTok);
|
|
585
|
+
const nextCtx = Math.max(prev.context ?? 0, ctx);
|
|
586
|
+
inputTokens += nextIn - prev.inputTokens;
|
|
587
|
+
outputTokens += nextOut - prev.outputTokens;
|
|
588
|
+
// A later line of an older call never moves lastContext off the newest call.
|
|
589
|
+
if (id === newestId) lastContext = nextCtx;
|
|
590
|
+
recent.delete(id);
|
|
591
|
+
recent.set(id, { inputTokens: nextIn, outputTokens: nextOut, context: nextCtx });
|
|
592
|
+
} else {
|
|
593
|
+
inputTokens += inTok;
|
|
594
|
+
outputTokens += outTok;
|
|
595
|
+
calls += 1;
|
|
596
|
+
lastContext = ctx;
|
|
597
|
+
newestId = id;
|
|
598
|
+
recent.set(id, { inputTokens: inTok, outputTokens: outTok, context: ctx });
|
|
599
|
+
if (recent.size > USAGE_RECENT_IDS_MAX) {
|
|
600
|
+
recent.delete(recent.keys().next().value);
|
|
601
|
+
}
|
|
602
|
+
}
|
|
550
603
|
}
|
|
551
604
|
}
|
|
552
|
-
const usage = { inputTokens, outputTokens };
|
|
605
|
+
const usage = { inputTokens, outputTokens, lastContext, calls };
|
|
553
606
|
usageCache.set(filePath, {
|
|
554
607
|
ino: stat.ino,
|
|
555
608
|
size: stat.size,
|
|
556
609
|
mtimeMs: stat.mtimeMs,
|
|
557
610
|
readOffset: start + lastNl + 1,
|
|
558
611
|
usage,
|
|
612
|
+
recentIds: [...recent],
|
|
613
|
+
newestId,
|
|
559
614
|
});
|
|
560
615
|
return usage;
|
|
561
616
|
}
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* validationQualityHandlers.cjs — `history:validation-quality` IPC and
|
|
3
|
+
* GET /admin/validation-quality?cwd=<abs>. Gathers each project's Epic
|
|
4
|
+
* verdict events (active index + archived Epic files) and scheduler rows
|
|
5
|
+
* (queue + the project's own history shard, which carry `fixes`) and feeds
|
|
6
|
+
* the pure calculator in lib/scheduler/validationQuality.cjs.
|
|
7
|
+
*
|
|
8
|
+
* Zero-scan: the IPC never enumerates ~/.claude/projects (lib/CLAUDE.md). Its
|
|
9
|
+
* project list is the cwd values of the scheduler rows, and those same cwds
|
|
10
|
+
* are the registered roots handed to the archive readers, so the archive
|
|
11
|
+
* path never falls back to defaultProjectRoots' allProjectCwds scan.
|
|
12
|
+
*
|
|
13
|
+
* Read-only; every gather resolves { ok: false, error } instead of throwing.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
'use strict';
|
|
17
|
+
|
|
18
|
+
const path = require('path');
|
|
19
|
+
const { computeValidationQuality } = require('./lib/scheduler/validationQuality.cjs');
|
|
20
|
+
|
|
21
|
+
const HISTORY_ROWS_PER_PROJECT = 500;
|
|
22
|
+
|
|
23
|
+
/** @param {unknown} e */
|
|
24
|
+
const errText = (e) => (e instanceof Error ? e.message : String(e));
|
|
25
|
+
/** @param {unknown} v */
|
|
26
|
+
const isObj = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
|
|
27
|
+
/** @param {string} p */
|
|
28
|
+
const norm = (p) => path.resolve(String(p)).replace(/[\\/]+$/, '');
|
|
29
|
+
|
|
30
|
+
/** Default loaders — required lazily so tests can inject fixtures. */
|
|
31
|
+
const defaults = {
|
|
32
|
+
/** Every live queue row (scheduler's merged queue read). */
|
|
33
|
+
async loadQueueJobs() {
|
|
34
|
+
const state = await require('./lib/scheduler/queueStore.cjs').readMerged();
|
|
35
|
+
return Array.isArray(state && state.jobs) ? state.jobs : [];
|
|
36
|
+
},
|
|
37
|
+
/** Newest federated history rows — only used to discover project cwds. */
|
|
38
|
+
async loadRecentHistory() {
|
|
39
|
+
return require('./lib/scheduler/queueHistory.cjs').readHistory({ limit: HISTORY_ROWS_PER_PROJECT });
|
|
40
|
+
},
|
|
41
|
+
/** One project's own history shard (newest-first, bounded tail). */
|
|
42
|
+
/** @param {string} cwd */
|
|
43
|
+
loadProjectHistory(cwd) {
|
|
44
|
+
const { readHistoryFileTailSync } = require('./lib/scheduler/queueHistory.cjs');
|
|
45
|
+
const { projectHistoryPath } = require('./lib/scheduler/queueStore.cjs');
|
|
46
|
+
return readHistoryFileTailSync(projectHistoryPath(cwd), { maxRows: HISTORY_ROWS_PER_PROJECT });
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/** Terminal history rows only (skip needs_review ledger lines, which carry a `kind`). */
|
|
51
|
+
function isHistoryJobRow(r) {
|
|
52
|
+
return isObj(r) && typeof r.slug === 'string' && typeof r.cwd === 'string' && !('kind' in r && r.kind);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Epic verdict events of one project: open Epics' chains from the active
|
|
57
|
+
* index, plus every archived Epic's events. Unreadable files are skipped.
|
|
58
|
+
* @param {string} cwd @param {() => string[]} projectRoots
|
|
59
|
+
*/
|
|
60
|
+
function epicsOf(cwd, projectRoots) {
|
|
61
|
+
const { readActiveIndex } = require('./lib/epic/epicMint.cjs');
|
|
62
|
+
const { listArchived, readArchived } = require('./promptSessionsIpc.cjs');
|
|
63
|
+
/** @type {Map<string, any[]>} */
|
|
64
|
+
const byId = new Map();
|
|
65
|
+
try {
|
|
66
|
+
const index = readActiveIndex(cwd);
|
|
67
|
+
for (const [epicId, chain] of Object.entries(isObj(index.events) ? index.events : {})) {
|
|
68
|
+
if (Array.isArray(chain)) byId.set(epicId, chain.slice());
|
|
69
|
+
}
|
|
70
|
+
} catch { /* no active index */ }
|
|
71
|
+
let ids = [];
|
|
72
|
+
try {
|
|
73
|
+
const listed = listArchived(cwd, { projectRoots });
|
|
74
|
+
ids = listed && Array.isArray(listed.ids) ? listed.ids : [];
|
|
75
|
+
} catch { /* unregistered or unreadable */ }
|
|
76
|
+
for (const epicId of ids) {
|
|
77
|
+
try {
|
|
78
|
+
const res = readArchived(cwd, epicId, { projectRoots });
|
|
79
|
+
const events = res && res.exists && isObj(res.data) && Array.isArray(res.data.events) ? res.data.events : [];
|
|
80
|
+
byId.set(epicId, [...(byId.get(epicId) || []), ...events]);
|
|
81
|
+
} catch { /* skip this archive */ }
|
|
82
|
+
}
|
|
83
|
+
return [...byId].map(([epicId, events]) => ({ cwd, epicId, events }));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Rows of the given projects: live queue rows + each project's history shard.
|
|
88
|
+
* Queue rows come first so a slug's live row wins over its archived copy.
|
|
89
|
+
*/
|
|
90
|
+
function rowsFor(cwds, queueJobs, loadProjectHistory) {
|
|
91
|
+
const want = new Set(cwds);
|
|
92
|
+
const rows = [];
|
|
93
|
+
for (const j of queueJobs) if (isObj(j) && typeof j.cwd === 'string' && want.has(norm(j.cwd))) rows.push({ ...j, cwd: norm(j.cwd) });
|
|
94
|
+
for (const cwd of cwds) {
|
|
95
|
+
let hist = [];
|
|
96
|
+
try { hist = loadProjectHistory(cwd) || []; } catch { /* no shard */ }
|
|
97
|
+
for (const r of hist) if (isHistoryJobRow(r) && norm(r.cwd) === cwd) rows.push({ ...r, cwd });
|
|
98
|
+
}
|
|
99
|
+
return rows;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* One project (cwd given) or every project that has scheduler rows (no cwd).
|
|
104
|
+
* @param {{ cwd?: string, nowMs?: number, projectRoots?: () => string[], loadQueueJobs?: () => Promise<any[]> | any[], loadRecentHistory?: () => Promise<any[]> | any[], loadProjectHistory?: (cwd: string) => any[] }} [opts]
|
|
105
|
+
* @returns {Promise<{ ok: true, projects: any[] } | { ok: false, error: string }>}
|
|
106
|
+
*/
|
|
107
|
+
async function gatherValidationQuality(opts = {}) {
|
|
108
|
+
try {
|
|
109
|
+
const o = isObj(opts) ? opts : {};
|
|
110
|
+
const now = typeof o.nowMs === 'number' && Number.isFinite(o.nowMs) ? o.nowMs : Date.now();
|
|
111
|
+
const loadQueueJobs = o.loadQueueJobs || defaults.loadQueueJobs;
|
|
112
|
+
const loadRecentHistory = o.loadRecentHistory || defaults.loadRecentHistory;
|
|
113
|
+
const loadProjectHistory = o.loadProjectHistory || defaults.loadProjectHistory;
|
|
114
|
+
|
|
115
|
+
const queueJobs = (await loadQueueJobs()) || [];
|
|
116
|
+
/** @type {string[]} */
|
|
117
|
+
let cwds;
|
|
118
|
+
if (o.cwd !== undefined) {
|
|
119
|
+
if (typeof o.cwd !== 'string' || !path.isAbsolute(o.cwd)) return { ok: false, error: 'cwd must be an absolute path' };
|
|
120
|
+
cwds = [norm(o.cwd)];
|
|
121
|
+
} else {
|
|
122
|
+
const seen = new Set();
|
|
123
|
+
for (const j of queueJobs) if (isObj(j) && typeof j.cwd === 'string' && path.isAbsolute(j.cwd)) seen.add(norm(j.cwd));
|
|
124
|
+
let recent = [];
|
|
125
|
+
try { recent = (await loadRecentHistory()) || []; } catch { /* queue rows alone */ }
|
|
126
|
+
for (const r of recent) if (isHistoryJobRow(r) && path.isAbsolute(r.cwd)) seen.add(norm(r.cwd));
|
|
127
|
+
cwds = [...seen].sort();
|
|
128
|
+
}
|
|
129
|
+
// The rows' own cwds are the registered roots for the IPC (no machine scan);
|
|
130
|
+
// the admin route passes its own registration source.
|
|
131
|
+
const projectRoots = o.projectRoots || (() => cwds);
|
|
132
|
+
|
|
133
|
+
const rows = rowsFor(cwds, queueJobs, loadProjectHistory);
|
|
134
|
+
const epics = cwds.flatMap((cwd) => epicsOf(cwd, projectRoots));
|
|
135
|
+
// A project with no rows and no Epic still gets its (empty) row.
|
|
136
|
+
for (const cwd of cwds) if (!epics.some((e) => e.cwd === cwd)) epics.push({ cwd, epicId: '', events: [] });
|
|
137
|
+
const { projects } = computeValidationQuality({ epics, rows, nowMs: now });
|
|
138
|
+
return { ok: true, projects };
|
|
139
|
+
} catch (e) {
|
|
140
|
+
return { ok: false, error: errText(e) };
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* GET /admin/validation-quality?cwd=<abs>
|
|
146
|
+
* → 200 { ok: true, project } | 400 missing/relative cwd | 404 unregistered project
|
|
147
|
+
* | 500 { ok: false, error } when the gather fails.
|
|
148
|
+
* @param {{ registerRoute: Function }} adminHttp
|
|
149
|
+
* @param {{ projectRoots?: () => string[], nowMs?: () => number, loadQueueJobs?: () => any, loadProjectHistory?: (cwd: string) => any[] }} [deps]
|
|
150
|
+
*/
|
|
151
|
+
function registerAdminRoute(adminHttp, deps = {}) {
|
|
152
|
+
const { sendJson } = require('./lib/feedback-remote/localAdminHttp.cjs');
|
|
153
|
+
adminHttp.registerRoute('GET', '/admin/validation-quality', async (/** @type {any} */ _req, /** @type {any} */ res, /** @type {any} */ query) => {
|
|
154
|
+
const cwd = query && typeof query.get === 'function' ? query.get('cwd') : null;
|
|
155
|
+
if (typeof cwd !== 'string' || !cwd || !path.isAbsolute(cwd)) {
|
|
156
|
+
sendJson(res, 400, { ok: false, error: 'cwd must be an absolute path' });
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
const root = norm(cwd);
|
|
160
|
+
try {
|
|
161
|
+
require('./lib/opsOwnership.cjs').opsPath(root);
|
|
162
|
+
} catch (e) {
|
|
163
|
+
sendJson(res, 400, { ok: false, error: errText(e) });
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
const { listArchived, defaultProjectRoots } = require('./promptSessionsIpc.cjs');
|
|
167
|
+
const projectRoots = deps.projectRoots || defaultProjectRoots;
|
|
168
|
+
try {
|
|
169
|
+
listArchived(root, { projectRoots });
|
|
170
|
+
} catch {
|
|
171
|
+
sendJson(res, 404, { ok: false, error: 'not a registered project' });
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
const out = await gatherValidationQuality({
|
|
175
|
+
cwd: root,
|
|
176
|
+
nowMs: deps.nowMs ? deps.nowMs() : Date.now(),
|
|
177
|
+
projectRoots,
|
|
178
|
+
loadQueueJobs: deps.loadQueueJobs,
|
|
179
|
+
loadProjectHistory: deps.loadProjectHistory,
|
|
180
|
+
});
|
|
181
|
+
if (!out.ok) {
|
|
182
|
+
sendJson(res, 500, out);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
const project = out.projects.find((p) => p.cwd === root) || out.projects[0] || null;
|
|
186
|
+
sendJson(res, 200, { ok: true, project });
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* @param {{ ipcMain?: { handle: Function }, gather?: typeof gatherValidationQuality }} [deps]
|
|
192
|
+
*/
|
|
193
|
+
function registerValidationQualityHandlers(deps = {}) {
|
|
194
|
+
const ipc = deps.ipcMain || require('electron').ipcMain;
|
|
195
|
+
const gather = deps.gather || gatherValidationQuality;
|
|
196
|
+
ipc.handle('history:validation-quality', async () => gather({ nowMs: Date.now() }));
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
module.exports = { gatherValidationQuality, registerValidationQualityHandlers, registerAdminRoute };
|
package/src/main/webRemote.cjs
CHANGED
|
@@ -84,6 +84,31 @@ let _configCache = null;
|
|
|
84
84
|
let _configCacheAt = 0;
|
|
85
85
|
let _repairNeeded = false; // relay rejected the device token (invalid_token / 401): terminal until re-pair
|
|
86
86
|
let _destroyed = false; // set at app shutdown to stop reconnect loops
|
|
87
|
+
let _frameAssembler = null; // inbound e2e:frame reassembly (lazy; reset with all clients)
|
|
88
|
+
let _frameSweepTimer = null;
|
|
89
|
+
const FRAME_SWEEP_MS = 30_000;
|
|
90
|
+
|
|
91
|
+
// Abilities this desktop advertises in event:remote:ready; web clients only send
|
|
92
|
+
// boxed e2e:frame sequences to desktops listing 'e2e-frames'.
|
|
93
|
+
const REMOTE_CAPABILITIES = Object.freeze(['e2e-frames', 'chat-images']);
|
|
94
|
+
|
|
95
|
+
function getFrameAssembler() {
|
|
96
|
+
if (!_frameAssembler) {
|
|
97
|
+
const { createFrameAssembler } = require('./lib/feedback-remote/remoteFrameAssembler.cjs');
|
|
98
|
+
_frameAssembler = createFrameAssembler();
|
|
99
|
+
}
|
|
100
|
+
return _frameAssembler;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function startFrameSweep() {
|
|
104
|
+
stopFrameSweep();
|
|
105
|
+
_frameSweepTimer = setInterval(() => { if (_frameAssembler) _frameAssembler.sweep(); }, FRAME_SWEEP_MS);
|
|
106
|
+
_frameSweepTimer.unref?.();
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function stopFrameSweep() {
|
|
110
|
+
if (_frameSweepTimer) { clearInterval(_frameSweepTimer); _frameSweepTimer = null; }
|
|
111
|
+
}
|
|
87
112
|
|
|
88
113
|
// E2E session state — reset on each new WS connection.
|
|
89
114
|
// .state: 'idle' | 'pending_sas' | 'authenticated' | 'failed'
|
|
@@ -254,6 +279,7 @@ function resetE2e() {
|
|
|
254
279
|
|
|
255
280
|
// Mark one client's session failed without touching any other client.
|
|
256
281
|
function failClient(client) {
|
|
282
|
+
if (_frameAssembler) _frameAssembler.dropClient(client.key);
|
|
257
283
|
client.e2e = makeState('failed');
|
|
258
284
|
client.peerPubKey = null;
|
|
259
285
|
client.deviceId = null;
|
|
@@ -383,6 +409,7 @@ function scheduleReconnect() {
|
|
|
383
409
|
async function disconnect() {
|
|
384
410
|
cancelReconnect();
|
|
385
411
|
stopHeartbeat();
|
|
412
|
+
stopFrameSweep();
|
|
386
413
|
resetE2e();
|
|
387
414
|
if (_ws) {
|
|
388
415
|
const ws = _ws;
|
|
@@ -453,6 +480,7 @@ async function connect() {
|
|
|
453
480
|
_backoffMs = BACKOFF_INIT_MS;
|
|
454
481
|
_missedPongs = 0;
|
|
455
482
|
startHeartbeat();
|
|
483
|
+
startFrameSweep();
|
|
456
484
|
// Update lastConnectedAt without exposing token
|
|
457
485
|
invalidateConfigCache(); // a pin written since the last cached read must not be overwritten
|
|
458
486
|
loadConfig().then(async (c) => {
|
|
@@ -479,6 +507,7 @@ async function connect() {
|
|
|
479
507
|
|
|
480
508
|
ws.on('close', (code) => {
|
|
481
509
|
stopHeartbeat();
|
|
510
|
+
stopFrameSweep();
|
|
482
511
|
stopAllSessionWatches();
|
|
483
512
|
resetE2e();
|
|
484
513
|
if (_ws === ws) _ws = null;
|
|
@@ -561,6 +590,7 @@ function pruneSessionWatchers() {
|
|
|
561
590
|
/** Tear down one client (its PTY streams + subscriptions) without touching others. */
|
|
562
591
|
function teardownClient(key) {
|
|
563
592
|
_lastRekeyMs.delete(key);
|
|
593
|
+
if (_frameAssembler) _frameAssembler.dropClient(key);
|
|
564
594
|
const rec = _clients.teardown(key);
|
|
565
595
|
pruneSessionWatchers();
|
|
566
596
|
return rec;
|
|
@@ -568,6 +598,7 @@ function teardownClient(key) {
|
|
|
568
598
|
|
|
569
599
|
/** Tear down every client — no client keeps a PTY stream or subscription afterwards. */
|
|
570
600
|
function teardownAllClients() {
|
|
601
|
+
_frameAssembler = null; // drops every client's partial frames
|
|
571
602
|
const n = _clients.teardownAll();
|
|
572
603
|
pruneSessionWatchers();
|
|
573
604
|
return n;
|
|
@@ -717,7 +748,7 @@ function stopAllSessionWatches() {
|
|
|
717
748
|
function finalizeE2eAuthenticated(logMessage, client) {
|
|
718
749
|
logs.writeLine({ scope: 'webRemote', level: 'info', message: logMessage });
|
|
719
750
|
broadcastStatus();
|
|
720
|
-
if (client && loadConfigSync().remoteEnabled) pushEventTo(client, 'event:remote:ready', { ts: Date.now() });
|
|
751
|
+
if (client && loadConfigSync().remoteEnabled) pushEventTo(client, 'event:remote:ready', { ts: Date.now(), capabilities: [...REMOTE_CAPABILITIES] });
|
|
721
752
|
}
|
|
722
753
|
|
|
723
754
|
// ─── Message handling & command dispatch ─────────────────────────────────────
|
|
@@ -897,6 +928,10 @@ async function handleMessage(raw, device) {
|
|
|
897
928
|
} catch {
|
|
898
929
|
return;
|
|
899
930
|
}
|
|
931
|
+
if (inner && typeof inner === 'object' && inner.type === 'e2e:frame') {
|
|
932
|
+
await handleFrame(inner, device, client);
|
|
933
|
+
return;
|
|
934
|
+
}
|
|
900
935
|
// Dispatch as if it arrived unencrypted
|
|
901
936
|
await dispatchEnvelope(inner, device, client);
|
|
902
937
|
return;
|
|
@@ -913,6 +948,31 @@ async function handleMessage(raw, device) {
|
|
|
913
948
|
await dispatchEnvelope(envelope, device, client);
|
|
914
949
|
}
|
|
915
950
|
|
|
951
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
952
|
+
|
|
953
|
+
/**
|
|
954
|
+
* One decrypted e2e:frame slice of a browser→desktop message too large for the relay's
|
|
955
|
+
* 256 KB cap. Only authenticated clients of an enabled remote are buffered; a completed
|
|
956
|
+
* message goes through the normal dispatchEnvelope gates.
|
|
957
|
+
*/
|
|
958
|
+
async function handleFrame(inner, device, client) {
|
|
959
|
+
if (client.e2e.state !== 'authenticated') return;
|
|
960
|
+
if (!(await loadConfig()).remoteEnabled) {
|
|
961
|
+
if (_frameAssembler) _frameAssembler.dropClient(client.key); // kill switch: free any partial
|
|
962
|
+
return;
|
|
963
|
+
}
|
|
964
|
+
const payload = inner.payload;
|
|
965
|
+
const result = getFrameAssembler().accept(client.key, payload);
|
|
966
|
+
if (result.status === 'complete') {
|
|
967
|
+
await dispatchEnvelope(result.envelope, device, client);
|
|
968
|
+
return;
|
|
969
|
+
}
|
|
970
|
+
if (result.status !== 'refused') return;
|
|
971
|
+
const msgId = payload && typeof payload.msgId === 'string' && UUID_RE.test(payload.msgId) ? payload.msgId : undefined;
|
|
972
|
+
await auditLog(new Date().toISOString(), 'e2e:frame', device.deviceId, msgId, `refused:${result.reason}`, client);
|
|
973
|
+
if (msgId) respond(msgId, { error: 'rejected' }, undefined, client);
|
|
974
|
+
}
|
|
975
|
+
|
|
916
976
|
const IPC_INVOKE_MAX_CALLS = 50;
|
|
917
977
|
let _ipcDispatcher = null;
|
|
918
978
|
|
|
@@ -1158,6 +1218,12 @@ function respond(msgId, payload, typeOverride, client) {
|
|
|
1158
1218
|
}
|
|
1159
1219
|
}
|
|
1160
1220
|
|
|
1221
|
+
// A 'project-video' macro is a background Video tool run only from the desktop's
|
|
1222
|
+
// Project Home ▸ Video — the phone remote neither lists nor starts one.
|
|
1223
|
+
function isRemoteMacro(macro) {
|
|
1224
|
+
return macro.surface !== 'project-video';
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1161
1227
|
// Lazy-loaded dispatch map — avoids circular require at module load time.
|
|
1162
1228
|
let _dispatchMap = null;
|
|
1163
1229
|
|
|
@@ -1269,33 +1335,75 @@ function getDispatchMap() {
|
|
|
1269
1335
|
// client — in-process call, no admin HTTP hop needed since webRemote
|
|
1270
1336
|
// already runs inside the Electron main process (PRD 753).
|
|
1271
1337
|
'cmd:chat:send': async (payload) => {
|
|
1272
|
-
const
|
|
1338
|
+
const result = schemas.remoteChatSend.safeParse(payload);
|
|
1339
|
+
if (!result.success) {
|
|
1340
|
+
const issues = result.error.issues;
|
|
1341
|
+
if (issues.length > 0 && issues.every((i) => i.path[0] === 'images')) {
|
|
1342
|
+
return { ok: false, disposition: 'refused', reason: 'attachment-invalid' };
|
|
1343
|
+
}
|
|
1344
|
+
throw result.error;
|
|
1345
|
+
}
|
|
1346
|
+
const parsed = result.data;
|
|
1273
1347
|
const { readActiveIndex } = require('./lib/epic/epicMint.cjs');
|
|
1274
1348
|
const data = await sessionsStore.load();
|
|
1275
1349
|
const tabs = data?.tabs ?? [];
|
|
1276
|
-
// Resolve the target in main: an open tab, or an ACTIVE Epic (by id or
|
|
1277
|
-
// claudeSessionId) of an open project. Anything else is a structured refusal.
|
|
1278
1350
|
const outcome = (r) => ({
|
|
1279
1351
|
ok: r.disposition !== 'refused',
|
|
1280
1352
|
disposition: r.disposition,
|
|
1281
1353
|
...(r.reason ? { reason: r.reason } : {}),
|
|
1282
1354
|
});
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1355
|
+
// 1. Resolve the target BEFORE writing anything: an open tab, or an ACTIVE
|
|
1356
|
+
// Epic (by id or claudeSessionId) of an open project. Anything else is a
|
|
1357
|
+
// structured refusal.
|
|
1358
|
+
let target = null;
|
|
1359
|
+
const openTab = tabs.find((t) => t && (t.sessionId === parsed.tabId || t.id === parsed.tabId));
|
|
1360
|
+
if (openTab) {
|
|
1361
|
+
target = { id: parsed.tabId, extra: undefined, projectCwd: openTab.cwd };
|
|
1362
|
+
} else {
|
|
1363
|
+
for (const tab of tabs) {
|
|
1364
|
+
const sessions = Object.values(readActiveIndex(tab.cwd)?.sessions ?? {});
|
|
1365
|
+
const epic = sessions.find((e) => e && (e.id === parsed.tabId || e.claudeSessionId === parsed.tabId));
|
|
1366
|
+
if (!epic) continue;
|
|
1367
|
+
if (epic.status !== 'active' || !epic.claudeSessionId) {
|
|
1368
|
+
return { ok: false, disposition: 'refused', reason: epic.status === 'proposed' ? 'proposed' : 'not-active' };
|
|
1369
|
+
}
|
|
1370
|
+
target = {
|
|
1371
|
+
id: epic.id,
|
|
1372
|
+
extra: { sessionId: epic.claudeSessionId, cwd: epic.cwd || tab.cwd },
|
|
1373
|
+
projectCwd: tab.cwd,
|
|
1374
|
+
};
|
|
1375
|
+
break;
|
|
1292
1376
|
}
|
|
1293
|
-
return outcome(await chatRunner.enqueueExternalPrompt(epic.id, parsed.prompt, {
|
|
1294
|
-
sessionId: epic.claudeSessionId,
|
|
1295
|
-
cwd: epic.cwd || tab.cwd,
|
|
1296
|
-
}));
|
|
1297
1377
|
}
|
|
1298
|
-
return { ok: false, disposition: 'refused', reason: 'unknown-target' };
|
|
1378
|
+
if (!target) return { ok: false, disposition: 'refused', reason: 'unknown-target' };
|
|
1379
|
+
|
|
1380
|
+
const enqueue = (prompt) => (target.extra
|
|
1381
|
+
? chatRunner.enqueueExternalPrompt(target.id, prompt, target.extra)
|
|
1382
|
+
: chatRunner.enqueueExternalPrompt(target.id, prompt));
|
|
1383
|
+
|
|
1384
|
+
const images = parsed.images ?? [];
|
|
1385
|
+
if (images.length === 0) return outcome(await enqueue(parsed.prompt));
|
|
1386
|
+
|
|
1387
|
+
// 2. Save images under the owning open tab's project (never logged: no
|
|
1388
|
+
// image data or names reach the audit trail).
|
|
1389
|
+
const { saveChatImages, composeAttachedPrompt, removeSavedAttachments } = require('./lib/epic/epicAttachments.cjs');
|
|
1390
|
+
// projectCwd is an open tab's cwd: register it with the write boundary
|
|
1391
|
+
// (as promptSessionsIpc does) so the save never depends on a pty having spawned.
|
|
1392
|
+
require('./config.cjs').addAllowedRoot(validatePath(target.projectCwd));
|
|
1393
|
+
const saved = await saveChatImages({ projectCwd: target.projectCwd, images });
|
|
1394
|
+
if (!saved.ok) return { ok: false, disposition: 'refused', reason: 'attachment-invalid' };
|
|
1395
|
+
|
|
1396
|
+
// 3. Enqueue; only a definite refusal removes the files ('unconfirmed' may
|
|
1397
|
+
// still land, so its files stay).
|
|
1398
|
+
let r;
|
|
1399
|
+
try {
|
|
1400
|
+
r = await enqueue(composeAttachedPrompt(parsed.prompt, saved.paths));
|
|
1401
|
+
} catch (err) {
|
|
1402
|
+
await removeSavedAttachments(target.projectCwd, saved.paths);
|
|
1403
|
+
throw err;
|
|
1404
|
+
}
|
|
1405
|
+
if (r.disposition === 'refused') await removeSavedAttachments(target.projectCwd, saved.paths);
|
|
1406
|
+
return { ...outcome(r), attachments: saved.names };
|
|
1299
1407
|
},
|
|
1300
1408
|
|
|
1301
1409
|
'cmd:session:options': async () => {
|
|
@@ -1308,7 +1416,7 @@ function getDispatchMap() {
|
|
|
1308
1416
|
projects: tabs.map((t) => ({ cwd: t.cwd, title: t.label })),
|
|
1309
1417
|
agents: personas.map((a) => ({ name: a.name, description: a.description })),
|
|
1310
1418
|
tags: EpicTagSchema.options,
|
|
1311
|
-
macros: await macroLibrary.listMacros(),
|
|
1419
|
+
macros: (await macroLibrary.listMacros()).filter(isRemoteMacro),
|
|
1312
1420
|
macroInputs: true,
|
|
1313
1421
|
};
|
|
1314
1422
|
},
|
|
@@ -1328,7 +1436,9 @@ function getDispatchMap() {
|
|
|
1328
1436
|
const macroLibrary = require('./lib/persona-macro/macroLibrary.cjs');
|
|
1329
1437
|
const macros = await macroLibrary.listMacros();
|
|
1330
1438
|
const macro = macros.find((m) => m.id === parsed.macroId);
|
|
1331
|
-
if (!macro || !macroLibrary.macroVisibleIn(macro, parsed.cwd))
|
|
1439
|
+
if (!macro || !isRemoteMacro(macro) || !macroLibrary.macroVisibleIn(macro, parsed.cwd)) {
|
|
1440
|
+
throw new Error('unknown macro');
|
|
1441
|
+
}
|
|
1332
1442
|
const result = macroLibrary.renderMacroPrompt(parsed.prompt, macro.inputs, parsed.inputs ?? {});
|
|
1333
1443
|
if (!result.ok) throw new Error(result.error);
|
|
1334
1444
|
prompt = result.prompt;
|
|
@@ -1600,9 +1710,11 @@ function destroy() {
|
|
|
1600
1710
|
_ws = null;
|
|
1601
1711
|
}
|
|
1602
1712
|
stopHeartbeat();
|
|
1713
|
+
stopFrameSweep();
|
|
1603
1714
|
}
|
|
1604
1715
|
|
|
1605
1716
|
module.exports = {
|
|
1717
|
+
REMOTE_CAPABILITIES,
|
|
1606
1718
|
loadConfig,
|
|
1607
1719
|
setIpcDispatcher,
|
|
1608
1720
|
attachWindow,
|