claude-code-session-manager 0.93.0 → 0.95.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 (78) hide show
  1. package/dist/assets/{DataModel-DDGx3qrn.js → DataModel-DZK9QZpV.js} +1 -1
  2. package/dist/assets/{History-CHBjYZyD.js → History-BDyJUGtR.js} +2 -2
  3. package/dist/assets/{Hooks-DG4c-Rzz.js → Hooks-CmK6l0uf.js} +3 -3
  4. package/dist/assets/HostBilko-D8TIx-Bx.js +1 -0
  5. package/dist/assets/{Library-CN1h5rAE.js → Library-DTxpOjx8.js} +25 -25
  6. package/dist/assets/{MarkdownEditor-DmBxrhdn.js → MarkdownEditor-BPJyrevq.js} +1 -1
  7. package/dist/assets/McpServers-B_rvIYDs.js +2 -0
  8. package/dist/assets/{Memory-Dk4uDCjg.js → Memory-B-9GlHqe.js} +6 -6
  9. package/dist/assets/{Permissions-BovobeZw.js → Permissions-DhMMp27n.js} +3 -3
  10. package/dist/assets/{Plugins-DvOf_B62.js → Plugins-DKfAlmMY.js} +2 -2
  11. package/dist/assets/{ProvenanceBadge-Dutz_4OY.js → ProvenanceBadge-ptlItdCK.js} +1 -1
  12. package/dist/assets/{SaveBar-CT5u6ZCJ.js → SaveBar-CSbNSl2W.js} +1 -1
  13. package/dist/assets/Scheduler--rn1QBYc.js +16 -0
  14. package/dist/assets/{ScopeSwitcher-BUYDpz2v.js → ScopeSwitcher-BJof-GWH.js} +1 -1
  15. package/dist/assets/{Settings-DIRmr3tL.js → Settings-Dsx6XZP5.js} +3 -3
  16. package/dist/assets/{SkillReferenceGraph-CdGr6d3_.js → SkillReferenceGraph-CGl4B89-.js} +2 -2
  17. package/dist/assets/{Skills-BQOheQv4.js → Skills-D522Zfol.js} +2 -2
  18. package/dist/assets/{SystemPrompt-5LsimKbX.js → SystemPrompt-DKj-q39J.js} +1 -1
  19. package/dist/assets/{TagLibrary-DreLsT3n.js → TagLibrary-BH7CG7-6.js} +1 -1
  20. package/dist/assets/{TiptapBody-C9kmlBnI.js → TiptapBody-BbcJL9az.js} +1 -1
  21. package/dist/assets/{Toggle-BKLCBu9A.js → Toggle-DAslvnnv.js} +1 -1
  22. package/dist/assets/{index-Db_SK9rW.js → index-Yf8e7VCB.js} +821 -821
  23. package/dist/assets/{settingsSchema-B5jBhSUP.js → settingsSchema-pzp0TgvN.js} +1 -1
  24. package/dist/index.html +1 -1
  25. package/package.json +8 -3
  26. package/scripts/README.md +6 -0
  27. package/src/main/__tests__/chat-cancel-terminal.test.cjs +5 -2
  28. package/src/main/__tests__/chat-exit-close-race.test.cjs +8 -2
  29. package/src/main/__tests__/chat-mcp-consent-notice.test.cjs +5 -2
  30. package/src/main/__tests__/health-tick-liveness.test.cjs +12 -0
  31. package/src/main/__tests__/intradayRefresh.test.cjs +39 -0
  32. package/src/main/__tests__/openExternalApp-spawn-error.test.cjs +25 -0
  33. package/src/main/__tests__/opsErrorLog.test.cjs +22 -0
  34. package/src/main/__tests__/pty-epic-worktree-spawn-cwd.test.cjs +21 -0
  35. package/src/main/__tests__/rateLimitPollerStreak.test.cjs +14 -0
  36. package/src/main/__tests__/runVerify-atomic-verdicts.test.cjs +26 -0
  37. package/src/main/__tests__/runVerify-landed-commit-outranks.test.cjs +11 -1
  38. package/src/main/__tests__/runVerify-transcript-commit-evidence.test.cjs +11 -1
  39. package/src/main/__tests__/runVerify.test.cjs +12 -1
  40. package/src/main/__tests__/scheduler-rate-limit-pause.test.cjs +15 -0
  41. package/src/main/__tests__/scheduler-utilization-hold.test.cjs +89 -0
  42. package/src/main/__tests__/transcriptsUsageFor.test.cjs +112 -1
  43. package/src/main/build-info.json +4 -4
  44. package/src/main/chatRunner.cjs +45 -10
  45. package/src/main/crashDiagnostics.cjs +9 -0
  46. package/src/main/git.cjs +9 -2
  47. package/src/main/health.cjs +25 -1
  48. package/src/main/historyAggregator.cjs +2 -19
  49. package/src/main/index.cjs +7 -8
  50. package/src/main/ipcSchemas.cjs +13 -3
  51. package/src/main/lib/__tests__/childWithLog.test.cjs +180 -0
  52. package/src/main/lib/__tests__/delegationReadiness.test.cjs +19 -0
  53. package/src/main/lib/__tests__/gitCacheBound.test.cjs +69 -0
  54. package/src/main/lib/__tests__/loopDelay.test.cjs +68 -0
  55. package/src/main/lib/__tests__/usageCircuit.test.cjs +86 -17
  56. package/src/main/lib/agentPersonaSchema.cjs +2 -0
  57. package/src/main/lib/childWithLog.cjs +92 -51
  58. package/src/main/lib/delegationReadiness.cjs +3 -1
  59. package/src/main/lib/epicSpawnPlan.cjs +27 -8
  60. package/src/main/lib/epicTranscriptPath.cjs +5 -1
  61. package/src/main/lib/headTailBuffer.cjs +43 -0
  62. package/src/main/lib/intradayRefresh.cjs +33 -0
  63. package/src/main/lib/loopDelay.cjs +44 -0
  64. package/src/main/lib/lruCache.cjs +39 -0
  65. package/src/main/lib/openExternalApp.cjs +27 -9
  66. package/src/main/lib/opsErrorLog.cjs +22 -0
  67. package/src/main/lib/promptSessionSchema.cjs +2 -0
  68. package/src/main/lib/rendererRecovery.cjs +141 -0
  69. package/src/main/lib/scheduleJobSchema.cjs +3 -0
  70. package/src/main/lib/usageCircuit.cjs +40 -12
  71. package/src/main/runVerify.cjs +3 -1
  72. package/src/main/scheduler.cjs +409 -260
  73. package/src/main/transcripts.cjs +54 -11
  74. package/src/main/usage.cjs +9 -1
  75. package/src/preload/api.d.ts +20 -3
  76. package/dist/assets/HostBilko-DHXcpV2c.js +0 -1
  77. package/dist/assets/McpServers-Beb_HD6I.js +0 -2
  78. package/dist/assets/Scheduler-B7GSnZj5.js +0 -16
@@ -37,6 +37,7 @@ function attachWindow(w) {
37
37
  }
38
38
 
39
39
  const { encodeCwd } = require('./lib/encodeCwd.cjs');
40
+ const { LRUCache } = require('./lib/lruCache.cjs');
40
41
  const { classifyLine } = require('./lib/classifyTranscriptLine.cjs');
41
42
  const { resolveEpicTranscriptPath } = require('./lib/epicTranscriptPath.cjs');
42
43
 
@@ -449,21 +450,32 @@ async function getBuffer(tabId) {
449
450
  // this size report null (omitted by the renderer) rather than a partial sum.
450
451
  const MAX_USAGE_FILE_BYTES = 64 * 1024 * 1024;
451
452
 
452
- /** Map<filePath, { mtimeMs, size, usage: {inputTokens, outputTokens} }> */
453
- const usageCache = new Map();
453
+ /** Max distinct transcripts whose running totals stay cached. */
454
+ const USAGE_CACHE_MAX = 200;
455
+
456
+ /**
457
+ * LRU<filePath, { ino, size, mtimeMs, readOffset, usage }>. `readOffset` is the
458
+ * byte just past the last complete (newline-terminated) line already summed, so
459
+ * the next call only parses [readOffset, size). The full parse keeps no
460
+ * de-dup state (every usage event is summed), so none is cached here.
461
+ */
462
+ const usageCache = new LRUCache(USAGE_CACHE_MAX);
454
463
 
455
464
  /**
456
465
  * Sum `usage` events out of one session's JSONL transcript — same
457
466
  * classifyLine()/field-name resolution live.ts's ingest uses for its running
458
467
  * per-tab totals (input_tokens/output_tokens, snake_case on the wire).
459
- * Cached by file mtime so repeat calls for an unchanged transcript are a
460
- * single fs.stat.
468
+ * Append-only tail parse: when the inode matches and the file has not shrunk,
469
+ * only the new bytes are read (positional fd.read) and a trailing partial line
470
+ * waits until completed; truncation / inode change → full re-parse.
471
+ * Cost per call: O(appended bytes) time and space; O(file) only on cold/reset.
461
472
  */
462
473
  async function usageForOne(filePath) {
463
474
  const stat = await fsp.stat(filePath).catch(() => null);
464
475
  if (!stat) return null;
465
476
  const cached = usageCache.get(filePath);
466
- if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) {
477
+ const canTail = !!cached && cached.ino === stat.ino && stat.size >= cached.readOffset;
478
+ if (canTail && cached.size === stat.size && cached.mtimeMs === stat.mtimeMs) {
467
479
  return cached.usage;
468
480
  }
469
481
  if (stat.size > MAX_USAGE_FILE_BYTES) {
@@ -475,11 +487,33 @@ async function usageForOne(filePath) {
475
487
  });
476
488
  return null;
477
489
  }
478
- const text = await fsp.readFile(filePath, 'utf8').catch(() => null);
479
- if (text === null) return null;
480
- let inputTokens = 0;
481
- let outputTokens = 0;
482
- for (const line of text.split('\n')) {
490
+ const start = canTail ? cached.readOffset : 0;
491
+ let inputTokens = canTail ? cached.usage.inputTokens : 0;
492
+ let outputTokens = canTail ? cached.usage.outputTokens : 0;
493
+ const want = stat.size - start;
494
+ let buf = Buffer.alloc(0);
495
+ if (want > 0) {
496
+ let fd;
497
+ try {
498
+ fd = await fsp.open(filePath, 'r');
499
+ buf = Buffer.alloc(want);
500
+ let got = 0;
501
+ while (got < want) {
502
+ const { bytesRead } = await fd.read(buf, got, want - got, start + got);
503
+ if (bytesRead === 0) break;
504
+ got += bytesRead;
505
+ }
506
+ buf = buf.subarray(0, got);
507
+ } catch {
508
+ return null;
509
+ } finally {
510
+ await fd?.close().catch(() => {});
511
+ }
512
+ }
513
+ // Consume only complete lines; a trailing partial line is re-read next call.
514
+ const lastNl = buf.lastIndexOf(0x0a);
515
+ const complete = lastNl === -1 ? '' : buf.subarray(0, lastNl + 1).toString('utf8');
516
+ for (const line of complete.split('\n')) {
483
517
  if (!line) continue;
484
518
  let obj;
485
519
  try {
@@ -496,7 +530,13 @@ async function usageForOne(filePath) {
496
530
  }
497
531
  }
498
532
  const usage = { inputTokens, outputTokens };
499
- usageCache.set(filePath, { mtimeMs: stat.mtimeMs, size: stat.size, usage });
533
+ usageCache.set(filePath, {
534
+ ino: stat.ino,
535
+ size: stat.size,
536
+ mtimeMs: stat.mtimeMs,
537
+ readOffset: start + lastNl + 1,
538
+ usage,
539
+ });
500
540
  return usage;
501
541
  }
502
542
 
@@ -562,6 +602,9 @@ module.exports = {
562
602
  // Test-only accessor onto the raw Subscription object (its lineIndex in
563
603
  // particular) — asserting a memory ceiling requires inspecting what's
564
604
  // actually held, not just what a read API returns.
605
+ __usageCacheForTest: usageCache,
606
+ __usageForOneForTest: usageForOne,
607
+ __usageCacheMaxForTest: USAGE_CACHE_MAX,
565
608
  __getSubForTest: (tabId) => subs.get(tabId),
566
609
  // Test-only: run a live (emit:true) flush directly against a subscription,
567
610
  // without going through the chokidar watcher — lets batching/IPC-shape
@@ -280,8 +280,16 @@ async function fetchUsage() {
280
280
  if (kind === 'meter_rate_limited') return { kind: 'meter_rate_limited', message: 'e2e stub', httpStatus: 429 };
281
281
  if (kind === 'transient') return { kind: 'transient', message: 'e2e stub', httpStatus: 503 };
282
282
  if (kind === 'auth') return { kind: 'auth', message: 'e2e stub', httpStatus: 401 };
283
+ // 'ok_weekly_binding': real-shape limits[] where the WEEKLY window binds (64%) while the
284
+ // session window reads 12% and a scoped entry reads 90% (must be ignored). Distinct values
285
+ // let an e2e prove the KPI was derived via bindingWindow(), not a flat five_hour fallback.
286
+ if (kind === 'ok_weekly_binding') {
287
+ const sessionReset = new Date(Date.now() + 3 * 3_600_000).toISOString();
288
+ const weeklyReset = new Date(Date.now() + (2 * 24 + 5) * 3_600_000).toISOString();
289
+ return { kind: 'ok', data: { usage: { five_hour: { utilization: 12, resets_at: sessionReset }, seven_day: { utilization: 64, resets_at: weeklyReset }, limits: [{ kind: 'session', group: 'session', percent: 12, severity: 'normal', resets_at: sessionReset, scope: null, is_active: false }, { kind: 'weekly_all', group: 'weekly', percent: 64, severity: 'normal', resets_at: weeklyReset, scope: null, is_active: true }, { kind: 'weekly_scoped', group: 'weekly', percent: 90, severity: 'warning', resets_at: weeklyReset, scope: { model: 'opus' }, is_active: false }], seven_day_sonnet: null, seven_day_opus: null, extra_usage: null }, subscriptionType: null, rateLimitTier: null, credentialsExpiresAt: null, fetchedAt: Date.now() } };
290
+ }
283
291
  // 'ok' stub returns a minimal valid payload.
284
- return { kind: 'ok', data: { usage: { five_hour: { utilization: 10, resets_at: null }, seven_day: { utilization: 10, resets_at: null }, seven_day_sonnet: null, seven_day_opus: null, extra_usage: null }, subscriptionType: null, rateLimitTier: null, credentialsExpiresAt: null, fetchedAt: Date.now() } };
292
+ return { kind: 'ok', data: { usage: { five_hour: { utilization: 10, resets_at: null }, seven_day: { utilization: 10, resets_at: null }, limits: [{ kind: 'session', group: 'session', percent: 10, severity: 'normal', resets_at: null, scope: null, is_active: false }, { kind: 'weekly_all', group: 'weekly', percent: 10, severity: 'normal', resets_at: null, scope: null, is_active: true }], seven_day_sonnet: null, seven_day_opus: null, extra_usage: null }, subscriptionType: null, rateLimitTier: null, credentialsExpiresAt: null, fetchedAt: Date.now() } };
285
293
  }
286
294
 
287
295
  await ensureHydrated();
@@ -1,3 +1,5 @@
1
+ import type { PromptSession } from '../renderer/state/promptSessions';
2
+
1
3
  export interface BuildTarget {
2
4
  registry: string;
3
5
  packageName: string;
@@ -152,12 +154,23 @@ export interface UsageWindow {
152
154
  resets_at: string | null;
153
155
  }
154
156
 
157
+ export interface UsageLimitEntry {
158
+ kind: string;
159
+ group: string;
160
+ percent: number | null;
161
+ severity: string | null;
162
+ resets_at: string | null;
163
+ scope: { model?: { display_name?: string } } | null;
164
+ is_active: boolean;
165
+ }
166
+
155
167
  export interface UsageSnapshot {
156
168
  five_hour: UsageWindow | null;
157
169
  seven_day: UsageWindow | null;
158
170
  seven_day_sonnet: UsageWindow | null;
159
171
  seven_day_opus: UsageWindow | null;
160
172
  seven_day_oauth_apps: UsageWindow | null;
173
+ limits?: UsageLimitEntry[] | null;
161
174
  extra_usage: {
162
175
  is_enabled: boolean;
163
176
  monthly_limit: number | null;
@@ -502,7 +515,7 @@ export interface ScheduleConfig {
502
515
  defaultCwd: string;
503
516
  /** Auto-fire policy. Default 'when-available'. */
504
517
  firePolicy: ScheduleFirePolicy;
505
- /** When firePolicy='when-available', fire only if five_hour utilization is
518
+ /** When firePolicy='when-available', fire only if binding-window utilization is
506
519
  * strictly below this percent. 0–100. Default 90. */
507
520
  utilizationThreshold: number;
508
521
  schemaVersion: 1;
@@ -856,8 +869,12 @@ export interface ScheduleStateSnapshot {
856
869
  launchBlocks?: Record<string, ScheduleLaunchBlock>;
857
870
  /** Degraded-mode launch env in force per persona. Empty when nothing is degraded. */
858
871
  launchMitigations?: Record<string, ScheduleLaunchMitigation>;
859
- /** Latest five_hour utilization percent (0–100) cached from billing.fetchUsage. null if unknown. */
872
+ /** Latest BINDING-window utilization percent (0–100) cached from billing.fetchUsage. null if unknown. */
860
873
  utilization: number | null;
874
+ /** Name/kind of the window `utilization` reads (e.g. 'five_hour', 'weekly_all'). null if unknown. */
875
+ utilizationWindow?: string | null;
876
+ /** Non-null while the when-available gate is holding the queue on utilization: which window, and its reset. */
877
+ utilizationHold?: { window: string | null; percent: number; threshold: number; resetsAt: string | null } | null;
861
878
  /** Poll health — last billing poll result; used to detect stale utilization. */
862
879
  pollHealth?: SchedulePollHealth;
863
880
  /** Effective concurrency cap and whether it's env-pinned or config-driven. */
@@ -2124,7 +2141,7 @@ export interface PromptSessionsCreateEpicPayload {
2124
2141
 
2125
2142
  export interface PromptSessionsCreateEpicResult {
2126
2143
  epicId: string;
2127
- session: Record<string, unknown>;
2144
+ session: PromptSession;
2128
2145
  }
2129
2146
 
2130
2147
  // ─────────────────────────────────── PromptSessions create-worktree (main-side createEpicWorktree)
@@ -1 +0,0 @@
1
- import{ay as i,aL as J,aV as P,aK as m,$ as Y,aM as Q,aj as t,l as $,aF as W}from"./index-Db_SK9rW.js";import"./monaco-editor-BW5C4Iv1.js";function X(r){return r.hasMarketingPage?r.packagePrivate&&!r.packageHomepage?{kind:"private-needs-confirm"}:{kind:"ready"}:{kind:"no-marketing-page"}}const Z=["home","marketing","feature","architecture"],ee={home:"Home page",marketing:"Marketing page",feature:"Feature page",architecture:"Architecture page"};function I(r){return ee[r]}function D(r){const n=r.find(l=>l.subpath==="");return Z.map(l=>{const p=r.find(h=>h.source.kind==="project-page-lens"&&h.source.lens===l);return p?{lens:l,status:p.subpath===""?"root":"hosted",subpath:p.subpath,documentId:p.id}:!n&&l==="marketing"?{lens:l,status:"root",subpath:"",documentId:null}:{lens:l,status:"available",subpath:l,documentId:null}})}function te(r){return r.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64)||"project"}const j="bilko-host-publisher",se="bilko-host-publisher",ne=[{value:"home",label:"Home lens"},{value:"marketing",label:"Marketing lens"},{value:"feature",label:"Feature lens"},{value:"architecture",label:"Architecture lens"}];function ae(r,n){for(const l of Object.values(r))if(l.cwd===n&&l.tag===j&&l.status==="active")return l;return null}function _(r){W(r),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"terminal"}))}function oe(){const r=J(),n=(r==null?void 0:r.cwd)??null,l=P(e=>e.sessions),p=P(e=>e.createPromptSession),h=P(e=>e.approveProposed),[o,C]=i.useState(null),[R,v]=i.useState(!1),[b,k]=i.useState(""),[E,H]=i.useState(!1),[M,B]=i.useState(!1),[u,L]=i.useState(null),[N,A]=i.useState(""),[f,T]=i.useState(""),[y,F]=i.useState("feature");i.useEffect(()=>{let e=!1;return window.api.agents.listPersonas().then(a=>{if(e)return;const s=a.find(g=>g.name===se);L(s?{name:s.name,description:s.description}:null)}).catch(()=>{e||L(null)}),()=>{e=!0}},[]);const c=i.useCallback(()=>{n&&(v(!1),window.api.bilkoHost.get(n).then(e=>{C(e),k(a=>{var s;return a||((s=e.bundleManifest)==null?void 0:s.slug)||e.defaultSlug}),v(!0)}).catch(e=>{v(!0),m.error(`Could not load bilko-host status: ${e instanceof Error?e.message:String(e)}`)}))},[n]);i.useEffect(()=>{C(null),k(""),H(!1),c()},[c]);const x=n?ae(l,n):null,O=i.useCallback(()=>{!n||!b||(B(!0),window.api.bilkoHost.prepareBundle(n,b).then(()=>c()).catch(e=>m.error(`Could not prepare bundle: ${e instanceof Error?e.message:String(e)}`)).finally(()=>B(!1)))},[n,b,c]),z=i.useCallback(()=>{if(!n)return;const e=te(N).replace(/^-+|-+$/g,"");if(!e||!f.trim()){m.error("A sub-path and a title are required.");return}const a={kind:"project-page-lens",lens:y};window.api.bilkoHost.addDocument(n,e,f.trim(),a).then(()=>{A(""),T(""),c()}).catch(s=>m.error(`Could not add document: ${s instanceof Error?s.message:String(s)}`))},[n,N,f,y,c]),G=i.useCallback((e,a)=>{n&&window.api.bilkoHost.addDocument(n,a,I(e),{kind:"project-page-lens",lens:e}).then(()=>c()).catch(s=>m.error(`Could not add ${e} page: ${s instanceof Error?s.message:String(s)}`))},[n,c]),K=i.useCallback(async()=>{if(!n||!o)return;const e=D(o.documents).filter(a=>a.status==="available");for(const a of e)try{await window.api.bilkoHost.addDocument(n,a.subpath,I(a.lens),{kind:"project-page-lens",lens:a.lens})}catch(s){m.error(`Could not add ${a.lens} page: ${s instanceof Error?s.message:String(s)}`)}c()},[n,o,c]),U=i.useCallback(e=>{n&&window.api.bilkoHost.removeDocument(n,e).then(()=>c()).catch(a=>m.error(`Could not remove document: ${a instanceof Error?a.message:String(a)}`))},[n,c]),V=i.useCallback(async()=>{if(!n||!b)return;if(x){_(x.id);return}const e=`Publish this project to bilko.run as a static-path listing, slug "${b}". Bundle is at session-manager-operations/bilko-host/dist/ (prepare it first via Prepare Bundle if it's missing or stale) — it may contain multiple documents (a root page plus sub-paths); publish the whole dist/ tree as one static-path app.`,{goalText:a,openingPrompt:s}=Y({title:"",goal:e,tag:j,agentName:u==null?void 0:u.name,agentDescription:(u==null?void 0:u.description)??void 0}),g=u?await p(n,a,j,"HostBilko",u.name):await p(n,a,j,"HostBilko");h(g.id,"HostBilko"),Q.getState().send({tabId:g.id,sessionId:g.claudeSessionId,cwd:n,prompt:s}),_(g.id)},[n,b,x,p,h,u]);if(!n)return t.jsx($,{title:"Open a project to host it on Bilko.run"});if(!R||!o)return null;const w=X(o);if(w.kind==="no-marketing-page")return t.jsx($,{title:"No Marketing page yet",hint:"Generate this project's Project Pages from Project Home first — the root document publishes the Marketing lens."});const d=o.publishState,q=(d==null?void 0:d.status)??(o.bundleManifest?"bundle-ready":"not-published"),S=w.kind==="ready"||E;return t.jsxs("div",{className:"max-w-2xl space-y-4",children:[t.jsxs("div",{className:"rounded-card border border-line bg-bg-hi p-5 space-y-4",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsxs("div",{children:[t.jsx("div",{className:"font-serif text-lg text-fg",children:o.projectName}),t.jsxs("div",{className:"text-xs text-fg-faint mt-0.5",children:["Status: ",t.jsx("span",{className:"font-mono",children:q}),o.bundleStale&&o.bundleManifest&&t.jsx("span",{className:"ml-2 text-accent",children:"bundle out of date — Prepare Bundle again"})]})]}),(d==null?void 0:d.status)==="published"&&d.url&&t.jsx("a",{href:d.url,target:"_blank",rel:"noreferrer",className:"text-xs text-accent hover:underline",children:d.url})]}),w.kind==="private-needs-confirm"&&!E&&t.jsxs("div",{className:"rounded-md border border-line bg-bg p-3 text-xs text-fg-dim",children:["This project's package.json is marked private with no public homepage. Confirm you want to publish it to bilko.run anyway.",t.jsx("button",{type:"button",onClick:()=>H(!0),className:"mt-2 block rounded-md bg-accent px-3 py-1.5 text-xs font-semibold text-bg-hi hover:bg-accent-dark",children:"Yes, this can be public"})]}),S&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"block text-xs text-fg-faint",children:["Slug (bilko.run/projects/<slug>/)",t.jsx("input",{value:b,onChange:e=>k(e.target.value.toLowerCase()),className:"mt-1 block w-full rounded-md border border-line bg-bg px-2.5 py-1.5 text-sm font-mono text-fg"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("button",{type:"button",onClick:O,disabled:M,className:"rounded-md border border-line bg-bg px-3.5 py-1.5 text-xs font-semibold text-fg hover:bg-bg-hi disabled:opacity-50",children:M?"Preparing…":"Prepare Bundle"}),t.jsx("button",{type:"button",onClick:()=>{V().catch(e=>{m.error(e instanceof Error?e.message:String(e))})},disabled:!o.bundleManifest,title:o.bundleManifest?void 0:"Prepare a bundle first",className:"rounded-md bg-accent px-3.5 py-1.5 text-xs font-semibold text-bg-hi hover:bg-accent-dark disabled:opacity-50",children:x?"View publish in progress":"Publish"})]}),o.bundleManifest&&t.jsxs("div",{className:"text-[11px] text-fg-faint font-mono",children:["bundle: ",(o.bundleManifest.bundle.sizeBytesGz/1024).toFixed(1)," KB gz ·"," ",o.bundleManifest.bundle.fileCount," document",o.bundleManifest.bundle.fileCount===1?"":"s"," · built"," ",new Date(o.bundleManifest.builtAt).toLocaleString()," · ",o.bundleManifest.gitSha]}),(d==null?void 0:d.status)==="publish-failed"&&d.lastError&&t.jsxs("div",{className:"text-xs text-accent",children:["Last publish failed: ",d.lastError]})]})]}),S&&(()=>{const e=D(o.documents),a=e.filter(s=>s.status==="available").length;return t.jsxs("div",{className:"rounded-card border border-line bg-bg-hi p-5 space-y-3",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("div",{className:"font-serif text-base text-fg",children:"Project Pages"}),a>1&&t.jsxs("button",{type:"button",onClick:K,className:"text-xs text-accent hover:underline",children:["Host all ",a," remaining"]})]}),t.jsxs("p",{className:"text-xs text-fg-faint",children:["This project generates 4 pages (Home / Marketing / Feature / Architecture). Marketing is the project's root (bilko.run/projects/",b||"<slug>","/); host any of the others as their own sub-page if you want them public too."]}),t.jsx("ul",{className:"space-y-1.5",children:e.map(s=>t.jsxs("li",{className:"flex items-center justify-between gap-2 rounded-md border border-line bg-bg px-3 py-2 text-xs",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-fg capitalize",children:s.lens}),t.jsx("div",{className:"text-fg-faint font-mono truncate",children:s.status==="root"?"(project root)":`/${s.subpath}/`})]}),s.status==="available"?t.jsxs("button",{type:"button",onClick:()=>G(s.lens,s.subpath),className:"shrink-0 rounded-md border border-line px-2 py-1 text-fg hover:bg-bg-hi",children:["+ Host as /",s.subpath,"/"]}):t.jsx("span",{className:"shrink-0 text-fg-faint",children:s.status==="root"?"root":"hosted"})]},s.lens))})]})})(),S&&t.jsxs("div",{className:"rounded-card border border-line bg-bg-hi p-5 space-y-3",children:[t.jsx("div",{className:"font-serif text-base text-fg",children:"Hosted documents"}),t.jsx("p",{className:"text-xs text-fg-faint",children:"One project, one Bilko listing — add as many explanatory pages as you want under it, each at its own sub-path. Removing one here takes it down on the next Publish."}),t.jsx("ul",{className:"space-y-1.5",children:o.documents.map(e=>t.jsxs("li",{className:"flex items-center justify-between gap-2 rounded-md border border-line bg-bg px-3 py-2 text-xs",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-fg truncate",children:e.title}),t.jsxs("div",{className:"text-fg-faint font-mono truncate",children:[e.subpath===""?"(root)":`/${e.subpath}/`," · ",e.url]})]}),e.subpath!==""&&t.jsx("button",{type:"button",onClick:()=>U(e.id),title:"Remove — takes effect on the next Publish",className:"shrink-0 rounded-md border border-line px-2 py-1 text-fg-faint hover:text-accent hover:border-accent/40",children:"Remove"})]},e.id))}),t.jsxs("div",{className:"rounded-md border border-line bg-bg p-3 space-y-2",children:[t.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-fg-faint",children:"Add a document"}),t.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[t.jsx("input",{value:N,onChange:e=>A(e.target.value),placeholder:"sub-path, e.g. special-doc/01",className:"rounded-md border border-line bg-bg-hi px-2.5 py-1.5 text-xs font-mono text-fg"}),t.jsx("input",{value:f,onChange:e=>T(e.target.value),placeholder:"Title",className:"rounded-md border border-line bg-bg-hi px-2.5 py-1.5 text-xs text-fg"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("select",{value:y,onChange:e=>F(e.target.value),className:"rounded-md border border-line bg-bg-hi px-2.5 py-1.5 text-xs text-fg",children:ne.map(e=>t.jsx("option",{value:e.value,children:e.label},e.value))}),t.jsx("button",{type:"button",onClick:z,className:"rounded-md border border-line bg-bg-hi px-3.5 py-1.5 text-xs font-semibold text-fg hover:bg-bg",children:"Add document"})]})]})]})]})}const le=i.memo(oe);export{le as HostBilko};
@@ -1,2 +0,0 @@
1
- import{aj as e,ay as c,aQ as oe,aL as ie,aS as ce,aN as N,l as O,u as $,q as de,a as Z,aK as q}from"./index-Db_SK9rW.js";import{S as xe}from"./SaveBar-CT5u6ZCJ.js";import{S as Y}from"./ScopeSwitcher-BUYDpz2v.js";import{P as G}from"./ProvenanceBadge-Dutz_4OY.js";import{M as ue,V as D}from"./Library-CN1h5rAE.js";import"./monaco-editor-BW5C4Iv1.js";const pe={live:"bg-emerald-400",idle:"bg-amber-400",offline:"bg-fg-faint",attention:"bg-accent",paused:"bg-zinc-500"},fe={sm:"w-1.5 h-1.5",md:"w-2 h-2"},me={on:"live",off:"offline",warn:"attention",live:"live",idle:"idle"};function W({state:n,kind:t,pulse:a=!1,size:d="sm",className:p="",title:b,"aria-label":o}){const j=n??(t?me[t]:"idle"),r=pe[j],h=fe[d],x=a?"animate-pulse":"",u=o??b??j;return e.jsx("span",{role:"img","aria-label":u,className:`inline-block rounded-full ${h} ${r} ${x} ${p}`.trim(),title:b})}const ge={failed:"Failed","needs-auth":"Needs auth",pending:"Pending approval"};function H(n,t){const a=t!=null&&t.ok?t.servers.find(d=>d.name===n):void 0;return!a||a.status==="unknown"?{state:"unprobed",label:"Not checked",probeStatus:(a==null?void 0:a.status)??null,badgeTone:"dim",dotState:"offline"}:a.status==="connected"?{state:"ready",label:"Ready",probeStatus:a.status,badgeTone:"good",dotState:"live"}:{state:"not-ready",label:ge[a.status],probeStatus:a.status,badgeTone:"warn",dotState:"attention"}}const Q=(n,t)=>({type:"mcp",name:n,command:t.command,args:t.args,url:t.url}),he=["stdio","http","streamable-http","sse","ws"],be=new Set(["workspace"]),je=new Set(["ide","tasks"]);function ve(n,t,a){return n==="user"?`${t}/.claude.json`:a?`${a}/.mcp.json`:null}function ye(n){if(n.trim()==="")return{full:{},servers:{},err:null};try{const t=JSON.parse(n),a=t.mcpServers??{};return{full:t,servers:a,err:null}}catch(t){return{full:{},servers:{},err:t.message}}}function Ne(n,t){return JSON.stringify({...n,mcpServers:t},null,2)+`
2
- `}function we(n){let t=Object.keys(n).length+1,a=`server-${t}`;for(;n[a];)t+=1,a=`server-${t}`;return a}function Se(){const n=oe(),t=ie(),a=(t==null?void 0:t.cwd)??null,d=ce(s=>s.navFace),p=c.useRef(!1),b=c.useRef(d),[o,j]=c.useState(()=>d==="project"&&a?"project":"user"),[r,h]=c.useState(null),[x,u]=c.useState("installed"),[w,_]=c.useState("");c.useEffect(()=>{if(b.current!==d){if(b.current=d,p.current){p.current=!1;return}j(d==="project"&&a?"project":"user")}},[d,a]);const f=c.useMemo(()=>n?ve(o,n,a):null,[n,o,a]),k=N(s=>s.files),l=N(s=>s.loadJson),v=N(s=>s.setDraft),m=N(s=>s.saveJson),I=N(s=>s.revert),T=N(s=>s.watchFile),X=N(s=>s.unwatchFile);c.useEffect(()=>{if(f)return k[f]||l(f),T(f),()=>X(f)},[f]);const[ee,R]=c.useState(null),[J,K]=c.useState(null),[B,z]=c.useState(!1),F=c.useRef(0),A=c.useRef(!0);c.useEffect(()=>()=>{A.current=!1},[]);const V=async()=>{const s=++F.current;z(!0);try{const i=await window.api.mcp.status();if(!A.current||s!==F.current)return;K(i),i.ok||q.error(i.error??"MCP status probe failed")}catch(i){if(!A.current||s!==F.current)return;K(null),q.error(i.message||"MCP status probe failed")}finally{A.current&&s===F.current&&z(!1)}};if(c.useEffect(()=>{V()},[]),!n)return e.jsx(O,{title:"loading…"});if(x==="library")return e.jsx($,{toolbar:e.jsx(D,{active:x,onChange:u}),children:e.jsx(ue,{})});if(o==="project"&&!a)return e.jsx($,{toolbar:e.jsxs(e.Fragment,{children:[e.jsx(D,{active:x,onChange:u}),e.jsx("span",{className:"mx-2 text-fg-faint",children:"·"}),e.jsx(Y,{scopes:["user","project"],active:o,onChange:s=>{p.current=!0,j(s)}})]}),children:e.jsx(O,{title:"no active project"})});if(!f)return e.jsx(O,{title:"loading…"});const y=k[f],{full:te,servers:g,err:se}=y?ye(y.draftRaw):{full:{},servers:{},err:null},L=Object.keys(g).sort(),M=r?g[r]:null,P=s=>{R(null),v(f,Ne(te,s))},ae=()=>{const s=we(g);P({...g,[s]:{type:"stdio",command:"",args:[]}}),h(s)},le=s=>{const i={...g};delete i[s],P(i),r===s&&h(null)},ne=(s,i)=>{if(!i||i===s||g[i])return;const S={};for(const C of Object.keys(g))S[C===s?i:C]=g[C];P(S),h(i)},re=(s,i)=>{P({...g,[s]:i})};return e.jsx($,{toolbar:e.jsxs(e.Fragment,{children:[e.jsx(D,{active:x,onChange:u}),e.jsx("span",{className:"mx-2 text-fg-faint",children:"·"}),e.jsx(Y,{scopes:["user","project"],active:o,onChange:s=>{p.current=!0,j(s)}}),e.jsxs("span",{className:"ml-3 px-1.5 py-0.5 text-[10px] rounded border border-line text-fg-faint",children:[L.length," server",L.length===1?"":"s"]}),e.jsx("span",{className:"ml-2 text-fg-faint truncate",children:f}),e.jsx("div",{className:"flex-1"}),r&&M&&e.jsx(G,{scope:o,input:Q(r,M),className:"mr-2"}),e.jsx("button",{onClick:V,disabled:B,className:"px-2 py-0.5 text-xs border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi disabled:opacity-50 mr-2",children:B?"checking…":"⟳ test connections"}),e.jsx("button",{onClick:ae,className:"px-2 py-0.5 text-xs border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi",children:"+ new server"})]}),footer:y?e.jsx(xe,{dirty:y.dirty,busy:y.busy,parseError:ee||se||y.parseError,lastSavedAt:y.lastSavedAt,onSave:async()=>{R(null);const s=await m(f);s.ok||R(s.error??"save failed")},onRevert:()=>{R(null),I(f)}}):null,children:e.jsx(de,{sidebar:e.jsxs("div",{className:"py-2",children:[e.jsx("div",{className:"px-2 pb-1",children:e.jsx("input",{value:w,onChange:s=>_(s.target.value),placeholder:"filter…",className:"w-full bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg"})}),L.length===0?e.jsx("div",{className:"px-3 py-1 text-xs text-fg-faint italic",children:"no servers"}):L.filter(s=>!w||s.toLowerCase().includes(w.toLowerCase())).map(s=>{var C;const i=H(s,J),S=(C=g[s].description)==null?void 0:C.trim();return e.jsxs("button",{onClick:()=>h(s),className:`w-full text-left px-3 py-1 text-xs flex flex-col gap-0.5 ${r===s?"bg-bg-hi text-fg":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:[e.jsxs("span",{className:"flex items-center gap-2 justify-between w-full",children:[e.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(W,{state:i.dotState,title:i.label}),e.jsx("span",{className:"truncate",children:s})]}),e.jsxs("span",{className:"ml-2 flex items-center gap-2 shrink-0",children:[e.jsx(Z,{tone:i.badgeTone,children:i.label}),e.jsx(G,{interactive:!1,scope:o,input:Q(s,g[s])}),e.jsx("span",{className:"text-fg-faint",children:g[s].type??"stdio"})]})]}),S?e.jsx("span",{className:"pl-5 text-fg-faint truncate",title:S,children:S}):null]},s)})]}),detail:r&&M?e.jsx(Ce,{name:r,server:M,connection:H(r,J),onTestConnection:V,testing:B,onRename:s=>ne(r,s),onChange:s=>re(r,s),onRemove:()=>le(r)}):e.jsx(O,{title:"select a server or click + new"})})})}const Le=c.memo(Se);function Ce({name:n,server:t,connection:a,onTestConnection:d,testing:p,onRename:b,onChange:o,onRemove:j}){var k;const r=t.type??"stdio",h=be.has(n),x=je.has(n),u=(k=t.permissions)==null?void 0:k.tools,w=u===void 0?"inherit":u==="allow"?"allow":u==="deny"?"deny":"list",_=Array.isArray(u)?u:[],f=(t.disabledTools??[]).join(", ");return e.jsxs("div",{className:"p-4 space-y-4 max-w-2xl",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(W,{state:a.dotState,size:"md",title:a.label}),e.jsx(Z,{tone:a.badgeTone,children:a.label}),e.jsx("button",{onClick:d,disabled:p,className:"ml-auto px-2 py-0.5 text-xs border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi disabled:opacity-50",children:p?"checking…":"test connection"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-xs text-fg-faint w-20",children:"name"}),e.jsx("input",{defaultValue:n,onBlur:l=>b(l.target.value.trim()),className:"flex-1 bg-bg-elev border border-line rounded px-2 py-1 text-xs text-fg font-mono"}),e.jsx("button",{onClick:j,className:"text-xs text-fg-faint hover:text-red-400 px-2 py-1 border border-line rounded",children:"delete"})]}),e.jsx(E,{label:"description",value:t.description??"",onChange:l=>o({...t,description:l||void 0}),placeholder:"what this server does…"}),h?e.jsxs("div",{className:"text-xs px-2 py-1 border border-red-500/50 rounded text-red-300 bg-red-500/5",children:["⚠ ",e.jsx("span",{className:"font-mono",children:n})," is a reserved name — Claude Code will refuse to load this server (v2.1.128+)."]}):x?e.jsxs("div",{className:"text-xs px-2 py-1 border border-yellow-600/50 rounded text-yellow-200 bg-yellow-500/5",children:["⚠ ",e.jsx("span",{className:"font-mono",children:n})," collides with a commonly-bundled MCP name; expect surprises in other tools."]}):null,e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-xs text-fg-faint w-20",children:"type"}),e.jsx("select",{value:r,onChange:l=>o({...t,type:l.target.value}),className:"bg-bg-elev border border-line rounded px-2 py-1 text-xs text-fg",children:he.map(l=>e.jsx("option",{value:l,children:l},l))}),r==="sse"?e.jsx("span",{className:"text-xs text-yellow-400/80",children:"sse is deprecated — prefer streamable-http"}):null]}),r==="stdio"?e.jsxs(e.Fragment,{children:[e.jsx(E,{label:"command",value:t.command??"",onChange:l=>o({...t,command:l}),placeholder:"npx / node / python …"}),e.jsx(E,{label:"args",value:(t.args??[]).join(" "),onChange:l=>o({...t,args:l.split(/\s+/).filter(Boolean)}),placeholder:"space-separated args"}),e.jsx(U,{label:"env",value:t.env??{},onChange:l=>o({...t,env:l})})]}):e.jsxs(e.Fragment,{children:[e.jsx(E,{label:"url",value:t.url??"",onChange:l=>o({...t,url:l}),placeholder:"https://…"}),e.jsx(U,{label:"headers",value:t.headers??{},onChange:l=>o({...t,headers:l})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-xs text-fg-faint w-20",children:"alwaysLoad"}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg",children:[e.jsx("input",{type:"checkbox",checked:t.alwaysLoad===!0,onChange:l=>o({...t,alwaysLoad:l.target.checked||void 0})}),e.jsx("span",{className:"text-fg-dim",children:"bypass tool-search deferral (v2.1.121+)"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-xs text-fg-faint w-20",children:"enabled"}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg",children:[e.jsx("input",{type:"checkbox",checked:t.enabled!==!1,onChange:l=>o({...t,enabled:l.target.checked?void 0:!1})}),e.jsx("span",{className:"text-fg-dim",children:"load this server in new sessions"})]})]}),e.jsx(E,{label:"disabledTools",value:f,onChange:l=>{const v=l.split(",").map(m=>m.trim()).filter(Boolean);o({...t,disabledTools:v.length?v:void 0})},placeholder:"comma-separated tool names to hide"}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("label",{className:"text-xs text-fg-faint w-20 pt-1",children:"permissions"}),e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsxs("select",{value:w,onChange:l=>{const v=l.target.value,m={...t};if(v==="inherit"){if(m.permissions){const{tools:I,...T}=m.permissions;m.permissions=Object.keys(T).length?T:void 0}}else v==="list"?m.permissions={...m.permissions??{},tools:[]}:m.permissions={...m.permissions??{},tools:v};o(m)},className:"bg-bg-elev border border-line rounded px-2 py-1 text-xs text-fg",children:[e.jsx("option",{value:"inherit",children:"inherit (default)"}),e.jsx("option",{value:"allow",children:"allow all tools"}),e.jsx("option",{value:"deny",children:"deny all tools"}),e.jsx("option",{value:"list",children:"allowlist…"})]}),w==="list"?e.jsx("input",{value:_.join(", "),onChange:l=>{const v=l.target.value.split(",").map(m=>m.trim()).filter(Boolean);o({...t,permissions:{...t.permissions??{},tools:v}})},placeholder:"comma-separated tool names",className:"w-full bg-bg-elev border border-line rounded px-2 py-1 text-xs text-fg font-mono"}):null]})]})]})}function E({label:n,value:t,onChange:a,placeholder:d}){return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-xs text-fg-faint w-20",children:n}),e.jsx("input",{value:t,onChange:p=>a(p.target.value),placeholder:d,className:"flex-1 bg-bg-elev border border-line rounded px-2 py-1 text-xs text-fg font-mono"})]})}function U({label:n,value:t,onChange:a}){const[d,p]=c.useState(""),[b,o]=c.useState(""),j=Object.entries(t);return e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("label",{className:"text-xs text-fg-faint w-20 pt-1",children:n}),e.jsxs("div",{className:"flex-1 space-y-1",children:[j.map(([r,h])=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{value:r,onChange:x=>{const u={...t};delete u[r],u[x.target.value]=h,a(u)},className:"w-32 bg-bg-elev border border-line rounded px-2 py-0.5 text-xs text-fg font-mono"}),e.jsx("input",{value:h,onChange:x=>a({...t,[r]:x.target.value}),className:"flex-1 bg-bg-elev border border-line rounded px-2 py-0.5 text-xs text-fg font-mono"}),e.jsx("button",{onClick:()=>{const x={...t};delete x[r],a(x)},className:"text-fg-faint hover:text-red-400 text-xs px-1",children:"×"})]},r)),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{value:d,onChange:r=>p(r.target.value),placeholder:"key",className:"w-32 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg-dim font-mono"}),e.jsx("input",{value:b,onChange:r=>o(r.target.value),placeholder:"value",className:"flex-1 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg-dim font-mono"}),e.jsx("button",{onClick:()=>{d.trim()&&(a({...t,[d.trim()]:b}),p(""),o(""))},className:"px-2 text-xs border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi",children:"+"})]})]})]})}export{Le as McpServers,we as nextServerName};
@@ -1,16 +0,0 @@
1
- import{aC as Ce,aq as ne,aG as ns,ae as ke,a8 as ae,ac as X,aK as V,aX as Ie,aV as ce,ay as f,b0 as as,a6 as fe,aj as t,b as Fe,I as he,L as rt,o as rs,K as pe,s as is,N as ls,d as os,T as ds,a2 as it,ao as St,a$ as Se,z as Ee,au as Re,A as Ke,aF as Qe,a9 as lt,H as Ct,v as $t,n as Pt,p as cs,m as ze,x as Xe,O as us,D as se,f as q,aa as Dt,aU as At,aY as ps,ax as fs,U as hs,ar as ot,aO as dt,l as ye,w as ct,k as xs,aI as gs,V as ms,t as Mt,aQ as bs,aN as ve,G as ws,C as vs,aZ as js,az as ys,Q as Ns,b1 as ks,a_ as ut,aE as Ss}from"./index-Db_SK9rW.js";import{l as Cs}from"./listSkills-QORduPIk.js";import{T as $s}from"./Toggle-BKLCBu9A.js";import"./monaco-editor-BW5C4Iv1.js";function Ps(e){const s=new Map(e.map(r=>[r.slug,r])),n=new Map,a=new Set,c=[];function o(r){n.set(r,1),c.push(r);const i=s.get(r);for(const u of(i==null?void 0:i.dependsOn)??[]){if(!s.has(u))continue;const l=n.get(u);if(l===1){const d=c.indexOf(u);for(let p=d;p<c.length;p++)a.add(c[p])}else l===void 0&&o(u)}c.pop(),n.set(r,2)}for(const r of e)n.has(r.slug)||o(r.slug);return a}function Ds(e,s){return(e.dependsOn??[]).map(n=>{const a=s.get(n);return a?{slug:n,status:a.status,missing:!1,needsReview:a.status==="needs_review"}:{slug:n,status:null,missing:!0,needsReview:!1}})}function As(e,s,n){const a=new Set(e.map(l=>l.slug)),c=new Set;for(const l of e)for(const d of l.dependsOn??[])a.has(d)&&c.add(d);const o=new Map,r=[];for(const l of e){const d=n.has(l.slug)?void 0:(l.dependsOn??[]).find(p=>a.has(p)&&!n.has(p));d?(o.has(d)||o.set(d,[]),o.get(d).push(l)):r.push(l)}const i=(l,d)=>l.slug.localeCompare(d.slug);r.sort(i);for(const l of o.values())l.sort(i);function u(l,d,p){const h=Ds(l,s),b=n.has(l.slug);p.add(l.slug);const x=b?[]:(o.get(l.slug)??[]).filter(g=>!p.has(g.slug)).map(g=>u(g,d+1,p));return p.delete(l.slug),{row:l,depth:d,children:x,blockers:h,blocked:h.some(g=>!g.missing&&g.status!=="completed"),hasNeedsReviewBlocker:h.some(g=>g.needsReview),hasMissingDep:h.some(g=>g.missing),cycle:b,parallelEligible:(l.dependsOn??[]).length===0&&!c.has(l.slug)}}return r.map(l=>u(l,0,new Set))}function Rt(e,s,n){const a=new Map((n??e).map(l=>[l.slug,l])),c=Ps(e),o=[],r=new Map,i=new Map;for(const l of e){const d=Ce(l,s),p=d.epicId??"__none__";r.has(p)||(o.push(p),r.set(p,[]),i.set(p,{epicId:d.epicId,label:d.known&&d.label?d.label:d.epicId?`Epic ${d.epicId.slice(0,12)}…`:"No Epic",known:d.known})),r.get(p).push(l)}const u=o.map(l=>{const d=i.get(l),p=r.get(l),h=As(p,a,c),b={};for(const x of p){const g=x.status??"unknown";b[g]=(b[g]??0)+1}return{epicId:d.epicId,label:d.label,known:d.known,nodes:h,counts:b,total:p.length}});return u.sort((l,d)=>l.epicId===null?1:d.epicId===null?-1:l.known!==d.known?l.known?-1:1:l.label.localeCompare(d.label)),u}function Te(e){const s=[],n=a=>{s.push(a);for(const c of a.children)n(c)};for(const a of e)n(a);return s}const Ms=15e4,Ue=e=>e==="completed"||e==="skipped",Ne=e=>e==="running"||e==="investigating",It=e=>e==="failed"||e==="needs_review"||e==="quarantined",Rs=e=>e==="failed"||e==="needs_review"||e==="quarantined";function Et(e){const s=Math.max(0,Math.floor(e/1e3)),n=Math.floor(s/3600),a=Math.floor(s%3600/60),c=s%60;return n>0?`${n}h${String(a).padStart(2,"0")}m`:a>0?`${a}m${String(c).padStart(2,"0")}s`:`${c}s`}function Tt(e){if(e<=5e3)return"~now";if(e<6e4)return`~${Math.round(e/1e3)}s`;const s=Math.round(e/6e4);return s<60?`~${s}m`:`~${Math.floor(s/60)}h${String(s%60).padStart(2,"0")}m`}function _t(e,s){const n=e.estimateMinutes?e.estimateMinutes*6e4:null;return n?`${Math.min(99,Math.floor(s/n*100))}%`:Et(s)}function Is(e){let s=0,n=0;for(const a of e)if(a.status==="completed"&&a.startedAt&&a.finishedAt){const c=Date.parse(a.finishedAt)-Date.parse(a.startedAt);c>0&&(s+=c,n++)}return n===0?Ms:s/n}function We(e){const s=ne(e);return s===null?1/0:Number(s)}function pt(e,s){const n=We(e.slug)-We(s.slug);return n!==0&&!Number.isNaN(n)?n:e.slug.localeCompare(s.slug)}function Es(e){let s=0;for(const n of e.statusHistory??[])n.to==="pending"&&n.from!==null&&s++;return s}function Ts(e){return e.some(n=>Ne(n.status))?"active":e.every(n=>Ue(n.status))?"done":e.filter(n=>n.status!=="quarantined").length===0?"draft":"queued"}function _s(e,s,n,a){switch(e){case"done":return`${s.doneCount}/${s.rows.length} done`;case"running":return`${s.runningCount} running · ${n}`;case"held":return`${s.heldCount} held`;case"blocked":return`${s.blockedCount+a} blocked`;default:return`${n} ready`}}function Os(e,s){return e._firstNum!==s._firstNum?e._firstNum<s._firstNum?-1:1:e._firstSlug.localeCompare(s._firstSlug)}function Ls(e,s){const n=new Map(e.map(o=>[o.row.slug,o.row.slug])),a=o=>{for(;n.get(o)!==o;)n.set(o,n.get(n.get(o))),o=n.get(o);return o};for(const o of e)for(const r of o.row.dependsOn??[])s.has(r)&&n.set(a(o.row.slug),a(r));const c=new Map;for(const o of e){const r=a(o.row.slug),i=c.get(r);i?i.push(o):c.set(r,[o])}return[...c.values()]}function Fs(e,s){if(e.length>0&&e.every(n=>!!n.row.planId)){const n=new Map;for(const a of e){const c=n.get(a.row.planId);c?c.push(a):n.set(a.row.planId,[a])}return[...n.values()]}return Ls(e,s)}function Ze(e,s){if(e.length===0)return[];const n=s.now??Date.now(),a=s.avgDurationMs??Is(e),c=Math.max(1,s.concurrency??1),o=new Map(e.map(d=>[d.slug,d])),r=d=>d.status==="pending"&&(d.dependsOn??[]).every(p=>o.get(p)===void 0||o.get(p).status==="completed"),i=new Map;e.filter(r).sort(pt).forEach((d,p)=>i.set(d.slug,p));const u=Rt(e,s.sessions,e),l=[];for(const d of u){const p=Te(d.nodes),h=new Set(p.map(g=>g.row.slug)),b=new Map(p.map(g=>[g.row.slug,g])),x=[];for(const g of Fs(p,h)){const v=new Set(g.map(C=>C.row.slug)),D=new Map,M=new Set,T=C=>{const k=b.get(C);return(k.row.dependsOn??[]).filter(L=>v.has(L)&&!(k.cycle&&b.get(L).cycle))},m=C=>{const k=D.get(C);if(k!==void 0)return k;if(M.has(C))return 0;M.add(C);let L=0;for(const F of T(C))L=Math.max(L,m(F));return M.delete(C),D.set(C,L+1),L+1};for(const C of g)m(C.row.slug);const R=g.map(C=>{const k=C.row,L=(k.dependsOn??[]).filter(F=>h.has(F));return{slug:k.slug,title:k.title,status:k.status,stage:D.get(k.slug),prdNumber:ne(k.slug),rowKind:"dep",rowTrailing:"",cycle:C.cycle,estimateMinutes:k.estimateMinutes??null,deps:L,crossEpicDeps:(k.dependsOn??[]).filter(F=>!h.has(F)),blockers:C.blockers,job:k}});R.sort(pt);const N=R.reduce((C,k)=>Math.max(C,k.stage),0),A=new Map;for(const C of R){const k=C.job,L=b.get(C.slug),F=k.status;let B;if(Ue(F)){const $=k.startedAt&&k.finishedAt?Date.parse(k.finishedAt)-Date.parse(k.startedAt):NaN;B={kind:"done",trailing:$>0?Et($):"",held:!1,blocked:!1}}else if(Ne(F)){const $=k.startedAt?Math.max(0,n-Date.parse(k.startedAt)):null;B={kind:"running",trailing:$===null?"":_t(k,$),held:!1,blocked:!1}}else if(F==="failed")B={kind:"failed",trailing:"failed",held:!1,blocked:!1};else if(F==="needs_review")B={kind:"review",trailing:"review",held:!1,blocked:!1};else if(F==="quarantined")B={kind:"quarantined",trailing:"quarantined",held:!1,blocked:!1};else{const $=L.blockers.filter(I=>!I.missing&&I.status!=="completed");if($.length>0){const I=$.some(Q=>Rs(Q.status)),O=$[0].slug;B={kind:"dep",trailing:`←${ne(O)??O}`,held:!I,blocked:I}}else if(k.heldReason)B={kind:"gate",trailing:"gate",held:!0,blocked:!1};else{const I=Es(k),O=i.get(k.slug)??0;B=I>0?{kind:"retry",trailing:`${I} ${I===1?"retry":"retries"}`,held:!1,blocked:!1}:{kind:"eta",trailing:Tt(O*a/c),held:!1,blocked:!1}}}A.set(C.slug,B)}const U=[];for(let C=1;C<=N;C++){const k=R.filter(G=>G.stage===C),L=k.find(G=>{const w=A.get(G.slug).kind;return G.status==="pending"&&(w==="eta"||w==="retry")});if(L){const G=A.get(L.slug);G.kind="next",G.trailing="next"}let F=0,B=0,$=0,I=0,O=0,Q=0;for(const G of k){const w=A.get(G.slug);G.rowKind=w.kind,G.rowTrailing=w.trailing,Ue(G.status)?F++:Ne(G.status)?B++:G.status==="pending"?(O++,w.held&&$++,w.blocked&&I++):It(G.status)&&Q++}const z=F===k.length?"done":B>0?"running":I+Q>0?"blocked":$>0?"held":"pending",Z={n:C,rows:k,doneCount:F,runningCount:B,heldCount:$,blockedCount:I};U.push({...Z,state:z,summary:_s(z,Z,O,Q)})}let K=0;for(const C of R){const k=C.estimateMinutes?C.estimateMinutes*6e4:a;if(C.status==="pending")K+=k;else if(Ne(C.status)){const L=C.job.startedAt?Math.max(0,n-Date.parse(C.job.startedAt)):0;K+=Math.max(0,k-L)}}const Y=R.reduce((C,k)=>Math.min(C,We(k.slug)),1/0);x.push({epicId:d.epicId,waveIndex:0,index:0,label:d.known?ns(d.label).title:d.label,status:Ts(R),prdCount:R.length,stageCount:N,doneCount:U.reduce((C,k)=>C+k.doneCount,0),runningCount:U.reduce((C,k)=>C+k.runningCount,0),heldCount:U.reduce((C,k)=>C+k.heldCount,0),blockedCount:U.reduce((C,k)=>C+k.blockedCount,0),etaMs:K/c,stages:U,_firstNum:Y,_firstSlug:R[0].slug})}x.sort(Os),x.forEach((g,v)=>{g.waveIndex=v+1,x.length>1&&(g.label=`${g.label} · plan ${v+1}/${x.length}`),l.push(g)})}return l.sort((d,p)=>{if(d._firstNum!==p._firstNum)return d._firstNum<p._firstNum?-1:1;const h=(d.epicId??"").localeCompare(p.epicId??"");return h!==0?h:d.waveIndex-p.waveIndex}),l.map(({_firstNum:d,_firstSlug:p,...h},b)=>({...h,index:b+1}))}function qs(e,s=Date.now()){const n=new Map(e.map(h=>[h.slug,h])),a=new Date(s).toDateString();let c=0,o=0,r=0,i=0,u=0,l=0,d=0;for(const h of e)h.status==="pending"?(o++,(h.dependsOn??[]).every(x=>n.get(x)===void 0||n.get(x).status==="completed")&&c++):Ne(h.status)?d++:h.status==="failed"?r++:h.status==="needs_review"?i++:h.status==="quarantined"?u++:h.status==="completed"&&h.finishedAt&&new Date(Date.parse(h.finishedAt)).toDateString()===a&&l++;let p=null;if(r+i+u>0){for(const h of Ze(e,{sessions:{},now:s}))for(const b of h.stages)if(b.rows.some(x=>It(x.status))){(p===null||b.n<p)&&(p=b.n);break}}return{readyNow:c,totalQueued:o,heldByDeps:o-c,needsYou:r+i+u,needsYouStage:p,failedCount:r,needsReviewCount:i,doneToday:l,inFlight:d}}function Bs(e){const s=new Map;for(const u of e.stages)for(const l of u.rows)s.set(l.slug,l);const n=u=>{var l;return((l=s.get(u))==null?void 0:l.cycle)===!0},a=new Map,c=new Set,o=(u,l)=>u.chain.length!==l.chain.length?u.chain.length>l.chain.length:u.est!==l.est?u.est>l.est:u.chain.join("\0")<l.chain.join("\0"),r=u=>{const l=a.get(u);if(l)return l;const d=s.get(u),p=d.estimateMinutes??0;if(c.has(u))return{chain:[u],est:p};c.add(u);let h=null;for(const x of d.deps){if(!s.has(x)||d.cycle&&n(x))continue;const g=r(x);(!h||o(g,h))&&(h=g)}c.delete(u);const b=h?{chain:[...h.chain,u],est:h.est+p}:{chain:[u],est:p};return a.set(u,b),b};let i=null;for(const u of s.keys()){const l=r(u);(!i||o(l,i))&&(i=l)}return i?i.chain:[]}function Ot({snap:e,now:s,avgDurationMs:n,runningJobs:a}){const{config:c,jobs:o,paused:r,nextReset:i,utilization:u,effectiveConcurrency:l}=e;let d=0,p=0;for(const D of o)D.status==="pending"?d++:D.status==="completed"&&p++;const h=a.length,b=d+h,x=(l==null?void 0:l.cap)??5;if(h>0){const D=a.reduce((N,A)=>(N.startedAt??"")<(A.startedAt??"")?N:A),M=D.startedAt?s-Date.parse(D.startedAt):0,T=p+h,m=p+b,R=h>1?` · ${h}/${x} parallel`:"";return{kind:"running",line1:`Running ${T}/${m}${R} · ${ke(M)}`,line2:h===1?D.title:a.map(N=>N.title).join(", "),tooltip:a.map(N=>`${N.slug} (g${N.parallelGroup})`).join("; ")}}if(r){const D=r.resumeAt?Date.parse(r.resumeAt)-s:null;return{kind:"paused",line1:{rate_limit:"Paused — tokens exhausted",auth:"Paused — authentication failed",network:"Paused — network unreachable",reset_failure:"Paused — billing data unavailable",manual:"Paused — manual (you paused the queue)"}[r.reason]??`Paused — ${r.reason}`,line2:r.reason==="auth"?"Run `claude` in any terminal to refresh credentials, then Resume":D!==null&&D>0?`auto-resume ${ae(Date.parse(r.resumeAt))} (in ${X(D)})`:r.resumeAt?"resuming…":"no auto-resume scheduled",tooltip:r.resumeAt??"",action:{label:"Resume",onClick:()=>window.api.schedule.resume(),title:"Clear the pause and resume queue immediately"}}}if(b===0)return{kind:"idle",line1:"No work queued",line2:null};const g=c.firePolicy??"when-available";if(g==="manual")return{kind:"manual",line1:`Manual · ${d} pending`,line2:"click Fire next batch now to fire",action:{label:"Fire next batch now",onClick:()=>window.api.schedule.forceTick().then(V.fromOutcome).catch(()=>V.error("Failed to fire batch")),title:"Bypasses the billing-usage poll. Use when the meter is rate-limited or you want immediate progress."}};if(g==="on-reset"){if(!i)return{kind:"on-reset",line1:"On-reset · waiting for billing data",line2:null};const D=Date.parse(i)+c.offsetMinutes*6e4,M=D-s;return{kind:"on-reset",line1:`On-reset · ${d} pending`,line2:M>0?`fires ${ae(D)} (in ${X(M)})`:"firing now…"}}const v=c.utilizationThreshold??90;if(u==null)return{kind:"auto-soon",line1:`Auto · ${d} pending`,line2:"checking token availability…"};if(u>=v){const D=i?Date.parse(i)-s:null;return{kind:"auto-throttled",line1:`Auto · throttled (util ${u.toFixed(0)}% ≥ ${v}%)`,line2:D&&D>0?`next reset ${ae(Date.parse(i))} (in ${X(D)})`:"will fire when usage drops"}}return{kind:"auto-soon",line1:`Auto · ${d} pending · util ${u.toFixed(0)}%`,line2:"fires within 2 min (poll cycle)"}}const Hs=15e3,Gs=new Set(["failed","needs_review","quarantined"]);function ft(){var n;const s=Array.from(document.querySelectorAll("[data-job-row]")).find(a=>Gs.has(a.dataset.jobStatus??""));(n=s==null?void 0:s.scrollIntoView)==null||n.call(s,{block:"center",behavior:"smooth"})}function Vs(e,s){var n;switch(e.kind){case"paused":return`paused: scheduler is paused (${e.reason??"manual"})`;case"launch-blocked":return`launch-blocked: ${e.agentType} jobs can't launch${(n=e.block)!=null&&n.kind?` (${e.block.kind})`:""}`;case"idle":return"idle: 0 pending";case"saturated":{const a=s!=null?`, oldest ${X(s)}`:"";return`saturated: ${e.totalSlots??"?"} slot(s) busy${a}`}case"blocked":{const a=e.blockedChains.length;return`blocked: ${e.pending} pending, ${e.dispatchable} dispatchable — ${a} chain${a===1?"":"s"} stuck behind a failed/skipped dependency`}case"stalled":return`stalled: no dispatch attempt in ${e.idleMs!=null?X(e.idleMs):"?"} with ${e.dispatchable} dispatchable`;case"running":default:return`running: ${e.runningCount} in flight, ${e.pending} pending`}}function Us(e){const[s,n]=f.useState(null);return f.useEffect(()=>{let a=!0;const c=()=>{window.api.schedule.queueHealth(e).then(r=>{a&&n(r)}).catch(()=>{})};c();const o=setInterval(c,Hs);return()=>{a=!1,clearInterval(o)}},[e]),s}const Ws={running:{dot:"bg-sage",text:"text-sage-dark"},paused:{dot:"bg-amber-500",text:"text-amber-600"},idle:{dot:"bg-fg-faint",text:"text-fg-faint"}};function Js(e,s,n){return e==="paused"||e==="launch-blocked"?"paused":e==="running"||e==="saturated"?"running":e?"idle":s?"paused":n>0?"running":"idle"}function Ys(e){return e>=1e9?`${(e/1e9).toFixed(1)}B`:e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:String(e)}const qe="px-2.5 py-1.5 rounded border border-line text-[12.5px] font-medium text-fg-dim hover:text-fg hover:bg-bg-hi disabled:opacity-40 disabled:cursor-not-allowed whitespace-nowrap";function Ks(e,s,n){if(e==="auth")return"Scheduler paused: Claude sign-in expired or invalid. Restart the app or re-run `claude login`, then Resume.";if(e==="rate_limit"){if(s){const a=new Date(s).getTime()-n;return a>0?`Paused for rate limit — resumes in ${X(a)}`:"Paused for rate limit — resume pending"}return"Paused for rate limit"}return e==="network"?"Paused: billing endpoint unreachable for 30+ min.":e==="manual"?"Scheduler paused manually — no new jobs start; running jobs continue. Click Resume to restart.":`Scheduler paused (${e})`}function Qs({now:e}){const s=Ie(d=>d.snapshot);if(!s)return null;const n=s.paused,a=Object.entries(s.launchBlocks??{}),c=Object.entries(s.launchMitigations??{}),o=(n==null?void 0:n.reason)==="auth"||(n==null?void 0:n.reason)==="network",r="flex items-start gap-3 border-b px-0 py-1.5 text-[12.5px]",i="bg-red-950/10 border-red-700/30 text-red-800",u="bg-amber-400/10 border-amber-600/30 text-amber-700",l="shrink-0 px-2 py-0.5 rounded border border-current/40 hover:bg-white/20 text-[12px] font-medium";return t.jsxs(t.Fragment,{children:[n&&t.jsxs("div",{"data-testid":"pause-banner",className:`${r} ${o?i:u}`,children:[t.jsx("span",{className:"flex-1 leading-snug",children:Ks(n.reason,n.resumeAt,e)}),t.jsx("button",{type:"button",onClick:()=>window.api.schedule.resume(),className:l,children:"Resume"})]}),a.map(([d,p])=>t.jsxs("div",{"data-testid":"launch-block-banner",className:`${r} ${i}`,children:[t.jsxs("div",{className:"flex-1 leading-snug min-w-0",children:[t.jsxs("div",{className:"font-medium",children:["Launches for ",t.jsx("span",{className:"font-mono",children:d})," jobs are failing before any work starts",p.httpStatus?` (HTTP ${p.httpStatus}, ${p.kind})`:` (${p.kind})`,p.exhausted?" — held until the Claude CLI version changes or you press Retry now.":p.until?` — next automatic probe ${new Date(p.until).getTime()>e?`in ${X(new Date(p.until).getTime()-e)}`:"on the next tick"}.`:"."]}),t.jsx("div",{className:"opacity-80",children:p.hint}),t.jsxs("div",{className:"font-mono text-[11.5px] opacity-70 truncate",title:p.message,children:[p.attempts," failed probe",p.attempts===1?"":"s",p.claudeVersion?` · CLI ${p.claudeVersion}`:"",p.lastSlug?` · last: ${p.lastSlug}`:""," · ",p.message]})]}),t.jsx("button",{type:"button",onClick:()=>window.api.schedule.resume(),className:l,children:"Retry now"})]},`launch-block-${d}`)),c.map(([d,p])=>t.jsx("div",{"data-testid":"launch-mitigation-banner",className:`${r} ${u}`,children:t.jsxs("div",{className:"flex-1 leading-snug min-w-0",children:[t.jsxs("div",{className:"font-medium",children:[t.jsx("span",{className:"font-mono",children:d})," jobs are running in degraded mode"," ","(",t.jsx("span",{className:"font-mono",children:Object.entries(p.env).map(([h,b])=>`${h}=${b}`).join(" ")}),")",p.claudeVersion?` since CLI ${p.claudeVersion}`:"","."]}),t.jsx("div",{className:"opacity-80",children:p.hint})]})},`launch-mitigation-${d}`))]})}function zs({scopeCwd:e,subView:s,onSubView:n,filterText:a,onFilterText:c,planMode:o,onPlanMode:r,planToolsRef:i}){const u=Ie(y=>y.snapshot),l=ce(y=>y.sessions),d=Us(e),[p,h]=f.useState(()=>Date.now()),[b,x]=f.useState("—");f.useEffect(()=>{const y=setInterval(()=>h(Date.now()),3e4);return()=>clearInterval(y)},[]),f.useEffect(()=>{let y=!0;return as(Promise.resolve().then(()=>window.api.history.dashboard({rangeDays:30})),5e3,"history.dashboard").then(_=>{if(!y)return;const P=_.totals,W=P.inputTokens+P.outputTokens+P.cacheReadTokens+P.cacheCreationTokens;x(`$${P.estimatedCostUsd.toFixed(2)} · ${Ys(W)} tok`)}).catch(()=>{}),()=>{y=!1}},[]);const g=f.useMemo(()=>((u==null?void 0:u.jobs)??[]).filter(y=>!e||y.cwd===e),[u,e]),v=f.useMemo(()=>qs(g,p),[g,p]),D=f.useMemo(()=>{const y=Ze(g,{sessions:l,now:p}),_=P=>y.filter(W=>W.status===P).length;return{active:_("active"),queued:_("queued"),draft:_("draft")}},[g,l,p]),M=f.useMemo(()=>{const y=new Date(p).toDateString(),_=[];for(const P of g)if(P.status==="completed"&&P.startedAt&&P.finishedAt&&new Date(Date.parse(P.finishedAt)).toDateString()===y){const W=Date.parse(P.finishedAt)-Date.parse(P.startedAt);W>0&&_.push(W)}return _.length?Math.round(_.reduce((P,W)=>P+W,0)/_.length/6e4):null},[g,p]);if(!u)return null;const T=d&&!d.unknown?d.verdict??null:null,m=d&&!d.unknown?d.slots??null:null,R=u.paused,N=Js((T==null?void 0:T.kind)??null,!!R,v.inFlight),A=Ws[N],U=g.filter(y=>y.status==="pending").length,K=g.filter(y=>y.status==="running").length,Y=Ot({snap:{...u,jobs:g},now:p,avgDurationMs:0,runningJobs:g.filter(y=>y.status==="running")}),C=d!=null&&d.unknown?`Queue health: unknown — ${d.reason??"state unavailable"}`:T?Vs(T,(d==null?void 0:d.oldestRunningAgeMs)??null):"queue health loading…",k=fe(u.lastRunAt?Date.parse(u.lastRunAt):null,p),L=d!=null&&d.lastDispatchAttemptAt?fe(Date.parse(d.lastDispatchAttemptAt),p):"never",F=[C,Y.line1,T?`dispatchable ${T.dispatchable} · needs_review ${T.needsReviewCount}`:null,(d==null?void 0:d.oldestRunningAgeMs)!=null?`oldest running ${X(d.oldestRunningAgeMs)} (any project)`:null,`last batch fired ${k} (lastRunAt — advances only when a job launches)`,`last dispatch attempt ${L} (advances on every driver evaluation)`].filter(Boolean).join(`
2
- `),B=u.utilization,$=u.pollHealth,I=$!=null&&!$.lastPollOk,O=u.nextReset?Date.parse(u.nextReset):null,Q=O?O>p?X(O-p):"soon":"—",z=u.effectiveConcurrency,Z=(z==null?void 0:z.cap)??5,G=(z==null?void 0:z.source)==="env",w=u.config.firePolicy??"when-available",S=U===0&&K===0;return t.jsxs("div",{"data-testid":"scheduler-top-bands",className:"shrink-0 px-[18px]",children:[t.jsxs(Fe,{height:40,testId:"queue-health-header",className:"gap-3",children:[t.jsx("h1",{className:"m-0 font-serif text-[21px] font-semibold leading-none tracking-tight text-fg",children:"Scheduler"}),t.jsx("span",{className:"w-px h-[20px] bg-rule-structural","aria-hidden":"true"}),t.jsxs("span",{className:`inline-flex items-center gap-1.5 text-[12.5px] font-medium ${A.text}`,"data-testid":"scheduler-state-word","data-state":N,children:[t.jsx("span",{className:`w-2 h-2 rounded-full ${A.dot}`,"aria-hidden":"true"}),N]}),t.jsxs("span",{className:"font-mono text-[12px] text-fg-faint whitespace-nowrap","data-testid":"scheduler-meta",children:[v.inFlight," in flight · ",v.heldByDeps," held · last batch ",k]}),t.jsxs(he,{title:F,testId:"scheduler-verdict-info",popoverTestId:"scheduler-info-popover",children:[t.jsx("pre",{className:"m-0 mb-2 whitespace-pre-wrap font-mono text-[11.5px] text-fg-dim",children:F}),rt.scheduler&&t.jsx(rs,{content:rt.scheduler})]}),t.jsxs("span",{className:"ml-auto flex items-center gap-2",children:[t.jsx("button",{type:"button",onClick:()=>window.api.schedule.rescan().then(V.fromOutcome).catch(()=>V.error("Failed to rescan")),title:"Re-scan the prds/ folder. Use when you've added or edited PRDs on disk and want the queue to reflect them immediately.",className:qe,children:"Refresh"}),R?t.jsx("button",{type:"button",onClick:()=>window.api.schedule.resume(),title:"Clear the pause and resume queue immediately",className:qe,children:"Resume"}):t.jsx("button",{type:"button",onClick:()=>window.api.schedule.pause(),title:"Stop NEW dispatch. Running jobs are not killed.",className:qe,children:"Pause"}),t.jsx("button",{type:"button",onClick:()=>window.api.schedule.forceTick().then(V.fromOutcome).catch(()=>V.error("Failed to fire batch")),disabled:S,title:"Bypasses the billing-usage poll. Use when the meter is rate-limited or you want immediate progress.",className:"px-3 py-1.5 rounded bg-accent text-white text-[12.5px] font-semibold whitespace-nowrap disabled:opacity-40 disabled:cursor-not-allowed hover:opacity-90",children:"Fire next batch"})]})]}),t.jsx(Qs,{now:p}),t.jsxs(Fe,{height:70,testId:"scheduler-kpi-band",children:[t.jsx(pe,{testId:"kpi-window",label:"Window used",info:I?`Billing poll failing — this reading may be outdated (last good reading ${fe($.lastPollAt,p)}). Machine-wide 5h window.`:"Share of the machine-wide 5h billing window consumed.",value:B==null?"—":`${Math.round(B)}%`,sub:`resets in ${Q}`,third:t.jsx(is,{pct:B??0,tone:I?"bg-amber-500":"bg-accent"})}),t.jsx(pe,{testId:"kpi-slots",label:"Slots",info:`Machine-wide session pool (${(m==null?void 0:m.source)==="env"?"SM_SESSION_SLOTS override":"Home tab cap"}), not scoped to this project`,value:m?`${m.inUse}/${m.total}`:"—",sub:"in use",third:m?t.jsx(ls,{filled:m.inUse,total:m.total}):null}),t.jsx(pe,{testId:"kpi-ready",label:"Ready now",info:"Pending rows whose dependsOn chain is fully satisfied right now",value:v.readyNow,sub:`of ${v.totalQueued} queued`,third:`${v.heldByDeps} held by deps`}),v.needsYou>0?t.jsx(pe,{testId:"kpi-needs-you",label:"Needs you",value:t.jsx("button",{type:"button","data-testid":"kpi-needs-you-jump",onClick:ft,className:"font-semibold text-accent hover:underline",title:"Scroll to the first failed / needs-review / quarantined row",children:v.needsYou}),sub:t.jsx("button",{type:"button",onClick:ft,className:"hover:underline",children:v.needsYouStage!=null?`blocking stage ${v.needsYouStage}`:"need attention"}),third:[v.failedCount>0&&`${v.failedCount} failed`,v.needsReviewCount>0&&`${v.needsReviewCount} needs review`,v.needsYou-v.failedCount-v.needsReviewCount>0&&`${v.needsYou-v.failedCount-v.needsReviewCount} quarantined`].filter(Boolean).join(" · ")}):t.jsx(pe,{testId:"kpi-needs-you",label:"Needs you",value:t.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[15px]",children:[t.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-sage","aria-hidden":"true"}),"all clear"]}),third:"0 failed · 0 needs review"}),t.jsx(pe,{testId:"kpi-done",label:"Done today",value:v.doneToday,sub:M!=null?`avg ${M}m`:"avg —",third:t.jsx("span",{"data-testid":"kpi-done-spend",children:b})}),t.jsx(pe,{testId:"kpi-concurrency",label:"Concurrency",info:"Start-jobs policy, concurrency cap and utilization threshold",infoTestId:"kpi-concurrency-info",infoAlignRight:!0,infoContent:t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-fg",children:"Start jobs"}),t.jsxs("select",{"data-testid":"kpi-fire-policy",value:w,onChange:y=>window.api.schedule.setConfig({firePolicy:y.target.value}),className:"border border-line bg-bg-hi rounded px-1 py-0.5 text-[12px] text-fg-dim",title:"when-available: poll usage and fire when tokens are below threshold. on-reset: fire after each 5h reset. manual: only on Run now.","aria-label":"Start jobs policy",children:[t.jsx("option",{value:"when-available",children:"when available"}),t.jsx("option",{value:"on-reset",children:"only on reset"}),t.jsx("option",{value:"manual",children:"manually"})]})]}),value:t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(ds,{value:Z,min:0,max:10,disabled:G,onChange:y=>{window.api.schedule.setSessionSlots(Math.max(0,Math.min(10,y)))},title:G?"pinned by SM_SESSION_SLOTS — unset the env var to edit":"Machine-wide claude -p session slots, shared with chat runs"}),G&&t.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-amber-600 bg-amber-400/10 border border-amber-400/30 rounded px-1 py-0",title:"Pinned by SM_SESSION_SLOTS — unset the env var to edit",children:"env"})]}),sub:"at once",third:w==="when-available"?t.jsxs("span",{children:["pause above"," ",t.jsx(os,{value:u.config.utilizationThreshold??90,min:0,max:100,testId:"kpi-threshold",title:"Fire only when 5h utilization is below this percent — click to edit",onCommit:y=>window.api.schedule.setConfig({utilizationThreshold:y})})]}):null})]}),t.jsxs(Fe,{height:30,testId:"scheduler-plans-toolbar",className:"gap-3",children:[t.jsx("span",{className:"text-[10.5px] font-semibold uppercase tracking-wide text-fg-faint",children:"Plans"}),t.jsxs("span",{className:"font-mono text-[12px] text-fg-faint whitespace-nowrap","data-testid":"scheduler-plans-meta",children:[D.active," active · ",D.queued," queued · ",D.draft," draft · ",g.length," PRDs"]}),t.jsxs("span",{className:"ml-auto flex items-center gap-3",children:[t.jsx("span",{ref:i,className:"contents","data-testid":"scheduler-plan-tools"}),t.jsx("input",{type:"text",value:a,onChange:y=>c(y.target.value),placeholder:"filter PRDs…","aria-label":"Filter PRDs by title, slug, or project","data-testid":"scheduler-filter-input",className:"w-[180px] bg-bg-hi border border-line rounded px-2 py-0.5 text-[12px] text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint"}),t.jsx("span",{className:"inline-flex border border-line rounded overflow-hidden",role:"group","aria-label":"Plan view mode",children:[["graph","Graph"],["list","List"],["critical","Critical path"]].map(([y,_])=>t.jsx("button",{type:"button","data-testid":`plan-mode-${y}`,"aria-pressed":o===y&&s==="queue",onClick:()=>{r(y),n("queue")},className:`px-2 py-0.5 text-[12px] ${o===y&&s==="queue"?"bg-bg-elev font-semibold text-fg":"text-fg-dim hover:text-fg"}`,children:_},y))}),t.jsx("span",{className:"w-px h-[16px] bg-rule-structural","aria-hidden":"true"}),[["prds","PRDs","Authored PRD source files on disk — edit, lint, archive, or queue them."],["history","History","The last 50 completed and failed jobs."],["machine","Machine","Machine-wide config that applies to every project — not this project’s live queue."]].map(([y,_,P])=>t.jsx("button",{type:"button",onClick:()=>n(y),"aria-pressed":s===y,title:P,className:`text-[12.5px] ${s===y?"font-semibold text-fg":"text-fg-faint hover:text-fg-dim"}`,children:_},y))]})]})]})}function Lt({options:e,value:s,onChange:n,pillPadding:a="px-3 py-1.5"}){return t.jsx("div",{className:"flex gap-1.5 flex-wrap",children:e.map(c=>{const o=c.value===s;return t.jsxs("button",{type:"button",onClick:()=>n(c.value),className:`rounded-full ${a} text-[12.5px] border transition-colors ${o?"bg-accent text-white border-accent font-semibold":"bg-bg-hi text-fg-dim border-line hover:border-fg-faint font-medium"}`,children:[c.label,c.count!==void 0&&t.jsxs("span",{children:[" ",c.count]})]},c.value)})})}function Ft(e,s=60){const n=e.trim();return n.length<=s?n:`${n.slice(0,s-1)}…`}function Xs(e){return Te([e]).filter(s=>s.children.length===0).map(s=>s.row.slug)}function qt(e){return e.nodes.map(s=>({rootSlug:s.row.slug,label:s.row.title||s.row.slug,terminals:Xs(s)}))}function Zs(e){const s=new Map;for(const n of e){const a=qt(n);n.nodes.forEach((c,o)=>{const r=a.filter((i,u)=>u!==o);for(const i of Te([c]))s.set(i.row.slug,r)})}return s}function Bt({job:e,headChoices:s}){const[n,a]=f.useState(!1),c=f.useCallback((o,r)=>{a(!0),window.api.schedule.setPrdDisposition({slug:e.slug,cwd:e.cwd??void 0,disposition:o,dependsOn:r}).then(V.fromOutcome).catch(()=>V.error("Failed to change disposition")).finally(()=>a(!1))},[e.slug,e.cwd]);return e.disposition!=="append"&&s.length===0?null:t.jsxs("select",{"data-testid":"job-row-disposition-control",disabled:n,value:"",onChange:o=>{const r=o.target.value;if(r==="__new-head__")c("new-head");else if(r){const i=s.find(u=>u.rootSlug===r);i&&c("append",i.terminals)}},className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border border-line/60 rounded px-1.5 py-0.5 cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed",title:"Change this wave's relationship to the rest of the Epic's plan",children:[t.jsx("option",{value:"",disabled:!0,children:"change disposition…"}),e.disposition==="append"&&t.jsx("option",{value:"__new-head__",children:"promote to new head"}),s.map(o=>t.jsxs("option",{value:o.rootSlug,children:["attach behind: ",Ft(o.label,40)]},o.rootSlug))]})}function en(e,s,n=null){if(s.length===0||e.length===0)return e;const a=new Set,c=new Set;for(const r of e){a.add(r.slug);for(const i of it(r))c.add(i)}const o=[];for(const r of s)r.archived!==!0||a.has(r.slug)||n&&r.cwd!==n||it(r).some(i=>c.has(i))&&(a.add(r.slug),o.push({slug:r.slug,title:r.title,cwd:r.cwd,parallelGroup:r.parallelGroup,estimateMinutes:r.estimateMinutes,bodyPreview:"",status:r.archivedStatus??"completed",runId:null,startedAt:null,finishedAt:null,exitCode:null,error:null,dependsOn:r.dependsOn??void 0,sourcePromptId:r.sourcePromptId??null,epicId:r.epicId??null,synthetic:!0}));return o.length===0?e:[...e,...o]}const tn=[],sn=new Set(["failed","needs_review","quarantined"]);function nn(e){switch(e.status){case"completed":case"skipped":return"bg-sage";case"running":case"investigating":return"bg-accent";case"failed":return"bg-accent";case"needs_review":return"bg-butter";case"quarantined":return"bg-butter/60";default:return e.rowKind==="eta"||e.rowKind==="next"||e.rowKind==="retry"?"border border-fg-faint bg-transparent":"bg-fg-faint/40"}}function an(e){switch(e.status){case"running":case"investigating":return"bg-butter/10";case"failed":return"bg-accent/10";case"needs_review":return"bg-butter/25";default:return""}}function rn(e){switch(e.rowKind){case"running":case"dep":case"failed":return"text-accent";case"review":return"text-butter font-semibold";default:return"text-fg-faint"}}function ln({row:e,elapsedMs:s,listIndex:n,onFocused:a,headChoices:c=tn}){const[o,r]=f.useState(!1),i=e.job,u=s!==null&&e.rowKind==="running"?_t(i,s):e.rowTrailing,l=e.status==="completed"||e.status==="skipped",d=e.rowKind==="dep"&&e.blockers.some(h=>!h.missing&&h.status!==null&&sn.has(h.status)),p=l||d;return t.jsxs("div",{role:"listitem","data-testid":"prd-row","data-slug":e.slug,className:"border-t border-rule-inner first:border-t-0",children:[t.jsxs("button",{type:"button","data-job-row":!0,"data-job-status":i.status,"data-job-index":n,onClick:()=>r(h=>!h),onFocus:()=>a(n),"aria-expanded":o,"aria-label":`${e.prdNumber?`PRD ${e.prdNumber}, `:""}${i.title}, ${i.status}${u?`, ${u}`:""}`,title:i.title,className:`w-full h-[31px] py-1 px-2 text-left flex items-center gap-1.5 hover:bg-bg/40 focus:outline-none focus:ring-1 focus:ring-accent focus:ring-inset ${an(e)}`,children:[t.jsx("span",{"aria-hidden":"true",className:`shrink-0 w-[7px] h-[7px] rounded-full ${nn(e)}`}),t.jsx("span",{className:"shrink-0 font-mono text-[10.5px] text-fg-faint w-[30px]",children:e.prdNumber?`#${e.prdNumber}`:""}),t.jsx("span",{className:`flex-1 min-w-0 truncate text-[12.5px] leading-tight ${p?"text-fg-faint":"text-fg font-medium"}`,children:i.title}),t.jsx("span",{"data-testid":"prd-row-trailing",className:`shrink-0 font-mono text-[10.5px] ${rn(e)}`,children:u})]}),o&&t.jsx(on,{row:e,elapsedMs:s,headChoices:c})]})}const Ht=f.memo(ln);function on({row:e,elapsedMs:s,headChoices:n}){const a=e.job,[c,o]=f.useState(!1),r=ce(b=>b.sessions),i=f.useMemo(()=>Ce(a,r),[a,r]),u=i.known&&i.epicId?r[i.epicId]:null,l=f.useCallback(b=>St(b),[]),d="font-mono text-[11.5px] text-fg-dim leading-snug break-words",p="text-[12px] font-semibold bg-transparent border-0 cursor-pointer p-0",h=a.error?a.error.split(`
3
- `)[0]:null;return t.jsxs("div",{"data-testid":"prd-row-detail",className:"px-3 py-2 bg-bg-elev/50 border-t border-rule-inner flex flex-col gap-1",children:[t.jsxs("div",{className:d,children:[a.status.replace(/_/g," "),a.exitCode!==null&&` · exit ${a.exitCode}`,a.verifierVerdict&&` · ${Se(a.verifierVerdict)}`,a.startedAt&&` · started ${ae(Date.parse(a.startedAt))}`,a.finishedAt&&` · finished ${ae(Date.parse(a.finishedAt))}`,s===null&&e.rowTrailing&&e.rowKind==="done"?` · took ${e.rowTrailing}`:""]}),e.cycle&&t.jsxs("div",{className:`${d} text-accent`,"data-testid":"job-row-cycle-warning",children:["⚠ dependsOn cycle — ",e.blockers.map(b=>b.slug).join(" ↔ ")||"self-referencing"]}),!e.cycle&&e.blockers.length>0&&t.jsxs("div",{className:d,"data-testid":"job-row-blockers",children:["depends on ",e.blockers.map(b=>`${b.slug} (${b.missing?"missing":(b.status??"unknown").replace(/_/g," ")})`).join(", ")]}),a.status==="pending"&&a.heldReason&&t.jsxs("div",{className:`${d} text-amber-400/90`,"data-testid":"job-row-held-reason",children:["held · ",a.heldReason]}),h&&t.jsx("div",{className:`${d} text-accent/80`,children:h}),!a.synthetic&&t.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 pt-0.5",children:[u&&t.jsx("button",{type:"button","data-testid":"job-row-prompt-session-link",title:u.goalText,onClick:()=>l(u.id),className:`${p} text-accent hover:text-accent/80`,children:"view epic →"}),a.runId&&t.jsx("button",{type:"button",onClick:()=>o(!0),className:`${p} text-fg-dim hover:text-fg`,children:"view log →"}),a.status==="quarantined"&&t.jsx("button",{type:"button","data-testid":"job-row-adopt-prd",title:"Stamp this PRD's provenance so the scheduler will run it — no unstamped PRD runs automatically.",onClick:()=>{window.api.schedule.adoptPrd(a.slug).then(V.fromOutcome).catch(()=>V.error("Failed to adopt PRD"))},className:`${p} text-accent hover:text-accent/80`,children:"adopt PRD →"}),a.status!=="pending"&&a.status!=="running"&&a.status!=="quarantined"&&t.jsx("button",{type:"button",onClick:()=>window.api.schedule.resetJob(a.slug),className:`${p} text-fg-dim hover:text-fg`,children:"reset to pending →"}),a.disposition&&(a.status==="pending"||a.status==="quarantined")&&t.jsx(Bt,{job:a,headChoices:n})]}),c&&a.runId&&t.jsx(Ee,{runId:a.runId,slug:a.slug,title:a.title||a.slug,onClose:()=>o(!1)})]})}const de=190,dn=7,cn=5,un=[],Gt=e=>e==="completed"||e==="skipped",Vt=e=>e==="running"||e==="investigating",Ut=e=>e==="failed"||e==="needs_review"||e==="quarantined";function De(e){return Vt(e.status)?0:Ut(e.status)?1:Gt(e.status)?3:2}const pn={done:"text-sage",running:"text-accent",held:"text-fg-faint",pending:"text-fg-faint",blocked:"text-butter"},fn={done:"bg-sage",running:"bg-accent",held:"bg-fg-faint/50",pending:"bg-fg-faint/50",blocked:"bg-butter"};function hn(e,s){return e.every(n=>Gt(n.status))?`+${e.length} done`:e.every(n=>n.rowKind==="dep"&&n.blockers.some(a=>!a.missing&&a.status!==null&&Ut(a.status)))?`+${e.length} blocked`:`+${e.length} in stage ${s}`}function xn({stage:e,epicId:s,now:n,hidden:a,indexBySlug:c,headChoicesBySlug:o,onRowFocused:r}){const[i,u]=f.useState(!1),l=f.useMemo(()=>e.rows.filter(m=>!(a.has(m.slug)&&(m.status==="completed"||m.status==="failed"))).map((m,R)=>({r:m,i:R})).sort((m,R)=>De(m.r)-De(R.r)||m.i-R.i).map(m=>m.r),[e.rows,a]),d=f.useMemo(()=>l.filter(m=>De(m)<=1).length,[l]),p=Math.max(e.state==="done"?cn:dn,d),h=i?l:l.slice(0,p),b=i?[]:l.slice(p),x=l.find(m=>m.status==="failed"),g=l.find(m=>m.status==="needs_review"),v=d>0&&(x!==void 0||g!==void 0),D=h.reduce((m,R,N)=>De(R)<=1?N:m,-1),M=m=>t.jsx(Ht,{row:m,elapsedMs:Vt(m.status)&&m.job.startedAt?n-Date.parse(m.job.startedAt):null,listIndex:c.get(m.slug)??0,onFocused:r,headChoices:o.get(m.slug)??un},m.slug),T="flex-1 min-w-0 truncate h-[24px] text-[11.5px] font-medium text-fg-dim hover:text-fg border border-rule-structural rounded-sm bg-transparent cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed";return t.jsxs("div",{"data-testid":"stage-column","data-stage":e.n,style:{width:de},className:"shrink-0 border-l border-rule-structural first:border-l-0 flex flex-col self-stretch",children:[t.jsxs("div",{className:"h-[30px] shrink-0 flex items-center gap-1.5 px-2 border-b border-rule-inner","data-testid":"stage-header",children:[t.jsx("span",{"aria-hidden":"true",className:`w-[7px] h-[7px] rounded-full shrink-0 ${fn[e.state]}`}),t.jsxs("span",{className:`text-[10px] font-semibold uppercase tracking-wide ${pn[e.state]}`,children:["Stage ",e.n]}),e.state==="blocked"&&t.jsx(he,{title:"Rows in this stage are failed / need review / are quarantined, or wait on one that is."}),t.jsx("span",{"data-testid":"stage-summary",className:"ml-auto font-mono text-[10.5px] text-fg-dim truncate",children:e.summary})]}),t.jsx("div",{role:"presentation",children:h.map((m,R)=>t.jsxs("div",{children:[M(m),v&&R===D&&t.jsxs("div",{"data-testid":"stage-attention-actions",className:"flex gap-1.5 px-2 py-1.5 border-t border-rule-inner",children:[x&&t.jsxs("button",{type:"button","data-testid":"stage-retry",title:`Reset ${x.slug} to pending`,onClick:()=>{window.api.schedule.resetJob(x.slug).then(N=>{N.ok||V.error(N.error??`Failed to reset ${x.slug}`)}).catch(()=>V.error(`Failed to reset ${x.slug}`))},className:T,children:["Retry ",x.prdNumber?`#${x.prdNumber}`:x.slug]}),g&&t.jsxs("button",{type:"button","data-testid":"stage-review",disabled:!s,title:s?"Open the authoring Epic — a needs_review PRD is a question routed back to it":"No authoring Epic recorded for this plan",onClick:()=>{s&&St(s)},className:T,children:["Review ",g.prdNumber?`#${g.prdNumber}`:g.slug]})]})]},m.slug))}),(b.length>0||i&&l.length>p)&&t.jsx("button",{type:"button","data-testid":"stage-footer","aria-expanded":i,onClick:()=>u(m=>!m),className:"mt-auto h-[26px] border-t border-rule-inner font-mono text-[11px] text-fg-faint hover:text-fg-dim bg-transparent cursor-pointer",children:i?"show less ▴":`${hn(b,e.n)} ▾`})]})}const me=6,Be=4,Me=4,ht=12,xt=5,Wt=2,gt=4,gn={done:"bg-sage",running:"bg-accent",attention:"bg-butter",failed:"bg-red-600",pending:"bg-fg-faint/50"};function mn(e){return e==="completed"||e==="skipped"?"done":e==="running"||e==="investigating"?"running":e==="failed"?"failed":e==="needs_review"||e==="quarantined"?"attention":"pending"}function bn(e){const s=[],n=[],a=[];let c=xt;for(const o of e){const r=Math.max(1,Math.ceil(o.rows.length/Me));n.push(c),a.push(r*me),o.rows.forEach((i,u)=>{s.push({x:c+Math.floor(u/Me)*me,y:Wt+u%Me*me,tone:mn(i.status),title:`${i.prdNumber?`#${i.prdNumber}`:i.slug} ${i.title} — ${i.status}`})}),c+=r*me+ht}return{dots:s,stageX:n,stageW:a,width:Math.max(0,c-ht)+xt}}function be(e,s){return e.findIndex(n=>n.rows.some(a=>s(a.status)))}const Je=e=>e==="running"||e==="investigating",Ye=e=>e==="failed"||e==="needs_review"||e==="quarantined";function wn({stages:e,first:s,perView:n,onSeek:a}){const c=f.useMemo(()=>bn(e),[e]),o=f.useMemo(()=>be(e,Je)>=0,[e]),r=f.useMemo(()=>be(e,Ye)>=0,[e]),i=f.useRef(!1),u=e.length,l=Math.min(u-1,s+n-1),d=c.stageX[Math.min(s,u-1)]??0,p=(c.stageX[l]??0)+(c.stageW[l]??0),h=x=>{const g=x.currentTarget.getBoundingClientRect(),v=x.clientX-g.left;let D=0;for(let M=0;M<u;M++)c.stageX[M]<=v&&(D=M);a(Math.max(0,Math.min(u-1,D-Math.floor(n/2))))},b="px-2 h-[20px] text-[11.5px] disabled:opacity-40 disabled:cursor-not-allowed";return t.jsxs("div",{"data-testid":"plan-minimap",className:"h-[28px] flex items-center gap-3 px-3 border-t border-rule-inner",children:[t.jsxs("span",{className:"shrink-0 flex items-center gap-1 text-[10.5px] font-semibold uppercase tracking-wide text-fg-faint",children:["Whole graph",t.jsx(he,{title:"Every PRD in this plan as one dot, grouped by stage. The rust box is the range of stages shown below — drag it to scroll."})]}),t.jsxs("div",{"data-testid":"plan-minimap-dots",role:"presentation",className:"relative shrink min-w-0 overflow-hidden cursor-ew-resize touch-none",style:{width:c.width,height:Me*me-(me-Be)+2*Wt},onPointerDown:x=>{var g,v;i.current=!0,(v=(g=x.currentTarget).setPointerCapture)==null||v.call(g,x.pointerId),h(x)},onPointerMove:x=>{i.current&&h(x)},onPointerUp:()=>{i.current=!1},onPointerCancel:()=>{i.current=!1},children:[c.dots.map((x,g)=>t.jsx("span",{title:x.title,"data-tone":x.tone,className:`absolute rounded-[1px] ${gn[x.tone]}`,style:{left:x.x,top:x.y,width:Be,height:Be}},g)),t.jsx("span",{"data-testid":"plan-minimap-brush","aria-hidden":"true",className:"absolute top-0 bottom-0 border border-accent bg-accent/10 rounded-[2px] pointer-events-none",style:{left:d-gt,width:p-d+2*gt}})]}),t.jsxs("span",{className:"ml-auto shrink-0 font-mono text-[11.5px] text-fg-faint","data-testid":"plan-minimap-range",children:["stages ",Math.min(s+1,u),"–",l+1," of ",u]}),t.jsxs("span",{className:"shrink-0 inline-flex border border-line rounded overflow-hidden",role:"group","aria-label":"Jump the stage window",children:[t.jsx("button",{type:"button","data-testid":"minimap-running",disabled:!o,title:o?"Scroll to the lowest stage with a running PRD":"No stage has a running PRD",onClick:()=>a(be(e,Je)),className:`${b} text-fg-dim hover:text-fg`,children:"Running"}),t.jsx("button",{type:"button","data-testid":"minimap-blockers",disabled:!r,title:r?"Scroll to the lowest stage with a failed / needs-review / quarantined PRD":"No stage has a failed, needs-review or quarantined PRD",onClick:()=>a(be(e,Ye)),className:`${b} text-fg-dim hover:text-fg border-l border-line`,children:"Blockers"})]})]})}const vn=148;function jn({stages:e,onSeek:s}){if(e.length===0)return null;const n=e[0].n,a=e[e.length-1].n;return t.jsxs("div",{"data-testid":"further-stages",style:{width:vn},className:"shrink-0 border-l border-rule-structural flex flex-col",children:[t.jsxs("div",{className:"h-[30px] shrink-0 flex items-center px-2 border-b border-rule-inner text-[10.5px] font-semibold uppercase tracking-wide text-fg-faint",children:["Stage ",n,"–",a]}),t.jsxs("div",{className:"h-[22px] shrink-0 flex items-center gap-1 px-2 text-[10.5px] font-semibold uppercase tracking-wide text-fg-faint",children:["Further stages",t.jsx(he,{title:"Stages beyond the visible window. Click one to scroll the stage columns to it."})]}),e.map(c=>{const o=c.rows.length===0?0:c.doneCount/c.rows.length*100;return t.jsxs("button",{type:"button","data-testid":"further-stage-row","data-stage":c.n,title:`${c.summary} — scroll to stage ${c.n}`,onClick:()=>s(c.n-1),className:"h-[26px] px-2 flex items-center gap-2 border-t border-rule-inner bg-transparent hover:bg-bg-hi cursor-pointer text-left",children:[t.jsxs("span",{className:"font-mono text-[10.5px] text-fg-dim w-[50px] whitespace-nowrap shrink-0",children:["stage ",c.n]}),t.jsx("span",{role:"progressbar","aria-valuenow":c.doneCount,"aria-valuemin":0,"aria-valuemax":c.rows.length,className:"flex-1 h-[4px] rounded-sm bg-rule-inner overflow-hidden",children:t.jsx("span",{className:"block h-full bg-sage",style:{width:`${o}%`}})})]},c.n)})]})}const yn=[],Nn=e=>e==="running"||e==="investigating";function kn(e){const s=Bs(e),n=new Map,a=new Map;for(const i of e.stages){a.set(i.n,i.rows.length);for(const u of i.rows)n.set(u.slug,u)}const c=new Map;let o=0;const r=[];for(const i of s){const u=n.get(i);o+=u.estimateMinutes??0,c.set(u.stage,(c.get(u.stage)??0)+1),r.push({row:u,totalMinutes:o,othersInStage:0})}for(const i of r)i.othersInStage=(a.get(i.row.stage)??0)-(c.get(i.row.stage)??0);return r}function Sn({plan:e,now:s,indexBySlug:n,headChoicesBySlug:a,onRowFocused:c}){const o=f.useMemo(()=>kn(e),[e]);return t.jsx("div",{"data-testid":"critical-path",className:"border-t border-rule-structural max-w-[640px]",children:o.map(({row:r,totalMinutes:i,othersInStage:u})=>t.jsxs("div",{"data-testid":"critical-entry","data-slug":r.slug,children:[t.jsxs("div",{className:"flex items-start",children:[t.jsx("div",{className:"flex-1 min-w-0",children:t.jsx(Ht,{row:r,elapsedMs:Nn(r.status)&&r.job.startedAt?s-Date.parse(r.job.startedAt):null,listIndex:n.get(r.slug)??0,onFocused:c,headChoices:a.get(r.slug)??yn})}),t.jsxs("span",{"data-testid":"critical-est",className:"shrink-0 h-[31px] px-3 flex items-center gap-2 font-mono text-[11.5px] text-fg-faint border-t border-rule-inner",children:[t.jsx("span",{title:"estimateMinutes",children:r.estimateMinutes?`${r.estimateMinutes}m`:"—"}),t.jsxs("span",{className:"text-fg-dim",title:"Running total along the chain",children:["Σ ",i,"m"]})]})]}),u>0&&t.jsxs("div",{"data-testid":"critical-others",className:"h-[22px] px-3 flex items-center font-mono text-[11.5px] text-fg-faint border-t border-rule-inner",children:["stage ",r.stage," · +",u," not on the critical path"]})]},r.slug))})}const mt=1,bt=1350,Cn={active:"border-l-accent",queued:"border-l-rule-structural",done:"border-l-sage",draft:"border-l-fg-faint/40 border-dashed"},$n={active:{label:"ACTIVE",cls:"bg-accent text-white border border-accent"},queued:{label:"QUEUED",cls:"text-fg-dim border border-fg-faint"},done:{label:"DONE",cls:"text-sage-dark border border-sage"},draft:{label:"DRAFT",cls:"text-fg-faint border border-dashed border-fg-faint"}},Pn=e=>String(e).padStart(2,"0");function Dn({plan:e}){const s=Math.max(1,e.prdCount),n=e.doneCount/s*100,a=e.runningCount/s*100;return t.jsxs("span",{"data-testid":"plan-progress",role:"progressbar","aria-valuenow":e.doneCount,"aria-valuemin":0,"aria-valuemax":e.prdCount,className:"flex w-[160px] h-[5px] rounded-sm overflow-hidden bg-rule-inner shrink-0",children:[t.jsx("span",{className:"h-full bg-sage",style:{width:`${n}%`}}),t.jsx("span",{className:"h-full bg-accent",style:{width:`${a}%`}})]})}function An({plan:e,mode:s="graph",now:n,hidden:a,indexBySlug:c,headChoicesBySlug:o,onRowFocused:r,onOpenPrds:i}){var F,B;const[u,l]=f.useState(e.status==="active"||e.status==="queued"),[d,p]=f.useState(!1),h=f.useRef(null),[b,x]=f.useState(0),[g,v]=f.useState(bt),D=f.useMemo(()=>{const $=be(e.stages,Je);return $>=0?$:Math.max(0,be(e.stages,Ye))},[e.stages]);f.useLayoutEffect(()=>{if(!u)return;const $=h.current,I=($==null?void 0:$.clientWidth)||bt,O=Math.max(0,Math.min(D,e.stageCount-Math.max(1,Math.ceil(I/de))));$!=null&&$.clientWidth&&v($.clientWidth),$&&($.scrollLeft=O*de),x(O)},[u]);const M=f.useMemo(()=>{let $=null;for(const I of e.stages)for(const O of I.rows){if(!O.job.runId)continue;const Q=O.job.finishedAt?Date.parse(O.job.finishedAt):0;(!$||Q>$.at)&&($={runId:O.job.runId,slug:O.slug,title:O.title,at:Q})}return $},[e.stages]),T=Re((B=(F=e.stages[0])==null?void 0:F.rows[0])==null?void 0:B.job.cwd)??"—",m=$n[e.status],R=Math.max(1,Math.ceil(g/de)),N=Math.max(0,Math.min(b-mt,e.stageCount)),A=Math.min(e.stageCount,b+R+mt),U=$=>{const I=Math.max(0,Math.min(e.stageCount-1,$));h.current&&(h.current.scrollLeft=I*de),x(I)},K=Math.min(e.stageCount,b+R),Y=$=>{const I=$.currentTarget,O=Math.floor(I.scrollLeft/de);O!==b&&x(O),I.clientWidth&&I.clientWidth!==g&&v(I.clientWidth)},C="h-[24px] px-3 text-[12px] font-medium text-fg border border-rule-structural rounded-sm bg-transparent hover:bg-bg-hi cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed shrink-0",k=(()=>{switch(e.status){case"active":return t.jsx("button",{type:"button","data-testid":"plan-action",title:"Pauses the WHOLE scheduler (machine-wide) — there is no per-plan pause.",onClick:()=>{window.api.schedule.pause().catch(()=>V.error("Failed to pause the scheduler"))},className:C,children:"Pause plan"});case"queued":return t.jsx("button",{type:"button","data-testid":"plan-action",title:"Fires the next scheduler batch machine-wide (force tick) — it does not target this plan.",onClick:()=>{window.api.schedule.forceTick().then(V.fromOutcome).catch(()=>V.error("Failed to fire the next batch"))},className:C,children:"Run now"});case"done":return t.jsx("button",{type:"button","data-testid":"plan-action",disabled:!M,title:M?`Open the run log of ${M.slug}, the plan's last run`:"No run log recorded for this plan",onClick:()=>p(!0),className:C,children:"View run"});case"draft":return t.jsx("button",{type:"button","data-testid":"plan-action",title:"Open the PRDs sub-view on this plan's first PRD (the PRDs view has no per-Epic filter).",onClick:()=>{var $,I;return i==null?void 0:i(((I=($=e.stages[0])==null?void 0:$.rows[0])==null?void 0:I.slug)??null)},className:C,children:"Schedule…"})}})(),L=e.etaMs>0?` · ${Tt(e.etaMs)} left`:"";return t.jsxs("section",{"data-testid":"plan-band","data-epic-id":e.epicId??"","data-plan-status":e.status,className:`border-l-[3px] ${Cn[e.status]} border-b border-rule-structural`,children:[t.jsxs("div",{className:"h-[32px] flex items-center gap-2.5 px-3","data-testid":"plan-header",children:[t.jsx("button",{type:"button","aria-expanded":u,"aria-label":u?"Collapse plan":"Expand plan","data-testid":"plan-toggle",onClick:()=>l($=>!$),className:"shrink-0 w-[14px] text-[11px] text-fg-faint hover:text-fg bg-transparent border-0 cursor-pointer p-0",children:u?"▾":"▸"}),t.jsx("span",{className:"font-mono text-[11.5px] text-fg-faint shrink-0",children:Pn(e.index)}),t.jsx("span",{className:"font-serif text-[15px] font-bold text-fg truncate shrink-0 max-w-[320px]",title:e.label,"data-testid":"plan-label",children:e.label}),t.jsx("span",{"data-testid":"plan-chip",className:`shrink-0 rounded-sm px-1.5 py-[1px] text-[10px] font-bold tracking-wide ${m.cls}`,children:m.label}),t.jsx("span",{"aria-hidden":"true",className:"shrink-0 w-px h-[16px] bg-rule-structural"}),t.jsxs("span",{className:"font-mono text-[11.5px] text-fg-faint truncate min-w-0","data-testid":"plan-meta",children:[T," · ",e.prdCount," PRD",e.prdCount===1?"":"s"," · ",e.stageCount," stage",e.stageCount===1?"":"s"]}),t.jsxs("span",{className:"font-mono text-[11.5px] text-fg-dim shrink-0","data-testid":"plan-step-count",children:[e.prdCount," step",e.prdCount===1?"":"s"," · ",e.doneCount," done"]}),t.jsx(he,{title:`${e.doneCount} done · ${e.runningCount} running · ${e.heldCount} held · ${e.blockedCount} blocked`}),t.jsxs("span",{className:"ml-auto font-mono text-[11.5px] text-fg-dim shrink-0","data-testid":"plan-progress-label",children:[e.doneCount,"/",e.prdCount,L]}),t.jsx(Dn,{plan:e}),k]}),u&&s==="critical"&&t.jsx(Sn,{plan:e,now:n,indexBySlug:c,headChoicesBySlug:o,onRowFocused:r}),u&&s!=="critical"&&e.status==="active"&&t.jsx(wn,{stages:e.stages,first:b,perView:R,onSeek:U}),u&&s!=="critical"&&t.jsxs("div",{className:"flex border-t border-rule-structural",children:[t.jsxs("div",{ref:h,"data-testid":"plan-stages",onScroll:Y,className:"flex flex-1 min-w-0 overflow-x-auto",children:[N>0&&t.jsx("div",{"aria-hidden":"true",className:"shrink-0",style:{width:N*de}}),e.stages.slice(N,A).map($=>t.jsx(xn,{stage:$,epicId:e.epicId,now:n,hidden:a,indexBySlug:c,headChoicesBySlug:o,onRowFocused:r},$.n)),A<e.stageCount&&t.jsx("div",{"aria-hidden":"true",className:"shrink-0",style:{width:(e.stageCount-A)*de}})]}),t.jsx(jn,{stages:e.stages.slice(K),onSeek:U})]}),d&&M&&t.jsx(Ee,{runId:M.runId,slug:M.slug,title:M.title||M.slug,onClose:()=>p(!1)})]})}function Mn({section:e,children:s}){const[n,a]=f.useState(!0),c=Object.entries(e.counts).map(([o,r])=>`${r} ${o.replace(/_/g," ")}`).join(" · ");return t.jsxs("div",{className:"border-t border-line","data-testid":"backlog-epic-section","data-epic-id":e.epicId??"",children:[t.jsxs("button",{type:"button",onClick:()=>a(o=>!o),className:"w-full flex items-center gap-2.5 px-[18px] py-2.5 bg-bg-elev/60 hover:bg-bg-elev text-left","aria-expanded":n,title:e.label,children:[t.jsx("span",{className:`text-fg-faint inline-flex shrink-0 transition-transform duration-150 ${n?"rotate-90":""}`,"aria-hidden":"true",children:t.jsx(Ke,{name:"chevron",size:12})}),t.jsx("span",{className:"font-serif text-[14.5px] font-semibold text-fg truncate","data-testid":"backlog-epic-label",children:e.label}),t.jsxs("span",{className:"font-mono text-[11px] text-fg-faint shrink-0",children:[e.total," PRD",e.total===1?"":"s"]}),t.jsx("span",{className:"font-mono text-[11px] text-fg-faint truncate",children:c})]}),n&&s]})}const Rn=[],In=[],En={depth:0,blockers:Rn,blocked:!1,hasNeedsReviewBlocker:!1,hasMissingDep:!1,cycle:!1,parallelEligible:!1};function Tn(e){return e.missing?`${e.slug} (missing)`:e.needsReview?`${e.slug} (needs review)`:`${e.slug} (${(e.status??"unknown").replace(/_/g," ")})`}function _n(e){return e.missing?"text-accent":e.needsReview?"text-butter font-semibold":e.status==="completed"?"text-sage":"text-amber-400/90"}function On({job:e,eta:s,elapsedMs:n,avgDurationMs:a,listIndex:c,onFocused:o,hold:r,backlog:i=En,headChoices:u=In}){const[l,d]=f.useState(!1),[p,h]=f.useState(!1),b=ce(A=>A.sessions),x=f.useMemo(()=>Ce(e,b),[e,b]),g=x.known&&x.epicId?b[x.epicId]:null,v=f.useCallback(A=>{Qe(A),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"terminal"}))},[]),D=e.status==="running",M=e.status==="failed";let T=null;D&&n!==null?T=`${lt(n)} elapsed`:e.status==="completed"&&e.startedAt&&e.finishedAt?T=`took ${ke(Date.parse(e.finishedAt)-Date.parse(e.startedAt))}`:s&&(T=s);const m=e.error??null,R=M&&m?m.split(`
4
- `)[0]:e.status==="needs_review"&&e.verifierVerdict?Se(e.verifierVerdict):null,N=D&&n!==null?Math.min(.99,n/a):0;return t.jsxs("div",{role:"listitem",className:"border-t border-line",children:[t.jsxs("button",{type:"button","data-job-row":!0,"data-job-status":e.status,"data-job-index":c,"data-depth":i.depth,onClick:()=>d(A=>!A),onFocus:()=>o(c),style:i.depth>0?{paddingLeft:18+i.depth*20}:void 0,className:`w-full text-left grid grid-cols-[116px_1fr_auto_auto] items-center gap-4 px-[18px] py-3.5 hover:bg-bg/40 focus:outline-none focus:ring-1 focus:ring-accent focus:ring-inset ${l?"bg-bg-elev/40":""}`,"aria-expanded":l,"aria-label":`${ne(e.slug)?`PRD ${ne(e.slug)}, `:""}${e.title}, ${e.status}${T?`, ${T}`:""}`,title:e.title,children:[t.jsx(Ct,{status:e.status}),t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-baseline gap-2 text-[14.5px] font-medium text-fg leading-snug",children:[ne(e.slug)&&t.jsx($t,{n:ne(e.slug)}),e.title,t.jsx(Pt,{leaked:e.leakedDescendants}),t.jsx(cs,{count:e.leftoverCount,truncated:e.leftoverPathsTruncated,salvagePatch:e.salvagePatch}),i.parallelEligible&&t.jsx("span",{"data-testid":"job-row-parallel-eligible",title:"No dependsOn, and nothing in this Epic depends on it — can run any time a slot is free",className:"text-[10px] font-semibold uppercase tracking-wide text-sage/90 bg-sage/10 border border-sage/30 rounded px-1.5 py-0.5",children:"parallel"})]}),i.cycle&&t.jsxs("div",{className:"text-[12.5px] mt-0.5 text-accent font-mono","data-testid":"job-row-cycle-warning",children:["⚠ dependsOn cycle — ",i.blockers.map(A=>A.slug).join(" ↔ ")||"self-referencing"]}),!i.cycle&&i.blockers.length>0&&t.jsxs("div",{className:"text-[12.5px] mt-0.5 font-mono","data-testid":"job-row-blockers",children:[t.jsx("span",{className:i.blocked||i.hasMissingDep?"text-amber-400/90":"text-fg-faint",children:i.blocked||i.hasMissingDep?"blocked by ":"depends on "}),i.blockers.map((A,U)=>t.jsxs("span",{className:_n(A),children:[U>0&&", ",Tn(A)]},A.slug))]}),R&&t.jsx("div",{className:`text-[12.5px] mt-0.5 ${M?"text-accent/80":"text-fg-faint"}`,children:R}),r&&t.jsx("div",{className:"text-[12.5px] mt-0.5 text-amber-400/90 font-mono","data-testid":"job-row-hold",children:r.dep?t.jsxs(t.Fragment,{children:["held · waiting on ",r.dep," (",r.depStatus,")"]}):t.jsxs(t.Fragment,{children:["held · ",r.reason??"launch blocked"]})}),!r&&e.status==="pending"&&e.heldReason&&t.jsxs("div",{className:"text-[12.5px] mt-0.5 text-amber-400/90 font-mono","data-testid":"job-row-held-reason",children:["held · ",e.heldReason]}),t.jsx(ze,{epicId:x.epicId,label:x.label?Ft(x.label):null,onOpen:v,testId:"job-row-prompt-session-chip",className:"mt-0.5"})]}),t.jsx(Xe,{cwd:e.cwd}),t.jsxs("span",{className:"inline-flex items-center gap-2.5 font-mono text-xs text-fg-faint shrink-0",children:[t.jsx(us,{status:e.status,overrun:e.overrun}),T,t.jsx("span",{className:`text-fg-faint inline-flex transition-transform duration-150 ${l?"rotate-90":""}`,"aria-hidden":"true",children:t.jsx(Ke,{name:"chevron",size:14})})]})]}),D&&!l&&t.jsx("div",{className:"h-1 bg-line mx-[18px] mb-3 rounded-full overflow-hidden",children:t.jsx("div",{className:"h-full bg-accent transition-all duration-1000",style:{width:`${Math.max(4,N*100)}%`}})}),l&&t.jsxs("div",{className:"px-[18px] py-5 grid grid-cols-[repeat(auto-fit,minmax(160px,1fr))] gap-5 bg-bg-elev/50 border-t border-line",children:[t.jsxs(se,{label:"Status",children:[t.jsx(q,{k:"result",v:e.exitCode!==null?`exit ${e.exitCode}`:"—"}),t.jsx(q,{k:"state",v:e.status.replace(/_/g," ")}),e.verifierVerdict&&t.jsx(q,{k:"verdict",v:Se(e.verifierVerdict)}),e.leakedDescendants&&e.leakedDescendants.length>0&&t.jsx(q,{k:"leaked",v:Dt(e.leakedDescendants),wrap:!0}),e.leftoverCount!=null&&e.leftoverCount>0&&t.jsx(q,{k:"uncommitted",v:`${e.leftoverCount} file${e.leftoverCount===1?"":"s"}${e.leftoverPathsTruncated?"+":""}: ${(e.leftoverPaths??[]).join(", ")}${e.salvagePatch?` — salvaged to ${e.salvagePatch}`:""}`,wrap:!0}),m&&t.jsx(q,{k:"error",v:m.split(`
5
- `)[0],wrap:!0})]}),e.statusHistory&&e.statusHistory.length>0&&t.jsx(se,{label:"History",children:t.jsx("div",{className:"grid gap-1",children:e.statusHistory.map((A,U)=>t.jsxs("div",{className:"font-mono text-xs leading-relaxed",children:[t.jsxs("div",{className:"text-fg",children:[A.from??"(new)"," → ",A.to,t.jsxs("span",{className:"text-fg-faint",children:[" · ",ae(Date.parse(A.at))]})]}),A.reason&&t.jsx("div",{className:"text-fg-faint break-words",children:A.reason})]},U))})}),t.jsxs(se,{label:"Timing",children:[t.jsx(q,{k:"started",v:e.startedAt?ae(Date.parse(e.startedAt)):"—"}),t.jsx(q,{k:"finished",v:e.finishedAt?ae(Date.parse(e.finishedAt)):"—"}),t.jsx(q,{k:"duration",v:e.startedAt&&e.finishedAt?ke(Date.parse(e.finishedAt)-Date.parse(e.startedAt)):D&&n!==null?lt(n):"—"})]}),t.jsxs(se,{label:"Location",children:[t.jsx(q,{k:"group",v:`${e.parallelGroup} · ${e.slug}`}),t.jsx(q,{k:"cwd",v:e.cwd??"—",wrap:!0}),t.jsx(q,{k:"session",v:x.label??x.epicId??"—",wrap:!0}),t.jsx(q,{k:"session id",v:x.epicId??"—",wrap:!0}),t.jsx(q,{k:"prompt id",v:e.sourcePromptId??"—",wrap:!0}),t.jsx(q,{k:"source tab",v:e.sourceTabId??"—",wrap:!0})]}),t.jsx(se,{label:"Actions",children:t.jsxs("div",{className:"flex flex-col gap-1.5 items-start",children:[g&&t.jsx("button",{type:"button","data-testid":"job-row-prompt-session-link",title:g.goalText,onClick:()=>v(g.id),className:"text-[13px] font-semibold text-accent hover:text-accent/80 bg-transparent border-0 cursor-pointer p-0",children:"view epic →"}),e.runId&&t.jsx("button",{type:"button",onClick:()=>h(!0),className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border-0 cursor-pointer p-0",children:"view log →"}),e.status==="quarantined"&&t.jsx("button",{type:"button","data-testid":"job-row-adopt-prd",title:"Stamp this PRD's provenance so the scheduler will run it — no unstamped PRD runs automatically.",onClick:()=>{window.api.schedule.adoptPrd(e.slug).then(V.fromOutcome).catch(()=>V.error("Failed to adopt PRD"))},className:"text-[13px] font-semibold text-accent hover:text-accent/80 bg-transparent border-0 cursor-pointer p-0",children:"adopt PRD →"}),e.status!=="pending"&&e.status!=="running"&&e.status!=="quarantined"&&t.jsx("button",{type:"button",onClick:()=>window.api.schedule.resetJob(e.slug),className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border-0 cursor-pointer p-0",children:"reset to pending →"}),e.disposition&&(e.status==="pending"||e.status==="quarantined")&&t.jsx(Bt,{job:e,headChoices:u})]})})]}),p&&e.runId&&t.jsx(Ee,{runId:e.runId,slug:e.slug,title:e.title||e.slug,onClose:()=>h(!1)})]})}const Ln=f.memo(On);function Fn({supervisorConfig:e,onSetConfig:s,onBack:n}){const[a,c]=f.useState([]),[o,r]=f.useState(()=>Date.now()),i=At();f.useEffect(()=>{if(!i)return;window.api.supervisor.getLog().then(c).catch(()=>{}),r(Date.now());const l=setInterval(()=>r(Date.now()),5e3);return()=>clearInterval(l)},[i]);const u={enabled:(e==null?void 0:e.enabled)??!0,intervalMinutes:(e==null?void 0:e.intervalMinutes)??15,maxConcurrentProbes:(e==null?void 0:e.maxConcurrentProbes)??2,probeStaleThresholdMinutes:(e==null?void 0:e.probeStaleThresholdMinutes)??10};return t.jsxs("div",{className:"bg-bg-elev/60",children:[t.jsxs("div",{className:"px-3 py-2 flex items-center gap-2 border-b border-line",children:[t.jsx("button",{type:"button",onClick:n,className:"text-[10px] text-fg-faint hover:text-fg-dim",title:"Back to queue",children:"← queue"}),t.jsx("span",{className:"text-[11px] font-medium text-fg-dim",children:"Supervisor"}),t.jsx("button",{type:"button",onClick:()=>window.api.supervisor.getLog().then(c).catch(()=>{}),className:"ml-auto text-[10px] text-fg-faint hover:text-fg-dim underline",title:"Refresh log",children:"refresh"})]}),t.jsxs("div",{className:"px-3 py-2 space-y-1.5 border-b border-line",children:[t.jsx("div",{className:"text-[9px] text-fg-faint uppercase tracking-wider",children:"Config"}),t.jsxs("div",{className:"flex items-center gap-3 flex-wrap text-[10px] text-fg-faint",children:[t.jsxs("label",{className:"flex items-center gap-1",children:[t.jsx("input",{type:"checkbox",checked:u.enabled,onChange:l=>s({enabled:l.target.checked}),className:"cursor-pointer"}),t.jsx("span",{children:"enabled"})]}),t.jsxs("label",{className:"flex items-center gap-1",title:"How often to check for wedged jobs (minutes)",children:[t.jsx("span",{children:"interval"}),t.jsx("input",{type:"number",min:5,max:60,value:u.intervalMinutes,onChange:l=>s({intervalMinutes:Number(l.target.value)}),className:"w-10 bg-bg border border-line rounded px-1 py-0.5 font-mono"}),t.jsx("span",{children:"min"})]}),t.jsxs("label",{className:"flex items-center gap-1",title:"Max concurrent Opus probes per tick",children:[t.jsx("span",{children:"probes"}),t.jsx("input",{type:"number",min:1,max:5,value:u.maxConcurrentProbes,onChange:l=>s({maxConcurrentProbes:Number(l.target.value)}),className:"w-8 bg-bg border border-line rounded px-1 py-0.5 font-mono"})]}),t.jsxs("label",{className:"flex items-center gap-1",title:"Probe a job only if no JSONL event in this many minutes",children:[t.jsx("span",{children:"stale"}),t.jsx("input",{type:"number",min:5,max:30,value:u.probeStaleThresholdMinutes,onChange:l=>s({probeStaleThresholdMinutes:Number(l.target.value)}),className:"w-8 bg-bg border border-line rounded px-1 py-0.5 font-mono"}),t.jsx("span",{children:"min"})]})]})]}),t.jsxs("div",{className:"px-3 py-2",children:[t.jsxs("div",{className:"text-[9px] text-fg-faint uppercase tracking-wider mb-1",children:["Recent probes (last ",a.length,")"]}),a.length===0?t.jsx("div",{className:"text-[10px] text-fg-faint italic",children:"No probes yet."}):t.jsx("div",{className:"space-y-0.5 max-h-64 overflow-y-auto",children:a.map((l,d)=>t.jsx(qn,{entry:l,now:o},`${l.ts}-${d}`))})]})]})}function qn({entry:e,now:s}){const n=e.action!=="none",a=X(s-e.ts);return t.jsxs("div",{className:`text-[10px] px-1.5 py-1 rounded font-mono ${n?"bg-red-500/10 border border-red-500/20":"bg-bg/40"}`,title:e.reason,children:[t.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[t.jsxs("span",{className:"text-fg-faint shrink-0",children:[a," ago"]}),t.jsx("span",{className:`shrink-0 px-1 rounded ${e.verdict==="stuck"?"text-red-400 bg-red-500/10":"text-green-500/70"}`,children:e.verdict}),t.jsx("span",{className:"truncate text-fg-dim",children:e.jobSlug}),n&&t.jsxs("span",{className:"shrink-0 text-red-400",children:[e.action,e.targetPid?` pid=${e.targetPid}`:""]}),e.costUsd!==null&&t.jsxs("span",{className:"shrink-0 text-fg-faint",children:["$",e.costUsd.toFixed(3)]})]}),t.jsx("div",{className:"text-fg-faint truncate mt-0.5",children:e.reason})]})}const Bn=[{title:"Start a session",body:"In Sessions, pick an Agent and a Mission, describe the outcome you want, then Approve & start. Its thread writes the PRD files into that session's own folder."},{title:"Queue what it wrote",body:"The PRDs tab lists every file the session produced. Queue one, or the whole session, and they appear here."},{title:"Leave it alone",body:"Jobs start themselves inside your window, pause on rate-limit, and resume at the reset. History records how each ended."}],Hn=[{term:"Session",def:"One goal, one Claude session, and the folder of PRDs written to reach it."},{term:"PRD",def:"One markdown file = one job. Authored by the session."},{term:"5-hour window",def:"Your Claude billing window, on a rolling clock."},{term:"Session pool",def:"5 slots shared with terminal and session chats."}];function Gn({navigate:e}){return t.jsx("div",{className:"overflow-y-auto h-full",children:t.jsx("div",{className:"px-9 py-6 max-w-[900px] mx-auto",children:t.jsxs("div",{className:"bg-bg-hi border border-line rounded-2xl px-9 py-8",children:[t.jsx("h2",{className:"m-0 font-serif text-[25px] font-semibold text-fg",children:"Nothing to run yet — the scheduler needs a session."}),t.jsx("p",{className:"mt-2 mb-6 text-[14.5px] text-fg-dim leading-relaxed max-w-[580px]",children:"You don't write PRDs here. A session breaks its goal into numbered PRD files, and this page runs them in order. Two steps, once."}),t.jsx("div",{className:"grid grid-cols-3 gap-3.5",children:Bn.map((s,n)=>{const a=n===0;return t.jsxs("div",{className:`bg-bg border rounded-xl px-4 py-4 flex flex-col gap-2 ${a?"border-accent shadow-[0_0_0_3px_rgba(184,92,52,.09)]":"border-line"}`,children:[t.jsx("span",{className:`w-6 h-6 rounded-full grid place-items-center font-mono text-[12px] font-semibold ${a?"bg-accent text-white":"bg-bg-elev text-fg-dim"}`,children:n+1}),t.jsx("h3",{className:"m-0 text-[15px] font-semibold text-fg",children:s.title}),t.jsx("p",{className:"m-0 text-[13.5px] text-fg-dim leading-relaxed",children:s.body}),a&&t.jsx("button",{type:"button",onClick:()=>e==null?void 0:e("terminal"),className:"self-start bg-accent text-white rounded-lg px-3.5 py-1.5 text-[13px] font-semibold mt-1",children:"Go to Sessions →"})]},s.title)})}),t.jsx("dl",{className:"flex mt-[22px] pt-4 border-t border-line gap-5 flex-wrap",children:Hn.map(({term:s,def:n})=>t.jsxs("div",{className:"flex-1 min-w-[150px]",children:[t.jsx("dt",{className:"text-[13.5px] font-semibold text-fg mb-0.5",children:s}),t.jsx("dd",{className:"m-0 text-[12.5px] text-fg-faint leading-relaxed",children:n})]},s))})]})})})}const Vn=5e3;let Ae=null,je=null;async function wt(e){const s=Date.now();return!(e!=null&&e.fresh)&&Ae&&s-Ae.at<Vn?Ae.result:je||(je=(async()=>{try{const n=await window.api.schedule.lintQueue();return Ae={result:n,at:Date.now()},n}finally{je=null}})(),je)}function Un({health:e,jobCount:s,lastRunAt:n,nextReset:a,now:c,onOpenSupervisor:o}){const[r,i]=f.useState(!1),[u,l]=f.useState(null),[d,p]=f.useState(!1),h=`${s}:${n??""}`;f.useEffect(()=>{let N=!0;return p(!0),wt().then(A=>{N&&l(A)}).catch(()=>{}).finally(()=>{N&&p(!1)}),()=>{N=!1}},[h]);let b=0,x=0;const g=u?u.reports.filter(N=>N.findings.length>0):[];for(const N of g)for(const A of N.findings)A.severity==="error"?b++:x++;const v=b===0&&x===0,D=u?`graph lint ${b} error${b===1?"":"s"}, ${x} warn${x===1?"":"s"}`:`graph lint ${d?"scanning…":"idle"}`,M=(e==null?void 0:e.consecutiveFailures)??0,m=[e?`${M} poll failure${M===1?"":"s"} since boot`:null,D].filter(Boolean).join(" · "),R="text-accent hover:underline bg-transparent border-0 p-0 cursor-pointer text-[12px]";return t.jsxs("div",{"data-testid":"scheduler-footer",className:"border-t border-rule-structural",children:[t.jsxs("div",{className:"h-[28px] flex items-center gap-2 px-[18px] font-mono text-[11.5px] text-fg-faint",children:[t.jsx("span",{"data-testid":"footer-summary",className:"truncate",children:m}),t.jsx("button",{type:"button","data-testid":"footer-info","aria-expanded":r,onClick:()=>i(N=>!N),className:"bg-transparent border-0 p-0 cursor-pointer",children:t.jsx(he,{title:"Scheduler poll health and queue-lint findings — click for the full detail"})}),t.jsxs("span",{className:"ml-auto flex items-center gap-3 shrink-0",children:[t.jsxs("span",{"data-testid":"footer-timing",children:[a?t.jsxs("span",{title:`next 5h reset: ${a}`,children:["reset ",X(Date.parse(a)-c)]}):null,a&&n?" · ":null,n?t.jsxs("span",{title:n,children:["last run ",X(c-Date.parse(n))," ago"]}):null]}),t.jsx("button",{type:"button","data-testid":"footer-supervisor",onClick:o,title:"Open supervisor log and settings",className:R,children:"supervisor"}),t.jsx("button",{type:"button","data-testid":"footer-folder",onClick:()=>window.api.schedule.openFolder(),className:R,children:"folder"})]})]}),r&&t.jsxs("div",{"data-testid":"footer-detail",className:"px-[18px] pb-2 space-y-2 font-mono text-[12px] text-fg-dim border-t border-rule-inner pt-2",children:[e&&t.jsxs("div",{className:"space-y-0.5",children:[t.jsxs("div",{children:["booted: ",fe(e.bootedAt,c)]}),t.jsxs("div",{children:["last poll: ",fe(e.lastPollAt,c)," · ",e.lastPollOk?"ok":"failed"]}),e.backoffNextAt!==null&&e.backoffNextAt>c&&t.jsxs("div",{children:["retry in: ",X(e.backoffNextAt-c)]}),e.nextResetCached&&t.jsxs("div",{children:["cached reset: ",ae(Date.parse(e.nextResetCached))]}),e.runningJobs.length>0&&t.jsxs("div",{children:["running: ",e.runningJobs.map(N=>`${N.slug}(pid ${N.pid})`).join(", ")]})]}),u&&t.jsxs("div",{className:"space-y-1",children:[v?t.jsxs("div",{className:"text-sage",children:["✓ no issues in ",u.reports.length," PRD",u.reports.length!==1?"s":""]}):g.map(N=>t.jsxs("div",{children:[t.jsx("div",{className:"text-fg-dim truncate",title:N.slug,children:N.slug}),N.findings.map((A,U)=>t.jsxs("div",{className:`pl-3 truncate ${A.severity==="error"?"text-accent/80":"text-butter/90"}`,title:A.snippet,children:[A.severity==="error"?"✗":"⚠"," L",A.line,": ",A.snippet]},`${N.slug}-${U}`))]},N.slug)),t.jsx("button",{type:"button","data-testid":"footer-rerun-lint",onClick:()=>{p(!0),wt({fresh:!0}).then(l).catch(()=>{}).finally(()=>p(!1))},className:"text-fg-faint hover:text-fg-dim underline",children:d?"…":"rerun lint"})]})]})]})}const Wn=5,Jn=1440*60*1e3,Jt="sm.scheduler.hiddenCompletedSlugs",He="sm.scheduler.focusedJobIndex",Yt="sm.scheduler.queueFilter",Yn=["all","running","investigating","pending","completed","skipped","needs_review","failed","quarantined"];function Kn(){try{const e=localStorage.getItem(Yt);if(!e)return{text:"",status:"all"};const s=JSON.parse(e);return{text:"",status:Yn.includes(s.status)?s.status:"all"}}catch{return{text:"",status:"all"}}}function vt(e){try{localStorage.setItem(Yt,JSON.stringify({status:e.status}))}catch{}}function jt(e,s){if(s.status==="all"&&!s.text)return e;const n=s.text.toLowerCase();return e.filter(a=>{if(s.status!=="all"&&a.status!==s.status)return!1;if(!n)return!0;const c=Re(a.cwd)??"";return a.title.toLowerCase().includes(n)||a.slug.toLowerCase().includes(n)||c.toLowerCase().includes(n)})}function Qn(){try{const e=localStorage.getItem(Jt);if(!e)return new Set;const s=JSON.parse(e);return Array.isArray(s)?new Set(s.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function yt(e){try{localStorage.setItem(Jt,JSON.stringify([...e]))}catch{}}function zn({scopeCwd:e=null,navigate:s,filterText:n,planMode:a="graph",onOpenPrds:c,planToolsEl:o=null}){var at;const r=Ie(j=>j.snapshot),i=f.useMemo(()=>!r||!e?r:{...r,jobs:r.jobs.filter(j=>j.cwd===e)},[r,e]),[u,l]=f.useState(null),[d,p]=f.useState(()=>Date.now()),[h,b]=f.useState(()=>Qn()),[x,g]=f.useState(!1),[v,D]=f.useState(()=>Kn()),M=f.useMemo(()=>n===void 0?v:{...v,text:n},[v,n]),[T,m]=f.useState(!1),[R,N]=f.useState("queue"),A=f.useRef(null),[U,K]=f.useState(()=>{try{return Number(localStorage.getItem(He))||0}catch{return 0}}),[Y,C]=f.useState(""),k=At();f.useEffect(()=>(window.api.schedule.health().then(l).catch(()=>{}),window.api.schedule.onState(()=>{window.api.schedule.health().then(l).catch(()=>{})})),[]),f.useEffect(()=>{if(!k)return;p(Date.now());const j=setInterval(()=>p(Date.now()),1e3);return()=>clearInterval(j)},[k]);const L=f.useMemo(()=>{if(!i)return 15e4;const j=[];for(const E of i.jobs)if(E.status==="completed"&&E.startedAt&&E.finishedAt){const H=Date.parse(E.finishedAt)-Date.parse(E.startedAt);H>0&&j.push(H)}return j.length===0?15e4:j.reduce((E,H)=>E+H,0)/j.length},[i]),F=f.useRef(new Map);f.useEffect(()=>{if(!i)return;const j=[];for(const E of i.jobs){const H=F.current.get(E.slug);H&&H!==E.status&&j.push(`${E.title}: ${H} → ${E.status}`),F.current.set(E.slug,E.status)}j.length>0&&C(j.join("; "))},[i]);const B=f.useMemo(()=>{var E;const j=new Map;for(const H of((E=i==null?void 0:i.lastTick)==null?void 0:E.holds)??[])j.set(H.slug,H);return j},[i==null?void 0:i.lastTick]),$=ce(j=>j.sessions),I=f.useMemo(()=>i?Rt(i.jobs,$,r==null?void 0:r.jobs):[],[i,$,r]),O=ps(),Q=f.useMemo(()=>i?jt(en(i.jobs,O,e),M):[],[i,O,e,M]),z=(at=i==null?void 0:i.effectiveConcurrency)==null?void 0:at.cap,Z=f.useMemo(()=>a==="list"?[]:Ze(Q,{sessions:$,avgDurationMs:L,concurrency:z}),[a,Q,$,L,z]),G=f.useMemo(()=>{const j=new Map;let E=0;for(const H of Z)for(const J of H.stages)for(const te of J.rows)j.set(te.slug,E++);return j},[Z]),w=f.useMemo(()=>Zs(I),[I]),S=h,y=f.useCallback(j=>{var ge;const E=(ge=A.current)==null?void 0:ge.querySelectorAll("[data-job-row]");if(!E||E.length===0)return;const H=Array.from(E),J=H.findIndex(ee=>ee.dataset.jobIndex===String(U)),te=ee=>{const ue=H[ee];if(!ue)return;const le=Number(ue.dataset.jobIndex);K(le);try{localStorage.setItem(He,String(le))}catch{}ue.focus()};j.key==="ArrowDown"?(j.preventDefault(),te(J===-1?0:Math.min(J+1,H.length-1))):j.key==="ArrowUp"&&(j.preventDefault(),te(J===-1?H.length-1:Math.max(J-1,0)))},[U]),_=f.useCallback(j=>{K(j);try{localStorage.setItem(He,String(j))}catch{}},[]);if(!i)return null;if(R==="supervisor")return t.jsx(Fn,{supervisorConfig:i.config.supervisor,onSetConfig:j=>window.api.schedule.setConfig({supervisor:j}),onBack:()=>N("queue")});const{jobs:P,paused:W,lastRunAt:xe,nextReset:Qt,effectiveConcurrency:_e}=i;if(P.length===0)return t.jsx(Gn,{navigate:s});const re={pending:0,running:0,investigating:0,completed:0,needs_review:0,failed:0};for(const j of P)j.status in re&&re[j.status]++;const Oe=P.filter(j=>j.status==="running"),zt=Ot({snap:i,now:d,avgDurationMs:L,runningJobs:Oe}),we=jt(P,M),Xt=Xn(we),{inline:$e,collapsedCount:Le}=Zn(we,h,d,x),Zt=ea($e,P,Xt,L,zt.kind,d),et=()=>{const j=new Set(h);for(const E of P)(E.status==="completed"||E.status==="failed")&&j.add(E.slug);b(j),yt(j)},tt=async()=>{const j=P.filter(J=>J.status!=="running").length;if(j===0)return;const E=`Archive ${j} non-running PRD${j===1?"":"s"} and remove from the queue?
6
-
7
- Files are moved to prds-archived/<timestamp>/ and can be restored from disk. Running jobs are kept.`;if(!window.confirm(E))return;const H=await window.api.schedule.clearQueue();H.ok||V.error(`Clear queue failed: ${H.error??"unknown error"}`)},st=()=>{b(new Set),yt(new Set),g(!1)},nt=a==="list"?$e.some(j=>j.status==="completed"):P.some(j=>(j.status==="completed"||j.status==="skipped")&&!h.has(j.slug)),es=P.filter(j=>(j.status==="completed"||j.status==="failed")&&h.has(j.slug)).length,ie=a==="list",Pe=ie?"":"px-[18px] py-2";return t.jsxs("div",{className:"overflow-y-auto h-full",children:[t.jsx("div",{"aria-live":"polite","aria-atomic":"true",className:"sr-only",children:Y}),t.jsxs("div",{className:ie?"px-9 py-6 max-w-[1100px] mx-auto space-y-4":"",children:[u&&u.consecutiveFailures>5&&u.lastFailureKind==="meter_rate_limited"&&!W&&!T&&t.jsx("div",{className:Pe,children:t.jsxs("div",{className:ie?"flex items-center gap-3 px-4 py-3 bg-amber-400/15 border border-amber-400/30 rounded-xl":"flex items-center gap-3 -mx-[18px] px-[18px] py-1 bg-amber-400/15 border-y border-amber-400/30",children:[t.jsx("span",{"aria-hidden":"true",children:"⚠"}),t.jsxs("span",{className:"text-[13.5px] text-amber-400/90",children:[t.jsx("strong",{className:"font-semibold",children:"Usage meter unavailable"})," — last good reading"," ",fe(u.lastPollAt,d),". Firing on a conservative estimate until it recovers."]}),t.jsx("button",{type:"button",onClick:()=>m(!0),className:"ml-auto text-[12px] text-amber-400/70 hover:text-amber-400 shrink-0",title:"Dismiss this banner. The scheduler continues firing normally.",children:"Dismiss"})]})}),ie&&Oe.length>0&&(()=>{const j=(_e==null?void 0:_e.cap)??5,E=P.filter(H=>H.status==="pending").length;return t.jsxs("div",{className:`flex items-center gap-2 text-[12px] font-mono ${Pe}`,children:[t.jsxs("span",{className:"px-2 py-0.5 rounded bg-amber-400/20 text-amber-400 shrink-0",children:[Oe.length,"/",j," running"]}),E>0&&t.jsxs("span",{className:"text-fg-faint",children:["+",E," ready in this group"]})]})})(),ie&&P.length>0&&t.jsx("div",{className:Pe,children:t.jsx(sa,{showText:n===void 0,filter:M,onChange:j=>{D(j),vt(j)}})}),!ie&&t.jsxs("div",{"data-testid":"plan-graph",children:[o&&fs.createPortal(t.jsx(ta,{jobCount:we.length,counts:re,filter:M,onFilter:j=>{D(j),vt(j)},hiddenInGraph:es,onUnhideAll:st,hasInlineCompleted:nt,onClearCompleted:et,onClearQueue:tt,clearQueueDisabled:P.every(j=>j.status==="running")}),o),Z.length===0&&t.jsx("div",{className:"px-[18px] py-6 text-[13px] text-fg-faint italic",children:"no matching jobs"}),t.jsx("div",{ref:A,role:"list","aria-label":"Job queue",onKeyDown:y,children:Z.map(j=>t.jsx(An,{plan:j,mode:a,now:d,hidden:S,indexBySlug:G,headChoicesBySlug:w,onRowFocused:_,onOpenPrds:c},`${j.epicId??"__none__"}#${j.waveIndex}`))})]}),ie&&t.jsxs("div",{className:"bg-bg-hi border border-line rounded-2xl overflow-hidden",children:[t.jsxs("div",{className:"flex items-center justify-between px-[18px] py-3 bg-bg-elev",children:[t.jsxs("span",{className:"font-serif text-base font-semibold text-fg",children:[we.length," job",we.length!==1?"s":""]}),t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsxs("span",{className:"font-mono text-[12px] text-fg-faint",children:[re.pending,"p · ",re.running,"r · ",re.completed,"d",re.failed>0&&t.jsxs("span",{className:"text-accent",children:[" · ",re.failed,"f"]})]}),nt&&t.jsx("button",{type:"button",onClick:et,className:"text-[12.5px] text-fg-dim hover:text-fg bg-transparent border-0 cursor-pointer font-medium",title:"Hide completed jobs from this view (queue.json unchanged — they remain in history)",children:"Clear completed"}),t.jsx("button",{type:"button",onClick:tt,disabled:P.every(j=>j.status==="running"),className:"text-[12px] text-accent border border-accent/40 hover:bg-accent/10 rounded-md px-2.5 py-1 cursor-pointer font-medium disabled:opacity-40 disabled:cursor-not-allowed",title:"Archive every non-running PRD (moved to prds-archived/<timestamp>/) and remove them from the queue. Running jobs are kept.",children:"Archive & clear queue…"})]})]}),$e.length===0&&Le===0&&t.jsx("div",{className:"px-[18px] py-6 text-[13px] text-fg-faint italic",children:"no matching jobs"}),t.jsx("div",{ref:A,role:"list","aria-label":"Job queue",onKeyDown:y,children:(()=>{const j=new Set($e.map(J=>J.slug));let E=0;return I.map(J=>{const te=qt(J),ge=J.nodes.map(ee=>{const ue=Te([ee]).filter(le=>j.has(le.row.slug)).map(le=>({node:le,listIndex:E++}));return{headRootSlug:ee.row.slug,rows:ue}}).filter(ee=>ee.rows.length>0);return{section:J,heads:ge,headChoices:te}}).filter(J=>J.heads.length>0).map(({section:J,heads:te,headChoices:ge})=>t.jsx(Mn,{section:J,children:te.map(({headRootSlug:ee,rows:ue},le)=>t.jsxs("div",{"data-testid":"backlog-head-group",children:[te.length>1&&t.jsxs("div",{className:"px-[18px] pt-2.5 pb-1 text-[11px] font-mono uppercase tracking-wide text-fg-faint bg-bg-elev/30 border-t border-line/60","data-testid":"backlog-head-label",children:["Plan ",le+1," of ",te.length]}),ue.map(({node:oe,listIndex:ts})=>t.jsx(Ln,{job:oe.row,backlog:oe,eta:Zt.get(oe.row.slug)??null,elapsedMs:oe.row.status==="running"&&oe.row.startedAt?d-Date.parse(oe.row.startedAt):null,avgDurationMs:L,listIndex:ts,hold:B.get(oe.row.slug),onFocused:_,headChoices:ge.filter(ss=>ss.rootSlug!==ee)},oe.row.slug))]},ee))},J.epicId??"__none__"))})()}),Le>0&&t.jsxs("button",{type:"button",onClick:()=>g(j=>!j),className:"w-full text-left text-[12px] text-fg-faint hover:text-fg-dim px-[18px] py-3 border-t border-line",title:x?"Re-collapse old/cleared completed":"Show all completed (incl. cleared and >24h)",children:[x?"▾":"▸"," ",Le," more completed",t.jsx("span",{className:"ml-1.5 font-mono text-[11.5px] text-fg-faint",children:"· fresh & capped at 5 shown inline"}),h.size>0&&t.jsx("span",{className:"ml-2 underline",onClick:j=>{j.stopPropagation(),st()},children:"un-hide"})]})]}),ie&&!W&&t.jsx("div",{className:Pe,children:t.jsxs("div",{className:"flex gap-2.5 bg-sage/10 border border-sage/30 rounded-xl px-3.5 py-2.5 text-[13.5px] text-fg-dim leading-relaxed",children:[t.jsx("span",{"aria-hidden":"true",children:"✓"}),t.jsxs("span",{children:[t.jsx("strong",{className:"font-semibold text-fg",children:"Nothing needed from you."})," ","Close the app if you like — jobs keep running, and History shows how each one ended."]})]})})]}),t.jsx(Un,{health:u,jobCount:P.length,lastRunAt:xe,nextReset:Qt,now:d,onOpenSupervisor:()=>N("supervisor")})]})}function Xn(e){const s=new Map(e.map(o=>[o.slug,o])),n=o=>(o.dependsOn??[]).filter(r=>{var i;return((i=s.get(r))==null?void 0:i.status)!=="completed"}).length,a=e.filter(o=>o.status==="running"||o.status==="pending").sort((o,r)=>n(o)-n(r)||o.slug.localeCompare(r.slug)),c=new Map;return a.forEach((o,r)=>c.set(o.slug,r)),c}function Zn(e,s,n,a){if(a)return{inline:e,collapsedCount:0};const c=e.filter(l=>l.status==="completed").sort((l,d)=>{const p=l.finishedAt?Date.parse(l.finishedAt):0;return(d.finishedAt?Date.parse(d.finishedAt):0)-p}),o=new Set;let r=0;for(const l of c){if(r>=Wn)break;s.has(l.slug)||l.finishedAt&&n-Date.parse(l.finishedAt)>Jn||(o.add(l.slug),r++)}const i=[];let u=0;for(const l of e){if(l.status==="failed"&&s.has(l.slug)){u++;continue}if(l.status!=="completed"){i.push(l);continue}o.has(l.slug)?i.push(l):u++}return{inline:i,collapsedCount:u}}function ea(e,s,n,a,c,o){const r=new Map;if(c==="paused"||c==="manual"||c==="auto-throttled"){for(const l of e)r.set(l.slug,null);return r}const i=s.find(l=>l.status==="running"&&l.startedAt),u=i!=null&&i.startedAt?o-Date.parse(i.startedAt):0;for(const l of e){if(l.status!=="pending"){r.set(l.slug,null);continue}const d=n.get(l.slug)??0;let p=d*a;d>0&&(p-=Math.min(a,u)),r.set(l.slug,p<=5e3?"~now":`~${ke(p)}`)}return r}const Kt=[{label:"All",value:"all"},{label:"Running",value:"running"},{label:"Investigating",value:"investigating"},{label:"Pending",value:"pending"},{label:"Completed",value:"completed"},{label:"Skipped",value:"skipped"},{label:"Needs review",value:"needs_review"},{label:"Failed",value:"failed"},{label:"Quarantined",value:"quarantined"}];function ta({jobCount:e,counts:s,filter:n,onFilter:a,hiddenInGraph:c,onUnhideAll:o,hasInlineCompleted:r,onClearCompleted:i,onClearQueue:u,clearQueueDisabled:l}){const d="block w-full text-left px-2 py-1 text-[12px] hover:bg-bg-hi disabled:opacity-40 disabled:cursor-not-allowed bg-transparent border-0 cursor-pointer";return t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"font-mono text-[11.5px] text-fg-faint whitespace-nowrap","data-testid":"plan-tools-counts",children:[e," job",e!==1?"s":""," · ",s.pending,"p · ",s.running,"r · ",s.completed,"d",s.failed>0&&t.jsxs("span",{className:"text-accent",children:[" · ",s.failed,"f"]})]}),c>0&&t.jsxs("button",{type:"button",onClick:o,className:"text-[12px] text-fg-faint hover:text-fg-dim underline bg-transparent border-0 cursor-pointer whitespace-nowrap",title:"Show the completed/failed jobs hidden by Clear completed",children:[c," hidden · un-hide"]}),t.jsx("select",{"data-testid":"scheduler-status-filter","aria-label":"Filter by status",value:n.status,onChange:p=>a({...n,status:p.target.value}),className:"bg-bg-hi border border-line rounded px-1 py-0.5 text-[12px] text-fg-dim",title:"Filter the plan graph by job status",children:Kt.map(p=>t.jsx("option",{value:p.value,children:p.value==="all"?"all statuses":p.label.toLowerCase()},p.value))}),t.jsx(he,{title:"Queue actions",testId:"plan-tools-menu",popoverTestId:"plan-tools-menu-popover",alignRight:!0,glyph:"⋯",widthCls:"w-52",children:t.jsxs("div",{className:"-mx-3 -my-2",children:[r&&t.jsx("button",{type:"button",onClick:i,className:`${d} text-fg-dim`,title:"Hide completed jobs from this view (queue.json unchanged — they remain in history)",children:"Clear completed"}),t.jsx("button",{type:"button",onClick:u,disabled:l,className:`${d} text-accent`,title:"Archive every non-running PRD (moved to prds-archived/<timestamp>/) and remove them from the queue. Running jobs are kept.",children:"Archive & clear queue…"})]})})]})}function sa({filter:e,onChange:s,showText:n}){const a=Kt;return t.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[n&&t.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-[320px]",children:[t.jsx("span",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-fg-faint inline-flex","aria-hidden":"true",children:t.jsx(Ke,{name:"search",size:15})}),t.jsx("input",{type:"text",value:e.text,onChange:c=>s({...e,text:c.target.value}),placeholder:"filter jobs…",className:"w-full bg-bg-hi border border-line rounded-xl py-2 pl-9 pr-3 text-[13.5px] text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint","aria-label":"Filter jobs by title, slug, or project"})]}),t.jsx(Lt,{options:a,value:e.status,onChange:c=>s({...e,status:c})})]})}new Set(hs.map(e=>e.tag).filter(e=>e!=="discussion"));const na=["title","cwd","estimateMinutes","parallelGroup","sourcePromptId","sourceTabId","tag","agentType","dependsOn","disposition","planId"];function aa(e,s){return!Array.isArray(e)||!Array.isArray(s)?!1:e.length===s.length&&e.every((n,a)=>n===s[a])}function ra(e){if(e==null)return"";if(typeof e=="boolean"||typeof e=="number")return String(e);const s=String(e);return s===""||/^(true|false|null|~)$/.test(s)||/^-?\d+(\.\d+)?$/.test(s)||/^\s|\s$/.test(s)||s.startsWith("'")||s.startsWith('"')||s.includes(`
8
- `)?s.includes("'")?`"${s.replace(/"/g,'\\"')}"`:`'${s}'`:s}function ia(e,s){var c;const n=[];for(const o of na){const r=e[o];if(r==null||r===""||Array.isArray(r)&&r.length===0)continue;const i=(c=e._raw)==null?void 0:c[o];if(i&&(Array.isArray(r)?aa(i.parsed,r):i.parsed===r)){n.push(i.line);continue}if(typeof r=="number"){n.push(`${o}: ${r}`);continue}if(Array.isArray(r)){n.push(`${o}: [${r.join(", ")}]`);continue}n.push(`${o}: ${ra(r)}`)}if(e.extras)for(const o of Object.keys(e.extras)){const r=e.extras[o];!r||!r.lines.length||n.push(r.lines.join(`
9
- `))}return`---
10
- ${n.join(`
11
- `)}
12
- ---
13
- ${s}`}function Ge(e){return e.filter(s=>!s.archived)}function la(e){Qe(e),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"terminal"}))}function Ve({label:e,tip:s,onClick:n,disabled:a,primary:c}){return t.jsx(ms,{content:s,align:"bottom-center",children:t.jsx("button",{title:s,onClick:n,disabled:a,className:`px-2 py-0.5 text-xs rounded border disabled:opacity-40 disabled:cursor-not-allowed ${c?"text-accent border-accent/50 hover:bg-bg-hi":"text-fg-dim border-line hover:text-fg hover:bg-bg-hi"}`,children:e})})}function oa({scopeCwd:e=null}){const[s,n]=f.useState([]),[a,c]=f.useState(null),[o,r]=f.useState(null),[i,u]=f.useState(null),[l,d]=f.useState(!1),[p,h]=f.useState(!0),[b,x]=f.useState(new Set),[g,v]=f.useState(!1),[D,M]=f.useState(!1),[T,m]=f.useState(!1),[R,N]=f.useState(null);f.useEffect(()=>{let w=!0;return window.api.schedule.listPrds().then(S=>{w&&(n(Ge(S)),h(!1))}).catch(S=>{w&&(h(!1),V.error(`Scheduler: failed to load PRD list — ${S instanceof Error?S.message:"unknown error"}`))}),()=>{w=!1}},[]);const A=Ie(w=>w.snapshot),U=ce(w=>w.sessions);f.useEffect(()=>{A&&c(A)},[A]);const K=f.useMemo(()=>[...s].filter(w=>!e||w.cwd===e).sort((w,S)=>S.mtimeMs-w.mtimeMs||w.slug.localeCompare(S.slug)),[s,e]);f.useEffect(()=>{const w=gs();w&&r(w);const S=y=>r(y.detail);return window.addEventListener("sm:select-prd",S),()=>window.removeEventListener("sm:select-prd",S)},[]);const Y=f.useMemo(()=>(a==null?void 0:a.jobs.find(w=>w.slug===o))??null,[a,o]),C=ot(Y);function k(w){var y;const S=(y=s.find(_=>_.slug===w))==null?void 0:y.cwd;return S?`${S}/session-manager-operations/scheduler/prds/${w}.md`:null}f.useEffect(()=>{if(!o)return;const w=k(o);w&&dt.getState().openFile(w)},[o,s]);function L(w){r(w),u(null),d(!1)}function F(){r(null)}async function B(){if(!o)return;if(!(Y!=null&&Y.runId)){u("no log available (job has not run yet)"),d(S=>!S);return}const w=await window.api.schedule.readLog(Y.runId,o);u(w.ok?w.text??"":`error: ${w.error}`),d(S=>!S)}if(p)return t.jsx(ye,{title:"loading PRDs…"});const $=w=>{x(S=>{const y=new Set(S);return y.has(w)?y.delete(w):y.add(w),y})};!(K.length>0&&K.every(w=>b.has(w.slug)))&&K.some(w=>b.has(w.slug));const O=()=>x(new Set);async function Q(){try{const w=await window.api.schedule.listPrds();n(Ge(w))}catch{}}async function z(){const w=`new-prd-${Date.now()}`,S=ia({title:"New PRD",cwd:"",estimateMinutes:60,parallelGroup:99},`## Task
14
-
15
- Describe the task here.
16
- `);try{const y=await window.api.schedule.writePrd(w,S);if(!y.ok){V.error(`Failed to create PRD: ${y.error}`);return}const _=await window.api.schedule.listPrds();n(Ge(_)),L(w)}catch(y){V.error(`Failed to create PRD: ${y instanceof Error?y.message:String(y)}`)}}async function Z(){var w;m(!0),N(null);try{const S=[...b],y=await window.api.schedule.archivePrds(S);if(!y.ok)N(y.error??"archive failed");else{const _=((w=y.results)==null?void 0:w.filter(P=>!P.ok))??[];_.length>0&&V.warn(`Archive: ${_.length} of ${y.results.length} PRD${_.length===1?"":"s"} failed to move`),O(),v(!1),await Q()}}catch(S){N(S instanceof Error?S.message:String(S))}finally{m(!1)}}async function G(w,S){m(!0),N(null);try{const y=[];for(const P of b){const W={slug:P};w!==null&&(W.parallelGroup=w),S!==null&&(W.estimateMinutes=S),y.push(W)}const _=await window.api.schedule.retagPrds(y);if(!_.ok)N(_.error??"retag failed");else{O(),M(!1),await Q();for(const P of _.results)if(P.newSlug&&P.newSlug!==P.slug){const W=k(P.slug),xe=k(P.newSlug);W&&xe&&dt.getState().renameOpenFile(W,xe)}o&&_.results.some(P=>P.slug===o&&P.newSlug&&P.newSlug!==P.slug)&&r(null)}}catch(y){N(y instanceof Error?y.message:String(y))}finally{m(!1)}}return t.jsxs(t.Fragment,{children:[o?t.jsxs("div",{className:"h-full flex flex-col min-h-0",children:[t.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-line flex-wrap shrink-0",children:[t.jsx("button",{type:"button",onClick:F,className:"text-[11px] text-fg-faint hover:text-fg",children:"← PRDs"}),t.jsx("span",{className:"font-mono text-xs text-fg-dim truncate",children:o}),t.jsx(ct,{status:C}),t.jsx("div",{className:"flex-1"}),t.jsx(Ve,{label:"Reset",tip:"Reset failed job to pending",onClick:()=>{window.api.schedule.resetJob(o)},disabled:C!=="failed"}),t.jsx(Ve,{label:"Run now",tip:"Run all pending jobs immediately",onClick:()=>{window.api.schedule.runNow()}}),t.jsx(Ve,{label:l?"Hide log":"Last run log",tip:"Toggle most recent run log",onClick:B})]}),t.jsx("div",{className:"flex-1 min-h-0",children:t.jsx(xs,{})}),l&&i!==null&&t.jsxs("div",{className:"border-t border-line max-h-64 overflow-auto bg-bg-elev",children:[t.jsxs("div",{className:"px-3 py-1.5 flex items-center gap-2 border-b border-line sticky top-0 bg-bg-elev",children:[t.jsxs("span",{className:"text-[10px] text-fg-faint font-mono",children:["run log",Y!=null&&Y.runId?` — ${Y.runId}`:""]}),t.jsx("button",{onClick:()=>d(!1),className:"ml-auto text-[10px] text-fg-faint hover:text-fg",children:"close"})]}),t.jsx("pre",{className:"p-3 text-[11px] font-mono text-fg-dim whitespace-pre-wrap",children:i})]})]}):t.jsxs("div",{className:"px-6 py-5 overflow-auto",children:[t.jsxs("div",{className:"flex items-start justify-between mb-5 gap-4",children:[t.jsxs("p",{className:"text-[14px] text-fg-dim leading-relaxed max-w-[560px]",children:["PRDs are the source the scheduler runs from. Each one becomes a"," ",t.jsx("code",{className:"font-mono text-[13px]",children:"claude -p"})," job when you queue it. This is where you write and edit the source — to watch a run in progress, use the Queue tab."]}),t.jsx("button",{type:"button",onClick:z,className:"shrink-0 bg-accent text-white rounded-lg px-4 py-[9px] text-[13.5px] font-semibold leading-none",children:"+ New PRD"})]}),b.size>0&&t.jsxs("div",{className:"mb-4 px-4 py-2 bg-bg border border-line rounded-lg flex items-center gap-2",children:[t.jsxs("span",{className:"text-xs text-fg-dim",children:[b.size," selected"]}),t.jsx("div",{className:"flex-1"}),t.jsx("button",{type:"button",onClick:()=>v(!0),className:"text-xs px-3 py-1.5 rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:"Archive…"}),t.jsx("button",{type:"button",onClick:()=>M(!0),className:"text-xs px-3 py-1.5 rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:"Retag…"}),t.jsx("button",{type:"button",onClick:O,className:"text-xs px-3 py-1.5 rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:"Clear"})]}),K.length===0?t.jsx(ye,{title:"no PRDs found"}):t.jsx("div",{className:"grid gap-3",children:K.map(w=>{const S=a==null?void 0:a.jobs.find(xe=>xe.slug===w.slug),y=ot(S),_=Ce({epicId:w.epicId??(S==null?void 0:S.epicId)??null,sourcePromptId:w.sourcePromptId??(S==null?void 0:S.sourcePromptId)??null,sourceTabId:(S==null?void 0:S.sourceTabId)??null},U),P=(S==null?void 0:S.status)==="running",W=(S==null?void 0:S.status)==="needs_review";return t.jsxs("div",{className:"flex items-stretch bg-bg-elev border border-line rounded-2xl overflow-hidden",children:[t.jsx("label",{className:"flex items-center px-3 cursor-pointer hover:bg-bg-hi",children:t.jsx("input",{type:"checkbox",checked:b.has(w.slug),onChange:()=>$(w.slug),className:"accent-accent w-3.5 h-3.5"})}),t.jsxs("div",{className:"flex-1 min-w-0 py-4 pr-2",children:[t.jsxs("div",{className:"flex items-center gap-2.5 mb-[5px] flex-wrap",children:[ne(w.slug)&&t.jsx($t,{n:ne(w.slug)}),t.jsx("button",{type:"button",onClick:()=>L(w.slug),className:"font-serif text-[18px] font-semibold text-fg leading-tight hover:underline text-left",children:w.title||w.slug}),t.jsx(ct,{status:y}),(S==null?void 0:S.status)&&t.jsx("span",{className:"sr-only",children:S.status})]}),t.jsxs("div",{className:"flex items-center gap-4 font-mono text-xs text-fg-faint flex-wrap",children:[t.jsx(Xe,{cwd:w.cwd}),t.jsx(ze,{epicId:_.epicId,label:_.label,onOpen:la}),w.estimateMinutes!=null&&t.jsxs("span",{children:[w.estimateMinutes,"m"]}),t.jsxs("span",{className:"opacity-60",title:"parallelGroup — a unique-per-PRD display hint, never an ordering barrier. dependsOn is the real ordering primitive.",children:["g",w.parallelGroup]}),w.dependsOn&&w.dependsOn.length>0&&t.jsxs("span",{title:`depends on: ${w.dependsOn.join(", ")}`,children:["⛓ ",w.dependsOn.length," dep",w.dependsOn.length===1?"":"s"]}),t.jsxs("span",{children:["edited ",fe(w.mtimeMs,Date.now())]})]}),t.jsx("button",{type:"button",onClick:()=>L(w.slug),className:"mt-1.5 font-mono text-[11px] text-fg-faint hover:text-fg-dim leading-none",children:w.slug}),W&&t.jsxs("div",{className:"mt-3 space-y-2",children:[(S==null?void 0:S.verifierVerdict)&&t.jsxs("div",{className:"text-xs text-fg-faint",children:["verdict: ",t.jsx("span",{className:"font-mono",children:Se(S.verifierVerdict)})]}),t.jsx("button",{type:"button",onClick:()=>window.api.schedule.resetJob(w.slug),className:"text-xs px-2.5 py-1 rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:"Re-fire"})]})]}),t.jsx("div",{className:"flex flex-col gap-2 items-stretch px-[18px] py-4",children:t.jsx("button",{type:"button",onClick:()=>window.api.schedule.runNow(),disabled:P,className:"bg-fg text-bg rounded-lg px-[18px] py-2 text-[13px] font-semibold whitespace-nowrap disabled:opacity-50",children:P?"Running…":"Queue job"})})]},w.slug)})})]}),t.jsx(da,{open:g,count:b.size,busy:T,onClose:()=>v(!1),onConfirm:Z}),t.jsx(ca,{open:D,count:b.size,busy:T,onClose:()=>M(!1),onConfirm:G})]})}function da({open:e,count:s,busy:n,onClose:a,onConfirm:c}){return t.jsxs(Mt,{open:e,onClose:a,title:"Archive PRDs",children:[t.jsxs("p",{className:"text-xs text-fg-dim",children:["Move ",t.jsx("span",{className:"font-mono",children:s})," PRD",s===1?"":"s"," to"," ",t.jsx("span",{className:"font-mono",children:"prds-archived/<timestamp>/"}),"?"]}),t.jsx("p",{className:"text-[10px] text-fg-faint mt-2",children:"Files are renamed, never deleted. Restore manually from disk if needed."}),t.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[t.jsx("button",{type:"button",onClick:a,disabled:n,className:"px-2 py-1 text-xs border border-line rounded text-fg-dim hover:text-fg disabled:opacity-40",children:"Cancel"}),t.jsx("button",{type:"button",onClick:c,disabled:n||s===0,className:"px-2 py-1 text-xs border border-accent/60 text-accent rounded hover:bg-bg-hi disabled:opacity-40",children:n?"Archiving…":`Archive ${s}`})]})]})}function ca({open:e,count:s,busy:n,onClose:a,onConfirm:c}){const[o,r]=f.useState(""),[i,u]=f.useState(""),[l,d]=f.useState(null);f.useEffect(()=>{e&&(r(""),u(""),d(null))},[e]);function p(){d(null);let h=null,b=null;if(o.trim()){const x=Number(o);if(!Number.isInteger(x)||x<0||x>999){d("parallelGroup must be 0–999");return}h=x}if(i.trim()){const x=Number(i);if(!Number.isInteger(x)||x<=0){d("estimateMinutes must be a positive integer");return}b=x}if(h===null&&b===null){d("set at least one field");return}c(h,b)}return t.jsxs(Mt,{open:e,onClose:a,title:"Retag PRDs",children:[t.jsxs("p",{className:"text-xs text-fg-dim",children:["Update ",t.jsx("span",{className:"font-mono",children:s})," PRD",s===1?"":"s",". Leave a field blank to keep its current value."]}),t.jsxs("p",{className:"text-[10px] text-fg-faint mt-2",children:["Changing parallelGroup on an ",t.jsx("span",{className:"font-mono",children:"NN-kebab"})," slug renames the file. Every change is logged to ",t.jsx("span",{className:"font-mono",children:"retag-log.jsonl"})," so it's reversible."]}),t.jsxs("div",{className:"mt-3 space-y-2",children:[t.jsxs("label",{className:"flex items-center gap-2 text-xs",children:[t.jsx("span",{className:"w-32 text-fg-faint",children:"parallelGroup:"}),t.jsx("input",{type:"number",min:0,max:999,value:o,onChange:h=>r(h.target.value),placeholder:"(unchanged)",className:"flex-1 bg-bg border border-line rounded px-2 py-1 font-mono text-xs"})]}),t.jsxs("label",{className:"flex items-center gap-2 text-xs",children:[t.jsx("span",{className:"w-32 text-fg-faint",children:"estimateMinutes:"}),t.jsx("input",{type:"number",min:1,value:i,onChange:h=>u(h.target.value),placeholder:"(unchanged)",className:"flex-1 bg-bg border border-line rounded px-2 py-1 font-mono text-xs"})]})]}),l&&t.jsx("div",{className:"mt-2 text-[10px] text-red-300",children:l}),t.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[t.jsx("button",{type:"button",onClick:a,disabled:n,className:"px-2 py-1 text-xs border border-line rounded text-fg-dim hover:text-fg disabled:opacity-40",children:"Cancel"}),t.jsx("button",{type:"button",onClick:p,disabled:n||s===0,className:"px-2 py-1 text-xs border border-accent/60 text-accent rounded hover:bg-bg-hi disabled:opacity-40",children:n?"Retagging…":`Retag ${s}`})]})]})}function ua(e){Qe(e),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"terminal"}))}function Nt(e){return e?e.slice(0,10):""}const pa=[{value:"all",label:"All"},{value:"completed",label:"Completed"},{value:"skipped",label:"Skipped"},{value:"failed",label:"Failed"}];function fa({scopeCwd:e=null}){const[s,n]=f.useState(null),[a,c]=f.useState(!0),[o,r]=f.useState(""),[i,u]=f.useState(""),[l,d]=f.useState(""),[p,h]=f.useState("all");f.useEffect(()=>{c(!0),window.api.schedule.getHistory().then(v=>n(v)).catch(v=>n({ok:!1,jobs:[],error:v instanceof Error?v.message:String(v)})).finally(()=>c(!1))},[]);const b=f.useMemo(()=>{if(!(s!=null&&s.jobs))return[];const v=new Set;for(const D of s.jobs){const M=Re(D.cwd);M&&v.add(M)}return[...v].sort()},[s]),x=f.useMemo(()=>s!=null&&s.jobs?s.jobs.filter(v=>!(e&&v.cwd!==e||p!=="all"&&v.status!==p||o&&Re(v.cwd)!==o||i&&Nt(v.finishedAt)<i||l&&Nt(v.finishedAt)>l)):[],[s,p,o,i,l,e]);if(a)return t.jsx(ye,{title:"Loading history…"});if(!(s!=null&&s.ok)||s.error)return t.jsxs("div",{className:"p-4 text-xs text-red-300",children:["Failed to load history: ",(s==null?void 0:s.error)??"unknown error"]});if(s.jobs.length===0)return t.jsx(ye,{title:"No history yet",hint:"Completed and failed jobs appear here."});const g=p!=="all"||!!o||!!i||!!l;return t.jsxs("div",{className:"h-full flex flex-col",children:[t.jsxs("div",{className:"shrink-0 flex items-center gap-2 px-4 py-2.5 border-b border-line flex-wrap",children:[t.jsx(Lt,{options:pa,value:p,onChange:h,pillPadding:"px-3 py-1"}),t.jsx("span",{className:"w-px h-4 bg-line mx-1","aria-hidden":"true"}),b.length>0&&t.jsxs("select",{value:o,onChange:v=>r(v.target.value),className:"bg-bg-hi border border-line rounded-lg px-2 py-1 text-[12.5px] text-fg-dim max-w-[12rem] font-medium",children:[t.jsx("option",{value:"",children:"All projects"}),b.map(v=>t.jsx("option",{value:v,children:v},v))]}),t.jsxs("div",{className:"flex items-center gap-1.5 text-[12px] text-fg-faint",children:[t.jsx("span",{children:"from"}),t.jsx("input",{type:"date",value:i,onChange:v=>u(v.target.value),className:"bg-bg-hi border border-line rounded-lg px-2 py-1 text-fg-dim font-mono text-[12px]"})]}),t.jsxs("div",{className:"flex items-center gap-1.5 text-[12px] text-fg-faint",children:[t.jsx("span",{children:"to"}),t.jsx("input",{type:"date",value:l,onChange:v=>d(v.target.value),className:"bg-bg-hi border border-line rounded-lg px-2 py-1 text-fg-dim font-mono text-[12px]"})]}),t.jsxs("span",{className:"text-[12px] text-fg-faint ml-auto font-mono",children:[x.length," / ",s.jobs.length]}),g&&t.jsx("button",{type:"button",onClick:()=>{h("all"),r(""),u(""),d("")},className:"text-[12px] text-fg-faint hover:text-fg-dim underline",children:"clear"})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:x.length===0?t.jsx(ye,{title:"No matches",hint:"Try adjusting the filters."}):t.jsxs("div",{className:"mx-4 my-3 bg-bg-hi border border-line rounded-2xl overflow-hidden",children:[t.jsx("div",{className:"flex items-center px-[18px] py-3 bg-bg-elev",children:t.jsxs("span",{className:"font-serif text-base font-semibold text-fg",children:[x.length," job",x.length!==1?"s":""]})}),x.map(v=>t.jsx(ha,{job:v},`${v.slug}-${v.finishedAt??""}`))]})})]})}function ha({job:e}){const[s,n]=f.useState(!1),[a,c]=f.useState(!1),o=ce(h=>h.sessions),r=f.useMemo(()=>Ce(e,o),[e,o]),i=e.startedAt&&e.finishedAt?Date.parse(e.finishedAt)-Date.parse(e.startedAt):null,u=e.startedAt?new Date(e.startedAt).toLocaleString():"—",l=e.finishedAt?new Date(e.finishedAt).toLocaleString():"—",d=i!==null?ke(i):"—",p=e.exitCode!==null?String(e.exitCode):"—";return t.jsxs("div",{className:"border-t border-line/60",children:[t.jsxs("button",{type:"button",className:`w-full text-left grid items-center gap-4 px-[18px] py-3.5 cursor-pointer transition-colors hover:bg-bg-elev ${s?"bg-bg-elev":"bg-transparent"}`,style:{gridTemplateColumns:"116px 1fr auto auto"},onClick:()=>n(h=>!h),"aria-expanded":s,children:[t.jsx(Ct,{status:e.status}),t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-baseline gap-2 text-[14.5px] font-medium text-fg leading-snug text-pretty",children:[e.title,t.jsx(Pt,{leaked:e.leakedDescendants})]}),e.error&&!s&&(e.status==="failed"||e.status==="needs_review")&&t.jsx("div",{className:"text-[12.5px] mt-0.5 text-accent/80 truncate",children:e.error}),r.epicId&&t.jsx("span",{className:"flex mt-0.5",children:t.jsx(ze,{epicId:r.epicId,label:r.label,onOpen:ua})})]}),t.jsx(Xe,{cwd:e.cwd}),t.jsxs("span",{className:"inline-flex items-center gap-2.5 font-mono text-xs text-fg-faint whitespace-nowrap",children:[d,t.jsx("span",{className:"inline-flex transition-transform duration-150",style:{transform:s?"rotate(90deg)":"none"},"aria-hidden":"true",children:"›"})]})]}),s&&t.jsxs("div",{className:"grid gap-5 px-[18px] pt-1 pb-5 bg-bg-elev",style:{gridTemplateColumns:"repeat(auto-fit, minmax(160px, 1fr))"},children:[t.jsxs(se,{label:"Status",children:[t.jsx(q,{k:"result",v:p}),t.jsx(q,{k:"state",v:e.status.replace("_"," ")}),e.verifierVerdict&&t.jsx(q,{k:"verifier",v:Se(e.verifierVerdict)}),e.leakedDescendants&&e.leakedDescendants.length>0&&t.jsx(q,{k:"leaked",v:Dt(e.leakedDescendants),wrap:!0})]}),t.jsxs(se,{label:"Timing",children:[t.jsx(q,{k:"started",v:u}),t.jsx(q,{k:"finished",v:l}),t.jsx(q,{k:"duration",v:d})]}),t.jsxs(se,{label:"Location",children:[t.jsx(q,{k:"group",v:e.parallelGroup!=null?String(e.parallelGroup):"—"}),t.jsx(q,{k:"slug",v:e.slug}),t.jsx(q,{k:"epic",v:r.label??r.epicId??"—",wrap:!0}),e.cwd&&t.jsx(q,{k:"cwd",v:e.cwd,wrap:!0})]}),t.jsx(se,{label:"Actions",children:t.jsxs("div",{className:"flex flex-col gap-2 items-start",children:[e.runId&&t.jsx("button",{type:"button",onClick:h=>{h.stopPropagation(),c(!0)},className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border-0 p-0 cursor-pointer",children:"view log →"}),e.status!=="pending"&&t.jsx("button",{type:"button",onClick:h=>{h.stopPropagation(),window.api.schedule.resetJob(e.slug)},className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border-0 p-0 cursor-pointer",children:"reset to pending →"}),e.error&&t.jsx("p",{className:"text-[12px] text-accent/90 mt-1 break-words whitespace-pre-wrap max-w-sm m-0",children:e.error})]})})]}),a&&e.runId&&t.jsx(Ee,{runId:e.runId,slug:e.slug,title:e.title||e.slug,onClose:()=>c(!1)})]})}function xa(e){return e?Object.values(e).reduce((s,n)=>s+(n??[]).reduce((a,c)=>{var o;return a+(((o=c.hooks)==null?void 0:o.length)??0)},0),0):0}function ga(e){var s,n,a;return e?(((s=e.allow)==null?void 0:s.length)??0)+(((n=e.deny)==null?void 0:n.length)??0)+(((a=e.ask)==null?void 0:a.length)??0):0}function ma({navigate:e}){const s=bs(),n=ve(m=>m.files),a=ve(m=>m.loadJson),c=ve(m=>m.loadText),o=ve(m=>m.watchFile),r=ve(m=>m.unwatchFile),i=s?ws.resolve("user",s,null):null,u=s?vs.resolve("user",s,null):null,l=s?`${s}/.claude.json`:null;f.useEffect(()=>{const m=[i,l].filter(Boolean);m.forEach(N=>{n[N]||a(N),o(N)});const R=[u].filter(Boolean);return R.forEach(N=>{n[N]||c(N),o(N)}),()=>{[...m,...R].forEach(N=>r(N))}},[i,u,l]);const[d,p]=f.useState(null);f.useEffect(()=>{if(!s)return;let m=!1;return(async()=>{const R=await Cs(`${s}/.claude/skills`);m||p(R.length)})(),()=>{m=!0}},[s]);const h=i?n[i]:null,b=l?n[l]:null,x=u?n[u]:null,g=f.useMemo(()=>{if(!(h!=null&&h.exists)||h.parseError)return null;const m=h.diskData;return m===null||typeof m!="object"||Array.isArray(m)?{}:m},[h]),v=f.useMemo(()=>{if(!(b!=null&&b.exists)||b.parseError)return null;const m=b.diskData;return m===null||typeof m!="object"||Array.isArray(m)?{}:m},[b]),D=h?h.parseError?"invalid JSON":null:"loading…",M=b?b.parseError?"invalid JSON":null:"loading…",T=[{key:"settings",title:"Settings",summary:D??(g?`${Object.keys(g).length} top-level key${Object.keys(g).length===1?"":"s"} configured`:"not configured")},{key:"permissions",title:"Permissions",summary:D??(g?`${ga(g.permissions)} rule(s) configured`:"not configured")},{key:"hooks",title:"Hooks",summary:D??(g?`${xa(g.hooks)} hook(s) configured`:"not configured")},{key:"mcp",title:"MCP Servers",summary:M??(v?`${Object.keys(v.mcpServers??{}).length} MCP server(s)`:"not configured")},{key:"system-prompt",title:"System Prompt",summary:x!=null&&x.exists&&x.diskRaw.trim().length>0?`configured (${x.diskRaw.length.toLocaleString()} chars)`:"not set"},{key:"skills",title:"Skills",summary:d===null?"loading…":`${d} skill(s) installed`}];return t.jsxs("section",{className:"border border-line rounded-xl bg-bg-hi px-5 py-4",children:[t.jsx("h2",{className:"m-0 mb-1 font-serif text-[18px] font-semibold text-fg",children:"Global Controls"}),t.jsx("p",{className:"mt-0 mb-3 text-[13px] text-fg-dim leading-relaxed",children:"Machine-wide (user-scope) config state for the tabs that default to global here on Home. Read-only summary — open a card to edit."}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:T.map(m=>t.jsxs("button",{type:"button",onClick:()=>e==null?void 0:e(m.key),className:"text-left border border-line rounded-lg bg-bg px-3 py-2.5 hover:border-accent transition-colors",children:[t.jsx("div",{className:"text-[13px] font-medium text-fg",children:m.title}),t.jsx("div",{className:"mt-0.5 text-[12px] text-fg-dim",children:m.summary})]},m.key))})]})}function ba({navigate:e}){const s=js(),[n,a]=f.useState(!1),[c,o]=f.useState(!1),[r,i]=f.useState(null);f.useEffect(()=>{let l=!0;return ys().then(d=>{l&&a(d.openToHomeOnLaunch===!0)}),()=>{l=!1}},[]),f.useEffect(()=>{var d,p;let l=!0;return(p=(d=window.api.schedule).worktreeBase)==null||p.call(d).then(h=>{l&&i(h)}).catch(()=>{}),()=>{l=!1}},[]);const u=async l=>{a(l),o(!0);try{await ks({openToHomeOnLaunch:l})}catch{a(!l),V.error('Failed to save "Open to Home on launch" — try again.')}finally{o(!1)}};return t.jsxs("div",{className:"max-w-[760px] space-y-6",children:[t.jsx(ma,{navigate:e}),t.jsxs("section",{className:"border border-line rounded-xl bg-bg-hi px-5 py-4",children:[t.jsx("h2",{className:"m-0 mb-1 font-serif text-[18px] font-semibold text-fg",children:"Session pool"}),t.jsxs("p",{className:"mt-0 mb-3 text-[13px] text-fg-dim leading-relaxed",children:["One machine-wide pool of concurrent Claude sessions. Scheduler jobs and Epic chat runs each request a slot before launching; work waits when the pool is full. Adjustable from 0 (pauses new launches) to 10 on the Home tab, default 5 — or pin it with"," ",t.jsx("code",{className:"font-mono text-[12px]",children:"SM_SESSION_SLOTS"})," (clamped 0–10)."]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ns,{total:(s==null?void 0:s.total)??5,inUse:(s==null?void 0:s.inUse)??0,size:"md"}),t.jsx("span",{className:"ml-2 font-mono text-[12.5px] text-fg-faint",children:s?`${s.inUse} / ${s.total} in use`:"loading…"})]}),s&&s.holders.length>0&&t.jsx("ul",{className:"mt-2 mb-0 pl-0 list-none space-y-0.5",children:s.holders.map((l,d)=>t.jsxs("li",{className:"font-mono text-[12px] text-fg-dim",children:[l.owner," ",t.jsxs("span",{className:"text-fg-faint",children:["since ",new Date(l.at).toLocaleTimeString()]})]},d))})]}),t.jsxs("section",{className:"border border-line rounded-xl bg-bg-hi px-5 py-4",children:[t.jsx("h2",{className:"m-0 mb-1 font-serif text-[18px] font-semibold text-fg",children:"Behavior"}),t.jsx("p",{className:"mt-0 mb-3 text-[13px] text-fg-dim leading-relaxed",children:"Cross-project app behavior, independent of any single project's config."}),t.jsx($s,{checked:n,onChange:u,disabled:c,label:"Open to Home on launch"})]}),t.jsxs("section",{className:"border border-line rounded-xl bg-bg-hi px-5 py-4",children:[t.jsx("h2",{className:"m-0 mb-1 font-serif text-[18px] font-semibold text-fg",children:"On disk"}),t.jsxs("p",{className:"mt-0 mb-2 text-[13px] text-fg-dim leading-relaxed",children:["Global runtime state is deliberately small — everything project-scoped lives inside that project's ",t.jsx("code",{className:"font-mono text-[12px]",children:"session-manager-operations/"})," folder."]}),t.jsxs("ul",{className:"m-0 pl-0 list-none space-y-1 font-mono text-[12px] text-fg-dim",children:[t.jsxs("li",{children:["~/.claude/session-manager/scheduler-machine.json ",t.jsx("span",{className:"text-fg-faint",children:"— policy + pause state"})]}),t.jsxs("li",{"data-testid":"worktree-base-path",children:[r??"…","/session-manager-epic-worktrees/ ",t.jsx("span",{className:"text-fg-faint",children:"— Epic git worktrees (SM_WORKTREE_ROOT overrides)"})]}),t.jsxs("li",{children:["<project>/session-manager-operations/scheduler/state/ ",t.jsx("span",{className:"text-fg-faint",children:"— per-project queue + history"})]}),t.jsxs("li",{children:["<project>/session-manager-operations/scheduler/epics/<epic>/prds/ ",t.jsx("span",{className:"text-fg-faint",children:"— PRD sources, per session"})]})]})]})]})}const kt="sm.schedulerTab.subView";function wa({navigate:e}={}){var x;const[s,n]=f.useState("graph"),[a,c]=f.useState(""),[o,r]=f.useState(null),[i,u]=f.useState(()=>{const g=localStorage.getItem(kt);return g==="prds"||g==="history"||g==="machine"?g:"queue"}),l=ut(g=>g.tabs),d=ut(g=>g.activeTabId),p=((x=l.find(g=>g.id===d))==null?void 0:x.cwd)??null,h=p;f.useEffect(()=>{p&&(ce.getState().hydrate(p),ce.getState().hydrateArchived(p))},[p]);const b=f.useCallback(g=>{g&&Ss(g),u("prds")},[]);return f.useEffect(()=>{localStorage.setItem(kt,i)},[i]),t.jsxs("div",{className:"h-full flex flex-col",children:[t.jsx(zs,{scopeCwd:h,subView:i,onSubView:u,filterText:a,onFilterText:c,planMode:s,onPlanMode:n,planToolsRef:r}),t.jsxs("div",{className:"flex-1 min-h-0",children:[i==="queue"&&t.jsx(zn,{scopeCwd:h,navigate:e,filterText:a,planMode:s,onOpenPrds:b,planToolsEl:o}),i==="prds"&&t.jsx(oa,{scopeCwd:h}),i==="history"&&t.jsx(fa,{scopeCwd:h}),i==="machine"&&t.jsx("div",{className:"h-full overflow-y-auto px-9 py-6",children:t.jsx(ba,{navigate:e})})]})]})}const ka=f.memo(wa);export{ka as Scheduler};