claude-code-session-manager 0.65.0 → 0.66.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 (60) hide show
  1. package/dist/assets/AgentLibrary-Bzg89D5Y.js +3 -0
  2. package/dist/assets/{History-DB-9-zwc.js → History-CNH9vA0A.js} +2 -2
  3. package/dist/assets/{Hooks-DnxqMRrR.js → Hooks-CyTksPza.js} +3 -3
  4. package/dist/assets/{HostBilko-Cw6JocV7.js → HostBilko-DXQVDNHn.js} +1 -1
  5. package/dist/assets/{Library-BYSB0dmY.js → Library-9E2UOIsm.js} +1 -1
  6. package/dist/assets/{ListDetail-BfKqnL0r.js → ListDetail-CQWU_Yn5.js} +1 -1
  7. package/dist/assets/{MarkdownEditor-Cs-l5JOv.js → MarkdownEditor-DQgfpSef.js} +1 -1
  8. package/dist/assets/{McpServers-bBqj3hGg.js → McpServers-r3qwDIj2.js} +2 -2
  9. package/dist/assets/{Memory-DzPGXT5J.js → Memory-BaxOpj-3.js} +6 -6
  10. package/dist/assets/{Panel-BX6UZ-W0.js → Panel-BhFD8Lqo.js} +1 -1
  11. package/dist/assets/{Permissions-Db7S4T3Z.js → Permissions-Cj-mODQQ.js} +3 -3
  12. package/dist/assets/{Plugins-CIuey9R3.js → Plugins-DEL3Fqng.js} +2 -2
  13. package/dist/assets/{ProvenanceBadge-FPWNWc_-.js → ProvenanceBadge-CIAg6-JQ.js} +1 -1
  14. package/dist/assets/Scheduler-YOuZKkES.js +14 -0
  15. package/dist/assets/{ScopeSwitcher-DU7M_q5-.js → ScopeSwitcher-DZ_3gEus.js} +1 -1
  16. package/dist/assets/{Settings-DEptXcEY.js → Settings-B0x4oflz.js} +3 -3
  17. package/dist/assets/{SkillReferenceGraph-CprLcOCe.js → SkillReferenceGraph-CoIwsol8.js} +1 -1
  18. package/dist/assets/{Skills-CGN56X1i.js → Skills-CN8R6AWn.js} +2 -2
  19. package/dist/assets/{SystemPrompt-DIEK7FpJ.js → SystemPrompt-DceChpAi.js} +1 -1
  20. package/dist/assets/{TagLibrary-q66s4N3i.js → TagLibrary-BKmz2W7B.js} +1 -1
  21. package/dist/assets/{TiptapBody-I22aArc2.js → TiptapBody-W7n5SwPM.js} +1 -1
  22. package/dist/assets/{Toggle-D9sapSAv.js → Toggle-QuxlVHGI.js} +1 -1
  23. package/dist/assets/{index-LlWpj2VJ.css → index-14dBLqE_.css} +1 -1
  24. package/dist/assets/{index-BRwaw_1W.js → index-TejhHSzN.js} +526 -525
  25. package/dist/assets/{settingsSchema-CTc4qelV.js → settingsSchema-DNqx6BKJ.js} +1 -1
  26. package/dist/index.html +2 -2
  27. package/package.json +1 -1
  28. package/plugins/session-manager-dev/skills/develop/SKILL.md +41 -13
  29. package/plugins/session-manager-dev/skills/ops-sweep/SKILL.md +10 -0
  30. package/src/main/__tests__/agentLibrary.test.cjs +40 -0
  31. package/src/main/__tests__/flatPrdTickSweep.test.cjs +110 -0
  32. package/src/main/__tests__/prdAdminRouteParity.test.cjs +68 -0
  33. package/src/main/__tests__/prdAdminRoutes.test.cjs +311 -0
  34. package/src/main/__tests__/prdCreate.test.cjs +7 -2
  35. package/src/main/__tests__/prdMigration.test.cjs +17 -0
  36. package/src/main/__tests__/prdMigrationLegacyAdopt.test.cjs +91 -0
  37. package/src/main/__tests__/reconcileFlatPrdSweep.test.cjs +109 -0
  38. package/src/main/__tests__/scheduleJobSchema.test.cjs +127 -0
  39. package/src/main/__tests__/scheduleJobStatusDrift.test.cjs +65 -0
  40. package/src/main/__tests__/scheduleJobTransitions.test.cjs +152 -0
  41. package/src/main/__tests__/scheduleJobTransitionsGrep.test.cjs +59 -0
  42. package/src/main/__tests__/scheduler-reconcile-invalid-repair.test.cjs +203 -0
  43. package/src/main/__tests__/scheduler-reconcile-quarantine.test.cjs +196 -0
  44. package/src/main/agentLibrary.cjs +40 -2
  45. package/src/main/index.cjs +2 -0
  46. package/src/main/ipcSchemas.cjs +60 -0
  47. package/src/main/lib/localAdminHttp.cjs +10 -3
  48. package/src/main/lib/prdAdminRoutes.cjs +175 -0
  49. package/src/main/lib/prdCreate.cjs +37 -2
  50. package/src/main/lib/prdFrontmatter.cjs +179 -1
  51. package/src/main/lib/prdMigration.cjs +82 -5
  52. package/src/main/lib/queueStore.cjs +41 -7
  53. package/src/main/lib/scheduleJobSchema.cjs +114 -0
  54. package/src/main/lib/scheduleJobTransitions.cjs +164 -0
  55. package/src/main/scheduler/prdParser.cjs +7 -0
  56. package/src/main/scheduler.cjs +649 -137
  57. package/src/preload/api.d.ts +54 -2
  58. package/src/preload/index.cjs +12 -0
  59. package/dist/assets/AgentLibrary-DYriNDGf.js +0 -1
  60. package/dist/assets/Scheduler-X5y252Qw.js +0 -14
@@ -208,6 +208,14 @@ export interface AgentPersona {
208
208
  color: string | null;
209
209
  /** Epic intent tags (tagLibrary.ts's TAG_LIBRARY) this persona is associated with. */
210
210
  tags: string[];
211
+ /** Project cwds whose Sessions toolbar shows a one-click Action button for this
212
+ * agent. The single entry `'*'` means every project. Empty = no Action button. */
213
+ projects: string[];
214
+ /** The opening instruction that Action button sends into the new session.
215
+ * Null when this persona isn't wired as an Action. */
216
+ action: string | null;
217
+ /** Caption override for the Action button (defaults to the persona name). */
218
+ actionLabel: string | null;
211
219
  /** "<Department> — <Human title>" (e.g. "Engineering — Architect"), free text — drives
212
220
  * department grouping in the New Epic Agent picker. Optional/null when not set. */
213
221
  title?: string | null;
@@ -227,6 +235,12 @@ export interface AgentPersonaSaveInput {
227
235
  model: string;
228
236
  color: string;
229
237
  tags: string[];
238
+ /** Project cwds (or the `'*'` sentinel) this persona's Action button appears in. */
239
+ projects?: string[];
240
+ /** Opening instruction sent by this persona's Action button. */
241
+ action?: string;
242
+ /** Caption override for this persona's Action button. */
243
+ actionLabel?: string;
230
244
  title?: string;
231
245
  body: string;
232
246
  }
@@ -346,7 +360,13 @@ export interface ScheduleConfig {
346
360
  schemaVersion: 1;
347
361
  }
348
362
 
349
- export type ScheduleJobStatus = 'pending' | 'running' | 'investigating' | 'completed' | 'failed' | 'needs_review';
363
+ /** Mirrors JOB_STATUSES (src/main/lib/scheduleJobSchema.cjs) — the single
364
+ * source of truth asserted at read time by queueStore.cjs's shapeJobs. This
365
+ * file can't require that .cjs module (types-only, erased at build time),
366
+ * so this union is a manually-kept copy; drift from JOB_STATUSES (and from
367
+ * the renderer's own mirrors in StatusBadge.tsx/SchedulePanel.tsx) is
368
+ * caught by src/main/__tests__/scheduleJobStatusDrift.test.cjs. */
369
+ export type ScheduleJobStatus = 'pending' | 'running' | 'investigating' | 'completed' | 'failed' | 'needs_review' | 'quarantined';
350
370
 
351
371
  export interface ScheduleJobRuntime {
352
372
  pid: number;
@@ -405,6 +425,19 @@ export interface ScheduleJob {
405
425
  * intent-carrying `sourcePromptId`/`sourceTabId`, which can disagree.
406
426
  * Authoritative source for "which Epic is this from" in every UI. */
407
427
  epicId?: string | null;
428
+ /** Bounded trail of accepted status transitions (scheduleJobTransitions.cjs's
429
+ * transitionJob), oldest-first, capped at ~20 entries. Lets a status
430
+ * change be reviewed after the fact instead of only inferred from a
431
+ * heartbeat count. */
432
+ statusHistory?: ScheduleJobStatusHistoryEntry[];
433
+ }
434
+
435
+ export interface ScheduleJobStatusHistoryEntry {
436
+ from: string | null;
437
+ to: string;
438
+ reason: string | null;
439
+ source: string | null;
440
+ at: string;
408
441
  }
409
442
 
410
443
  export interface SchedulePaths {
@@ -522,6 +555,12 @@ export interface ScheduleEffectiveConcurrency {
522
555
  source: 'env' | 'pool';
523
556
  }
524
557
 
558
+ export interface ScheduleStallEvent {
559
+ message: string;
560
+ total: number;
561
+ byProject: Record<string, Record<string, number>>;
562
+ }
563
+
525
564
  export interface ScheduleStateSnapshot {
526
565
  config: ScheduleConfig & { supervisor?: SupervisorConfig };
527
566
  /** Why the last tick fired (or didn't). Null before the first tick. */
@@ -1128,7 +1167,16 @@ export interface ChatCreatePrdPayload {
1128
1167
  }
1129
1168
 
1130
1169
  export type ChatCreatePrdResult =
1131
- | { ok: true; nn: number; filename: string }
1170
+ | {
1171
+ ok: true;
1172
+ nn: number;
1173
+ filename: string;
1174
+ prdPath: string | null;
1175
+ epicId: string | null;
1176
+ /** Always false — this call only writes the PRD file; the queue row is derived by the next scheduler reconcile pass, never created here. */
1177
+ enqueued: false;
1178
+ note: string;
1179
+ }
1132
1180
  | { ok: false; status: number; error: string };
1133
1181
 
1134
1182
  export interface ChatRunQueuedEvent {
@@ -1412,12 +1460,16 @@ export interface SessionManagerAPI {
1412
1460
  listPrds: () => Promise<PrdListItem[]>;
1413
1461
  health: () => Promise<ScheduleHealthSnapshot>;
1414
1462
  onState: (handler: (snapshot: ScheduleStateSnapshot) => void) => () => void;
1463
+ /** Heartbeat-driven stall alert: queue holds jobs but 0 running / 0 pending / not paused for a full poll interval. Fires at most once per stall episode. */
1464
+ onStall: (handler: (event: ScheduleStallEvent) => void) => () => void;
1415
1465
  /** Bundle D — scan all PRDs for unbounded loops + missing frontmatter. */
1416
1466
  lintQueue: () => Promise<LintQueueResult>;
1417
1467
  /** Bundle D — move PRDs to prds-archived/<ISO>/. Never deletes. */
1418
1468
  archivePrds: (slugs: string[]) => Promise<ArchivePrdResult>;
1419
1469
  /** Bundle D — bulk retag parallelGroup and/or estimateMinutes. */
1420
1470
  retagPrds: (items: RetagPrdItem[]) => Promise<RetagPrdResult>;
1471
+ /** Stamps a 'quarantined' PRD (no createdVia provenance) as legacy-adopted via the update-prd API, then reconciles it to 'pending'. */
1472
+ adoptPrd: (slug: string) => Promise<ActionOutcome>;
1421
1473
  /** Return the last N completed/failed jobs from queue.json (newest first). */
1422
1474
  getHistory: (limit?: number) => Promise<ScheduleHistoryResult>;
1423
1475
  };
@@ -233,10 +233,22 @@ contextBridge.exposeInMainWorld('api', {
233
233
  ipcRenderer.on('schedule:state', listener);
234
234
  return () => ipcRenderer.removeListener('schedule:state', listener);
235
235
  },
236
+ // Heartbeat-driven stall alert (PRD: queue holds jobs but 0 running / 0
237
+ // pending / not paused for a full poll interval) — rate-limited to one
238
+ // push per stall episode by the main-process heartbeat, not per-tick.
239
+ onStall: (handler) => {
240
+ const listener = (_e, payload) => handler(payload);
241
+ ipcRenderer.on('schedule:stall', listener);
242
+ return () => ipcRenderer.removeListener('schedule:stall', listener);
243
+ },
236
244
  // Bundle D — queue ops (queueOps.cjs).
237
245
  lintQueue: () => ipcRenderer.invoke('schedule:lint-queue'),
238
246
  archivePrds: (slugs) => ipcRenderer.invoke('schedule:archive-prd', { slugs }),
239
247
  retagPrds: (items) => ipcRenderer.invoke('schedule:retag-prd', { items }),
248
+ // Stamps a quarantined PRD's provenance (createdVia: legacy-adopted) via
249
+ // the same update-prd API path the admin route/MCP tool use, then
250
+ // reconciles so the row promotes to 'pending' on the very same call.
251
+ adoptPrd: (slug) => ipcRenderer.invoke('schedule:adopt-prd', { slug }),
240
252
  // History — last N completed/failed jobs from queue.json.
241
253
  getHistory: (limit) => ipcRenderer.invoke('schedule:get-history', limit !== undefined ? { limit } : {}),
242
254
  },
@@ -1 +0,0 @@
1
- import{I as e,o as q,X as c,c as F,a as P,a4 as h,a1 as Q,T as U,a3 as V}from"./index-BRwaw_1W.js";import{P as Z}from"./Panel-BX6UZ-W0.js";import{L as ee}from"./ListDetail-BfKqnL0r.js";import"./monaco-editor-BW5C4Iv1.js";function j({children:a,onClick:r,disabled:d,variant:x="default",tooltip:o,type:f="button",className:v}){const S=`px-2 py-0.5 text-xs rounded border transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${x==="primary"?"text-accent border-accent/50 hover:bg-bg-hi":x==="danger"?"text-red-400 hover:text-red-300 border-line hover:border-red-400/50":"text-fg-dim border-line hover:text-fg hover:bg-bg-hi"} ${v??""}`,g=e.jsx("button",{type:f,title:o,onClick:r,disabled:d,className:S,children:a});return o?e.jsx(q,{content:o,align:"bottom-center",children:g}):g}const te=["inherit","haiku","sonnet","opus"],B=["Read","Grep","Glob","Bash","Write","Edit","WebFetch","WebSearch","Task"],ne=["","red","orange","yellow","green","cyan","blue","purple","pink"],W={red:"#c0392b",orange:"#b85c34",yellow:"#c9a227",green:"#6f7d52",cyan:"#3f8f8a",blue:"#4a6fa5",purple:"#7a6a8a",pink:"#b45a80"};function R(a){return{name:a.name,description:a.description??"",tools:a.tools,model:a.model??"inherit",color:a.color??"",tags:a.tags,body:a.body}}const G={name:"new-agent",description:"",tools:["Read","Grep"],model:"inherit",color:"",tags:[],body:""};function ae(){const[a,r]=c.useState(null),[d,x]=c.useState(null),[o,f]=c.useState(""),[v,m]=c.useState(null),[S,g]=c.useState(!1),[L,w]=c.useState(!1),[E,y]=c.useState(null),[N,n]=c.useState(!1),u=c.useRef(!0);c.useEffect(()=>()=>{u.current=!1},[]);const p=async t=>{try{const i=await window.api.agents.listPersonas();if(!u.current)return;r(i),x(k=>{var D;return t??k??((D=i[0])==null?void 0:D.name)??null})}catch(i){if(!u.current)return;r([]),h.error(i.message||"failed to load agent personas")}};if(c.useEffect(()=>{p()},[]),c.useEffect(()=>window.api.agents.onChanged(()=>p()),[]),c.useEffect(()=>{const t=Q();t&&x(t);const i=k=>x(k.detail);return window.addEventListener("sm:select-persona",i),()=>window.removeEventListener("sm:select-persona",i)},[]),a===null)return e.jsx(F,{title:"loading…"});const $=o.toLowerCase(),T=a.filter(t=>!$||t.name.toLowerCase().includes($)||(t.description??"").toLowerCase().includes($)),l=a.find(t=>t.name===d)??a[0]??null,s=v??(l?R(l):null),A=!!v&&!!l&&JSON.stringify(v)!==JSON.stringify(R(l)),C=S,z=t=>{m(null),g(!1),w(!1),y(null),x(t)},_=t=>m(i=>({...i??(l?R(l):G),...t})),I=()=>{m({...G}),g(!0),w(!1)},J=()=>{s&&(m({...s,name:s.name+"-copy"}),g(!0))},K=()=>{m(null),g(!1)},H=async()=>{if(s){if(!/^[a-z][a-z0-9-]*$/.test(s.name)){h.error('agent name must be lowercase, hyphenated (e.g. "my-agent")');return}n(!0);try{const t={name:s.name,originalName:C||l==null?void 0:l.name,description:s.description,tools:s.tools,model:s.model,color:s.color,tags:s.tags,body:s.body};await window.api.agents.savePersona(t),h.info(C?`created ${s.name}`:`saved ${s.name}`),m(null),g(!1),await p(s.name)}catch(t){h.error(t.message||"failed to save agent persona")}finally{n(!1)}}},M=async()=>{if(l){n(!0);try{await window.api.agents.deletePersona({name:l.name}),h.info(`deleted ${l.name}`),w(!1),m(null),g(!1),await p()}catch(t){h.error(t.message||"failed to delete agent persona")}finally{n(!1)}}},X=async t=>{n(!0);try{await window.api.agents.deletePersona({name:t}),h.info(`deleted ${t}`),y(null),d===t&&(m(null),g(!1)),await p()}catch(i){h.error(i.message||"failed to delete agent persona")}finally{n(!1)}},Y=async t=>{if(l)try{await window.api.agents.removeOverride({name:l.name,projectName:t}),h.info(`removed ${t}'s override of ${l.name}`),await p(l.name)}catch(i){h.error(i.message||"failed to remove override")}};return e.jsx(Z,{toolbar:e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-fg-faint",children:[a.length," persona",a.length===1?"":"s"]}),e.jsx("input",{value:o,onChange:t=>f(t.target.value),placeholder:"filter…",className:"bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg w-40"}),e.jsx("div",{className:"flex-1"}),e.jsx(j,{variant:"primary",onClick:I,children:"+ New agent"})]}),children:e.jsx(ee,{sidebar:e.jsxs("div",{className:"py-1",children:[C&&e.jsx("div",{className:"w-full text-left px-3 py-1 text-xs flex flex-col gap-0.5 bg-bg-hi text-fg border-l-2 border-accent",children:e.jsxs("span",{className:"flex items-center gap-2 justify-between w-full",children:[e.jsx("span",{className:"truncate font-mono",children:s==null?void 0:s.name}),e.jsx("span",{className:"shrink-0 text-[10px] font-semibold text-accent",children:"new"})]})}),T.length===0&&!C?e.jsx("div",{className:"px-3 py-1 text-xs text-fg-faint italic",children:"no agent personas found"}):T.map(t=>{const i=!C&&t.name===d,k=i&&A,D=E===t.name;return e.jsxs("div",{"data-agent-row":t.name,className:`group w-full text-left px-3 py-1 text-xs flex flex-col gap-0.5 border-l-2 cursor-pointer ${i?"bg-bg-hi text-fg border-accent":"text-fg-dim hover:text-fg hover:bg-bg-hi border-transparent"}`,onClick:()=>z(t.name),children:[e.jsxs("span",{className:"flex items-center gap-2 justify-between w-full",children:[e.jsxs("span",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx("span",{className:"w-2 h-2 rounded-sm shrink-0",style:{background:t.color?W[t.color]??t.color:"var(--fg-faint, #999)",opacity:t.color?1:.35}}),e.jsx("span",{className:"truncate font-mono",children:t.name})]}),e.jsxs("span",{className:"shrink-0 flex items-center gap-1.5",children:[k&&e.jsx("span",{className:"text-[10px] font-semibold text-accent",children:"unsaved"}),!k&&t.overridingProjects.length>0&&e.jsxs(P,{tone:"dim",children:[t.overridingProjects.length," override",t.overridingProjects.length>1?"s":""]}),D?e.jsxs("span",{className:"flex items-center gap-1",onClick:O=>O.stopPropagation(),children:[e.jsx("button",{onClick:()=>X(t.name),disabled:N,title:`Delete ${t.name}`,className:"text-[10px] font-semibold text-red-400 hover:text-red-300",children:"confirm"}),e.jsx("button",{onClick:()=>y(null),title:"Cancel",className:"text-[10px] text-fg-faint hover:text-fg",children:"cancel"})]}):e.jsx("button",{onClick:O=>{O.stopPropagation(),y(t.name)},title:`Delete ${t.name}`,className:"opacity-0 group-hover:opacity-100 text-fg-faint hover:text-red-400 transition-opacity",children:"×"})]})]}),t.description&&e.jsx("span",{className:"truncate text-fg-faint",children:t.description})]},t.name)})]}),detail:s?e.jsx(se,{obj:s,set:_,saved:l,dirty:A,isNew:C,busy:N,confirmDelete:L,setConfirmDelete:w,onDuplicate:J,onRevert:K,onSave:H,onDelete:M,onDropOverride:Y}):e.jsx(F,{title:"select an agent"})})})}const de=c.memo(ae);function se({obj:a,set:r,saved:d,dirty:x,isNew:o,busy:f,confirmDelete:v,setConfirmDelete:m,onDuplicate:S,onRevert:g,onSave:L,onDelete:w,onDropOverride:E}){const y=`~/.claude/agents/${a.name}.md`,N=x||o;return e.jsxs("div",{className:"max-w-3xl",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-line flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-semibold text-fg font-mono",children:a.name}),o?e.jsx(P,{tone:"accent",children:"unsaved draft"}):x?e.jsx(P,{tone:"warn",children:"edited"}):e.jsx(P,{tone:"good",children:"saved"}),e.jsx("span",{className:"ml-auto text-[11px] text-fg-faint font-mono",children:y})]}),e.jsxs("div",{className:"p-4 space-y-4",children:[e.jsx(b,{label:"name",hint:"Filename on disk — lowercase, hyphenated.",children:e.jsx("input",{value:a.name,onChange:n=>r({name:n.target.value.toLowerCase()}),className:"w-full bg-bg border border-line rounded px-2 py-1 text-xs text-fg font-mono"})}),e.jsx(b,{label:"description",hint:"Shown in the list and in agent pickers.",children:e.jsx("input",{value:a.description,onChange:n=>r({description:n.target.value}),className:"w-full bg-bg border border-line rounded px-2 py-1 text-xs text-fg"})}),e.jsx(b,{label:"default model",hint:"This persona's default model for its Epics — sets the --model an Epic launches with (Terminal + Chat both honor it). 'inherit' falls back to each view's own default, not this Settings page. Cheap models for read-only personas; opus for judgement calls.",children:e.jsx(re,{options:te,value:a.model,onChange:n=>r({model:n}),mono:!0})}),e.jsx(b,{label:"tools",hint:`${a.tools.length} of ${B.length} granted. Anything not ticked is refused at call time.`,children:e.jsx("div",{className:"flex flex-wrap gap-1.5",children:B.map(n=>{const u=a.tools.includes(n);return e.jsx("button",{onClick:()=>r({tools:u?a.tools.filter(p=>p!==n):[...a.tools,n]}),className:`px-2 py-0.5 rounded-full text-[11px] font-mono border ${u?"bg-sage/15 text-sage-dark border-sage/30":"bg-bg-hi text-fg-faint border-line"}`,children:n},n)})})}),e.jsx(b,{label:"color",children:e.jsx("div",{className:"flex gap-1.5",children:ne.map(n=>e.jsx("button",{title:n||"none",onClick:()=>r({color:n}),className:"w-5 h-5 rounded",style:{background:n?W[n]:"transparent",border:a.color===n?"2px solid var(--accent, #b85c34)":"1px solid var(--line, #555)"}},n||"none"))})}),e.jsx(b,{label:"tags",hint:"Epic intent tags this persona is associated with — shown as the default agent on that tag's own page.",children:e.jsx("div",{className:"flex flex-wrap gap-1.5",children:U.map(n=>{const u=a.tags.includes(n.tag),p=V(n.tag);return e.jsxs("button",{onClick:()=>r({tags:u?a.tags.filter($=>$!==n.tag):[...a.tags,n.tag]}),className:`px-2 py-0.5 rounded-full text-[11px] font-mono border ${u?`${p.bg} ${p.text} ${p.border?"border-current/30":"border-transparent"}`:"bg-bg-hi text-fg-faint border-line"}`,children:["#",n.tag]},n.tag)})})}),e.jsx(b,{label:"definition",hint:"The system prompt this persona runs under.",children:e.jsx("textarea",{rows:9,value:a.body,onChange:n=>r({body:n.target.value}),className:"w-full bg-bg border border-line rounded px-2 py-1.5 text-xs text-fg font-mono leading-relaxed resize-y"})}),e.jsx(b,{label:"project overrides",hint:"Open projects that shadow this definition with a local copy.",children:d&&d.overridingProjects.length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:d.overridingProjects.map(n=>e.jsxs("span",{className:"inline-flex items-center gap-1.5 bg-bg-elev border border-line rounded px-2 py-0.5 text-[11px] font-mono text-fg-dim",children:[n,e.jsx("button",{onClick:()=>E(n),title:"Drop the local copy",className:"text-fg-faint hover:text-fg",children:"×"})]},n))}):e.jsx("div",{className:"text-xs text-fg-faint italic",children:o?"save first to see project overrides.":"no open project overlays this agent — the global definition applies everywhere."})})]}),e.jsx("div",{className:"px-4 py-2.5 border-t border-line flex items-center gap-2 flex-wrap",children:v?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-xs text-fg-dim",children:["Delete ",e.jsx("strong",{className:"font-mono",children:a.name})," and its file?"]}),e.jsx(j,{variant:"danger",onClick:w,disabled:f,children:"Delete"}),e.jsx(j,{onClick:()=>m(!1),children:"Keep"})]}):e.jsxs(e.Fragment,{children:[e.jsx(j,{onClick:S,disabled:f,children:"Duplicate"}),!o&&e.jsx(j,{variant:"danger",onClick:()=>m(!0),disabled:f,children:"Delete"}),e.jsx("div",{className:"flex-1"}),N&&e.jsx("span",{className:"text-[11px] text-fg-faint",children:"unsaved changes"}),e.jsx(j,{onClick:g,disabled:!N||f,children:"Revert"}),e.jsx(j,{variant:"primary",onClick:L,disabled:!N||f,children:f?"Saving…":o?"Create":"Save"})]})})]})}function b({label:a,hint:r,children:d}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[10.5px] font-semibold uppercase tracking-wide text-fg-faint mb-1.5 font-mono",children:a}),d,r&&e.jsx("div",{className:"text-[11px] text-fg-faint mt-1 leading-snug",children:r})]})}function re({options:a,value:r,onChange:d,mono:x}){return e.jsx("div",{className:"flex flex-wrap gap-1",children:a.map(o=>{const f=o===r;return e.jsx("button",{onClick:()=>d(o),className:`px-2.5 py-1 rounded text-xs border ${x?"font-mono":""} ${f?"bg-accent/15 text-accent border-accent/40 font-semibold":"bg-bg-hi text-fg-dim border-line"}`,children:o},o)})})}export{de as AgentLibrary};
@@ -1,14 +0,0 @@
1
- import{I as e,af as we,X as r,ac as Te,A as ue,t as V,a4 as O,y as q,G as le,v as Y,W as be,F as Le,ad as re,$ as ve,a0 as je,w as ke,ai as de,n as Me,N as W,g as Oe,d as Ne,i as ye,D as G,b as D,l as Fe,O as Pe,a8 as Ce,c as ae,h as Ae,E as Ue,a2 as Ve,o as ze,M as _e,a9 as Qe,a7 as se,m as We,C as Ye,ag as Ke,Y as Xe,aj as Ze,ah as $e,L as et,f as he}from"./index-BRwaw_1W.js";import{l as tt}from"./listSkills-QORduPIk.js";import{T as st}from"./Toggle-D9sapSAv.js";import"./monaco-editor-BW5C4Iv1.js";function nt({options:t,active:s,onChange:n}){return e.jsx("div",{className:"inline-flex gap-1 bg-bg-hi p-1 rounded-xl shadow-[inset_0_0_0_1px] shadow-line",children:t.map(({key:a,label:p})=>{const i=s===a;return e.jsx("button",{type:"button",onClick:()=>n(a),className:`px-[18px] py-[7px] rounded-lg text-[13.5px] transition-colors ${i?"bg-bg-elev shadow-[inset_0_0_0_1px] shadow-line font-semibold text-fg":"font-medium text-fg-dim hover:text-fg"}`,children:p},a)})})}const at=5e3;let oe=null,ne=null;async function De(t){const s=Date.now();return!(t!=null&&t.fresh)&&oe&&s-oe.at<at?oe.result:ne||(ne=(async()=>{try{const n=await window.api.schedule.lintQueue();return oe={result:n,at:Date.now()},n}finally{ne=null}})(),ne)}const lt=5,rt=1440*60*1e3,He="sm.scheduler.hiddenCompletedSlugs",ce="sm.scheduler.focusedJobIndex",qe="sm.scheduler.queueFilter";function it(t,s=60){const n=t.trim();return n.length<=s?n:`${n.slice(0,s-1)}…`}const ot=["all","running","investigating","pending","completed","needs_review","failed"];function ct(){try{const t=localStorage.getItem(qe);if(!t)return{text:"",status:"all"};const s=JSON.parse(t);return{text:"",status:ot.includes(s.status)?s.status:"all"}}catch{return{text:"",status:"all"}}}function dt(t){try{localStorage.setItem(qe,JSON.stringify({status:t.status}))}catch{}}function ut(t,s){if(s.status==="all"&&!s.text)return t;const n=s.text.toLowerCase();return t.filter(a=>{if(s.status!=="all"&&a.status!==s.status)return!1;if(!n)return!0;const p=be(a.cwd)??"";return a.title.toLowerCase().includes(n)||a.slug.toLowerCase().includes(n)||p.toLowerCase().includes(n)})}function xt(){try{const t=localStorage.getItem(He);if(!t)return new Set;const s=JSON.parse(t);return Array.isArray(s)?new Set(s.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function Re(t){try{localStorage.setItem(He,JSON.stringify([...t]))}catch{}}function pt({scopeCwd:t=null,navigate:s}){const n=we(x=>x.snapshot),a=r.useMemo(()=>!n||!t?n:{...n,jobs:n.jobs.filter(x=>x.cwd===t)},[n,t]),[p,i]=r.useState(null),[c,u]=r.useState(!1),[o,d]=r.useState(()=>Date.now()),[b,w]=r.useState(()=>xt()),[h,v]=r.useState(!1),[N,C]=r.useState(()=>ct()),[f,j]=r.useState(!1),[A,k]=r.useState("queue"),g=r.useRef(null),[I,P]=r.useState(()=>{try{return Number(localStorage.getItem(ce))||0}catch{return 0}}),[B,xe]=r.useState(""),J=Te();r.useEffect(()=>(window.api.schedule.health().then(i).catch(()=>{}),window.api.schedule.onState(()=>{window.api.schedule.health().then(i).catch(()=>{})})),[]),r.useEffect(()=>{if(!J)return;d(Date.now());const x=setInterval(()=>d(Date.now()),1e3);return()=>clearInterval(x)},[J]);const L=r.useMemo(()=>{if(!a)return 15e4;const x=[];for(const y of a.jobs)if(y.status==="completed"&&y.startedAt&&y.finishedAt){const T=Date.parse(y.finishedAt)-Date.parse(y.startedAt);T>0&&x.push(T)}return x.length===0?15e4:x.reduce((y,T)=>y+T,0)/x.length},[a]),K=r.useRef(new Map);r.useEffect(()=>{if(!a)return;const x=[];for(const y of a.jobs){const T=K.current.get(y.slug);T&&T!==y.status&&x.push(`${y.title}: ${T} → ${y.status}`),K.current.set(y.slug,y.status)}x.length>0&&xe(x.join("; "))},[a]);const X=r.useMemo(()=>{var y;const x=new Map;for(const T of((y=a==null?void 0:a.lastTick)==null?void 0:y.holds)??[])x.set(T.slug,T);return x},[a==null?void 0:a.lastTick]),Z=r.useCallback(x=>{var T,ie,Se;const y=(T=g.current)==null?void 0:T.querySelectorAll("[data-job-row]");if(!(!y||y.length===0)){if(x.key==="ArrowDown"){x.preventDefault();const U=Math.min(I+1,y.length-1);P(U);try{localStorage.setItem(ce,String(U))}catch{}(ie=y[U])==null||ie.focus()}else if(x.key==="ArrowUp"){x.preventDefault();const U=Math.max(I-1,0);P(U);try{localStorage.setItem(ce,String(U))}catch{}(Se=y[U])==null||Se.focus()}}},[I]),pe=r.useCallback(x=>{P(x);try{localStorage.setItem(ce,String(x))}catch{}},[]);if(!a)return null;if(A==="supervisor")return e.jsx($t,{supervisorConfig:a.config.supervisor,onSetConfig:x=>window.api.schedule.setConfig({supervisor:x}),onBack:()=>k("queue")});const{config:ee,jobs:M,paused:me,lastRunAt:H,nextReset:z,effectiveConcurrency:$}=a;if(M.length===0)return e.jsx(ft,{navigate:s});const F={pending:0,running:0,investigating:0,completed:0,needs_review:0,failed:0};for(const x of M)x.status in F&&F[x.status]++;const te=M.filter(x=>x.status==="running"),l=gt({snap:a,now:o,avgDurationMs:L,runningJobs:te}),m=ut(M,N),S=bt(m),{inline:E,collapsedCount:R}=wt(m,b,o,h),_=kt(E,M,S,L,l.kind,o),Q=()=>{const x=new Set(b);for(const y of M)(y.status==="completed"||y.status==="failed")&&x.add(y.slug);w(x),Re(x)},Be=async()=>{const x=M.filter(ie=>ie.status!=="running").length;if(x===0)return;const y=`Archive ${x} non-running PRD${x===1?"":"s"} and remove from the queue?
2
-
3
- Files are moved to prds-archived/<timestamp>/ and can be restored from disk. Running jobs are kept.`;if(!window.confirm(y))return;const T=await window.api.schedule.clearQueue();T.ok||O.error(`Clear queue failed: ${T.error??"unknown error"}`)},Je=()=>{w(new Set),Re(new Set),v(!1)},Ge=E.some(x=>x.status==="completed");return e.jsxs("div",{className:"overflow-y-auto h-full",children:[e.jsx("div",{"aria-live":"polite","aria-atomic":"true",className:"sr-only",children:B}),e.jsxs("div",{className:"px-9 py-6 max-w-[1100px] mx-auto space-y-4",children:[e.jsxs("div",{className:`flex flex-wrap items-center gap-3 px-4 py-3 rounded-xl border ${vt(l.kind)}`,title:l.tooltip,children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:`w-[38px] h-[38px] rounded-xl bg-bg border border-line flex items-center justify-center shrink-0 ${jt(l.kind)}`,children:e.jsx(ue,{name:"clock",size:19})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[14px] text-fg truncate",children:yt(St(l.line1,a.utilization))}),l.line2&&e.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:l.line2})]})]}),e.jsxs("span",{className:"ml-auto font-mono text-[11.5px] text-fg-faint whitespace-nowrap",children:[($==null?void 0:$.cap)??5," slot",(($==null?void 0:$.cap)??5)!==1?"s":""," · last batch ",V(H?Date.parse(H):null,o)]}),l.action&&e.jsx("button",{type:"button",onClick:l.action.onClick,className:"text-[12px] px-3 py-1.5 border border-line hover:border-fg-faint rounded-lg shrink-0 hover:bg-bg-hi text-fg-dim hover:text-fg",title:l.action.title,children:l.action.label})]}),p&&p.consecutiveFailures>5&&p.lastFailureKind==="meter_rate_limited"&&!me&&!f&&e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 bg-amber-400/15 border border-amber-400/30 rounded-xl",children:[e.jsx("span",{"aria-hidden":"true",children:"⚠"}),e.jsxs("span",{className:"text-[13.5px] text-amber-400/90",children:[e.jsx("strong",{className:"font-semibold",children:"Usage meter unavailable"})," — last good reading"," ",V(p.lastPollAt,o),". Firing on a conservative estimate until it recovers."]}),e.jsx("button",{type:"button",onClick:()=>j(!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"})]}),e.jsxs("div",{className:"flex items-center gap-[18px] flex-wrap bg-bg-elev border border-line rounded-xl px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[13px] text-fg-dim",children:"Start jobs"}),e.jsxs("select",{value:ee.firePolicy??"when-available",onChange:x=>window.api.schedule.setConfig({firePolicy:x.target.value}),className:"appearance-none border border-line bg-bg-hi rounded-lg px-2.5 py-1.5 font-sans text-[13px] text-fg font-medium",title:"when-available: poll usage and fire when tokens are below threshold. on-reset: fire after each 5h reset. manual: only on Run now.",children:[e.jsx("option",{value:"when-available",children:"when available"}),e.jsx("option",{value:"on-reset",children:"only on reset"}),e.jsx("option",{value:"manual",children:"manually"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[13px] text-fg-dim",children:"Up to"}),($==null?void 0:$.source)==="env"&&e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-amber-400/90 bg-amber-400/10 border border-amber-400/30 rounded px-1.5 py-0.5",title:"Pinned by SM_SESSION_SLOTS — unset the env var to edit",children:"env"}),e.jsx("input",{type:"number",min:0,max:10,value:($==null?void 0:$.cap)??5,disabled:($==null?void 0:$.source)==="env",onChange:x=>{window.api.schedule.setSessionSlots(Number(x.target.value))},className:"w-11 text-center border border-line bg-bg-hi rounded-lg py-1.5 font-mono text-[13px] text-fg disabled:opacity-50 disabled:cursor-not-allowed",title:($==null?void 0:$.source)==="env"?"pinned by SM_SESSION_SLOTS — unset the env var to edit":"Machine-wide claude -p session slots, shared with chat runs"}),e.jsx("span",{className:"text-[13px] text-fg-dim",children:"at once"})]}),(ee.firePolicy??"when-available")==="when-available"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[13px] text-fg-dim",children:"Pause above"}),e.jsx("input",{type:"number",min:0,max:100,value:ee.utilizationThreshold??90,onChange:x=>window.api.schedule.setConfig({utilizationThreshold:Number(x.target.value)}),className:"w-11 text-center border border-line bg-bg-hi rounded-lg py-1.5 font-mono text-[13px] text-fg",title:"Fire only when 5h utilization is below this percent"}),e.jsx("span",{className:"text-[13px] text-fg-dim",children:"% of window"})]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[e.jsx("button",{type:"button",onClick:()=>window.api.schedule.forceTick().then(O.fromOutcome).catch(()=>O.error("Failed to fire batch")),disabled:F.pending===0&&F.running===0,className:"bg-accent text-white rounded-lg px-4 py-2 text-[13px] font-semibold whitespace-nowrap disabled:opacity-40 disabled:cursor-not-allowed hover:opacity-90",title:"Bypasses the billing-usage poll. Use when the meter is rate-limited or you want immediate progress.",children:"Fire next batch now"}),e.jsx("button",{type:"button",onClick:()=>window.api.schedule.rescan().then(O.fromOutcome).catch(()=>O.error("Failed to rescan")),className:"bg-bg-hi border border-line text-fg-dim hover:text-fg rounded-lg px-3.5 py-2 text-[13px] font-medium",title:"Re-scan the prds/ folder. Use when you've added or edited PRDs on disk and want the queue to reflect them immediately.",children:"Refresh"})]})]}),te.length>0&&(()=>{const x=($==null?void 0:$.cap)??5,y=M.filter(T=>T.status==="pending").length;return e.jsxs("div",{className:"flex items-center gap-2 text-[12px] font-mono",children:[e.jsxs("span",{className:"px-2 py-0.5 rounded bg-amber-400/20 text-amber-400 shrink-0",children:[te.length,"/",x," running"]}),y>0&&e.jsxs("span",{className:"text-fg-faint",children:["+",y," ready in this group"]})]})})(),M.length>0&&e.jsx(At,{filter:N,onChange:x=>{C(x),dt(x)}}),e.jsxs("div",{className:"bg-bg-hi border border-line rounded-2xl overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-[18px] py-3 bg-bg-elev",children:[e.jsxs("span",{className:"font-serif text-base font-semibold text-fg",children:[m.length," job",m.length!==1?"s":""]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"font-mono text-[12px] text-fg-faint",children:[F.pending,"p · ",F.running,"r · ",F.completed,"d",F.failed>0&&e.jsxs("span",{className:"text-accent",children:[" · ",F.failed,"f"]})]}),Ge&&e.jsx("button",{type:"button",onClick:Q,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"}),e.jsx("button",{type:"button",onClick:Be,disabled:M.every(x=>x.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&&R===0&&e.jsx("div",{className:"px-[18px] py-6 text-[13px] text-fg-faint italic",children:"no matching jobs"}),e.jsx("div",{ref:g,role:"list","aria-label":"Job queue",onKeyDown:Z,children:E.map((x,y)=>e.jsx(Ct,{job:x,eta:_.get(x.slug)??null,elapsedMs:x.status==="running"&&x.startedAt?o-Date.parse(x.startedAt):null,avgDurationMs:L,listIndex:y,hold:X.get(x.slug),onFocused:pe},x.slug))}),R>0&&e.jsxs("button",{type:"button",onClick:()=>v(x=>!x),className:"w-full text-left text-[12px] text-fg-faint hover:text-fg-dim px-[18px] py-3 border-t border-line",title:h?"Re-collapse old/cleared completed":"Show all completed (incl. cleared and >24h)",children:[h?"▾":"▸"," ",R," more completed",e.jsx("span",{className:"ml-1.5 font-mono text-[11.5px] text-fg-faint",children:"· fresh & capped at 5 shown inline"}),b.size>0&&e.jsx("span",{className:"ml-2 underline",onClick:x=>{x.stopPropagation(),Je()},children:"un-hide"})]})]}),e.jsx(Rt,{snap:a,health:p,now:o,open:c,setOpen:u}),!me&&e.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:[e.jsx("span",{"aria-hidden":"true",children:"✓"}),e.jsxs("span",{children:[e.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."]})]}),e.jsxs("div",{className:"flex items-center justify-between text-[12px] text-fg-faint pt-1 border-t border-line",children:[e.jsxs("span",{children:[z&&e.jsxs("span",{title:`next 5h reset: ${z}`,children:["reset ",q(Date.parse(z)-o)]}),H&&e.jsxs("span",{className:"ml-2",title:H,children:["last run ",q(o-Date.parse(H))," ago"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{type:"button",onClick:()=>k("supervisor"),className:"hover:text-fg-dim underline",title:"Open supervisor log and settings",children:"supervisor"}),e.jsx("button",{type:"button",onClick:()=>window.api.schedule.openFolder(),className:"hover:text-fg-dim underline",children:"folder"})]})]})]})]})}const mt=[{title:"Create an Epic",body:"Describe the outcome you want in the Epics tab. Its thread writes the PRD files into the epic's folder."},{title:"Queue what it wrote",body:"The PRDs tab lists every file the epic produced. Queue one, or the whole epic, 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."}],ht=[{term:"Epic",def:"A goal, and the folder of PRDs written to reach it."},{term:"PRD",def:"One markdown file = one job. Authored by the epic."},{term:"5-hour window",def:"Your Claude billing window, on a rolling clock."},{term:"Session pool",def:"5 slots shared with terminal and epic chats."}];function ft({navigate:t}){return e.jsx("div",{className:"overflow-y-auto h-full",children:e.jsx("div",{className:"px-9 py-6 max-w-[900px] mx-auto",children:e.jsxs("div",{className:"bg-bg-hi border border-line rounded-2xl px-9 py-8",children:[e.jsx("h2",{className:"m-0 font-serif text-[25px] font-semibold text-fg",children:"Nothing to run yet — the scheduler needs an Epic."}),e.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. An Epic breaks its goal into numbered PRD files, and this page runs them in order. Two steps, once."}),e.jsx("div",{className:"grid grid-cols-3 gap-3.5",children:mt.map((s,n)=>{const a=n===0;return e.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:[e.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}),e.jsx("h3",{className:"m-0 text-[15px] font-semibold text-fg",children:s.title}),e.jsx("p",{className:"m-0 text-[13.5px] text-fg-dim leading-relaxed",children:s.body}),a&&e.jsx("button",{type:"button",onClick:()=>t==null?void 0:t("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 Epics →"})]},s.title)})}),e.jsx("dl",{className:"flex mt-[22px] pt-4 border-t border-line gap-5 flex-wrap",children:ht.map(({term:s,def:n})=>e.jsxs("div",{className:"flex-1 min-w-[150px]",children:[e.jsx("dt",{className:"text-[13.5px] font-semibold text-fg mb-0.5",children:s}),e.jsx("dd",{className:"m-0 text-[12.5px] text-fg-faint leading-relaxed",children:n})]},s))})]})})})}function gt({snap:t,now:s,avgDurationMs:n,runningJobs:a}){const{config:p,jobs:i,paused:c,nextReset:u,utilization:o,effectiveConcurrency:d}=t;let b=0,w=0;for(const j of i)j.status==="pending"?b++:j.status==="completed"&&w++;const h=a.length,v=b+h,N=(d==null?void 0:d.cap)??5;if(h>0){const j=a.reduce((P,B)=>(P.startedAt??"")<(B.startedAt??"")?P:B),A=j.startedAt?s-Date.parse(j.startedAt):0,k=w+h,g=w+v,I=h>1?` · ${h}/${N} parallel`:"";return{kind:"running",line1:`Running ${k}/${g}${I} · ${le(A)}`,line2:h===1?j.title:a.map(P=>P.title).join(", "),tooltip:a.map(P=>`${P.slug} (g${P.parallelGroup})`).join("; ")}}if(c){const j=c.resumeAt?Date.parse(c.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"}[c.reason]??`Paused — ${c.reason}`,line2:c.reason==="auth"?"Run `claude` in any terminal to refresh credentials, then Resume":j!==null&&j>0?`auto-resume ${Y(Date.parse(c.resumeAt))} (in ${q(j)})`:c.resumeAt?"resuming…":"no auto-resume scheduled",tooltip:c.resumeAt??"",action:{label:"Resume",onClick:()=>window.api.schedule.resume(),title:"Clear the pause and resume queue immediately"}}}if(v===0)return{kind:"idle",line1:"No work queued",line2:null};const C=p.firePolicy??"when-available";if(C==="manual")return{kind:"manual",line1:`Manual · ${b} pending`,line2:"click Fire next batch now to fire",action:{label:"Fire next batch now",onClick:()=>window.api.schedule.forceTick().then(O.fromOutcome).catch(()=>O.error("Failed to fire batch")),title:"Bypasses the billing-usage poll. Use when the meter is rate-limited or you want immediate progress."}};if(C==="on-reset"){if(!u)return{kind:"on-reset",line1:"On-reset · waiting for billing data",line2:null};const j=Date.parse(u)+p.offsetMinutes*6e4,A=j-s;return{kind:"on-reset",line1:`On-reset · ${b} pending`,line2:A>0?`fires ${Y(j)} (in ${q(A)})`:"firing now…"}}const f=p.utilizationThreshold??90;if(o==null)return{kind:"auto-soon",line1:`Auto · ${b} pending`,line2:"checking token availability…"};if(o>=f){const j=u?Date.parse(u)-s:null;return{kind:"auto-throttled",line1:`Auto · throttled (util ${o.toFixed(0)}% ≥ ${f}%)`,line2:j&&j>0?`next reset ${Y(Date.parse(u))} (in ${q(j)})`:"will fire when usage drops"}}return{kind:"auto-soon",line1:`Auto · ${b} pending · util ${o.toFixed(0)}%`,line2:"fires within 2 min (poll cycle)"}}function bt(t){const s=t.filter(a=>a.status==="running"||a.status==="pending").sort((a,p)=>a.parallelGroup-p.parallelGroup||a.slug.localeCompare(p.slug)),n=new Map;return s.forEach((a,p)=>n.set(a.slug,p)),n}function wt(t,s,n,a){if(a)return{inline:t,collapsedCount:0};const p=t.filter(d=>d.status==="completed").sort((d,b)=>{const w=d.finishedAt?Date.parse(d.finishedAt):0;return(b.finishedAt?Date.parse(b.finishedAt):0)-w}),i=new Set;let c=0;for(const d of p){if(c>=lt)break;s.has(d.slug)||d.finishedAt&&n-Date.parse(d.finishedAt)>rt||(i.add(d.slug),c++)}const u=[];let o=0;for(const d of t){if(d.status==="failed"&&s.has(d.slug)){o++;continue}if(d.status!=="completed"){u.push(d);continue}i.has(d.slug)?u.push(d):o++}return{inline:u,collapsedCount:o}}function vt(t){return t==="running"?"bg-amber-400/10 border-amber-400/25":t==="paused"?"bg-amber-500/10 border-amber-500/25":t==="auto-throttled"?"bg-amber-500/5 border-amber-500/15":"bg-bg-elev border-line"}function jt(t){return t==="running"||t==="auto-soon"?"text-accent":t==="idle"?"text-sage":t==="paused"||t==="auto-throttled"?"text-butter":"text-fg-faint"}const Nt=["Running","Paused","Manual","On-reset","Auto"];function yt(t){for(const s of Nt)if(t.startsWith(s))return e.jsxs(e.Fragment,{children:[e.jsx("strong",{className:"font-bold",children:s}),t.slice(s.length)]});return t}function St(t,s){return s==null||t.includes("util")?t:`${t} · util ${Math.round(s)}%`}function kt(t,s,n,a,p,i){const c=new Map;if(p==="paused"||p==="manual"||p==="auto-throttled"){for(const d of t)c.set(d.slug,null);return c}const u=s.find(d=>d.status==="running"&&d.startedAt),o=u!=null&&u.startedAt?i-Date.parse(u.startedAt):0;for(const d of t){if(d.status!=="pending"){c.set(d.slug,null);continue}const b=n.get(d.slug)??0;let w=b*a;b>0&&(w-=Math.min(a,o)),c.set(d.slug,w<=5e3?"~now":`~${le(w)}`)}return c}function Pt({job:t,eta:s,elapsedMs:n,avgDurationMs:a,listIndex:p,onFocused:i,hold:c}){const[u,o]=r.useState(!1),[d,b]=r.useState(!1),w=re(I=>I.sessions),h=r.useMemo(()=>ve(t,w),[t,w]),v=h.known&&h.epicId?w[h.epicId]:null,N=r.useCallback(I=>{je(I),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"terminal"}))},[]),C=t.status==="running",f=t.status==="failed";let j=null;C&&n!==null?j=`${ke(n)} elapsed`:t.status==="completed"&&t.startedAt&&t.finishedAt?j=`took ${le(Date.parse(t.finishedAt)-Date.parse(t.startedAt))}`:s&&(j=s);const A=t.error??null,k=f&&A?A.split(`
4
- `)[0]:t.status==="needs_review"&&t.verifierVerdict?de(t.verifierVerdict):null,g=C&&n!==null?Math.min(.99,n/a):0;return e.jsxs("div",{role:"listitem",className:"border-t border-line",children:[e.jsxs("button",{type:"button","data-job-row":!0,"data-job-index":p,onClick:()=>o(I=>!I),onFocus:()=>i(p),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 ${u?"bg-bg-elev/40":""}`,"aria-expanded":u,"aria-label":`${W(t.slug)?`PRD ${W(t.slug)}, `:""}${t.title}, ${t.status}${j?`, ${j}`:""}`,title:t.title,children:[e.jsx(Me,{status:t.status}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-baseline gap-2 text-[14.5px] font-medium text-fg leading-snug",children:[W(t.slug)&&e.jsx(Oe,{n:W(t.slug)}),t.title]}),k&&e.jsx("div",{className:`text-[12.5px] mt-0.5 ${f?"text-accent/80":"text-fg-faint"}`,children:k}),c&&e.jsxs("div",{className:"text-[12.5px] mt-0.5 text-amber-400/90 font-mono",children:["held · waiting on ",c.dep," (",c.depStatus,")"]}),e.jsx(Ne,{epicId:h.epicId,label:h.label?it(h.label):null,onOpen:N,testId:"job-row-prompt-session-chip",className:"mt-0.5"})]}),e.jsx(ye,{cwd:t.cwd}),e.jsxs("span",{className:"inline-flex items-center gap-2.5 font-mono text-xs text-fg-faint shrink-0",children:[j,e.jsx("span",{className:`text-fg-faint inline-flex transition-transform duration-150 ${u?"rotate-90":""}`,"aria-hidden":"true",children:e.jsx(ue,{name:"chevron",size:14})})]})]}),C&&!u&&e.jsx("div",{className:"h-1 bg-line mx-[18px] mb-3 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-accent transition-all duration-1000",style:{width:`${Math.max(4,g*100)}%`}})}),u&&e.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:[e.jsxs(G,{label:"Status",children:[e.jsx(D,{k:"result",v:t.exitCode!==null?`exit ${t.exitCode}`:"—"}),e.jsx(D,{k:"state",v:t.status.replace(/_/g," ")}),t.verifierVerdict&&e.jsx(D,{k:"verdict",v:de(t.verifierVerdict)}),A&&e.jsx(D,{k:"error",v:A.split(`
5
- `)[0],wrap:!0})]}),e.jsxs(G,{label:"Timing",children:[e.jsx(D,{k:"started",v:t.startedAt?Y(Date.parse(t.startedAt)):"—"}),e.jsx(D,{k:"finished",v:t.finishedAt?Y(Date.parse(t.finishedAt)):"—"}),e.jsx(D,{k:"duration",v:t.startedAt&&t.finishedAt?le(Date.parse(t.finishedAt)-Date.parse(t.startedAt)):C&&n!==null?ke(n):"—"})]}),e.jsxs(G,{label:"Location",children:[e.jsx(D,{k:"group",v:`${t.parallelGroup} · ${t.slug}`}),e.jsx(D,{k:"cwd",v:t.cwd??"—",wrap:!0}),e.jsx(D,{k:"epic",v:h.label??h.epicId??"—",wrap:!0}),e.jsx(D,{k:"epic id",v:h.epicId??"—",wrap:!0}),e.jsx(D,{k:"prompt id",v:t.sourcePromptId??"—",wrap:!0}),e.jsx(D,{k:"source tab",v:t.sourceTabId??"—",wrap:!0})]}),e.jsx(G,{label:"Actions",children:e.jsxs("div",{className:"flex flex-col gap-1.5 items-start",children:[v&&e.jsx("button",{type:"button","data-testid":"job-row-prompt-session-link",title:v.goalText,onClick:()=>N(v.id),className:"text-[13px] font-semibold text-accent hover:text-accent/80 bg-transparent border-0 cursor-pointer p-0",children:"view epic →"}),t.runId&&e.jsx("button",{type:"button",onClick:()=>b(!0),className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border-0 cursor-pointer p-0",children:"view log →"}),t.status!=="pending"&&t.status!=="running"&&e.jsx("button",{type:"button",onClick:()=>window.api.schedule.resetJob(t.slug),className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border-0 cursor-pointer p-0",children:"reset to pending →"})]})})]}),d&&t.runId&&e.jsx(Fe,{runId:t.runId,slug:t.slug,title:t.title||t.slug,onClose:()=>b(!1)})]})}const Ct=r.memo(Pt);function At({filter:t,onChange:s}){const n=[{label:"All",value:"all"},{label:"Running",value:"running"},{label:"Investigating",value:"investigating"},{label:"Pending",value:"pending"},{label:"Completed",value:"completed"},{label:"Needs review",value:"needs_review"},{label:"Failed",value:"failed"}];return e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-[320px]",children:[e.jsx("span",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-fg-faint inline-flex","aria-hidden":"true",children:e.jsx(ue,{name:"search",size:15})}),e.jsx("input",{type:"text",value:t.text,onChange:a=>s({...t,text:a.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"})]}),e.jsx(Le,{options:n,value:t.status,onChange:a=>s({...t,status:a})})]})}function $t({supervisorConfig:t,onSetConfig:s,onBack:n}){const[a,p]=r.useState([]),[i,c]=r.useState(()=>Date.now()),u=Te();r.useEffect(()=>{if(!u)return;window.api.supervisor.getLog().then(p).catch(()=>{}),c(Date.now());const d=setInterval(()=>c(Date.now()),5e3);return()=>clearInterval(d)},[u]);const o={enabled:(t==null?void 0:t.enabled)??!0,intervalMinutes:(t==null?void 0:t.intervalMinutes)??15,maxConcurrentProbes:(t==null?void 0:t.maxConcurrentProbes)??2,probeStaleThresholdMinutes:(t==null?void 0:t.probeStaleThresholdMinutes)??10};return e.jsxs("div",{className:"bg-bg-elev/60",children:[e.jsxs("div",{className:"px-3 py-2 flex items-center gap-2 border-b border-line",children:[e.jsx("button",{type:"button",onClick:n,className:"text-[10px] text-fg-faint hover:text-fg-dim",title:"Back to queue",children:"← queue"}),e.jsx("span",{className:"text-[11px] font-medium text-fg-dim",children:"Supervisor"}),e.jsx("button",{type:"button",onClick:()=>window.api.supervisor.getLog().then(p).catch(()=>{}),className:"ml-auto text-[10px] text-fg-faint hover:text-fg-dim underline",title:"Refresh log",children:"refresh"})]}),e.jsxs("div",{className:"px-3 py-2 space-y-1.5 border-b border-line",children:[e.jsx("div",{className:"text-[9px] text-fg-faint uppercase tracking-wider",children:"Config"}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap text-[10px] text-fg-faint",children:[e.jsxs("label",{className:"flex items-center gap-1",children:[e.jsx("input",{type:"checkbox",checked:o.enabled,onChange:d=>s({enabled:d.target.checked}),className:"cursor-pointer"}),e.jsx("span",{children:"enabled"})]}),e.jsxs("label",{className:"flex items-center gap-1",title:"How often to check for wedged jobs (minutes)",children:[e.jsx("span",{children:"interval"}),e.jsx("input",{type:"number",min:5,max:60,value:o.intervalMinutes,onChange:d=>s({intervalMinutes:Number(d.target.value)}),className:"w-10 bg-bg border border-line rounded px-1 py-0.5 font-mono"}),e.jsx("span",{children:"min"})]}),e.jsxs("label",{className:"flex items-center gap-1",title:"Max concurrent Opus probes per tick",children:[e.jsx("span",{children:"probes"}),e.jsx("input",{type:"number",min:1,max:5,value:o.maxConcurrentProbes,onChange:d=>s({maxConcurrentProbes:Number(d.target.value)}),className:"w-8 bg-bg border border-line rounded px-1 py-0.5 font-mono"})]}),e.jsxs("label",{className:"flex items-center gap-1",title:"Probe a job only if no JSONL event in this many minutes",children:[e.jsx("span",{children:"stale"}),e.jsx("input",{type:"number",min:5,max:30,value:o.probeStaleThresholdMinutes,onChange:d=>s({probeStaleThresholdMinutes:Number(d.target.value)}),className:"w-8 bg-bg border border-line rounded px-1 py-0.5 font-mono"}),e.jsx("span",{children:"min"})]})]})]}),e.jsxs("div",{className:"px-3 py-2",children:[e.jsxs("div",{className:"text-[9px] text-fg-faint uppercase tracking-wider mb-1",children:["Recent probes (last ",a.length,")"]}),a.length===0?e.jsx("div",{className:"text-[10px] text-fg-faint italic",children:"No probes yet."}):e.jsx("div",{className:"space-y-0.5 max-h-64 overflow-y-auto",children:a.map((d,b)=>e.jsx(Dt,{entry:d,now:i},`${d.ts}-${b}`))})]})]})}function Dt({entry:t,now:s}){const n=t.action!=="none",a=q(s-t.ts);return e.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:t.reason,children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsxs("span",{className:"text-fg-faint shrink-0",children:[a," ago"]}),e.jsx("span",{className:`shrink-0 px-1 rounded ${t.verdict==="stuck"?"text-red-400 bg-red-500/10":"text-green-500/70"}`,children:t.verdict}),e.jsx("span",{className:"truncate text-fg-dim",children:t.jobSlug}),n&&e.jsxs("span",{className:"shrink-0 text-red-400",children:[t.action,t.targetPid?` pid=${t.targetPid}`:""]}),t.costUsd!==null&&e.jsxs("span",{className:"shrink-0 text-fg-faint",children:["$",t.costUsd.toFixed(3)]})]}),e.jsx("div",{className:"text-fg-faint truncate mt-0.5",children:t.reason})]})}function Rt({snap:t,health:s,now:n,open:a,setOpen:p}){const[i,c]=r.useState(null),[u,o]=r.useState(!1),d=`${t.jobs.length}:${t.lastRunAt??""}`;r.useEffect(()=>{let k=!0;return o(!0),De().then(g=>{k&&c(g)}).catch(()=>{}).finally(()=>{k&&o(!1)}),()=>{k=!1}},[d]);let b=0,w=0;const h=i?i.reports.filter(k=>k.findings.length>0):[];for(const k of h)for(const g of k.findings)g.severity==="error"?b++:w++;const v=b===0&&w===0,N=i?v?`queue lint clear (${i.reports.length} scanned)`:`queue lint ${b} error${b===1?"":"s"}${w>0?`, ${w} warn${w===1?"":"s"}`:""}`:u?"scanning…":"idle",C=(s==null?void 0:s.consecutiveFailures)??0,f=s?`${C} poll failure${C===1?"":"s"} since boot`:null,j=C>0||((s==null?void 0:s.pauseReason)??null)!==null||!v,A=[f,N].filter(Boolean);return e.jsxs("div",{className:"flex flex-col gap-2 bg-bg-hi border border-line rounded-xl px-4 py-3 text-[13.5px] text-fg-dim",children:[e.jsxs("button",{type:"button",onClick:()=>p(!a),className:"flex items-center gap-2.5 w-full text-left","aria-expanded":a,title:"Scheduler poll health and queue-lint findings, in one place",children:[e.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${j?"bg-butter":"bg-sage"}`,"aria-hidden":"true"}),e.jsx("strong",{className:"text-fg font-semibold shrink-0",children:"Diagnostics"}),e.jsx("span",{className:"truncate",children:A.join(" · ")}),e.jsx("span",{className:"ml-auto text-fg-faint shrink-0","aria-hidden":"true",children:a?"▾":"▸"})]}),a&&e.jsxs("div",{className:"pl-[18px] space-y-3 font-mono text-[12px]",children:[s&&e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{children:["booted: ",V(s.bootedAt,n)]}),e.jsxs("div",{children:["last poll: ",V(s.lastPollAt,n)," · ",s.lastPollOk?"ok":"failed"]}),s.backoffNextAt!==null&&s.backoffNextAt>n&&e.jsxs("div",{children:["retry in: ",q(s.backoffNextAt-n)]}),s.nextResetCached&&e.jsxs("div",{children:["cached reset: ",Y(Date.parse(s.nextResetCached))]}),s.runningJobs.length>0&&e.jsxs("div",{children:["running: ",s.runningJobs.map(k=>`${k.slug}(pid ${k.pid})`).join(", ")]})]}),i&&e.jsxs("div",{className:"space-y-1",children:[v?e.jsxs("div",{className:"text-sage",children:["✓ no issues in ",i.reports.length," PRD",i.reports.length!==1?"s":""]}):h.map(k=>e.jsxs("div",{children:[e.jsx("div",{className:"text-fg-dim truncate",title:k.slug,children:k.slug}),k.findings.map((g,I)=>e.jsxs("div",{className:`pl-3 truncate ${g.severity==="error"?"text-accent/80":"text-butter/90"}`,title:g.snippet,children:[g.severity==="error"?"✗":"⚠"," L",g.line,": ",g.snippet]},`${k.slug}-${I}`))]},k.slug)),e.jsx("button",{type:"button",onClick:()=>{o(!0),De({fresh:!0}).then(c).catch(()=>{}).finally(()=>o(!1))},className:"text-fg-faint hover:text-fg-dim underline",children:u?"…":"rerun lint"})]})]})]})}const Et=["title","cwd","estimateMinutes","parallelGroup","sourcePromptId","sourceTabId","tag"];function It(t){if(t==null)return"";if(typeof t=="boolean"||typeof t=="number")return String(t);const s=String(t);return s===""||/^(true|false|null|~)$/.test(s)||/^-?\d+(\.\d+)?$/.test(s)||/^\s|\s$/.test(s)||s.startsWith("'")||s.startsWith('"')||s.includes(`
6
- `)?s.includes("'")?`"${s.replace(/"/g,'\\"')}"`:`'${s}'`:s}function Tt(t,s){var p;const n=[];for(const i of Et){const c=t[i];if(c==null||c==="")continue;const u=(p=t._raw)==null?void 0:p[i];if(u&&u.parsed===c){n.push(u.line);continue}if(typeof c=="number"){n.push(`${i}: ${c}`);continue}n.push(`${i}: ${It(c)}`)}if(t.extras)for(const i of Object.keys(t.extras)){const c=t.extras[i];!c||!c.lines.length||n.push(c.lines.join(`
7
- `))}return`---
8
- ${n.join(`
9
- `)}
10
- ---
11
- ${s}`}function fe(t){return t.filter(s=>!s.archived)}function Lt(t){je(t),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"terminal"}))}function ge({label:t,tip:s,onClick:n,disabled:a,primary:p}){return e.jsx(ze,{content:s,align:"bottom-center",children:e.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 ${p?"text-accent border-accent/50 hover:bg-bg-hi":"text-fg-dim border-line hover:text-fg hover:bg-bg-hi"}`,children:t})})}function Mt({scopeCwd:t=null}){const[s,n]=r.useState([]),[a,p]=r.useState(null),[i,c]=r.useState(null),[u,o]=r.useState(null),[d,b]=r.useState(!1),[w,h]=r.useState(!0),[v,N]=r.useState(new Set),[C,f]=r.useState(!1),[j,A]=r.useState(!1),[k,g]=r.useState(!1),[I,P]=r.useState(null);r.useEffect(()=>{let l=!0;return window.api.schedule.listPrds().then(m=>{l&&(n(fe(m)),h(!1))}).catch(m=>{l&&(h(!1),O.error(`Scheduler: failed to load PRD list — ${m instanceof Error?m.message:"unknown error"}`))}),()=>{l=!1}},[]);const B=we(l=>l.snapshot),xe=re(l=>l.sessions);r.useEffect(()=>{B&&p(B)},[B]);const J=r.useMemo(()=>[...s].filter(l=>!t||l.cwd===t).sort((l,m)=>m.mtimeMs-l.mtimeMs||l.slug.localeCompare(m.slug)),[s,t]);r.useEffect(()=>{const l=Ve();l&&c(l);const m=S=>c(S.detail);return window.addEventListener("sm:select-prd",m),()=>window.removeEventListener("sm:select-prd",m)},[]);const L=r.useMemo(()=>(a==null?void 0:a.jobs.find(l=>l.slug===i))??null,[a,i]),K=Pe(L);function X(l){var S;const m=(S=s.find(E=>E.slug===l))==null?void 0:S.cwd;return m?`${m}/session-manager-operations/scheduler/prds/${l}.md`:null}r.useEffect(()=>{if(!i)return;const l=X(i);l&&Ce.getState().openFile(l)},[i,s]);function Z(l){c(l),o(null),b(!1)}function pe(){c(null)}async function ee(){if(!i)return;if(!(L!=null&&L.runId)){o("no log available (job has not run yet)"),b(m=>!m);return}const l=await window.api.schedule.readLog(L.runId,i);o(l.ok?l.text??"":`error: ${l.error}`),b(m=>!m)}if(w)return e.jsx(ae,{title:"loading PRDs…"});const M=l=>{N(m=>{const S=new Set(m);return S.has(l)?S.delete(l):S.add(l),S})};!(J.length>0&&J.every(l=>v.has(l.slug)))&&J.some(l=>v.has(l.slug));const H=()=>N(new Set);async function z(){try{const l=await window.api.schedule.listPrds();n(fe(l))}catch{}}async function $(){const l=`new-prd-${Date.now()}`,m=Tt({title:"New PRD",cwd:"",estimateMinutes:60,parallelGroup:99},`## Task
12
-
13
- Describe the task here.
14
- `);try{const S=await window.api.schedule.writePrd(l,m);if(!S.ok){O.error(`Failed to create PRD: ${S.error}`);return}const E=await window.api.schedule.listPrds();n(fe(E)),Z(l)}catch(S){O.error(`Failed to create PRD: ${S instanceof Error?S.message:String(S)}`)}}async function F(){var l;g(!0),P(null);try{const m=[...v],S=await window.api.schedule.archivePrds(m);if(!S.ok)P(S.error??"archive failed");else{const E=((l=S.results)==null?void 0:l.filter(R=>!R.ok))??[];E.length>0&&O.warn(`Archive: ${E.length} of ${S.results.length} PRD${E.length===1?"":"s"} failed to move`),H(),f(!1),await z()}}catch(m){P(m instanceof Error?m.message:String(m))}finally{g(!1)}}async function te(l,m){g(!0),P(null);try{const S=[];for(const R of v){const _={slug:R};l!==null&&(_.parallelGroup=l),m!==null&&(_.estimateMinutes=m),S.push(_)}const E=await window.api.schedule.retagPrds(S);if(!E.ok)P(E.error??"retag failed");else{H(),A(!1),await z();for(const R of E.results)if(R.newSlug&&R.newSlug!==R.slug){const _=X(R.slug),Q=X(R.newSlug);_&&Q&&Ce.getState().renameOpenFile(_,Q)}i&&E.results.some(R=>R.slug===i&&R.newSlug&&R.newSlug!==R.slug)&&c(null)}}catch(S){P(S instanceof Error?S.message:String(S))}finally{g(!1)}}return e.jsxs(e.Fragment,{children:[i?e.jsxs("div",{className:"h-full flex flex-col min-h-0",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-line flex-wrap shrink-0",children:[e.jsx("button",{type:"button",onClick:pe,className:"text-[11px] text-fg-faint hover:text-fg",children:"← PRDs"}),e.jsx("span",{className:"font-mono text-xs text-fg-dim truncate",children:i}),e.jsx(Ae,{status:K}),e.jsx("div",{className:"flex-1"}),e.jsx(ge,{label:"Reset",tip:"Reset failed job to pending",onClick:()=>{window.api.schedule.resetJob(i)},disabled:K!=="failed"}),e.jsx(ge,{label:"Run now",tip:"Run all pending jobs immediately",onClick:()=>{window.api.schedule.runNow()}}),e.jsx(ge,{label:d?"Hide log":"Last run log",tip:"Toggle most recent run log",onClick:ee})]}),e.jsx("div",{className:"flex-1 min-h-0",children:e.jsx(Ue,{})}),d&&u!==null&&e.jsxs("div",{className:"border-t border-line max-h-64 overflow-auto bg-bg-elev",children:[e.jsxs("div",{className:"px-3 py-1.5 flex items-center gap-2 border-b border-line sticky top-0 bg-bg-elev",children:[e.jsxs("span",{className:"text-[10px] text-fg-faint font-mono",children:["run log",L!=null&&L.runId?` — ${L.runId}`:""]}),e.jsx("button",{onClick:()=>b(!1),className:"ml-auto text-[10px] text-fg-faint hover:text-fg",children:"close"})]}),e.jsx("pre",{className:"p-3 text-[11px] font-mono text-fg-dim whitespace-pre-wrap",children:u})]})]}):e.jsxs("div",{className:"px-6 py-5 overflow-auto",children:[e.jsxs("div",{className:"flex items-start justify-between mb-5 gap-4",children:[e.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"," ",e.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."]}),e.jsx("button",{type:"button",onClick:$,className:"shrink-0 bg-accent text-white rounded-lg px-4 py-[9px] text-[13.5px] font-semibold leading-none",children:"+ New PRD"})]}),v.size>0&&e.jsxs("div",{className:"mb-4 px-4 py-2 bg-bg border border-line rounded-lg flex items-center gap-2",children:[e.jsxs("span",{className:"text-xs text-fg-dim",children:[v.size," selected"]}),e.jsx("div",{className:"flex-1"}),e.jsx("button",{type:"button",onClick:()=>f(!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…"}),e.jsx("button",{type:"button",onClick:()=>A(!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…"}),e.jsx("button",{type:"button",onClick:H,className:"text-xs px-3 py-1.5 rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:"Clear"})]}),J.length===0?e.jsx(ae,{title:"no PRDs found"}):e.jsx("div",{className:"grid gap-3",children:J.map(l=>{const m=a==null?void 0:a.jobs.find(Q=>Q.slug===l.slug),S=Pe(m),E=ve({epicId:l.epicId??(m==null?void 0:m.epicId)??null,sourcePromptId:l.sourcePromptId??(m==null?void 0:m.sourcePromptId)??null,sourceTabId:(m==null?void 0:m.sourceTabId)??null},xe),R=(m==null?void 0:m.status)==="running",_=(m==null?void 0:m.status)==="needs_review";return e.jsxs("div",{className:"flex items-stretch bg-bg-elev border border-line rounded-2xl overflow-hidden",children:[e.jsx("label",{className:"flex items-center px-3 cursor-pointer hover:bg-bg-hi",children:e.jsx("input",{type:"checkbox",checked:v.has(l.slug),onChange:()=>M(l.slug),className:"accent-accent w-3.5 h-3.5"})}),e.jsxs("div",{className:"flex-1 min-w-0 py-4 pr-2",children:[e.jsxs("div",{className:"flex items-center gap-2.5 mb-[5px] flex-wrap",children:[W(l.slug)&&e.jsx(Oe,{n:W(l.slug)}),e.jsx("button",{type:"button",onClick:()=>Z(l.slug),className:"font-serif text-[18px] font-semibold text-fg leading-tight hover:underline text-left",children:l.title||l.slug}),e.jsx(Ae,{status:S}),(m==null?void 0:m.status)&&e.jsx("span",{className:"sr-only",children:m.status})]}),e.jsxs("div",{className:"flex items-center gap-4 font-mono text-xs text-fg-faint flex-wrap",children:[e.jsx(ye,{cwd:l.cwd}),e.jsx(Ne,{epicId:E.epicId,label:E.label,onOpen:Lt}),l.estimateMinutes!=null&&e.jsxs("span",{children:[l.estimateMinutes,"m"]}),e.jsxs("span",{children:["g",l.parallelGroup]}),e.jsxs("span",{children:["edited ",V(l.mtimeMs,Date.now())]})]}),e.jsx("button",{type:"button",onClick:()=>Z(l.slug),className:"mt-1.5 font-mono text-[11px] text-fg-faint hover:text-fg-dim leading-none",children:l.slug}),_&&e.jsxs("div",{className:"mt-3 space-y-2",children:[(m==null?void 0:m.verifierVerdict)&&e.jsxs("div",{className:"text-xs text-fg-faint",children:["verdict: ",e.jsx("span",{className:"font-mono",children:de(m.verifierVerdict)})]}),e.jsx("button",{type:"button",onClick:()=>window.api.schedule.resetJob(l.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"})]})]}),e.jsx("div",{className:"flex flex-col gap-2 items-stretch px-[18px] py-4",children:e.jsx("button",{type:"button",onClick:()=>window.api.schedule.runNow(),disabled:R,className:"bg-fg text-bg rounded-lg px-[18px] py-2 text-[13px] font-semibold whitespace-nowrap disabled:opacity-50",children:R?"Running…":"Queue job"})})]},l.slug)})})]}),e.jsx(Ot,{open:C,count:v.size,busy:k,onClose:()=>f(!1),onConfirm:F}),e.jsx(Ft,{open:j,count:v.size,busy:k,onClose:()=>A(!1),onConfirm:te})]})}function Ot({open:t,count:s,busy:n,onClose:a,onConfirm:p}){return e.jsxs(_e,{open:t,onClose:a,title:"Archive PRDs",children:[e.jsxs("p",{className:"text-xs text-fg-dim",children:["Move ",e.jsx("span",{className:"font-mono",children:s})," PRD",s===1?"":"s"," to"," ",e.jsx("span",{className:"font-mono",children:"prds-archived/<timestamp>/"}),"?"]}),e.jsx("p",{className:"text-[10px] text-fg-faint mt-2",children:"Files are renamed, never deleted. Restore manually from disk if needed."}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.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"}),e.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?"Archiving…":`Archive ${s}`})]})]})}function Ft({open:t,count:s,busy:n,onClose:a,onConfirm:p}){const[i,c]=r.useState(""),[u,o]=r.useState(""),[d,b]=r.useState(null);r.useEffect(()=>{t&&(c(""),o(""),b(null))},[t]);function w(){b(null);let h=null,v=null;if(i.trim()){const N=Number(i);if(!Number.isInteger(N)||N<0||N>999){b("parallelGroup must be 0–999");return}h=N}if(u.trim()){const N=Number(u);if(!Number.isInteger(N)||N<=0){b("estimateMinutes must be a positive integer");return}v=N}if(h===null&&v===null){b("set at least one field");return}p(h,v)}return e.jsxs(_e,{open:t,onClose:a,title:"Retag PRDs",children:[e.jsxs("p",{className:"text-xs text-fg-dim",children:["Update ",e.jsx("span",{className:"font-mono",children:s})," PRD",s===1?"":"s",". Leave a field blank to keep its current value."]}),e.jsxs("p",{className:"text-[10px] text-fg-faint mt-2",children:["Changing parallelGroup on an ",e.jsx("span",{className:"font-mono",children:"NN-kebab"})," slug renames the file. Every change is logged to ",e.jsx("span",{className:"font-mono",children:"retag-log.jsonl"})," so it's reversible."]}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"w-32 text-fg-faint",children:"parallelGroup:"}),e.jsx("input",{type:"number",min:0,max:999,value:i,onChange:h=>c(h.target.value),placeholder:"(unchanged)",className:"flex-1 bg-bg border border-line rounded px-2 py-1 font-mono text-xs"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"w-32 text-fg-faint",children:"estimateMinutes:"}),e.jsx("input",{type:"number",min:1,value:u,onChange:h=>o(h.target.value),placeholder:"(unchanged)",className:"flex-1 bg-bg border border-line rounded px-2 py-1 font-mono text-xs"})]})]}),d&&e.jsx("div",{className:"mt-2 text-[10px] text-red-300",children:d}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.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"}),e.jsx("button",{type:"button",onClick:w,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 _t(t){je(t),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"terminal"}))}function Ee(t){return t?t.slice(0,10):""}const Ht=[{value:"all",label:"All"},{value:"completed",label:"Completed"},{value:"failed",label:"Failed"}];function qt({scopeCwd:t=null}){const[s,n]=r.useState(null),[a,p]=r.useState(!0),[i,c]=r.useState(""),[u,o]=r.useState(""),[d,b]=r.useState(""),[w,h]=r.useState("all");r.useEffect(()=>{p(!0),window.api.schedule.getHistory().then(f=>n(f)).catch(f=>n({ok:!1,jobs:[],error:f instanceof Error?f.message:String(f)})).finally(()=>p(!1))},[]);const v=r.useMemo(()=>{if(!(s!=null&&s.jobs))return[];const f=new Set;for(const j of s.jobs){const A=be(j.cwd);A&&f.add(A)}return[...f].sort()},[s]),N=r.useMemo(()=>s!=null&&s.jobs?s.jobs.filter(f=>!(t&&f.cwd!==t||w!=="all"&&f.status!==w||i&&be(f.cwd)!==i||u&&Ee(f.finishedAt)<u||d&&Ee(f.finishedAt)>d)):[],[s,w,i,u,d,t]);if(a)return e.jsx(ae,{title:"Loading history…"});if(!(s!=null&&s.ok)||s.error)return e.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 e.jsx(ae,{title:"No history yet",hint:"Completed and failed jobs appear here."});const C=w!=="all"||!!i||!!u||!!d;return e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsxs("div",{className:"shrink-0 flex items-center gap-2 px-4 py-2.5 border-b border-line flex-wrap",children:[e.jsx(Le,{options:Ht,value:w,onChange:h,pillPadding:"px-3 py-1"}),e.jsx("span",{className:"w-px h-4 bg-line mx-1","aria-hidden":"true"}),v.length>0&&e.jsxs("select",{value:i,onChange:f=>c(f.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:[e.jsx("option",{value:"",children:"All projects"}),v.map(f=>e.jsx("option",{value:f,children:f},f))]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-[12px] text-fg-faint",children:[e.jsx("span",{children:"from"}),e.jsx("input",{type:"date",value:u,onChange:f=>o(f.target.value),className:"bg-bg-hi border border-line rounded-lg px-2 py-1 text-fg-dim font-mono text-[12px]"})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-[12px] text-fg-faint",children:[e.jsx("span",{children:"to"}),e.jsx("input",{type:"date",value:d,onChange:f=>b(f.target.value),className:"bg-bg-hi border border-line rounded-lg px-2 py-1 text-fg-dim font-mono text-[12px]"})]}),e.jsxs("span",{className:"text-[12px] text-fg-faint ml-auto font-mono",children:[N.length," / ",s.jobs.length]}),C&&e.jsx("button",{type:"button",onClick:()=>{h("all"),c(""),o(""),b("")},className:"text-[12px] text-fg-faint hover:text-fg-dim underline",children:"clear"})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:N.length===0?e.jsx(ae,{title:"No matches",hint:"Try adjusting the filters."}):e.jsxs("div",{className:"mx-4 my-3 bg-bg-hi border border-line rounded-2xl overflow-hidden",children:[e.jsx("div",{className:"flex items-center px-[18px] py-3 bg-bg-elev",children:e.jsxs("span",{className:"font-serif text-base font-semibold text-fg",children:[N.length," job",N.length!==1?"s":""]})}),N.map(f=>e.jsx(Bt,{job:f},`${f.slug}-${f.finishedAt??""}`))]})})]})}function Bt({job:t}){const[s,n]=r.useState(!1),[a,p]=r.useState(!1),i=re(h=>h.sessions),c=r.useMemo(()=>ve(t,i),[t,i]),u=t.startedAt&&t.finishedAt?Date.parse(t.finishedAt)-Date.parse(t.startedAt):null,o=t.startedAt?new Date(t.startedAt).toLocaleString():"—",d=t.finishedAt?new Date(t.finishedAt).toLocaleString():"—",b=u!==null?le(u):"—",w=t.exitCode!==null?String(t.exitCode):"—";return e.jsxs("div",{className:"border-t border-line/60",children:[e.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:[e.jsx(Me,{status:t.status}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[14.5px] font-medium text-fg leading-snug text-pretty",children:t.title}),t.error&&!s&&(t.status==="failed"||t.status==="needs_review")&&e.jsx("div",{className:"text-[12.5px] mt-0.5 text-accent/80 truncate",children:t.error}),c.epicId&&e.jsx("span",{className:"flex mt-0.5",children:e.jsx(Ne,{epicId:c.epicId,label:c.label,onOpen:_t})})]}),e.jsx(ye,{cwd:t.cwd}),e.jsxs("span",{className:"inline-flex items-center gap-2.5 font-mono text-xs text-fg-faint whitespace-nowrap",children:[b,e.jsx("span",{className:"inline-flex transition-transform duration-150",style:{transform:s?"rotate(90deg)":"none"},"aria-hidden":"true",children:"›"})]})]}),s&&e.jsxs("div",{className:"grid gap-5 px-[18px] pt-1 pb-5 bg-bg-elev",style:{gridTemplateColumns:"repeat(auto-fit, minmax(160px, 1fr))"},children:[e.jsxs(G,{label:"Status",children:[e.jsx(D,{k:"result",v:w}),e.jsx(D,{k:"state",v:t.status.replace("_"," ")}),t.verifierVerdict&&e.jsx(D,{k:"verifier",v:de(t.verifierVerdict)})]}),e.jsxs(G,{label:"Timing",children:[e.jsx(D,{k:"started",v:o}),e.jsx(D,{k:"finished",v:d}),e.jsx(D,{k:"duration",v:b})]}),e.jsxs(G,{label:"Location",children:[e.jsx(D,{k:"group",v:t.parallelGroup!=null?String(t.parallelGroup):"—"}),e.jsx(D,{k:"slug",v:t.slug}),e.jsx(D,{k:"epic",v:c.label??c.epicId??"—",wrap:!0}),t.cwd&&e.jsx(D,{k:"cwd",v:t.cwd,wrap:!0})]}),e.jsx(G,{label:"Actions",children:e.jsxs("div",{className:"flex flex-col gap-2 items-start",children:[t.runId&&e.jsx("button",{type:"button",onClick:h=>{h.stopPropagation(),p(!0)},className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border-0 p-0 cursor-pointer",children:"view log →"}),t.status!=="pending"&&e.jsx("button",{type:"button",onClick:h=>{h.stopPropagation(),window.api.schedule.resetJob(t.slug)},className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border-0 p-0 cursor-pointer",children:"reset to pending →"}),t.error&&e.jsx("p",{className:"text-[12px] text-accent/90 mt-1 break-words whitespace-pre-wrap max-w-sm m-0",children:t.error})]})})]}),a&&t.runId&&e.jsx(Fe,{runId:t.runId,slug:t.slug,title:t.title||t.slug,onClose:()=>p(!1)})]})}function Jt(t){return t?Object.values(t).reduce((s,n)=>s+(n??[]).reduce((a,p)=>{var i;return a+(((i=p.hooks)==null?void 0:i.length)??0)},0),0):0}function Gt(t){var s,n,a;return t?(((s=t.allow)==null?void 0:s.length)??0)+(((n=t.deny)==null?void 0:n.length)??0)+(((a=t.ask)==null?void 0:a.length)??0):0}function Ut({navigate:t}){const s=Qe(),n=se(g=>g.files),a=se(g=>g.loadJson),p=se(g=>g.loadText),i=se(g=>g.watchFile),c=se(g=>g.unwatchFile),u=s?We.resolve("user",s,null):null,o=s?Ye.resolve("user",s,null):null,d=s?`${s}/.claude.json`:null;r.useEffect(()=>{const g=[u,d].filter(Boolean);g.forEach(P=>{n[P]||a(P),i(P)});const I=[o].filter(Boolean);return I.forEach(P=>{n[P]||p(P),i(P)}),()=>{[...g,...I].forEach(P=>c(P))}},[u,o,d]);const[b,w]=r.useState(null);r.useEffect(()=>{if(!s)return;let g=!1;return(async()=>{const I=await tt(`${s}/.claude/skills`);g||w(I.length)})(),()=>{g=!0}},[s]);const h=u?n[u]:null,v=d?n[d]:null,N=o?n[o]:null,C=r.useMemo(()=>{if(!(h!=null&&h.exists)||h.parseError)return null;const g=h.diskData;return g===null||typeof g!="object"||Array.isArray(g)?{}:g},[h]),f=r.useMemo(()=>{if(!(v!=null&&v.exists)||v.parseError)return null;const g=v.diskData;return g===null||typeof g!="object"||Array.isArray(g)?{}:g},[v]),j=h?h.parseError?"invalid JSON":null:"loading…",A=v?v.parseError?"invalid JSON":null:"loading…",k=[{key:"settings",title:"Settings",summary:j??(C?`${Object.keys(C).length} top-level key${Object.keys(C).length===1?"":"s"} configured`:"not configured")},{key:"permissions",title:"Permissions",summary:j??(C?`${Gt(C.permissions)} rule(s) configured`:"not configured")},{key:"hooks",title:"Hooks",summary:j??(C?`${Jt(C.hooks)} hook(s) configured`:"not configured")},{key:"mcp",title:"MCP Servers",summary:A??(f?`${Object.keys(f.mcpServers??{}).length} MCP server(s)`:"not configured")},{key:"system-prompt",title:"System Prompt",summary:N!=null&&N.exists&&N.diskRaw.trim().length>0?`configured (${N.diskRaw.length.toLocaleString()} chars)`:"not set"},{key:"skills",title:"Skills",summary:b===null?"loading…":`${b} skill(s) installed`}];return e.jsxs("section",{className:"border border-line rounded-xl bg-bg-hi px-5 py-4",children:[e.jsx("h2",{className:"m-0 mb-1 font-serif text-[18px] font-semibold text-fg",children:"Global Controls"}),e.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."}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:k.map(g=>e.jsxs("button",{type:"button",onClick:()=>t==null?void 0:t(g.key),className:"text-left border border-line rounded-lg bg-bg px-3 py-2.5 hover:border-accent transition-colors",children:[e.jsx("div",{className:"text-[13px] font-medium text-fg",children:g.title}),e.jsx("div",{className:"mt-0.5 text-[12px] text-fg-dim",children:g.summary})]},g.key))})]})}function Vt({navigate:t}){const s=Ke(),[n,a]=r.useState(!1),[p,i]=r.useState(!1);r.useEffect(()=>{let u=!0;return Xe().then(o=>{u&&a(o.openToHomeOnLaunch===!0)}),()=>{u=!1}},[]);const c=async u=>{a(u),i(!0);try{await Ze({openToHomeOnLaunch:u})}catch{a(!u),O.error('Failed to save "Open to Home on launch" — try again.')}finally{i(!1)}};return e.jsxs("div",{className:"max-w-[760px] space-y-6",children:[e.jsx(Ut,{navigate:t}),e.jsxs("section",{className:"border border-line rounded-xl bg-bg-hi px-5 py-4",children:[e.jsx("h2",{className:"m-0 mb-1 font-serif text-[18px] font-semibold text-fg",children:"Session pool"}),e.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"," ",e.jsx("code",{className:"font-mono text-[12px]",children:"SM_SESSION_SLOTS"})," (clamped 0–10)."]}),e.jsxs("div",{className:"flex items-center gap-2",children:[Array.from({length:(s==null?void 0:s.total)??5},(u,o)=>e.jsx("span",{className:`w-3.5 h-3.5 rounded-full border ${o<((s==null?void 0:s.inUse)??0)?"bg-accent border-accent":"bg-bg border-line"}`},o)),e.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&&e.jsx("ul",{className:"mt-2 mb-0 pl-0 list-none space-y-0.5",children:s.holders.map((u,o)=>e.jsxs("li",{className:"font-mono text-[12px] text-fg-dim",children:[u.owner," ",e.jsxs("span",{className:"text-fg-faint",children:["since ",new Date(u.at).toLocaleTimeString()]})]},o))})]}),e.jsxs("section",{className:"border border-line rounded-xl bg-bg-hi px-5 py-4",children:[e.jsx("h2",{className:"m-0 mb-1 font-serif text-[18px] font-semibold text-fg",children:"Behavior"}),e.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."}),e.jsx(st,{checked:n,onChange:c,disabled:p,label:"Open to Home on launch"})]}),e.jsxs("section",{className:"border border-line rounded-xl bg-bg-hi px-5 py-4",children:[e.jsx("h2",{className:"m-0 mb-1 font-serif text-[18px] font-semibold text-fg",children:"On disk"}),e.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 ",e.jsx("code",{className:"font-mono text-[12px]",children:"session-manager-operations/"})," folder."]}),e.jsxs("ul",{className:"m-0 pl-0 list-none space-y-1 font-mono text-[12px] text-fg-dim",children:[e.jsxs("li",{children:["~/.claude/session-manager/scheduler-machine.json ",e.jsx("span",{className:"text-fg-faint",children:"— policy + pause state"})]}),e.jsxs("li",{children:["<project>/session-manager-operations/scheduler/state/ ",e.jsx("span",{className:"text-fg-faint",children:"— per-project queue + history"})]}),e.jsxs("li",{children:["<project>/session-manager-operations/scheduler/epics/<epic>/prds/ ",e.jsx("span",{className:"text-fg-faint",children:"— PRD sources, per Epic"})]})]})]})]})}const Ie="sm.schedulerTab.subView",zt=[{key:"queue",label:"Queue"},{key:"prds",label:"PRDs"},{key:"history",label:"History"}];function Qt(t,s){const n=new Date(t),a=new Date(s);return n.getFullYear()===a.getFullYear()&&n.getMonth()===a.getMonth()&&n.getDate()===a.getDate()}function Wt(t,s,n){if(t==="auth")return"Scheduler paused: Claude sign-in expired or invalid. Restart the app or re-run `claude login`, then Resume.";if(t==="rate_limit"){if(s){const p=new Date(s).getTime()-n;return p>0?`Paused for rate limit — resumes in ${q(p)}`:"Paused for rate limit — resume pending"}return"Paused for rate limit"}return t==="network"?"Paused: billing endpoint unreachable for 30+ min.":t==="manual"?"Scheduler paused manually. Click Resume to restart.":`Scheduler paused (${t})`}function Yt({scopeCwd:t}){const{snapshot:s}=we(),[n,a]=r.useState(()=>Date.now());if(r.useEffect(()=>{const f=setInterval(()=>a(Date.now()),3e4);return()=>clearInterval(f)},[]),!s)return null;const p=(s.jobs??[]).filter(f=>!t||f.cwd===t),i=p.filter(f=>f.status==="pending").length,c=p.filter(f=>f.status==="running").length,u=p.filter(f=>f.status==="completed"&&(f.finishedAt?Qt(f.finishedAt,n):!1)).length,o=s.nextReset?new Date(s.nextReset).getTime():null,d=o?o>n?q(o-n):"soon":"—",b=V(s.lastRunAt?new Date(s.lastRunAt).getTime():null,n),w=s.paused,h=s.pollHealth,v=h!=null&&!h.lastPollOk,C=(w==null?void 0:w.reason)==="auth"||(w==null?void 0:w.reason)==="network"?"bg-red-950/60 border-red-700/50 text-red-200":"bg-amber-950/60 border-amber-700/50 text-amber-200";return e.jsxs("div",{className:"flex flex-col gap-2",children:[w&&e.jsxs("div",{className:`flex items-center gap-3 border rounded-xl px-4 py-2.5 text-[13px] ${C}`,children:[e.jsx("span",{className:"flex-1 leading-snug",children:Wt(w.reason,w.resumeAt,n)}),e.jsx("button",{type:"button",onClick:()=>window.api.schedule.resume(),className:"shrink-0 px-2.5 py-1 rounded border border-current/40 hover:bg-white/10 transition-colors text-[12px] font-medium",children:"Resume"})]}),e.jsxs("div",{className:"flex items-center gap-5 flex-wrap bg-bg-hi border border-line rounded-xl px-4 py-3",children:[e.jsxs("span",{className:"inline-flex items-center gap-2 text-[13.5px] text-fg font-semibold whitespace-nowrap",children:[e.jsx("span",{className:"text-sage","aria-hidden":"true",children:e.jsx(ue,{name:"clock",size:15})}),"Window resets in ",d]}),e.jsx("span",{className:"w-px h-[18px] bg-rule shrink-0","aria-hidden":"true"}),e.jsx(he,{dotClass:"bg-fg-faint",n:i,label:"pending"}),e.jsx(he,{dotClass:"bg-accent",n:c,label:"running"}),e.jsx(he,{dotClass:"bg-sage",n:u,label:"completed today"}),s.utilization!==null&&s.utilization!==void 0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"w-px h-[18px] bg-rule shrink-0","aria-hidden":"true"}),v?e.jsxs("span",{className:"font-mono text-[12.5px] text-amber-400/70",title:"Billing poll failing — this reading may be outdated",children:[Math.round(s.utilization),"% of window used · last good reading"," ",V(h.lastPollAt,n)]}):e.jsxs("span",{className:"font-mono text-[12.5px] text-fg-faint",children:[Math.round(s.utilization),"% of window used"]})]}),e.jsxs("span",{className:"ml-auto font-mono text-[12.5px] text-fg-faint whitespace-nowrap",children:["last batch ",b]})]})]})}function Kt({navigate:t}={}){var u;const[s,n]=r.useState(()=>{const o=localStorage.getItem(Ie);return o==="prds"||o==="history"||o==="machine"?o:"queue"}),a=$e(o=>o.tabs),p=$e(o=>o.activeTabId),i=((u=a.find(o=>o.id===p))==null?void 0:u.cwd)??null,c=i;return r.useEffect(()=>{i&&(re.getState().hydrate(i),re.getState().hydrateArchived(i))},[i]),r.useEffect(()=>{localStorage.setItem(Ie,s)},[s]),e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsxs("div",{className:"shrink-0 px-9 pt-7 pb-0",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsx("div",{className:"text-xs font-bold text-fg-faint tracking-[0.8px] uppercase mb-1",children:"Workspace"}),e.jsx(et,{active:"scheduler"})]}),e.jsx("h1",{className:"m-0 font-serif text-[40px] font-semibold leading-none tracking-tight text-fg",children:"Scheduler"}),e.jsxs("p",{className:"mt-2 text-[14.5px] text-fg-dim leading-relaxed max-w-[600px]",children:["Global scheduler policy and the machine-wide session pool, plus — when a project tab is active — that project's PRDs, run as"," ",e.jsx("code",{className:"font-mono text-[13.5px]",children:"claude -p"})," ","jobs against your 5-hour window. Jobs auto-pause on rate-limit and resume on the next reset."]}),e.jsx("div",{className:"mt-[18px] mb-[22px]",children:e.jsx(Yt,{scopeCwd:c})}),e.jsxs("div",{className:"flex items-center gap-3 pb-0",children:[e.jsx(nt,{options:zt,active:s,onChange:n}),e.jsxs("button",{type:"button",onClick:()=>n("machine"),"aria-pressed":s==="machine",className:`inline-flex items-center gap-1.5 px-[15px] py-2 rounded-lg text-[13.5px] transition-colors ${s==="machine"?"bg-bg-elev border border-line font-semibold text-fg":"text-fg-faint hover:text-fg-dim"}`,title:"Machine-wide config that applies to every project — not this project's live queue.",children:[e.jsx("span",{"aria-hidden":"true",children:"⚙"})," Machine"]})]}),s==="queue"&&e.jsx("p",{className:"mt-2 text-[14.5px] text-fg-dim leading-relaxed max-w-[600px]",children:"What's running right now, and what fires next."}),s==="prds"&&e.jsx("p",{className:"mt-2 text-[14.5px] text-fg-dim leading-relaxed max-w-[600px]",children:"Authored PRD source files on disk — edit, lint, archive, or queue them."}),s==="history"&&e.jsx("p",{className:"mt-2 text-[14.5px] text-fg-dim leading-relaxed max-w-[600px]",children:"The last 50 completed and failed jobs, for this project."}),s==="machine"&&e.jsx("p",{className:"mt-2 text-[14.5px] text-fg-dim leading-relaxed max-w-[600px]",children:"Machine-wide setup that applies to every project."})]}),e.jsxs("div",{className:"flex-1 min-h-0",children:[s==="queue"&&e.jsx(pt,{scopeCwd:c,navigate:t}),s==="prds"&&e.jsx(Mt,{scopeCwd:c}),s==="history"&&e.jsx(qt,{scopeCwd:c}),s==="machine"&&e.jsx("div",{className:"h-full overflow-y-auto px-9 py-6",children:e.jsx(Vt,{navigate:t})})]})]})}const ss=r.memo(Kt);export{ss as Scheduler};