claude-code-session-manager 0.140.0 → 0.142.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +80 -70
- package/bin/cli.cjs +11 -0
- package/dist/assets/AppSettings-BcZgIvvY.js +2 -0
- package/dist/assets/{History--JwsFnbn.js → History-DpZuJXi1.js} +1 -1
- package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +3 -0
- package/dist/assets/{Panel-CALyU0pe.js → Panel-BjdJjhqt.js} +1 -1
- package/dist/assets/{ProjectClaudeConfig-sdlA-fUb.js → ProjectClaudeConfig-BTClYV6i.js} +7 -7
- package/dist/assets/Scheduler-DPobKx1Z.js +16 -0
- package/dist/assets/{SkillReferenceGraph-CxAuwhNN.js → SkillReferenceGraph-Cqyu4mef.js} +1 -1
- package/dist/assets/{Skills-DtRzghn5.js → Skills-vv0noNVI.js} +5 -5
- package/dist/assets/{TiptapBody-DApeu7x8.js → TiptapBody-CXi8Pvut.js} +1 -1
- package/dist/assets/Toggle-CiYCWLjh.js +1 -0
- package/dist/assets/{VoiceButton-DtStfv1H.js → VoiceButton-4NKKd1sC.js} +1 -1
- package/dist/assets/{historyTotals-ydfnwepc.js → historyTotals-DDunb8Ch.js} +1 -1
- package/dist/assets/index-Cn5E9958.js +3133 -0
- package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
- package/dist/index.html +2 -2
- package/dist-web/app.css +1 -1
- package/dist-web/app.js +496 -484
- package/package.json +4 -2
- package/plugins/AGENTS.md +4 -3
- package/plugins/session-manager-dev/hooks/hooks.json +15 -0
- package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
- package/plugins/session-manager-dev/skills/builder/SKILL.md +4 -2
- package/plugins/session-manager-dev/skills/develop/SKILL.md +55 -18
- package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
- package/scripts/README.md +1 -0
- package/scripts/hooks/guard-tool-risk.cjs +5 -1
- package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
- package/scripts/scheduler-mcp-server.cjs +737 -110
- package/src/main/adminRouteRegistry.cjs +59 -0
- package/src/main/agentLibrary.cjs +72 -4
- package/src/main/agentsIpc.cjs +3 -2
- package/src/main/build-info.json +4 -4
- package/src/main/chatRunner.cjs +231 -16
- package/src/main/config.cjs +30 -0
- package/src/main/docEdit.cjs +4 -2
- package/src/main/health.cjs +91 -0
- package/src/main/index.cjs +98 -48
- package/src/main/ipcSchemas.cjs +171 -8
- package/src/main/lib/AGENTS.md +1 -1
- package/src/main/lib/chatBootRecovery.cjs +2 -0
- package/src/main/lib/claude/agentModelResolve.cjs +51 -25
- package/src/main/lib/claude/agentSnapshot.cjs +186 -0
- package/src/main/lib/claude/environmentProfiles.cjs +242 -0
- package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
- package/src/main/lib/claude/personaToolScope.cjs +82 -31
- package/src/main/lib/claude/runClaudeP.cjs +4 -2
- package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
- package/src/main/lib/claude/usageCircuit.cjs +49 -21
- package/src/main/lib/claude/vaultRefs.cjs +277 -0
- package/src/main/lib/demo-video-kit/capture.cjs +282 -12
- package/src/main/lib/demo-video-kit/cast.md +43 -0
- package/src/main/lib/demo-video-kit/character.cjs +722 -30
- package/src/main/lib/demo-video-kit/checks.cjs +120 -1
- package/src/main/lib/demo-video-kit/export.cjs +218 -0
- package/src/main/lib/demo-video-kit/frames.cjs +104 -9
- package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
- package/src/main/lib/demo-video-kit/kind-tiktok.md +99 -0
- package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
- package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
- package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
- package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
- package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
- package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
- package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
- package/src/main/lib/epic/artifactIpc.cjs +153 -0
- package/src/main/lib/epic/artifactNotice.cjs +72 -0
- package/src/main/lib/epic/artifactRetention.cjs +310 -0
- package/src/main/lib/epic/artifactStore.cjs +392 -0
- package/src/main/lib/epic/delegationReadiness.cjs +76 -2
- package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
- package/src/main/lib/epic/epicEventLog.cjs +214 -0
- package/src/main/lib/epic/epicMint.cjs +43 -1
- package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
- package/src/main/lib/epic/epicOutsideState.cjs +18 -4
- package/src/main/lib/epic/epicPurge.cjs +347 -0
- package/src/main/lib/epic/epicReopen.cjs +5 -2
- package/src/main/lib/epic/epicSettle.cjs +4 -13
- package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
- package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
- package/src/main/lib/epic/epicTransitions.cjs +139 -0
- package/src/main/lib/epic/epicValidationHook.cjs +81 -2
- package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
- package/src/main/lib/externalContract.cjs +37 -4
- package/src/main/lib/feedback-remote/crossProjectReply.cjs +389 -126
- package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
- package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
- package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
- package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
- package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
- package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
- package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
- package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
- package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
- package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
- package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
- package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +2 -1
- package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
- package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
- package/src/main/lib/feedback-remote/pendingReplies.cjs +189 -0
- package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +188 -10
- package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
- package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
- package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
- package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
- package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
- package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
- package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
- package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
- package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
- package/src/main/lib/git/worktreeDeps.cjs +77 -2
- package/src/main/lib/mcpToolCatalog.cjs +315 -30
- package/src/main/lib/opsOwnership.cjs +29 -1
- package/src/main/lib/opsRetentionSettings.cjs +27 -5
- package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
- package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
- package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
- package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
- package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
- package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
- package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +263 -0
- package/src/main/lib/phaseProjection.cjs +103 -0
- package/src/main/lib/prd/depSlugResolve.cjs +4 -13
- package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
- package/src/main/lib/prd/prdCreate.cjs +67 -5
- package/src/main/lib/prd/prdCriteria.cjs +225 -0
- package/src/main/lib/prd/prdFrontmatter.cjs +68 -3
- package/src/main/lib/prd/prdGateFiles.cjs +125 -49
- package/src/main/lib/prd/prdSizing.cjs +3 -1
- package/src/main/lib/process/cleanEnv.cjs +52 -1
- package/src/main/lib/process/leftoverRenice.cjs +178 -0
- package/src/main/lib/process/memoryScope.cjs +31 -3
- package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
- package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
- package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
- package/src/main/lib/project-pages/voicePreview.cjs +196 -0
- package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
- package/src/main/lib/promptSessionSchema.cjs +6 -0
- package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
- package/src/main/lib/scheduler/cpuSample.cjs +133 -42
- package/src/main/lib/scheduler/criteriaChecks.cjs +169 -0
- package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
- package/src/main/lib/scheduler/jobMemoryStats.cjs +313 -0
- package/src/main/lib/scheduler/loadGate.cjs +82 -4
- package/src/main/lib/scheduler/planRecordHarvest.cjs +32 -2
- package/src/main/lib/scheduler/prdOutcomeRecord.cjs +133 -0
- package/src/main/lib/scheduler/preflightCheck.cjs +97 -0
- package/src/main/lib/scheduler/reviewNotice.cjs +39 -0
- package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
- package/src/main/lib/scheduler/scheduleJobSchema.cjs +5 -0
- package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
- package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
- package/src/main/lib/scheduler/schedulerPaths.cjs +0 -3
- package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
- package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
- package/src/main/lib/scheduler/slotsRoute.cjs +237 -0
- package/src/main/lib/scheduler/toolClearance.cjs +258 -0
- package/src/main/lib/scheduler/validatorVerdictSchema.cjs +140 -10
- package/src/main/lib/tasks/memoryConsolidation.cjs +300 -0
- package/src/main/lib/tasks/mitigationReview.cjs +294 -0
- package/src/main/lib/tasks/taskAdminRoutes.cjs +312 -22
- package/src/main/lib/tasks/taskIpc.cjs +22 -18
- package/src/main/lib/tasks/taskLedger.cjs +147 -25
- package/src/main/lib/tasks/taskRun.cjs +186 -17
- package/src/main/lib/tasks/taskSwitch.cjs +85 -12
- package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
- package/src/main/lib/telemetry/auditEvents.cjs +207 -6
- package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
- package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
- package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
- package/src/main/lib/toolUseClassify.cjs +181 -0
- package/src/main/lib/util/smfileRange.cjs +77 -0
- package/src/main/projectPages.cjs +3 -1
- package/src/main/promptSessionEvents.cjs +5 -0
- package/src/main/pty.cjs +68 -0
- package/src/main/queueOps.cjs +32 -13
- package/src/main/runVerify.cjs +74 -9
- package/src/main/scheduler/AGENTS.md +1 -0
- package/src/main/scheduler/budget.cjs +6 -5
- package/src/main/scheduler/prdParser.cjs +62 -14
- package/src/main/scheduler/reviewLadder.cjs +45 -28
- package/src/main/scheduler/starvation.cjs +69 -0
- package/src/main/scheduler/utilizationHold.cjs +101 -0
- package/src/main/scheduler.cjs +1745 -210
- package/src/main/templates/PRD_AUTHORING.md +13 -2
- package/src/main/webRemote.cjs +463 -6
- package/src/preload/api.d.ts +529 -38
- package/src/preload/apiSurface.json +209 -7
- package/src/preload/index.cjs +46 -1
- package/src/seed/agents/architect.md +6 -1
- package/src/seed/agents/blender-artist.md +2 -1
- package/src/seed/agents/competitive-analyst.md +3 -1
- package/src/seed/agents/competitive-researcher.md +2 -1
- package/src/seed/agents/demo-video-builder.md +87 -83
- package/src/seed/agents/dev-lead.md +3 -3
- package/src/seed/agents/project-home-builder.md +9 -31
- package/src/seed/agents/validator.md +9 -10
- package/dist/assets/AppSettings-CMFEM68R.js +0 -2
- package/dist/assets/HomeClaudeConfig-ijEXs--3.js +0 -3
- package/dist/assets/Scheduler-YT3j8SUa.js +0 -16
- package/dist/assets/ViewTabs-B7qLXRAH.js +0 -1
- package/dist/assets/index-CtxruO1L.js +0 -3121
- package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{aC as e,x as He,o as Be,bA as _,aS as o,ax as Fe,$ as Ue,v as ze,aF as je,D as We,aE as Je,a4 as ve,a3 as we,a5 as le,b0 as Ve,a2 as Ge,m as ce,a6 as qe,ah as Pe,bb as Q,a1 as Xe,b as ee,bz as de,bx as Ye,c as U,bf as Ke,a9 as Ae,br as Ze,a as Qe,a8 as et,bm as tt,bi as nt,e as st,aT as at,bE as rt}from"./index-Cn5E9958.js";import{T as V,S as it}from"./Toggle-CiYCWLjh.js";import{V as ot,T as lt}from"./VoiceButton-4NKKd1sC.js";import{P as ct}from"./Panel-BjdJjhqt.js";import"./monaco-editor-BsIlgG7c.js";function dt({open:t,onClose:n,title:s,children:r,variant:i="overlay"}){return e.jsxs(He,{open:t,onClose:n,size:"xl",fillHeight:!0,noPadding:!0,title:void 0,variant:i,children:[i==="overlay"&&e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-line shrink-0",children:[e.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:s}),e.jsx("button",{type:"button",onClick:n,"aria-label":"Close",className:"px-2 py-0.5 text-fg-dim hover:text-fg hover:bg-bg-hi rounded text-base leading-none",children:"✕"})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:e.jsx(Be,{children:r})})]})}function pt(){const t=_(h=>h.isRecording),n=_(h=>h.levelMeterEnabled),[s,r]=o.useState(0),[i,a]=o.useState(0),c=o.useRef(0);c.current=i;const[p,v]=o.useState(0),[u,g]=o.useState(!1),f=o.useRef(null);if(o.useEffect(()=>{if(!t||!n){r(0),a(0);return}let h=0,k=!1,N=null,C=null;const I=()=>{if(k)return;const E=C??Fe();if(!E){h=requestAnimationFrame(I);return}C!==E&&(C=E,N=new Uint8Array(new ArrayBuffer(E.fftSize)));const T=N;E.getByteTimeDomainData(T);let P=0;for(let $=0;$<T.length;$++){const G=T[$]-128;P+=G*G}const R=Math.sqrt(P/T.length)/128,w=R>0?20*Math.log10(R):-60,b=Math.max(0,Math.min(1,(w+60)/60));a(R),r(b),R>=.95&&(g(!0),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>g(!1),150)),h=requestAnimationFrame(I)};h=requestAnimationFrame(I);const x=setInterval(()=>{k||v(Math.round(c.current*100))},250);return()=>{k=!0,cancelAnimationFrame(h),clearInterval(x),f.current&&(clearTimeout(f.current),f.current=null)}},[t,n]),!t||!n)return null;const m=u?"bg-red-500":i>=.7?"bg-amber-400":"bg-green-500";return e.jsx("div",{role:"meter","aria-label":"Microphone input level","aria-valuenow":p,"aria-valuemin":0,"aria-valuemax":100,"data-testid":"mic-level-meter",className:`mx-3 mb-2 h-1 rounded bg-bg overflow-hidden ${u?"ring-1 ring-red-500":""}`,children:e.jsx("div",{className:`h-full ${m} transition-[width] duration-75 ease-out`,style:{width:`${s*100}%`}})})}function mt({open:t,onClose:n,variant:s="overlay"}){return e.jsx(dt,{open:t,onClose:n,title:"Voice / Microphone",variant:s,children:e.jsxs("div",{className:"p-4 space-y-4",children:[e.jsx(ht,{}),e.jsx(Ue,{}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(ot,{}),e.jsx(ze,{}),e.jsx(lt,{})]}),e.jsx(ut,{}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx("button",{type:"button",onClick:()=>_.getState().openWizard(),className:"text-xs text-fg-faint hover:text-fg-dim underline","data-testid":"run-mic-check",children:"Run mic check"}),e.jsx(gt,{})]}),e.jsx(pt,{})]})})}function ut(){const t=_(a=>a.isRecording),[n,s]=o.useState(null);if(o.useEffect(()=>{let a=!1;window.api.voice.getHotkeyConfig().then(p=>{a||s(p)}).catch(()=>{});const c=window.api.voice.onHotkeyConfigChanged(p=>s(p));return()=>{a=!0,c()}},[]),t||!n)return null;const r=n.mode==="hold"?"Hold":"Press",i=ft(n.accelerator);return e.jsxs("div",{className:"text-[11px] text-fg-faint",children:[e.jsxs("span",{children:[r," "]}),e.jsx("kbd",{className:"px-1 py-0.5 rounded border border-line bg-bg font-mono text-fg-dim",children:i}),e.jsx("span",{children:" to record"})]})}function ft(t){const n=typeof navigator<"u"&&/Mac/.test(navigator.platform);return t.replace(/CommandOrControl/g,n?"⌘":"Ctrl").replace(/CmdOrCtrl/g,n?"⌘":"Ctrl").replace(/Command/g,"⌘").replace(/Control/g,"Ctrl").replace(/Option/g,n?"⌥":"Alt").replace(/Shift/g,n?"⇧":"Shift")}function gt(){const[t,n]=o.useState(null);if(o.useEffect(()=>{let r=!1;window.api.voice.getHotkeyConfig().then(a=>{r||n(a)}).catch(a=>je.warn("voice-hotkey","getHotkeyConfig (toggle) failed",{error:String(a)}));const i=window.api.voice.onHotkeyConfigChanged(a=>{n(a)});return()=>{r=!0,i()}},[]),!t)return null;const s=async r=>{if(t.mode===r)return;const i={...t,mode:r};n(i);try{await window.api.voice.setHotkeyConfig(i)}catch(a){je.warn("voice-hotkey","setHotkeyConfig (toggle) failed",{error:a instanceof Error?a.message:String(a)})}};return e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-fg-faint select-none",title:"Mic hotkey behavior. Tap on/off: press once to start, again to stop. Hold to talk: record only while held (push-to-talk).",children:[e.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[e.jsx("input",{type:"radio",name:"hotkey-mode",checked:t.mode==="toggle",onChange:()=>s("toggle"),className:"cursor-pointer","data-testid":"hotkey-mode-toggle"}),e.jsx("span",{children:"Tap on/off"})]}),e.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[e.jsx("input",{type:"radio",name:"hotkey-mode",checked:t.mode==="hold",onChange:()=>s("hold"),className:"cursor-pointer","data-testid":"hotkey-mode-hold"}),e.jsx("span",{children:"Hold to talk"})]})]})}function ht(){const t=_(a=>a.isRecording),n=_(a=>a.lastTranscript),s=_(a=>a.error),r=_(a=>a.modelStatus),i=_(a=>a.loadingProgress);return s?e.jsxs("div",{className:"text-[11px] text-red-400",title:s,children:["⚠ ",s]}):t?e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-fg-dim border border-line rounded px-2 py-1.5",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse shrink-0"}),e.jsx("span",{className:"truncate",title:n,children:n||"Listening…"})]}):r==="loading"?e.jsxs("div",{className:"text-[11px] text-fg-faint",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{children:"Loading speech model"}),e.jsxs("span",{className:"font-mono",children:[i,"%"]})]}),e.jsx("div",{className:"h-1 rounded bg-bg overflow-hidden",children:e.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${i}%`}})})]}):null}const xt=["dark","light","paper"];function yt(){const[t,n]=o.useState(We),[s,r]=o.useState(!1);o.useEffect(()=>{let c=!1;return Je().then(p=>{c||(n(p),r(!0))}),()=>{c=!0}},[]);const i=c=>{s&&n(p=>{const v={...p,...c};return Ve(v),v})},a=c=>{i({fontSize:Math.min(we,Math.max(ve,t.fontSize+c))})};return e.jsxs("section",{className:"mb-6","data-testid":"home-terminal-appearance",children:[e.jsxs("div",{className:"flex items-baseline justify-between mb-3",children:[e.jsx("h2",{className:"m-0 font-serif text-[22px] font-medium",children:"Terminal appearance"}),e.jsx("span",{className:"font-mono text-[12px] text-fg-faint",children:"every terminal, this machine"})]}),e.jsxs("div",{className:"border border-line rounded-xl bg-bg-hi px-5 py-4",children:[e.jsxs("p",{className:"mt-0 mb-4 text-[13px] text-fg-dim leading-relaxed",children:["Applies to ",e.jsx("strong",{className:"text-fg",children:"every terminal in the app at once"})," — project Terminal tabs, an Epic’s Terminal view of its session, and the inline permission prompt. It is not per project, per session, or per tab. It does not restyle the app chrome (there is no app theme switch), and the code editor keeps its own separate paper/dark setting in the Editor tab’s Display menu. Stored in"," ",e.jsx("code",{className:"font-mono text-[12px]",children:"~/.claude/session-manager/ui-settings-prefs.json"}),", applied live without restarting a session."]}),e.jsxs("div",{className:"grid gap-5",style:{gridTemplateColumns:"minmax(0,1fr) 220px"},children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-fg-faint mb-1.5",children:"Theme"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:xt.map(c=>e.jsxs("button",{type:"button",onClick:()=>i({theme:c}),disabled:!s,"aria-pressed":t.theme===c,"data-testid":`terminal-theme-${c}`,className:`px-2 py-2 rounded-lg text-[11px] font-medium border transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${t.theme===c?"bg-bg border-accent text-fg":"bg-bg border-line text-fg-dim hover:text-fg hover:border-fg-faint"}`,children:[e.jsx(bt,{theme:c}),e.jsx("div",{className:"mt-1.5 capitalize",children:c})]},c))})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-fg-faint",children:"Font size"}),e.jsxs("span",{className:"font-mono text-[11px] text-fg-dim",children:[t.fontSize,"px"]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{type:"button",onClick:()=>a(-1),disabled:!s||t.fontSize<=ve,"aria-label":"Decrease font size",className:"flex-1 py-1.5 rounded border border-line bg-bg text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed",children:"−"}),e.jsx("button",{type:"button",onClick:()=>i({fontSize:Ge}),disabled:!s,className:"flex-1 py-1.5 rounded border border-line bg-bg text-[11px] text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed",children:"reset"}),e.jsx("button",{type:"button",onClick:()=>a(1),disabled:!s||t.fontSize>=we,"aria-label":"Increase font size",className:"flex-1 py-1.5 rounded border border-line bg-bg text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed",children:"+"})]}),e.jsxs("div",{className:"mt-3 rounded border border-line px-3 py-2 font-mono",style:{background:le[t.theme].background,color:le[t.theme].foreground,fontSize:`${t.fontSize}px`,lineHeight:1.35},"aria-hidden":!0,children:[e.jsx("span",{style:{color:le[t.theme].green},children:"$"})," claude"]})]})]})]})]})}function bt({theme:t}){const n=le[t];return e.jsxs("div",{"aria-hidden":!0,className:"w-full h-5 rounded border relative overflow-hidden",style:{background:n.background,borderColor:"rgba(0,0,0,0.15)"},children:[e.jsx("div",{style:{position:"absolute",top:3,left:4,width:"40%",height:2,background:n.foreground}}),e.jsx("div",{style:{position:"absolute",top:9,left:4,width:"25%",height:2,background:n.green??n.foreground}}),e.jsx("div",{style:{position:"absolute",top:15,left:4,width:"55%",height:2,background:n.cyan??n.foreground}})]})}const jt=1440*60*1e3;function vt(t){if(!t)return"never";const n=new Date(t).getTime();return Number.isNaN(n)?"never":new Date(n).toLocaleString()}function ke(t){return t?new Date(t).toLocaleString():"never"}function wt(){return e.jsxs("div",{className:"p-4 max-w-3xl space-y-8 text-sm",children:[e.jsx(kt,{}),e.jsx("hr",{className:"border-line"}),e.jsx(Nt,{})]})}function kt(){const[t,n]=o.useState(null),[s,r]=o.useState(null),[i,a]=o.useState(null),[c,p]=o.useState(null),[v,u]=o.useState(!1),[g,f]=o.useState(null),[m,h]=o.useState(null);if(o.useEffect(()=>{let x=!1;return Promise.all([window.api.otel.getConfig(),window.api.otel.status(),window.api.otel.configPath()]).then(([E,T,P])=>{x||(n(E),a(E),r(T),p(P))}).catch(E=>{console.warn("[telemetry] load failed:",E==null?void 0:E.message)}),()=>{x=!0}},[]),!i||!t)return e.jsx(ce,{title:"loading…"});const k=JSON.stringify(i)!==JSON.stringify(t),N=(x,E)=>{f(null),a({...i,[x]:E})},C=async()=>{u(!0),f(null);try{const x=await window.api.otel.setConfig(i);!x.ok&&x.error&&f(x.error),n(x.config),a(x.config),r(x.status),h(Date.now())}catch(x){f(x instanceof Error?x.message:String(x))}finally{u(!1)}},I=()=>{f(null),a(t)};return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("header",{className:"space-y-1",children:[e.jsx("h2",{className:"text-fg text-base font-medium",children:"OpenTelemetry export"}),e.jsx("p",{className:"text-fg-dim text-xs leading-relaxed",children:"When enabled, every classified transcript event (tool_use, todo_write, plan, usage, agent_spawn) is mirrored as a 0-duration OTLP/HTTP span. Point this at a local collector (Jaeger, Grafana Tempo, SigNoz, Honeycomb) for cross-session analysis."}),c&&e.jsxs("p",{className:"text-fg-faint text-[11px]",children:["stored at ",e.jsx("span",{className:"font-mono",children:c})]})]}),e.jsxs("section",{className:"border border-line rounded p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-fg",children:"Export transcripts to OTEL"}),e.jsx("div",{className:"text-fg-faint text-xs",children:"Toggle off to disable all span emission immediately."})]}),e.jsx(V,{checked:i.enabled,onChange:x=>N("enabled",x),label:i.enabled?"on":"off"})]}),e.jsxs("label",{className:"block space-y-1",children:[e.jsx("span",{className:"text-fg-dim text-xs",children:"OTLP/HTTP traces endpoint"}),e.jsx("input",{type:"text",value:i.endpoint,onChange:x=>N("endpoint",x.target.value),placeholder:"http://localhost:4318/v1/traces",className:"w-full bg-bg border border-line rounded px-2 py-1 text-fg font-mono text-xs"})]}),e.jsxs("label",{className:"block space-y-1",children:[e.jsxs("span",{className:"text-fg-dim text-xs",children:["Headers (newline-separated ",e.jsx("span",{className:"font-mono",children:"Key: Value"}),")"]}),e.jsx("textarea",{value:i.headers,onChange:x=>N("headers",x.target.value),placeholder:"x-honeycomb-team: YOUR_API_KEY",rows:3,className:"w-full bg-bg border border-line rounded px-2 py-1 text-fg font-mono text-xs"})]}),e.jsxs("label",{className:"block space-y-1",children:[e.jsx("span",{className:"text-fg-dim text-xs",children:"Service name"}),e.jsx("input",{type:"text",value:i.serviceName,onChange:x=>N("serviceName",x.target.value),placeholder:"session-manager",className:"w-full bg-bg border border-line rounded px-2 py-1 text-fg font-mono text-xs"})]}),e.jsxs("div",{className:"flex items-start justify-between gap-3 pt-1",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-fg",children:"Include content (PII)"}),e.jsxs("div",{className:"text-fg-faint text-xs leading-relaxed",children:["Adds tool inputs, plan text, and agent prompts to span attributes. Off by default — matches upstream Claude Code's ",e.jsx("span",{className:"font-mono",children:"OTEL_LOG_USER_PROMPTS"})," opt-in."]})]}),e.jsx(V,{checked:i.includeContent,onChange:x=>N("includeContent",x),label:i.includeContent?"on":"off"})]})]}),s&&e.jsxs("section",{className:"border border-line rounded p-3 text-xs space-y-1",children:[e.jsx("div",{className:"text-fg-dim",children:"Runtime status"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-fg-faint",children:"enabled:"})," ",e.jsx("span",{className:s.enabled?"text-accent":"text-fg-dim",children:String(s.enabled)})]}),s.error&&e.jsxs("div",{className:"text-red-400 break-words",children:[e.jsx("span",{className:"text-fg-faint",children:"error:"})," ",s.error]}),!s.error&&s.enabled&&e.jsx("div",{className:"text-fg-faint",children:"spans batched and exported in the background. Verify by enabling and pointing at a local Jaeger."})]}),e.jsxs("footer",{className:"flex items-center gap-3 pt-2 border-t border-line",children:[e.jsx("button",{onClick:C,disabled:!k||v,className:"px-3 py-1 text-xs rounded bg-accent text-bg disabled:opacity-50 disabled:cursor-not-allowed",children:v?"saving…":"Save"}),e.jsx("button",{onClick:I,disabled:!k||v,className:"px-3 py-1 text-xs rounded border border-line text-fg-dim hover:text-fg disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert"}),g&&e.jsx("span",{className:"text-red-400 text-xs",children:g}),!g&&m&&!k&&e.jsx("span",{className:"text-fg-faint text-xs",children:"saved"})]})]})}function Nt(){const[t,n]=o.useState(null),[s,r]=o.useState(null),[i,a]=o.useState("Copy"),[c,p]=o.useState(!1),[v,u]=o.useState(null),[g,f]=o.useState(null),[m,h]=o.useState(null),[k,N]=o.useState(!1),C=()=>{window.api.telemetry.status().then(r).catch(w=>{console.warn("[product-telemetry] status reload failed:",w==null?void 0:w.message)})};if(o.useEffect(()=>{let w=!1;return Promise.all([window.api.telemetry.getConfig(),window.api.telemetry.status()]).then(([b,$])=>{w||(n(b),r($))}).catch(b=>{console.warn("[product-telemetry] load failed:",b==null?void 0:b.message)}),()=>{w=!0}},[]),!t||!s)return e.jsx(ce,{title:"loading…"});const I=async w=>{f(null);try{const b=await window.api.telemetry.setConfig(w);n(b.config),r(b.status),window.dispatchEvent(new CustomEvent(Xe,{detail:b.config}))}catch(b){f(b instanceof Error?b.message:String(b))}},x=w=>{I({...t,enabled:w})},E=async()=>{await Pe(t.installId)?(a("Copied"),setTimeout(()=>a("Copy"),1500)):Q.error("Could not copy install id to the clipboard")},T=async()=>{p(!0),u(null);try{const w=await window.api.telemetry.flushNow();u(`sent ${w.sent.length}, failed ${w.failed.length}`),C()}catch(w){u(w instanceof Error?w.message:String(w))}finally{p(!1)}},P=async()=>{if(k){N(!1);return}try{const w=await window.api.telemetry.recentRecords();h(w),N(!0)}catch(w){console.warn("[product-telemetry] recentRecords failed:",w instanceof Error?w.message:w)}},R=t.lastDailyFlushAt?new Date(t.lastDailyFlushAt).getTime()+jt:null;return e.jsxs("div",{className:"space-y-5","data-testid":"product-telemetry-section",children:[e.jsxs("header",{className:"space-y-1",children:[e.jsx("h2",{className:"text-fg text-base font-medium",children:"Product telemetry (bilko.run)"}),e.jsxs("p",{className:"text-fg-dim text-xs leading-relaxed",children:["Anonymous, strictly non-identifying usage/error reporting that helps improve this app. On by default; switchable off in one click. See"," ",e.jsx("span",{className:"font-mono",children:"session-manager-operations/architecture/telemetry.md"})," for the full data model."]})]}),e.jsx(qe,{cfg:t,onSaved:(w,b)=>{n(w),r(b)}}),e.jsxs("section",{className:"border border-line rounded p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-fg",children:"Send anonymous product telemetry"}),e.jsx("div",{className:"text-fg-faint text-xs",children:"Sent on start-up, after an update, and once a day. Strictly anonymous — an install id only, never an email, name, or other identifier."})]}),e.jsx(V,{checked:t.enabled,onChange:x,label:t.enabled?"on":"off"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-fg-dim text-xs",children:"Anonymous install id"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"text",readOnly:!0,value:t.installId,"aria-label":"Anonymous install identifier",className:"flex-1 bg-bg border border-line rounded px-2 py-1 text-fg font-mono text-xs"}),e.jsx("button",{onClick:E,className:"px-2 py-1 text-xs rounded border border-line text-fg-dim hover:text-fg",children:i})]})]}),e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsx("div",{className:"text-fg-faint",children:"Endpoint"}),e.jsx("div",{className:"font-mono text-fg-dim break-all",children:t.endpoint})]}),e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsx("div",{className:"text-fg-faint",children:"Send cadence"}),e.jsx("div",{className:"text-fg-dim",children:"on start-up, after an update, and once a day"})]}),g&&e.jsx("div",{className:"text-red-400 text-xs",children:g})]}),s.pendingCount>0&&s.sentCount===0&&e.jsxs("section",{"data-testid":"telemetry-never-delivered-warning",className:"border border-red-400 rounded p-3 text-xs space-y-1 text-red-400",children:[e.jsx("div",{className:"font-medium",children:"Never delivered"}),e.jsxs("div",{className:"leading-relaxed",children:[s.pendingCount," record",s.pendingCount===1?"":"s",' queued but none have ever been sent to bilko.run on this install. Check the endpoint/network, or click "Send now" below.']})]}),e.jsxs("section",{className:"border border-line rounded p-3 text-xs space-y-1.5",children:[e.jsx("div",{className:"text-fg-dim",children:"Runtime status"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-fg-faint",children:"last send:"})," ",ke(s.lastFlushAt)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-fg-faint",children:"next daily send due:"})," ",vt(R?new Date(R).toISOString():null)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-fg-faint",children:"queued records:"})," ",s.pendingCount]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-fg-faint",children:"delivered so far:"})," ",s.sentCount]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-fg-faint",children:"de-duplicated:"})," ",s.dedupedAppends]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-fg-faint",children:"evicted:"})," ",s.evictedCount]}),s.lastError&&e.jsxs("div",{className:"text-red-400 break-words",children:[e.jsx("span",{className:"text-fg-faint",children:"last error:"})," ",s.lastError.message," ","(",ke(s.lastError.at),")"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:T,disabled:c,className:"px-3 py-1 text-xs rounded bg-accent text-bg disabled:opacity-50 disabled:cursor-not-allowed",children:c?"sending…":"Send now"}),v&&e.jsx("span",{className:"text-fg-faint text-xs",children:v})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx("button",{onClick:P,className:"px-3 py-1 text-xs rounded border border-line text-fg-dim hover:text-fg",children:k?"Hide last records":"Inspect last records sent"}),k&&e.jsx("pre",{"data-testid":"telemetry-inspector-json",className:"bg-bg border border-line rounded p-2 text-[11px] font-mono overflow-auto max-h-96 whitespace-pre-wrap",children:JSON.stringify(m??[],null,2)})]})]})}function J({children:t,right:n}){return e.jsxs("div",{className:"flex items-baseline justify-between mb-2.5",children:[e.jsx("span",{className:"text-[11.5px] font-bold uppercase tracking-[0.8px] text-fg-faint",children:t}),n]})}function A({kind:t="soft",icon:n,children:s,onClick:r,disabled:i,testId:a}){return e.jsxs("button",{type:"button","data-testid":a,onClick:r,disabled:i,className:`shrink-0 inline-flex items-center gap-2 rounded-lg px-3.5 py-2 text-[13px] font-semibold transition-colors disabled:opacity-50 ${t==="soft"?"bg-bg-hi border border-line text-fg hover:bg-bg":"text-fg-dim hover:text-fg"}`,children:[n&&e.jsx(ee,{name:n,size:15}),s]})}function he({icon:t,title:n,subtitle:s,badge:r,action:i,testId:a}){return e.jsxs("div",{"data-testid":a,className:"flex items-center gap-3.5 bg-bg-hi border border-line rounded-xl px-[18px] py-3.5",children:[e.jsx("span",{className:"w-[34px] h-[34px] rounded-lg bg-bg border border-line grid place-items-center text-fg-dim shrink-0",children:e.jsx(ee,{name:t,size:17})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2.5 mb-0.5",children:[e.jsx("span",{className:"text-sm font-semibold text-fg truncate",children:n}),r]}),e.jsx("div",{className:"font-mono text-[11.5px] text-fg-faint truncate",children:s})]}),i]})}function xe({onClick:t,disabled:n,testId:s,children:r="Revoke"}){return e.jsx("button",{"data-testid":s,onClick:t,disabled:n,className:"shrink-0 rounded-lg border border-line bg-bg text-accent px-3.5 py-1.5 text-[12.5px] font-semibold hover:bg-bg-hi disabled:opacity-50 transition-colors",children:r})}function Ne({code:t,onConfirm:n,testId:s,codeTestId:r,confirmTestId:i,peer:a="browser"}){return e.jsxs("div",{"data-testid":s,className:"flex items-start gap-3.5 px-5 py-4 rounded-2xl border border-accent/40 bg-accent/[0.06]",children:[e.jsx("span",{className:"w-[38px] h-[38px] rounded-[11px] shrink-0 grid place-items-center bg-bg-hi text-accent",children:e.jsx(ee,{name:"shield",size:20})}),e.jsxs("div",{className:"flex-1 min-w-0 text-sm text-fg",children:[e.jsx("strong",{className:"font-semibold",children:"Verify E2E session."})," Compare this code with the ",a," — they must match.",e.jsx("div",{"data-testid":r,className:"my-2 text-3xl font-mono tracking-[0.3em] text-center text-accent select-all",children:t}),e.jsx("p",{className:"text-[12.5px] text-fg-faint mb-3",children:"If the codes match, confirm below. Mutating commands are blocked until confirmed."}),e.jsx("button",{"data-testid":i,onClick:n,className:"rounded-lg bg-accent text-white px-4 py-2 text-[13px] font-semibold hover:opacity-90 transition-opacity",children:"Codes match — confirm"})]})]})}function St({children:t,testId:n}){return e.jsx("div",{"data-testid":n,className:"bg-bg-hi border border-line rounded-xl p-5 text-center text-[13.5px] text-fg-faint italic font-serif",children:t})}const Z=["feedback_list_projects","feedback_open_session","macro_list","macro_run","epic_get","events_read"],Se=64,Ct={relay_unsupported:"The bilko.run relay does not accept services yet",device_token_invalid:"Re-pair this desktop with the phone first",rate_limited:"Too many codes this hour"},X=t=>(t==null?void 0:t.message)||String(t),Et=t=>/^[A-Za-z0-9._\-/~]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`,It=t=>t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"service";function Ce(t){const n=`~/.session-manager-service/${It(t.name)}`;return`npx claude-code-session-manager service pair --code ${t.code} --device ${t.deviceId.slice(0,8)} --name ${Et(t.name)} --state-dir ${n}`}function Tt(t){const n=Math.max(0,Math.ceil(t/1e3));return`${Math.floor(n/60)}:${String(n%60).padStart(2,"0")}`}function Rt({pending:t,onConfirm:n,onDeny:s,busy:r}){const[i,a]=o.useState("");return e.jsxs("div",{"data-testid":"remote-service-pending",className:"bg-bg-hi border border-accent/40 rounded-xl px-[18px] py-3.5",children:[e.jsxs("div",{className:"text-sm font-semibold text-fg mb-0.5",children:["Verify ",t.name]}),e.jsx("div",{className:"text-[12.5px] text-fg-faint mb-2.5",children:"Type the 6-digit code the service printed. It must match before the service can call any tool."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{"data-testid":"remote-service-sas-input",value:i,onChange:c=>a(c.target.value.replace(/\D/g,"").slice(0,6)),inputMode:"numeric",maxLength:6,placeholder:"000000",className:"w-[130px] bg-bg border border-line rounded-lg px-3 py-1.5 font-mono text-[18px] tracking-[4px] text-fg"}),e.jsx(A,{testId:"remote-service-sas-confirm",onClick:()=>n(t.pairingId,i),disabled:r||i.length!==6,children:"Confirm"}),e.jsx(A,{testId:"remote-service-sas-deny",kind:"ghost",onClick:()=>s(t.pairingId),disabled:r,children:"Deny"})]})]})}function Pt({enabled:t,hasDevice:n,refreshKey:s}){const r=de(l=>l.show),i=Ye(l=>l.tabs),a=o.useMemo(()=>Array.from(new Set(i.map(l=>l.cwd))),[i]),[c,p]=o.useState([]),[v,u]=o.useState([]),[g,f]=o.useState([]),[m,h]=o.useState(!1),[k,N]=o.useState(""),[C,I]=o.useState(""),[x,E]=o.useState(Z),[T,P]=o.useState(!1),[R,w]=o.useState(null),[b,$]=o.useState(null),[G,ne]=o.useState(()=>Date.now()),[Y,M]=o.useState(null),[L,H]=o.useState(null),O=t&&n,D=o.useCallback(async()=>{try{const l=await window.api.webRemote.servicesList();p(l.services??[]),u(l.pending??[]),f(l.relayOrphans??[])}catch(l){r("error",`Services: ${X(l)}`)}},[r]);o.useEffect(()=>{O&&D()},[O,D,s]),o.useEffect(()=>{!C&&a.length>0&&I(a[0])},[a,C]),o.useEffect(()=>{if(!b)return;ne(Date.now());const l=setInterval(()=>ne(Date.now()),1e3);return()=>clearInterval(l)},[b]);const q=()=>{h(!1),N(""),E(Z),w(null),$(null)},me=l=>E(j=>j.includes(l)?j.filter(S=>S!==l):Z.filter(S=>S===l||j.includes(S))),se=async()=>{const l=k.trim();if(!(!l||!C||x.length===0)){P(!0),w(null);try{const j=await window.api.webRemote.servicePairStart({name:l,homeCwd:C,scope:x});if(!j.ok){const S=Ct[j.error];S?w(S):r("error",`Service pairing: ${j.error}`);return}$({code:j.code,pairingId:j.pairingId,codeExpiresAt:j.codeExpiresAt,deviceId:j.deviceId,name:l}),await D()}catch(j){r("error",`Service pairing: ${X(j)}`)}finally{P(!1)}}},K=async()=>{if(!b)return;await Pe(Ce(b))?r("info","Pair command copied."):r("error","Could not copy the pair command.")},B=async(l,j)=>{M(l);try{const S=await window.api.webRemote.serviceConfirmSas(l,j);if(!S.ok){r("error",S.error==="sas_mismatch"?"The code does not match the service.":`Confirm failed: ${S.error}`);return}r("info",`${S.service.name} paired.`),(b==null?void 0:b.pairingId)===l&&q(),await D()}catch(S){r("error",`Confirm failed: ${X(S)}`)}finally{M(null)}},z=async l=>{M(l);try{const j=await window.api.webRemote.servicePairCancel(l);if(!j.ok){r("error",`Deny failed: ${j.error}`);return}(b==null?void 0:b.pairingId)===l&&q(),await D()}catch(j){r("error",`Deny failed: ${X(j)}`)}finally{M(null)}},ue=async l=>{H(null),M(l);try{const j=await window.api.webRemote.serviceRevoke(l);if(!j.ok){r("error",`Revoke failed: ${j.error}`);return}j.relayRevoked||r("warn","Revoked here; the relay could not be reached — revoke its client below when it shows."),await D()}catch(j){r("error",`Revoke failed: ${X(j)}`)}finally{M(null)}},ae=async l=>{H(null),M(l);try{const j=await window.api.webRemote.relayClientRevoke(l);if(!j.ok){r("error",`Revoke failed: ${j.error||"unknown error"}`);return}await D()}catch(j){r("error",`Revoke failed: ${X(j)}`)}finally{M(null)}},d=(l,j,S)=>L===l?e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[e.jsx(xe,{testId:`${j}-confirm`,onClick:S,disabled:Y===l,children:"Confirm revoke"}),e.jsx(A,{kind:"ghost",onClick:()=>H(null),children:"cancel"})]}):e.jsx(xe,{testId:j,onClick:()=>H(l),disabled:Y===l}),y=b?b.codeExpiresAt-G:0,fe=!T&&k.trim().length>0&&!!C&&x.length>0;return e.jsxs("div",{"data-testid":"remote-services",children:[e.jsx(J,{children:"Services"}),O?m?b?e.jsxs("div",{"data-testid":"remote-service-code-panel",className:"bg-bg-hi border border-accent/40 rounded-2xl px-6 py-[18px] space-y-2.5",children:[e.jsxs("div",{className:"text-[11.5px] font-bold uppercase tracking-[0.8px] text-fg-faint",children:["One-time code for ",b.name]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("span",{"data-testid":"remote-service-code",className:"font-mono text-[30px] font-semibold tracking-[6px] text-fg select-all",children:b.code}),e.jsx("span",{"data-testid":"remote-service-countdown",className:`text-[12.5px] ${y>0?"text-fg-faint":"text-accent"}`,children:y>0?`expires in ${Tt(y)}`:"Code expired — start again"})]}),e.jsx("code",{className:"block font-mono text-[11.5px] text-fg-dim break-all",children:Ce(b)}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(A,{testId:"remote-service-copy",icon:"copy",onClick:K,children:"Copy command"}),e.jsx(A,{kind:"ghost",onClick:q,children:"done"})]}),e.jsx("div",{className:"text-[12px] text-fg-faint",children:"Run it where the service lives. It prints a 6-digit code; type it below to finish."})]}):e.jsxs("div",{"data-testid":"remote-service-form",className:"bg-bg-hi border border-accent/40 rounded-2xl px-6 py-[18px] space-y-3",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"block text-[12px] font-semibold text-fg-dim mb-1",children:"Name"}),e.jsx("input",{"data-testid":"remote-service-name",value:k,maxLength:Se,onChange:l=>N(l.target.value.slice(0,Se)),placeholder:"Kiln",className:"w-full bg-bg border border-line rounded-lg px-3 py-1.5 text-[13px] text-fg"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"block text-[12px] font-semibold text-fg-dim mb-1",children:"Home project"}),e.jsxs("select",{"data-testid":"remote-service-home",value:C,onChange:l=>I(l.target.value),className:"w-full bg-bg border border-line rounded-lg px-3 py-1.5 text-[13px] text-fg font-mono",children:[a.length===0&&e.jsx("option",{value:"",children:"Open a project tab first"}),a.map(l=>e.jsx("option",{value:l,children:l},l))]})]}),e.jsxs("fieldset",{children:[e.jsx("legend",{className:"text-[12px] font-semibold text-fg-dim mb-1",children:"Tools it may call"}),e.jsx("div",{className:"grid grid-cols-2 gap-1",children:Z.map(l=>e.jsxs("label",{className:"flex items-center gap-2 text-[12.5px] text-fg font-mono",children:[e.jsx("input",{type:"checkbox","data-testid":`remote-service-scope-${l}`,checked:x.includes(l),onChange:()=>me(l)}),l]},l))})]}),R&&e.jsx("div",{"data-testid":"remote-service-error",className:"text-[12.5px] text-accent",children:R}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(A,{testId:"remote-service-start",onClick:se,disabled:!fe,children:T?"Starting…":"Start"}),e.jsx(A,{kind:"ghost",onClick:q,disabled:T,children:"cancel"})]})]}):e.jsxs("div",{className:"flex items-center justify-between gap-4 bg-bg-hi border border-line rounded-2xl px-5 py-[18px]",children:[e.jsx("div",{className:"text-[13.5px] text-fg-dim leading-relaxed max-w-[420px]",children:"Let a named service (such as Kiln) drive work in one home project through a scoped set of tools."}),e.jsx(A,{testId:"remote-service-pair",icon:"link",onClick:()=>h(!0),children:"Pair a service…"})]}):e.jsxs("div",{"data-testid":"remote-service-disabled",className:"flex items-center justify-between gap-4 bg-bg-hi border border-line rounded-2xl px-5 py-[18px] opacity-70",children:[e.jsx("div",{className:"text-[13.5px] text-fg-dim leading-relaxed max-w-[420px]",children:t?"Pair a device above first — a service pairs through this desktop’s device.":"Turn on “Allow remote control from the web” above to pair a service."}),e.jsx(A,{testId:"remote-service-pair",icon:"link",onClick:()=>{},disabled:!0,children:"Pair a service…"})]}),O&&v.length>0&&e.jsx("div",{className:"space-y-2 mt-2.5",children:v.map(l=>e.jsx(Rt,{pending:l,onConfirm:B,onDeny:z,busy:Y===l.pairingId},l.pairingId))}),O&&c.length>0&&e.jsxs("div",{className:"mt-[18px]",children:[e.jsx(J,{right:e.jsxs("span",{className:"text-[11.5px] text-fg-faint",children:[c.length," paired"]}),children:"Paired services"}),e.jsx("div",{className:"space-y-2",children:c.map(l=>e.jsx("div",{"data-testid":"remote-service-row",children:e.jsx(he,{icon:"link",title:l.name,subtitle:`${l.homeCwd} · ${l.scope.length} of ${Z.length} tools · paired ${new Date(l.pairedAt).toLocaleDateString()}`,action:d(l.serviceId,"remote-service-revoke",()=>ue(l.serviceId))})},l.serviceId))})]}),O&&g.length>0&&e.jsxs("div",{className:"mt-[18px]",children:[e.jsx(J,{children:"Relay clients without a service"}),e.jsx("div",{className:"space-y-2",children:g.map(l=>e.jsx("div",{"data-testid":"remote-relay-orphan-row",children:e.jsx(he,{icon:"wifi",title:l.clientName||"unnamed client",subtitle:l.clientId,action:d(l.clientId,"remote-relay-orphan-revoke",()=>ae(l.clientId))})},l.clientId))})]})]})}function Ee({label:t,hint:n,on:s,onChange:r,warn:i,disabled:a,first:c,testId:p}){return e.jsxs("div",{className:`flex items-center justify-between gap-4 px-[18px] py-[15px] ${c?"":"border-t border-rule"} ${a?"opacity-50":""}`,children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-semibold text-fg mb-0.5",children:t}),e.jsxs("div",{className:`text-[12.5px] leading-snug flex items-center gap-1.5 ${i?"text-honey-dark":"text-fg-faint"}`,children:[i&&e.jsx("span",{"aria-hidden":!0,children:"⚠"}),n]})]}),e.jsx("span",{"data-testid":p,className:"inline-flex",children:e.jsx(V,{checked:s,onChange:a?()=>{}:r,disabled:a})})]})}function At({device:t,online:n,onRevoke:s,revoking:r}){const i=t.lastConnectedAt?new Date(t.lastConnectedAt).toLocaleString():`paired ${new Date(t.issuedAt).toLocaleDateString()}`;return e.jsx(he,{testId:"settings-remote-device",icon:"wifi",title:t.deviceName,badge:n?e.jsx(U,{tone:"default",className:"!text-sage !border-sage/40",children:"online"}):void 0,subtitle:`${t.deviceId} · last seen ${i}`,action:e.jsx(xe,{testId:"settings-remote-revoke",onClick:()=>s(t.deviceId),disabled:r})})}const F=t=>(t==null?void 0:t.message)||String(t);function $t(){var ae;const t=de(d=>d.show),[n,s]=o.useState(null),[r,i]=o.useState(!0),[a,c]=o.useState(!1),[p,v]=o.useState(!1),[u,g]=o.useState("idle"),[f,m]=o.useState(""),[h,k]=o.useState(null),[N,C]=o.useState(!1),[I,x]=o.useState([]),[E,T]=o.useState(!1),P=o.useRef(null);o.useEffect(()=>{let d=!1;const y=()=>window.api.webRemote.getStatus().then(S=>{d||s(S)}).catch(()=>{});window.api.webRemote.getStatus().then(S=>{d||(s(S),i(!1))}).catch(S=>{d||(t("error",`Remote status: ${F(S)}`),i(!1))});const fe=window.api.webRemote.onStatus(S=>s(S)),l=window.api.webRemote.onTokenRevoked(()=>{t("warn","Remote device token was revoked. Re-pair to reconnect."),y()}),j=window.api.webRemote.onRevokedAll(({revokedCount:S})=>{t("info",`Panic: all ${S} device(s) revoked and sessions torn down.`),y()});return()=>{d=!0,fe(),l(),j()}},[t]),o.useEffect(()=>{if(u!=="enter-otp")return;const d=setTimeout(()=>{var y;return(y=P.current)==null?void 0:y.focus()},50);return()=>clearTimeout(d)},[u]);const R=async()=>s(await window.api.webRemote.getStatus()),w=async()=>{if(n){c(!0);try{const d=n.enabled?await window.api.webRemote.disable():await window.api.webRemote.enable();d&&d.ok===!1&&t("error",d.error||"Failed to change remote state."),await R()}catch(d){t("error",`Failed: ${F(d)}`)}finally{c(!1)}}},b=async()=>{if(n){v(!0);try{const d=n.remoteControlEnabled?await window.api.webRemote.disableControl():await window.api.webRemote.enableControl();d&&d.ok===!1&&t("error",d.error||"Failed to change command writes."),await R()}catch(d){t("error",`Failed: ${F(d)}`)}finally{v(!1)}}},$=async()=>{const d=f.trim().toUpperCase();if(!/^[A-Z0-9]{8}$/.test(d)){t("warn","Pairing code must be 8 alphanumeric characters.");return}g("pairing");try{const y=await window.api.webRemote.pair(d);if(!y.ok){t("error",y.error||"Pairing failed."),g("enter-otp");return}t("info","Device paired successfully."),m(""),g("idle"),await R()}catch(y){t("error",`Pairing error: ${F(y)}`),g("enter-otp")}},G=async d=>{k(d);try{const y=await window.api.webRemote.revokeDevice(d);if(!y.ok){t("error",y.error||"Revoke failed.");return}await R()}catch(y){t("error",`Revoke error: ${F(y)}`)}finally{k(null)}},ne=async()=>{C(!0);try{const d=await window.api.webRemote.revokeAll();d.ok||t("error",d.error||"Panic revoke failed.")}catch(d){t("error",`Panic revoke error: ${F(d)}`)}finally{C(!1)}},Y=async()=>{if(E){T(!1);return}try{const d=await window.api.webRemote.auditTail(100);if(!d.ok){t("error",`Audit log: ${d.error||"unavailable"}`);return}x(d.lines??[]),T(!0)}catch(d){t("error",`Audit log: ${F(d)}`)}},M=async d=>{try{const y=await window.api.webRemote.confirmSas(d);y!=null&&y.ok||t("error",`SAS confirm failed: ${(y==null?void 0:y.error)??"unexpected state — reconnect the mobile app"}`)}catch(y){t("error",`SAS confirm failed: ${F(y)}`)}};if(r)return e.jsx("div",{className:"p-6 text-fg-faint text-sm",children:"Loading…"});const L=(n==null?void 0:n.enabled)??!1,H=(n==null?void 0:n.remoteControlEnabled)??!1,O=(n==null?void 0:n.connected)??!1,D=(n==null?void 0:n.e2eActive)??!1,q=(n==null?void 0:n.e2eAuthenticated)??!1,me=(n==null?void 0:n.e2eState)??"idle",se=(n==null?void 0:n.pendingSas)??null,K=((n==null?void 0:n.clients)??[]).filter(d=>d.state==="pending_sas"&&d.pendingSas),B=(n==null?void 0:n.devices)??[],z=L&&O,ue=O?((ae=B.reduce((d,y)=>y.lastConnectedAt&&(!d||(d.lastConnectedAt??"")<y.lastConnectedAt)?y:d,null))==null?void 0:ae.deviceId)??null:null;return e.jsxs("div",{"data-testid":"settings-remote",className:"p-4 max-w-[760px] space-y-[22px]",children:[K.length>0?K.map((d,y)=>e.jsxs("div",{"data-testid":"settings-remote-sas-row",children:[K.length>1&&e.jsxs("div",{className:"text-[12px] font-semibold text-fg-dim mb-1",children:["Browser ",y+1]}),e.jsx(Ne,{testId:y===0?"settings-remote-sas":void 0,codeTestId:y===0?"settings-remote-sas-code":void 0,confirmTestId:y===0?"settings-remote-sas-confirm":void 0,code:d.pendingSas,onConfirm:()=>M(d.key)})]},d.key)):se&&e.jsx(Ne,{testId:"settings-remote-sas",codeTestId:"settings-remote-sas-code",confirmTestId:"settings-remote-sas-confirm",code:se,onConfirm:()=>M()}),me==="failed"&&e.jsxs("div",{className:"flex items-center gap-3.5 px-5 py-4 rounded-2xl border border-[#eccdbe] bg-[#f8e8e0]",children:[e.jsx("span",{className:"w-4 h-4 rounded-full bg-accent text-white grid place-items-center text-[11px] font-bold shrink-0",children:"!"}),e.jsxs("div",{className:"text-[13px] text-[#9a3f1f]",children:[e.jsx("strong",{className:"font-semibold",children:"E2E key exchange failed."})," ",e.jsx("span",{className:"text-fg-dim",children:"The session key could not be established. Reconnect the mobile app to retry."})]})]}),e.jsxs("div",{className:`flex items-center gap-3.5 px-5 py-4 rounded-2xl border ${z?"border-[#e8cdb9] bg-[#f5e9df]":"border-line bg-bg-hi"}`,children:[e.jsx("span",{className:`w-[38px] h-[38px] rounded-[11px] shrink-0 grid place-items-center ${z?"bg-[#f0d9c8] text-accent":"bg-[#e4ebd6] text-sage"}`,children:e.jsx(ee,{name:z?"wifi":"shield",size:20})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[14.5px] font-semibold text-fg mb-0.5",children:z?"Remote control is active":L?"Remote control is idle":"Remote control is off"}),e.jsx("div",{className:"text-[13px] text-fg-dim leading-snug",children:z?"A web session can send commands to this machine. Revoke below if unexpected.":L&&(n==null?void 0:n.linkState)==="repair-needed"?"The relay no longer recognises this device. Re-pair it with a new code to reconnect.":L?"The relay is on but no device is connected. Pair a device to begin.":"The relay connection is closed — no remote commands are accepted. Enable it below only when you need it."})]}),D&&q?e.jsx(U,{tone:"default",className:"!text-sage !border-sage/40",children:"E2E authenticated"}):D?e.jsx(U,{tone:"warn",children:"E2E · awaiting SAS"}):e.jsx(U,{tone:"dim",children:"relay only · not E2E yet"})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Remote control"}),e.jsxs("div",{className:"bg-bg-hi border border-line rounded-2xl overflow-hidden",children:[e.jsx(Ee,{first:!0,testId:"settings-remote-enable",label:"Allow remote control from the web",hint:"Master switch. When off, the relay refuses every connection.",on:L,disabled:a,onChange:()=>{a||w()}}),e.jsx(Ee,{testId:"settings-remote-control",label:"Allow command writes (pty + scheduler)",hint:H?"A paired device can run shell commands and queue jobs on this machine.":"Paired devices can watch session output but cannot send commands.",warn:H,disabled:!L||p,on:H&&L,onChange:()=>{L&&!p&&b()}})]})]}),e.jsxs("div",{children:[e.jsx(J,{children:"Pair a device"}),u==="idle"?e.jsxs("div",{className:"flex items-center justify-between gap-4 bg-bg-hi border border-line rounded-2xl px-5 py-[18px]",children:[e.jsxs("div",{"data-testid":"settings-remote-pair-hint",className:"text-[13.5px] text-fg-dim leading-relaxed max-w-[420px]",children:["On your phone open ",e.jsx("strong",{className:"text-fg font-semibold",children:"bilko.run/projects/session-manager"}),", sign in, and tap"," ",e.jsx("strong",{className:"text-fg font-semibold",children:"Generate pairing code"}),". Enter the 8-character code here."]}),e.jsx(A,{testId:"settings-remote-pair-start",kind:"soft",icon:"link",onClick:()=>g("enter-otp"),children:"Pair Device…"})]}):e.jsxs("div",{className:"flex items-center gap-5 bg-bg-hi border border-accent/40 rounded-2xl px-6 py-[22px]",children:[e.jsx("span",{className:"w-[52px] h-[52px] rounded-xl bg-bg border border-line grid place-items-center text-accent shrink-0",children:e.jsx(ee,{name:"link",size:24})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[11.5px] font-bold uppercase tracking-[0.8px] text-fg-faint mb-2",children:"Enter the code from your phone"}),e.jsx("input",{ref:P,"data-testid":"settings-remote-otp",value:f,onChange:d=>m(d.target.value.toUpperCase().replace(/[^A-Z0-9]/g,"")),onKeyDown:d=>{d.key==="Enter"&&$()},maxLength:8,placeholder:"XXXXXXXX",disabled:u==="pairing",className:"w-full bg-transparent border-0 outline-none font-mono text-[30px] font-semibold tracking-[6px] text-fg placeholder:text-fg-faint/40 disabled:opacity-50"})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(A,{testId:"settings-remote-pair-confirm",kind:"soft",onClick:$,disabled:u==="pairing"||f.length<8,children:u==="pairing"?"Pairing…":"Confirm"}),e.jsx(A,{kind:"ghost",onClick:()=>{g("idle"),m("")},disabled:u==="pairing",children:"cancel"})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{right:B.length>0?e.jsxs("span",{className:"text-[11.5px] text-fg-faint",children:[B.length," paired"]}):void 0,children:"Paired devices"}),B.length===0?e.jsx(St,{children:"No devices paired yet."}):e.jsx("div",{className:"space-y-2",children:B.map(d=>e.jsx(At,{device:d,online:d.deviceId===ue,onRevoke:G,revoking:h===d.deviceId},d.deviceId))})]}),e.jsx(Pt,{enabled:L,hasDevice:B.length>0,refreshKey:((n==null?void 0:n.clients)??[]).map(d=>`${d.key}:${d.state}`).join(",")}),e.jsxs("div",{children:[e.jsx(J,{right:e.jsx("button",{"data-testid":"settings-remote-audit-toggle",onClick:Y,className:"text-[12px] text-fg-faint hover:text-fg-dim transition-colors",children:E?"Hide":"Show last 100 · 0600, stays on this machine"}),children:"Audit log"}),E&&e.jsx("div",{className:"bg-bg-hi border border-line rounded-xl overflow-auto max-h-64 mb-2",children:I.length===0?e.jsx("p",{className:"p-4 text-[12.5px] text-fg-faint",children:"No entries today."}):e.jsx("pre",{"data-testid":"settings-remote-audit",className:"p-4 text-[12px] text-fg-dim font-mono whitespace-pre-wrap leading-relaxed",children:I.join(`
|
|
2
|
+
`)})}),e.jsxs("p",{className:"text-[12px] text-fg-faint",children:["Full log at"," ",e.jsx("code",{className:"font-mono text-fg-faint",children:"~/.claude/session-manager/logs/remote-audit-YYYY-MM-DD.log"})," ","(0600, never leaves this machine)"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4 bg-[#f8e8e0] border border-[#eccdbe] rounded-2xl px-5 py-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"w-4 h-4 rounded-full bg-accent text-white grid place-items-center text-[11px] font-bold shrink-0",children:"!"}),e.jsx("span",{className:"text-sm font-semibold text-[#9a3f1f]",children:"Panic — disconnect & revoke everything"})]}),e.jsx("div",{className:"text-[12.5px] text-fg-dim leading-snug max-w-[440px]",children:"Tears down every active session and invalidates all paired-device tokens. Devices must re-pair. Use if you suspect compromise."})]}),e.jsx("button",{"data-testid":"settings-remote-revoke-all",onClick:ne,disabled:N,className:"shrink-0 rounded-lg bg-accent text-white px-[18px] py-2 text-[13px] font-semibold hover:opacity-90 disabled:opacity-50 transition-opacity",children:N?"Revoking…":"Revoke all"})]})]})}const re="px-2 py-1 rounded border border-line text-xs text-fg hover:bg-bg-hi disabled:opacity-50";function Mt(){const t=Ke(),n=de(p=>p.show),s=async p=>{try{const u=await p();u&&u.ok===!1&&n("error",u.error??"Update action failed")}catch(v){n("error",v instanceof Error?v.message:String(v))}};if(!t)return null;const{state:r}=t,i=r==="unsupported",a=t.latest?`v${t.latest}`:"—",c=()=>{window.confirm("Installing now will stop all running jobs and terminals. Continue?")&&s(()=>window.api.updater.install(!0))};return e.jsxs("section",{"data-testid":"settings-updates",className:"border border-line rounded p-3 space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-fg text-xs font-medium",children:"Updates"}),e.jsxs("div",{className:"text-fg-dim text-xs flex gap-4",children:[e.jsxs("span",{children:["Current v",t.current]}),e.jsxs("span",{children:["Latest ",a]})]})]}),i?e.jsx("p",{className:"text-fg-faint text-[11px]",children:"Auto-update runs only in the installed Windows app or the Linux AppImage. npx builds update via npx."}):e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(V,{checked:t.enabled,onChange:p=>void s(()=>window.api.updater.setEnabled(p)),label:"Update automatically"}),e.jsx("button",{type:"button","data-testid":"updates-check",className:re,disabled:r==="checking"||r==="downloading",onClick:()=>void s(()=>window.api.updater.check()),children:"Check for updates"})]}),r==="checking"&&e.jsx("p",{className:"text-fg-dim text-xs",children:"Checking…"}),r==="downloading"&&e.jsxs("p",{className:"text-fg-dim text-xs",children:["Downloading… ",t.progress!=null?`${Math.round(t.progress)}%`:""]}),r==="ready"&&e.jsxs("button",{type:"button","data-testid":"updates-install",className:re,onClick:()=>void s(()=>window.api.updater.install(!1)),children:["Restart to install v",t.latest]}),r==="deferred"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-fg-dim text-xs",children:["Waiting for ",t.busyReason??"work"," to finish"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{type:"button",className:re,onClick:c,children:"Install now"}),e.jsx("button",{type:"button",className:re,onClick:()=>void s(()=>window.api.updater.cancelDeferred()),children:"Cancel"})]})]}),r==="error"&&e.jsx("p",{className:"text-red-400 text-xs",children:t.error})]})}function Lt(t){return t?t.supported?t.starts==="npx"?"Runs npx claude-code-session-manager@latest at login, so it starts the newest release.":t.starts==="app"?"Starts the installed app at login.":t.reason??"":t.reason??"Start at login is not available here.":"Checking…"}function Dt(){const[t,n]=o.useState(null),[s,r]=o.useState(!1);o.useEffect(()=>{let c=!0;return window.api.loginItem.status().then(p=>{c&&n(p)}).catch(p=>Q.error(p instanceof Error?p.message:String(p))),()=>{c=!1}},[]);const i=async c=>{r(!0);try{const p=await window.api.loginItem.setEnabled(c);p.ok?n(p.status):Q.error(p.error)}catch(p){Q.error(p instanceof Error?p.message:String(p))}finally{r(!1)}},a=(t==null?void 0:t.supported)===!0;return e.jsxs("section",{"data-testid":"settings-start-at-login",className:"space-y-1",children:[e.jsx(V,{checked:(t==null?void 0:t.enabled)===!0,onChange:c=>void i(c),disabled:!a||s,label:"Start at login"}),e.jsx("p",{"data-testid":"start-at-login-desc",className:"text-fg-faint text-[11px]",children:Lt(t)})]})}const Ot=[{key:"maxAgeDays",label:"Run logs: keep for",unit:"days",min:3,max:3650},{key:"runsArchiveDays",label:"Runs archive: keep for",unit:"days",min:1,max:3650},{key:"auditLogMonths",label:"Audit log: keep for",unit:"months",min:1,max:120},{key:"reservedMarkersKeep",label:"Reserved markers: keep",unit:"markers",min:1,max:1e5}],_t="w-24 px-2 py-1 rounded border border-line bg-transparent text-xs text-fg";function Ie(t,n){return n==="maxAgeDays"?t.runLogs.maxAgeDays:t[n]}function Ht(t,n){return t==="maxAgeDays"?{runLogs:{maxAgeDays:n}}:{[t]:n}}function $e(t){if(!Number.isFinite(t)||t<=0)return"0 B";const n=["B","KB","MB","GB","TB"];let s=0,r=t;for(;r>=1024&&s<n.length-1;)r/=1024,s++;return`${s===0?r:r.toFixed(1)} ${n[s]}`}function ge(t,n,s){return`${t}: ${$e(n)} in ${s.toLocaleString("en-US")} files`}function Bt(){const t=de(m=>m.show),[n,s]=o.useState(null),[r,i]=o.useState({}),[a,c]=o.useState(null),p=o.useCallback(m=>t("error",m instanceof Error?m.message:String(m)),[t]),v=o.useCallback(async()=>{try{c(await window.api.opsRetention.preview())}catch(m){p(m)}},[p]);o.useEffect(()=>{let m=!0;return window.api.opsRetention.get().then(h=>{m&&s(h)}).catch(h=>{m&&p(h)}),v(),()=>{m=!1}},[p,v]);const u=async m=>{if(!n)return;const h=r[m.key];if(h===void 0)return;const k=Number(h);if(i(C=>{const{[m.key]:I,...x}=C;return x}),h.trim()===""||!Number.isFinite(k))return;const N=Math.min(m.max,Math.max(m.min,Math.round(k)));if(N!==Ie(n,m.key))try{s(await window.api.opsRetention.set(Ht(m.key,N))),await v()}catch(C){p(C)}},g=a?a.runLogs.bytes+a.runsArchive.bytes+a.tmp.bytes:0,f=a?a.runLogs.files+a.runsArchive.entries+a.tmp.files:0;return e.jsxs("section",{"data-testid":"settings-ops-retention",className:"border border-line rounded p-3 space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-fg text-xs font-medium",children:"Ops data retention"}),e.jsx("p",{className:"text-fg-faint text-[11px]",children:"How long the daily sweep keeps scheduler and audit data. Machine-wide."})]}),n&&e.jsxs("div",{className:"space-y-2",children:[Ot.map(m=>e.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-dim",children:[e.jsx("span",{className:"w-48",children:m.label}),e.jsx("input",{type:"number","data-testid":`ops-retention-${m.key}`,className:_t,min:m.min,max:m.max,value:r[m.key]??String(Ie(n,m.key)),onChange:h=>i(k=>({...k,[m.key]:h.target.value})),onBlur:()=>void u(m)}),e.jsx("span",{className:"text-fg-faint",children:m.unit})]},m.key)),e.jsx("p",{className:"text-fg-dim text-xs",children:"Archived transcripts: kept forever"})]}),a&&e.jsxs("div",{"data-testid":"ops-retention-preview",className:"space-y-1 text-xs text-fg-dim",children:[e.jsxs("div",{className:"text-fg",children:["Current policy would free ",$e(g)," in ",f.toLocaleString("en-US")," files"]}),e.jsx("div",{children:ge("Run logs",a.runLogs.bytes,a.runLogs.files)}),e.jsx("div",{children:ge("Runs archive",a.runsArchive.bytes,a.runsArchive.entries)}),e.jsx("div",{children:ge("Stale temp files",a.tmp.bytes,a.tmp.files)}),e.jsx("p",{className:"text-fg-faint text-[11px]",children:"Nothing is deleted until the daily sweep runs."})]})]})}const pe=[{id:"project",label:"Project & Tab",realm:"machine",blurb:"A PROJECT is a cwd; a TAB is one open project.",tone:{chip:"bg-bg-elev text-fg-dim",border:"border-line",dot:"bg-fg-faint"}},{id:"epic",label:"Epic (PromptSession)",realm:"project",blurb:"The central aggregate root — one unit of work, one claude session.",tone:{chip:"bg-accent-muted text-accent-dark",border:"border-accent",dot:"bg-accent"}},{id:"scheduler",label:"Scheduler",realm:"project",blurb:"PRDs + the headless jobs that execute them.",tone:{chip:"bg-butter/30 text-honey-dark",border:"border-honey",dot:"bg-honey"}},{id:"agents",label:"Agents & Taxonomy",realm:"machine",blurb:"The ACTOR and MISSION halves of AIM.",tone:{chip:"bg-sage/20 text-sage-dark",border:"border-sage",dot:"bg-sage"}},{id:"memory",label:"Memory",realm:"machine",blurb:"Workspace, cross-project, and per-agent memory.",tone:{chip:"bg-hive-teal/20 text-hive-teal",border:"border-hive-teal",dot:"bg-hive-teal"}},{id:"transcript",label:"Transcript & Usage",realm:"machine",blurb:"The Claude CLI's own JSONL, classified events, and billing.",tone:{chip:"bg-bg-hi text-fg-dim",border:"border-rule",dot:"bg-fg-dim"}},{id:"brief",label:"Project Home & Publishing",realm:"project",blurb:"The synthesized Brief, generated pages, and bilko.run publish state.",tone:{chip:"bg-accent-muted/60 text-accent-dark",border:"border-accent-muted",dot:"bg-accent-muted"}},{id:"config",label:"Machine Config",realm:"machine",blurb:"Settings, layout, and the single-writer ownership map.",tone:{chip:"bg-line text-fg-faint",border:"border-rule",dot:"bg-fg-faint"}}];function Me(t){const n=pe.find(s=>s.id===t);if(!n)throw new Error(`unknown ErdGroupId: ${t}`);return n}const te=[{id:"project",name:"Project",aka:"cwd — Main Project",group:"project",store:{path:"identity only, no record of its own — folded at read time from ~/.claude/projects/<encoded>",format:"in-memory",definedIn:"src/renderer/lib/knownProjectAggregate.ts (aggregateProjectsByCwd) "},summary:"A folder whose cwd never resolved from transcript content is DROPPED, never guessed — the naive decode once reported 2044 phantom projects.",fields:[{name:"cwd",type:"string",key:"pk",note:"resolved working directory — the project's identity"},{name:"name",type:"string",note:"display name: the cwd's last path segment"},{name:"encoded",type:"string",note:"representative transcript folder (most recently active)"},{name:"encodedIds",type:"string[]",note:"every ~/.claude/projects/<encoded> folder that resolved to this cwd"},{name:"sessionCount",type:"number"},{name:"sizeBytes",type:"number"},{name:"lastSession",type:"number"}]},{id:"tab",name:"PersistedTab",aka:"TAB",group:"project",store:{path:"~/.claude/session-manager/tabs.json",format:"json",definedIn:"src/main/sessionsStore.cjs "},summary:"One TAB per project — extra sessions within a project are Epics, not tabs.",fields:[{name:"id",type:"string",key:"pk"},{name:"sessionId",type:"string"},{name:"cwd",type:"string",key:"fk",ref:"project.cwd"},{name:"label",type:"string"},{name:"presetId",type:"string | null"}]},{id:"epic",name:"PromptSession",aka:"EPIC",group:"epic",store:{path:"<cwd>/session-manager-operations/prompt-sessions/active-index.json -> sessions[id]",format:"json",writer:"epics",definedIn:"src/main/lib/epic/epicMint.cjs (ensureEpic) + src/renderer/state/promptSessions.ts "},summary:"The central aggregate root — created in exactly ONE place, a human pressing New Epic.",fields:[{name:"id",type:"string",key:"pk"},{name:"cwd",type:"string",key:"fk",ref:"project.cwd"},{name:"goalText",type:"string",note:"the original top-level prompt text that started this goal"},{name:"claudeSessionId",type:"string",note:"independently minted — never shared with any tab.sessionId"},{name:"status",type:"'proposed' | 'active' | 'completed'"},{name:"createdAt",type:"string"},{name:"completedAt",type:"string | null"},{name:"resumedFromId",type:"string",optional:!0,key:"fk",ref:"epic.id"},{name:"tag",type:"TicketTag",optional:!0,key:"fk",ref:"tag.tag"},{name:"openingPrompt",type:"string | null",optional:!0},{name:"source",type:"EpicSource",optional:!0,note:"{ producer, prdSlug?, runId?, sourceTabId?, fromCwd?, fromEpicId? }"},{name:"agentType",type:"string",optional:!0,key:"fk",ref:"agentPersona.name"},{name:"model",type:"string",optional:!0,note:"per-Epic model override; absent = the persona model"},{name:"effort",type:"string",optional:!0,note:"per-Epic effort override; absent = the persona effort"},{name:"developLoop",type:"false",optional:!0,note:"false = started with the develop loop off; absent = on"},{name:"restoredSession",type:"true",optional:!0,note:"claudeSessionId adopted from an existing CLI session"},{name:"agentCli",type:"string",optional:!0,note:"agent CLI running the session; absent = Claude Code; fixed for the session"},{name:"agentCliModel",type:"string",optional:!0,note:"model string passed to agentCli; absent = its default"},{name:"sections",type:"EpicIntakeSection[]",optional:!0},{name:"worktree",type:"{ dir, branch, baseCwd, status, conflictReason? }",optional:!0,note:"own git worktree on branch 'sm-epic/<id>' when Active"}],notes:["SINGLE-CREATOR LAW, fail-closed in epicMint.cjs — the New Epic IPC handler and crossProjectFeedback.cjs are the only mint authorities.","Every Epic is born proposed; nothing is created directly as active.","EPIC : claude-session is 1:1 — Chat and Terminal are two VIEWS over one session.","Title + objective are fixed for the life of the session — iterate in follow-up messages, don't repurpose."]},{id:"epicEvent",name:"PromptSessionEvent",group:"epic",store:{path:"<cwd>/session-manager-operations/prompt-sessions/active-index.json -> events[]",format:"json",writer:"epics",definedIn:"src/renderer/state/promptSessions.ts + src/main/lib/epic/activeIndexMerge.cjs "},summary:"One step in an Epic's Prompt → PRD → Response → ... → Closed chain.",fields:[{name:"id",type:"string",key:"pk"},{name:"promptSessionId",type:"string",key:"fk",ref:"epic.id"},{name:"kind",type:"'prompt' | 'prd_created' | 'response' | 'closed'"},{name:"causedByEventId",type:"string | null",key:"fk",ref:"epicEvent.id",note:"must be the session's current tail event — a chain, not a tree"},{name:"at",type:"string"},{name:"prdSlug",type:"string",optional:!0,key:"fk",ref:"prd.slug"},{name:"text",type:"string",optional:!0},{name:"outcome",type:"'completed' | 'failed' | 'needs_review'",optional:!0},{name:"validation",type:"'unvalidated' | 'validating' | 'verified' | 'refuted'",optional:!0}]},{id:"epicTranscriptTurn",name:"PromptSessionTranscriptTurn",group:"epic",store:{path:"<cwd>/session-manager-operations/prompt-sessions/transcripts/<epicId>.jsonl",format:"jsonl",writer:"epics",definedIn:"src/main/promptSessionTranscript.cjs "},summary:"The durable per-Epic transcript store, kept alongside the CLI's own JSONL as a fallback source of turns.",fields:[{name:"v",type:"1"},{name:"epicId",type:"string",key:"fk",ref:"epic.id"},{name:"eventId",type:"string | null",key:"fk",ref:"epicEvent.id"},{name:"role",type:"'user' | 'assistant'"},{name:"at",type:"string"},{name:"text",type:"string"}]},{id:"epicArchive",name:"PromptSessionArchive",group:"epic",store:{path:"<cwd>/session-manager-operations/prompt-sessions/<epicId>.json",format:"json",writer:"epics",definedIn:"src/renderer/state/promptSessions.ts (promptSessionArchivePath) "},summary:"On-disk archive written once at completion — freezes the Epic, its events, and its transcript.",fields:[{name:"session",type:"PromptSession"},{name:"events",type:"PromptSessionEvent[]"},{name:"transcript",type:"string"},{name:"archivedAt",type:"string"},{name:"durableTurns",type:"Array<{ role, text, at }>",optional:!0}]},{id:"epicWorktreeConfig",name:"EpicWorktreeConfig",group:"epic",store:{path:"<cwd>/session-manager-operations/prompt-sessions/epic-worktree-config.json",format:"json",writer:"epics",definedIn:"src/main/lib/epic/epicWorktreeProjectConfig.cjs "},summary:"Per-project 'disable Epic worktree isolation' toggle, read by gitWorktree.cjs's isWorktreeDisabled('epic', cwd) on every worktree creation attempt.",fields:[{name:"disabled",type:"boolean"}],notes:["One-shot migration from the legacy machine-wide ~/.claude/session-manager/epic-worktree-project-config.json map, keyed by project cwd — that file is left in place, never deleted."]},{id:"exchange",name:"Exchange",group:"epic",store:{path:"<cwd>/session-manager-operations/prompt-sessions/exchanges.jsonl",format:"jsonl",writer:"epics",definedIn:"src/main/exchanges.cjs "},summary:"One durable NDJSON record per completed terminal-chat exchange, appended off the hot path.",fields:[{name:"ts",type:"string"},{name:"sessionId",type:"string",key:"fk",ref:"epic.claudeSessionId",note:"the tab's claude session id"},{name:"cwd",type:"string",key:"fk",ref:"project.cwd"},{name:"prompt",type:"string"},{name:"result",type:"string"},{name:"summary",type:"string",note:"produced by the shared Haiku summarizer"},{name:"model",type:"string"},{name:"degraded",type:"string",optional:!0,note:"set when summarization failed — the exchange itself is never dropped"},{name:"promptId",type:"string",optional:!0,key:"fk",ref:"prd.slug",note:"originating PromptTicket.id when dispatched from the per-tab queue; forward-only, never backfilled"}],notes:["Written via raw fs O_APPEND (not config.cjs writeJson) for atomicity across concurrent writers — assertOpsWrite is called explicitly since raw fs bypasses the normal enforcement point.","Historical rows from before this store existed remain, untouched and unmigrated, in the old global ~/.claude/knowledge-log/exchanges/<encodeCwd(cwd)>.jsonl."]},{id:"prd",name:"PRD",group:"scheduler",store:{path:"<cwd>/session-manager-operations/scheduler/epics/<epicId>/prds/<slug>.md",format:"markdown",writer:"scheduler",definedIn:"src/main/lib/prd/prdLocations.cjs + scheduler_create_prd MCP tool "},summary:"PRD authoring is API-only via the scheduler_create_prd MCP tool — a PRD joins an EXISTING Epic and never conjures one.",fields:[{name:"slug",type:"string",key:"pk",note:"<nn>-<kebab-title>.md filename stem"},{name:"title",type:"string"},{name:"cwd",type:"string",key:"fk",ref:"project.cwd"},{name:"epicId",type:"string | null",key:"fk",ref:"epic.id",note:"derived from the PRD's DIRECTORY — fact on disk"},{name:"sourcePromptId",type:"string",optional:!0,key:"fk",ref:"epic.id",note:"frontmatter intent — can disagree with epicId"},{name:"sourceTabId",type:"string",optional:!0},{name:"estimateMinutes",type:"number"},{name:"tag",type:"'feature' | 'bug' | 'discussion' | 'build' | 'project-home-builder' | 'art' | 'portfolio'",optional:!0,key:"fk",ref:"tag.tag"},{name:"dependsOn",type:"string[]",optional:!0,key:"fk",ref:"prd.slug",note:"the SOLE ordering primitive"},{name:"goal",type:"string"},{name:"acceptanceCriteria",type:"string[]"},{name:"implementationNotes",type:"string"},{name:"outOfScope",type:"string[]",optional:!0},{name:"createdVia",type:"string",optional:!0},{name:"issuedAt",type:"string",optional:!0}],notes:["Flat scheduler/prds/ is RETIRED — auto-consolidated into prds-archived/ on every reconcile() pass.","epicId is derived from the DIRECTORY (fact on disk) while sourcePromptId is frontmatter intent and can disagree."]},{id:"scheduleJob",name:"ScheduleJob",group:"scheduler",store:{path:"<cwd>/session-manager-operations/scheduler/state/queue.json -> jobs[]",format:"json",writer:"scheduler",definedIn:"src/main/lib/scheduler/queueStore.cjs + src/main/lib/scheduler/scheduleJobSchema.cjs "},summary:"dependsOn is the SOLE ordering primitive — parallelGroup is a display hint, never a barrier.",fields:[{name:"slug",type:"string",key:"pk",note:"shared identity with the PRD it executes"},{name:"title",type:"string"},{name:"cwd",type:"string | null",key:"fk",ref:"project.cwd"},{name:"parallelGroup",type:"number"},{name:"estimateMinutes",type:"number | null"},{name:"bodyPreview",type:"string"},{name:"status",type:"'pending' | 'running' | 'investigating' | 'completed' | 'failed' | 'needs_review' | 'quarantined'"},{name:"runId",type:"string | null",key:"fk",ref:"runLog.runId"},{name:"startedAt",type:"string | null"},{name:"finishedAt",type:"string | null"},{name:"exitCode",type:"number | null"},{name:"error",type:"string | null"},{name:"sessionId",type:"string",optional:!0},{name:"runtime",type:"ScheduleJobRuntime",optional:!0,note:"{ pid, runId, startedAt, sessionId?, cwd? }"},{name:"verifierVerdict",type:"string",optional:!0},{name:"dependsOn",type:"string[]",optional:!0,key:"fk",ref:"prd.slug"},{name:"originSessionId",type:"string | null",optional:!0,key:"fk",ref:"epic.id"},{name:"sourceTabId",type:"string | null",optional:!0},{name:"sourcePromptId",type:"string | null",optional:!0,key:"fk",ref:"epic.id"},{name:"epicId",type:"string | null",optional:!0,key:"fk",ref:"epic.id",note:"authoritative — derived from the PRD directory"},{name:"statusHistory",type:"ScheduleJobStatusHistoryEntry[]",optional:!0}],notes:["Every launch must take a slot from lib/scheduler/sessionSlots.cjs — the single machine-wide concurrency limit.","--model is always pinned on every claude -p call site.","A job in needs_review is a QUESTION routed back to the authoring Epic and never creates work on its own."]},{id:"scheduleJobStatusHistory",name:"ScheduleJobStatusHistoryEntry",group:"scheduler",store:{path:"<cwd>/session-manager-operations/scheduler/state/queue.json -> jobs[].statusHistory[]",format:"json",writer:"scheduler",definedIn:"src/main/lib/scheduler/scheduleJobTransitions.cjs "},summary:"Bounded trail (~20 entries) of accepted status transitions for one ScheduleJob.",fields:[{name:"from",type:"string | null"},{name:"to",type:"string"},{name:"reason",type:"string | null"},{name:"source",type:"string | null"},{name:"at",type:"string"}]},{id:"scheduleHistoryEntry",name:"Schedule history entry",group:"scheduler",store:{path:"<cwd>/session-manager-operations/scheduler/state/history.jsonl",format:"jsonl",writer:"scheduler",definedIn:"src/main/lib/scheduler/queueStore.cjs "},summary:"Terminal jobs aged out of queue.json land here, one JSON object per line.",fields:[{name:"slug",type:"string",key:"fk",ref:"prd.slug"},{name:"status",type:"ScheduleJobStatus"},{name:"finishedAt",type:"string | null"},{name:"epicId",type:"string | null",optional:!0,key:"fk",ref:"epic.id"},{name:"runId",type:"string | null",optional:!0,key:"fk",ref:"runLog.runId"}]},{id:"scheduleConfig",name:"ScheduleConfig",group:"scheduler",store:{path:"~/.claude/session-manager/scheduler-machine.json",format:"json",writer:"scheduler",definedIn:"src/main/lib/scheduler/schedulerConfig.cjs + src/main/lib/scheduler/queueStore.cjs "},summary:"Machine-level auto-fire policy and utilization gate (scheduler-machine.json, not per-project queue.json).",fields:[{name:"enabled",type:"boolean",note:"legacy on/off, kept for v0.4 backwards compat"},{name:"offsetMinutes",type:"number"},{name:"defaultCwd",type:"string",key:"fk",ref:"project.cwd"},{name:"firePolicy",type:"'manual' | 'when-available'"},{name:"utilizationThreshold",type:"number"},{name:"schemaVersion",type:"1"}]},{id:"runLog",name:"Run log",group:"scheduler",store:{path:"~/.claude/session-manager/scheduled-plans/runs/<runId>/",format:"directory",definedIn:"src/main/scheduler.cjs (RUNS_DIR) "},summary:"One directory per headless claude -p invocation — stdout/stderr/exit capture for a ScheduleJob's run.",fields:[{name:"runId",type:"string",key:"pk"}]},{id:"agentPersona",name:"AgentPersona",aka:"ACTOR",group:"agents",store:{path:"~/.claude/agents/<name>.md",format:"markdown",definedIn:"src/main/agentLibrary.cjs + src/main/lib/persona-macro/agentPersonaSchema.cjs "},summary:"One global persona. The action/actionLabel frontmatter keys are retired legacy fields — no longer a live concept.",fields:[{name:"name",type:"string",key:"pk"},{name:"description",type:"string | null"},{name:"tools",type:"string[]"},{name:"model",type:"string | null",note:"wins over the Settings default for this Epic"},{name:"color",type:"string | null"},{name:"tags",type:"AgentPersonaTag[]",key:"fk",ref:"tag.tag"},{name:"projects",type:"string[]",key:"fk",ref:"project.cwd",note:"'*' means every project"},{name:"effort",type:"string | null",optional:!0,note:"per-Epic carve-out like model — persona frontmatter wins over the Settings default"},{name:"title",type:"string | null",optional:!0},{name:"path",type:"string"},{name:"body",type:"string"},{name:"overridingProjects",type:"string[]"}]},{id:"tag",name:"Tag",aka:"MISSION — EpicTag",group:"agents",store:{path:"src/renderer/lib/tagLibrary.ts (TAG_LIBRARY)",format:"code",definedIn:"src/renderer/lib/tagLibrary.ts + src/renderer/lib/agentTagDefs.ts "},summary:"The closed 7-tag union — Epic creation is agentType (who) + tag (what), two independent selections.",fields:[{name:"tag",type:"'feature' | 'bug' | 'discussion' | 'build' | 'project-home-builder' | 'art' | 'portfolio'",key:"pk"},{name:"label",type:"string"},{name:"description",type:"string"},{name:"developEagerness",type:"'expected-default' | 'available-not-assumed'"},{name:"developsVia",type:"string"}]},{id:"macro",name:"Macro",aka:"HOT KEY",group:"agents",store:{path:"~/.claude/session-manager/macros.json",format:"json",writer:"src/main/lib/persona-macro/macroLibrary.cjs",definedIn:"src/main/lib/persona-macro/macroLibrary.cjs "},summary:"A saved (agent, tag, prompt) hot key — machine-local library; a Sessions hot key is shown per project, a Project Home tool in every project; pressing it is the same act as New Session.",fields:[{name:"id",type:"string",key:"pk"},{name:"label",type:"string"},{name:"agentName",type:"string",key:"fk",ref:"agentPersona.name"},{name:"tag",type:"TicketTag",key:"fk",ref:"tag.tag"},{name:"prompt",type:"string"},{name:"projects",type:"string[]",key:"fk",ref:"project.cwd"},{name:"surface",type:"string"},{name:"builtin",type:"boolean",optional:!0},{name:"builtinVersion",type:"number",optional:!0},{name:"createdAt",type:"string"},{name:"updatedAt",type:"string"},{name:"inputs",type:"MacroInput[]",optional:!0},{name:"autoStartTargets",type:"string[]",optional:!0,key:"fk",ref:"project.cwd"}]},{id:"memoryEntry",name:"MemoryEntry",group:"memory",store:{path:"~/.claude/projects/<encodedCwd>/memory/<name>.md",format:"markdown",definedIn:"src/main/memoryTool.cjs "},summary:"One workspace memory file, semantically organized by topic.",fields:[{name:"name",type:"string",key:"pk"},{name:"path",type:"string"},{name:"mtimeMs",type:"number"},{name:"bytes",type:"number"},{name:"workspace",type:"string",key:"fk",ref:"project.cwd",note:"carried on MemoryListResult, denormalized here — the directory this entry lives under"}]},{id:"memoryCluster",name:"MemoryCluster",group:"memory",store:{path:"<cwd>/session-manager-operations/memory-clusters/clusters.json",format:"json",writer:"memory-clusters",definedIn:"src/main/memoryAggregate.cjs "},summary:"Derived grouping of related MemoryEntry files, computed and cached per workspace.",fields:[{name:"id",type:"string",key:"pk"},{name:"name",type:"string"},{name:"summary",type:"string"},{name:"memberSlugs",type:"string[]",key:"fk",ref:"memoryEntry.name"},{name:"links",type:"MemoryClusterLink[]",note:"{ from, to, label? }"}]},{id:"agentMemoryEntry",name:"AgentMemoryEntry",group:"memory",store:{path:"~/.claude/agent-memory/<agent>/ | .claude/agent-memory/<agent>/ | .claude/agent-memory-local/<agent>/",format:"directory",definedIn:"src/main/lib/memoryDirResolve.cjs (resolveAgentMemoryDir)"},summary:"Per-subagent memory in Claude Code's native agent-memory directories (user, project, local scope), keyed by agent name — markdown files with a MEMORY.md index.",fields:[{name:"agent",type:"string",key:"pk",ref:"agentPersona.name",note:"directory name under the scope root"},{name:"scope",type:"'user' | 'project' | 'local'",note:"selects which agent-memory root resolveAgentMemoryDir returns"},{name:"files",type:"markdown[]",note:"topic files plus MEMORY.md index, read live from disk"}]},{id:"claudeTranscript",name:"Claude transcript",group:"transcript",store:{path:"~/.claude/projects/<encodedCwd>/<sessionUuid>.jsonl",format:"jsonl",definedIn:"written by the Claude Code CLI; tailed by src/main/transcripts.cjs "},summary:"The CLI's own append-only transcript — Session Manager only tails and classifies it, never writes it.",fields:[{name:"sessionUuid",type:"string",key:"pk"},{name:"encodedCwd",type:"string",key:"fk",ref:"project.cwd"}]},{id:"transcriptEvent",name:"TranscriptEvent",group:"transcript",store:{path:"in-memory ring buffer, broadcast as transcript:event:<tabId>",format:"in-memory",definedIn:"src/main/transcripts.cjs -> src/renderer/state/live.ts "},summary:"Classified, bounded-preview view over one raw transcript line — never the source of truth.",fields:[{name:"kind",type:"TranscriptEventKind"},{name:"data",type:"unknown"},{name:"raw",type:"unknown"},{name:"previewText",type:"string"},{name:"ref",type:"TranscriptEventRef | null",note:"{ filePath, byteOffset, byteLength }"},{name:"tabId",type:"string",key:"fk",ref:"tab.id"}]},{id:"historyRollupDay",name:"History rollup day",group:"transcript",store:{path:"~/.claude/session-manager/history-rollup.jsonl",format:"jsonl",definedIn:"src/main/lib/historyRollup.cjs "},summary:"One finalized day-per-project analytics row (History tab is analytics/cost/charts only).",fields:[{name:"date",type:"string",key:"pk"},{name:"projectCwd",type:"string",key:"fk",ref:"project.cwd"},{name:"promptCount",type:"number"},{name:"inputTokens",type:"number"},{name:"outputTokens",type:"number"},{name:"estimatedCostUsd",type:"number"}]},{id:"billingUsage",name:"UsageSnapshot",group:"transcript",store:{path:"~/.claude/session-manager/billing-cache.json",format:"json",definedIn:"src/main/usage.cjs (CACHE_PATH) "},summary:"Cached rolling-window utilization percentages from the account's billing API.",fields:[{name:"five_hour",type:"UsageWindow | null"},{name:"seven_day",type:"UsageWindow | null"},{name:"seven_day_sonnet",type:"UsageWindow | null"},{name:"seven_day_opus",type:"UsageWindow | null"},{name:"seven_day_oauth_apps",type:"UsageWindow | null"},{name:"extra_usage",type:"{ is_enabled, monthly_limit, used_credits, utilization, currency } | null"}]},{id:"projectBrief",name:"ProjectBrief",group:"brief",store:{path:"<cwd>/session-manager-operations/project-brief/brief.json",format:"json",writer:"project-home",definedIn:"src/main/projectBrief.cjs "},summary:"The synthesized project Brief — generated, with a hand-edit escape hatch.",fields:[{name:"version",type:"number"},{name:"synthesizedAt",type:"string"},{name:"editedAt",type:"string | null"},{name:"model",type:"string"},{name:"purpose",type:"string"},{name:"what",type:"string[]"},{name:"areas",type:"ProjectBriefArea[]",note:"{ name, files, note, epic, heat }"},{name:"scope",type:"ProjectBriefScopeEntry[]",note:"{ when, kind, text, src }"},{name:"conventions",type:"string[]"},{name:"pins",type:"{ what: boolean; conventions: boolean }"},{name:"pinned",type:"{ what: string[] | null; conventions: string[] | null }"}]},{id:"projectPages",name:"ProjectPagesOutput",group:"brief",store:{path:"<cwd>/session-manager-operations/project-pages/ (knowledge/<id>/, videos/<id>/, videos/_character/)",format:"directory",writer:"project-home",definedIn:"src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs (pages, videos and character routes)"},summary:"The Project Home library: Knowledge Pages and Video Pages, each a folder holding index.html + meta.json.",fields:[{name:"html",type:"string | null"},{name:"mtimeMs",type:"number | null"}]},{id:"settingsScope",name:"Settings (scoped)",group:"config",store:{path:"~/.claude/settings.json + <cwd>/.claude/settings.json + <cwd>/.claude/settings.local.json",format:"json",definedIn:"src/main/config.cjs + src/renderer/state/config.ts + src/renderer/lib/mergeScopes.ts "},summary:"Substrate, not per-Epic curation — model is the one field carved out per-Epic (persona wins over Settings).",fields:[{name:"scope",type:"'system' | 'project' | 'local'",key:"pk"},{name:"cwd",type:"string",optional:!0,key:"fk",ref:"project.cwd"},{name:"model",type:"string",optional:!0}]},{id:"layoutEnvelope",name:"LayoutEnvelope",group:"config",store:{path:"~/.claude/session-manager/workbench-layout.json",format:"json",definedIn:"src/main/layoutStore.cjs + src/renderer/state/layout.ts "},summary:"Persisted dockview panel layout, pruned against the live panel registry on hydrate.",fields:[{name:"version",type:"number"},{name:"panels",type:"string[]",key:"fk",ref:"tab.id"},{name:"dockview",type:"Record<string, unknown>",note:"opaque SerializedDockview blob"}]},{id:"opsNamespace",name:"Ops namespace ownership",aka:"the SINGLE-WRITER LAW",group:"config",store:{path:"src/main/lib/opsOwnership.cjs (OWNERS)",format:"code",definedIn:"src/main/lib/opsOwnership.cjs (assertOpsWrite) "},summary:"Fail-closed — a new top-level ops folder must land in OWNERS (or the deliberately-unowned list) in the same PR that creates it.",fields:[{name:"namespace",type:"string",key:"pk",note:"e.g. 'prompt-sessions', 'scheduler', 'project-brief'"},{name:"writer",type:"string",note:"e.g. 'epics', 'scheduler', 'project-home'"}]},{id:"mcpServerRegistry",name:"MCP server registry",aka:"mcpServers",group:"config",store:{path:"~/.claude.json -> mcpServers",format:"json",definedIn:"src/renderer/components/tabs/McpServers.tsx "},summary:"User-scope MCP server config — no single writer, since both the claude CLI and this app read/write the same file.",fields:[{name:"name",type:"string",key:"pk"},{name:"type",type:"'stdio' | 'http' | 'sse' | 'ws' | 'streamable-http'",optional:!0},{name:"command",type:"string",optional:!0},{name:"args",type:"string[]",optional:!0},{name:"url",type:"string",optional:!0},{name:"env",type:"Record<string, string>",optional:!0},{name:"headers",type:"Record<string, string>",optional:!0},{name:"alwaysLoad",type:"boolean",optional:!0},{name:"enabled",type:"boolean",optional:!0},{name:"disabledTools",type:"string[]",optional:!0}]},{id:"pluginRegistry",name:"Installed plugins manifest",aka:"installed_plugins.json",group:"config",store:{path:"~/.claude/plugins/installed_plugins.json",format:"json",definedIn:"src/renderer/components/tabs/Plugins.tsx "},summary:'Registry of installed plugin versions, keyed by "<name>@<marketplace>" — written by `claude plugin install`, read-only in the Plugins screen.',fields:[{name:"pluginKey",type:"string",key:"pk",note:"<name>@<marketplace>"},{name:"scope",type:"string"},{name:"installPath",type:"string"},{name:"version",type:"string"},{name:"installedAt",type:"string"},{name:"lastUpdated",type:"string"},{name:"gitCommitSha",type:"string",optional:!0}]},{id:"systemPrompt",name:"User CLAUDE.md",aka:"~/.claude/CLAUDE.md",group:"config",store:{path:"~/.claude/CLAUDE.md",format:"markdown",definedIn:"src/renderer/components/tabs/SystemPrompt.tsx "},summary:"The real ~/.claude/CLAUDE.md the claude CLI loads into every session it starts on this machine, in every project — edited here as plain markdown.",fields:[{name:"content",type:"string"},{name:"imports",type:"string[]",note:"@-imported files, listed in a left rail"}]},{id:"skillsAndCommands",name:"Skills & Commands",group:"config",store:{path:"~/.claude/skills/**/SKILL.md + ~/.claude/commands/*.md (and the <cwd>/.claude equivalents for project scope)",format:"directory",definedIn:"src/renderer/components/tabs/Skills.tsx "},summary:"User- and project-scope skill/command markdown files, each editable in place.",fields:[{name:"kind",type:"'skills' | 'commands'"},{name:"scope",type:"'user' | 'project'"},{name:"name",type:"string",key:"pk"},{name:"path",type:"string",note:"absolute path to the editable markdown file"},{name:"dir",type:"string | null",note:"skill directory, if applicable"},{name:"disabled",type:"boolean",note:"skills only — disable-model-invocation: true frontmatter"},{name:"description",type:"string",optional:!0}]},{id:"mcpStatusProbe",name:"MCP status probe",group:"config",store:{path:"in-memory result of `claude mcp list`, never persisted",format:"in-memory",definedIn:"src/main/mcpStatus.cjs (runProbe) "},summary:"Read-only, non-polling live connection probe — models an in-memory-only shape honestly, the same way transcriptEvent does.",fields:[{name:"ok",type:"boolean"},{name:"servers",type:"McpServerStatus[]",note:"{ name, target, transport, status }"},{name:"error",type:"string",optional:!0},{name:"checkedAt",type:"number"}]},{id:"appPrefs",name:"App preferences",aka:"app-prefs / ui-settings-prefs / ui-chrome-prefs",group:"config",store:{path:"~/.claude/session-manager/app-prefs.json + ~/.claude/session-manager/ui-settings-prefs.json + ~/.claude/session-manager/ui-chrome-prefs.json",format:"json",definedIn:"src/renderer/lib/appPrefs.ts (app-prefs.json) + src/renderer/lib/uiSettingsPrefs.ts (ui-settings-prefs.json) + src/renderer/state/uiChromePrefs.ts (ui-chrome-prefs.json) "},summary:"Three small machine-level renderer-owned pref files, read/written through window.api.config — distinct from scheduler-machine.json.",fields:[{name:"openToHomeOnLaunch",type:"boolean",optional:!0,note:"app-prefs.json — read by layout.ts at boot"},{name:"uiSettings",type:"Record<string, unknown>",optional:!0,note:"ui-settings-prefs.json — Settings page UI state"},{name:"uiChrome",type:"Record<string, unknown>",optional:!0,note:"ui-chrome-prefs.json — app chrome UI state"}]},{id:"uiPrefs",name:"UiPrefs",aka:"ui-prefs/prefs.json",group:"config",store:{path:"<cwd>/session-manager-operations/ui-prefs/prefs.json",format:"json",writer:"ui-prefs",definedIn:"src/renderer/lib/uiPrefs.ts "},summary:"Per-project UI state that used to live in scattered global/localStorage keys — one file per project keeps it scoped to the project it belongs to by construction (PRD 1398/1399).",fields:[{name:"fileTreeExpanded",type:"string[]",optional:!0,note:"FileTree.tsx — expanded folder paths in the Files sidebar"},{name:"hiddenCompletedSlugs",type:"string[]",optional:!0,note:'SchedulePanel.tsx — "Clear completed" hides, renderer-side only'},{name:"queueFilterStatus",type:"string",optional:!0,note:"SchedulePanel.tsx — the queue's status filter chip"},{name:"epicPins",type:"Record<string, boolean>",optional:!0,key:"fk",ref:"epic.id",note:"epicsPrefs.ts — pinned-to-top Epic ids, keyed by epicId (moved off the global epics-prefs.json)"},{name:"chatVerbosityPerEpic",type:"Record<string, ChatVerbosity>",optional:!0,key:"fk",ref:"epic.id",note:"chatPrefs.ts — per-Epic verbosity overrides, keyed by epicId (moved off the global chat-prefs.json)"},{name:"editorSession",type:"{ openFiles: string[]; activeFilePath: string | null; viewModeByPath: Record<string, string> }",optional:!0,note:"editor.ts — the Editor scene's structural tab strip only; buffers/baselines/dirty are never persisted (PRD 1400)"}]}];function be(t){const n=te.find(s=>s.id===t);if(!n)throw new Error(`unknown ErdEntity id: ${t}`);return n}const Le=[{from:"tab",to:"project",cardinality:"N-1",label:"belongs to"},{from:"epic",to:"project",cardinality:"N-1",label:"belongs to"},{from:"epic",to:"tag",cardinality:"N-1",label:"mission",optional:!0},{from:"epic",to:"agentPersona",cardinality:"N-1",label:"actor",optional:!0},{from:"epic",to:"epic",cardinality:"N-1",label:"resumed from",optional:!0},{from:"epic",to:"claudeTranscript",cardinality:"1-1",label:"1:1 session"},{from:"epicEvent",to:"epic",cardinality:"N-1",label:"belongs to"},{from:"epicEvent",to:"epicEvent",cardinality:"N-1",label:"caused by",optional:!0},{from:"epicEvent",to:"prd",cardinality:"N-1",label:"about",optional:!0},{from:"epicTranscriptTurn",to:"epic",cardinality:"N-1",label:"belongs to"},{from:"epicTranscriptTurn",to:"epicEvent",cardinality:"N-1",label:"labeled by",optional:!0},{from:"epicArchive",to:"epic",cardinality:"1-1",label:"freezes"},{from:"exchange",to:"epic",cardinality:"N-1",label:"session for",optional:!0},{from:"exchange",to:"project",cardinality:"N-1",label:"belongs to"},{from:"prd",to:"epic",cardinality:"N-1",label:"joins (directory fact)"},{from:"prd",to:"epic",cardinality:"N-1",via:"sourcePromptId",label:"authored from (frontmatter intent)",optional:!0},{from:"prd",to:"project",cardinality:"N-1",label:"belongs to"},{from:"prd",to:"tag",cardinality:"N-1",label:"mission",optional:!0},{from:"scheduleJob",to:"prd",cardinality:"1-1",label:"executes"},{from:"scheduleJob",to:"prd",cardinality:"N-N",via:"dependsOn",label:"depends on",optional:!0},{from:"scheduleJob",to:"epic",cardinality:"N-1",label:"belongs to",optional:!0},{from:"scheduleJob",to:"runLog",cardinality:"N-1",label:"ran as",optional:!0},{from:"scheduleJob",to:"scheduleJob",cardinality:"N-N",via:"dependsOn",label:"depends on (self)",optional:!0},{from:"scheduleJobStatusHistory",to:"scheduleJob",cardinality:"N-1",label:"transitions of"},{from:"scheduleHistoryEntry",to:"prd",cardinality:"N-1",label:"archives"},{from:"scheduleHistoryEntry",to:"epic",cardinality:"N-1",label:"belongs to",optional:!0},{from:"scheduleHistoryEntry",to:"runLog",cardinality:"N-1",label:"ran as",optional:!0},{from:"scheduleConfig",to:"project",cardinality:"1-1",label:"configures"},{from:"agentPersona",to:"tag",cardinality:"N-N",label:"tagged with"},{from:"agentPersona",to:"project",cardinality:"N-N",label:"scoped to"},{from:"memoryEntry",to:"project",cardinality:"N-1",label:"workspace"},{from:"memoryCluster",to:"memoryEntry",cardinality:"1-N",label:"clusters"},{from:"agentMemoryEntry",to:"agentPersona",cardinality:"N-1",label:"belongs to"},{from:"transcriptEvent",to:"tab",cardinality:"N-1",label:"classified for"},{from:"transcriptEvent",to:"claudeTranscript",cardinality:"N-1",label:"classified from"},{from:"claudeTranscript",to:"project",cardinality:"N-1",label:"belongs to"},{from:"historyRollupDay",to:"project",cardinality:"N-N",label:"aggregates"},{from:"billingUsage",to:"scheduleConfig",cardinality:"1-N",label:"gates when-available firing"},{from:"projectBrief",to:"project",cardinality:"1-1",label:"describes"},{from:"projectBrief",to:"epic",cardinality:"N-1",via:"areas[].epic",label:"traces to",optional:!0},{from:"projectPages",to:"project",cardinality:"1-1",label:"generated for"},{from:"settingsScope",to:"project",cardinality:"N-1",label:"scoped to",optional:!0},{from:"layoutEnvelope",to:"tab",cardinality:"1-N",label:"panels for"},{from:"opsNamespace",to:"epic",cardinality:"1-N",label:"governs writes"},{from:"opsNamespace",to:"prd",cardinality:"1-N",label:"governs writes"},{from:"opsNamespace",to:"projectBrief",cardinality:"1-N",label:"governs writes"}];function De(t){return Le.filter(n=>n.from===t||n.to===t)}function Ft(t){const n=new Set;for(const s of De(t)){const r=s.from===t?s.to:s.from;r!==t&&n.add(r)}return[...n]}function Ut(t){switch(t){case"1-1":return"1—1";case"1-N":return"1—N";case"N-1":return"N—1";case"N-N":return"N—N"}}const Te=220,ye=7,zt=44,Wt=16,Jt=10,Vt=96,Gt=28,ie=24;function qt(t){const n=Math.min(t,ye)+(t>ye?1:0);return zt+n*Wt+Jt}function Xt(t){const n=t.x+t.w,s=t.y+t.h*.35,r=t.y+t.h*.65,i=n+48;return{d:`M ${n} ${s} C ${i} ${s}, ${i} ${r}, ${n} ${r}`,mx:i,my:(s+r)/2}}function Yt(t=te,n=Le){const s=pe.map(u=>u.id).filter(u=>t.some(g=>g.group===u)),r=[],i=new Map;s.forEach((u,g)=>{const f=ie+g*(Te+Vt);let m=ie;for(const h of t){if(h.group!==u)continue;const k=qt(h.fields.length),N={id:h.id,group:u,x:f,y:m,w:Te,h:k};r.push(N),i.set(h.id,N),m+=k+Gt}});const a=new Set(t.map(u=>u.id)),c=[];for(const u of n){if(!a.has(u.from)||!a.has(u.to))continue;const g=i.get(u.from),f=i.get(u.to);if(!g||!f)continue;if(u.from===u.to){const P=Xt(g);c.push({relation:u,...P});continue}const m=g.x<f.x,h=m?g.x+g.w:g.x,k=g.y+g.h/2,N=m?f.x:f.x+f.w,C=f.y+f.h/2,I=Math.max(40,Math.abs(N-h)/2),x=h+(m?I:-I),E=N+(m?-I:I),T=`M ${h} ${k} C ${x} ${k}, ${E} ${C}, ${N} ${C}`;c.push({relation:u,d:T,mx:(h+N)/2,my:(k+C)/2})}const p=r.reduce((u,g)=>Math.max(u,g.x+g.w),0),v=r.reduce((u,g)=>Math.max(u,g.y+g.h),0);return{boxes:r,edges:c,width:p+ie,height:v+ie}}const Kt=[{key:"diagram",label:"Diagram"},{key:"tables",label:"Tables"}];function Zt(){const[t,n]=o.useState("diagram"),[s,r]=o.useState(null),[i,a]=o.useState(()=>new Set),c=o.useMemo(()=>te.filter(f=>!i.has(f.group)),[i]),p=o.useMemo(()=>Yt(c),[c]),v=f=>{a(m=>{const h=new Set(m);return h.has(f)?h.delete(f):h.add(f),h}),r(null)},u=s?be(s):null,g=f=>c.some(m=>m.id===f);return e.jsx(ct,{toolbar:e.jsxs(e.Fragment,{children:[e.jsx(Ae,{options:Kt,active:t,onChange:n}),e.jsx(en,{hiddenGroups:i,onToggle:v}),e.jsxs("span",{className:"ml-auto text-fg-faint",children:[te.length," entities"]})]}),children:t==="diagram"?e.jsxs("div",{className:"h-full flex",children:[e.jsx("div",{className:"flex-1 min-w-0 overflow-auto",children:e.jsx(tn,{layout:p,selectedId:s,onSelect:f=>r(m=>m===f?null:f)})}),e.jsx("div",{className:"w-96 shrink-0 border-l border-line overflow-y-auto",children:u?e.jsx(sn,{entity:u,onSelectRelated:f=>g(f)?r(f):void 0}):e.jsx(ce,{title:"select an entity",hint:"click a box in the diagram to see its storage, fields, and relations"})})]}):e.jsx(an,{})})}const Qt=o.memo(Zt);function en({hiddenGroups:t,onToggle:n}){return e.jsx("div",{className:"flex items-center gap-1.5 flex-wrap",children:pe.map(s=>{const r=t.has(s.id);return e.jsxs("button",{onClick:()=>n(s.id),title:`${s.blurb} (${s.realm})`,className:`flex items-center gap-1 px-1.5 py-0.5 rounded border text-[10.5px] ${r?"border-line text-fg-faint opacity-50":"border-line text-fg-dim hover:text-fg"}`,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${s.tone.dot}`}),s.label,e.jsx("span",{className:"text-fg-faint",children:s.realm})]},s.id)})})}function tn({layout:t,selectedId:n,onSelect:s}){const r=o.useMemo(()=>n?new Set(Ft(n)):null,[n]),i=a=>!!n&&(a.relation.from===n||a.relation.to===n);return t.boxes.length===0?e.jsx(ce,{title:"no entities in view",hint:"toggle a group in the legend to show its entities"}):e.jsxs("div",{className:"relative p-4",style:{width:t.width+32,height:t.height+32},children:[e.jsxs("svg",{width:t.width,height:t.height,className:"absolute left-4 top-4 overflow-visible",children:[t.edges.map(a=>{const c=i(a);return e.jsx("path",{"data-testid":`erd-edge-${a.relation.from}-${a.relation.to}`,d:a.d,fill:"none",className:c?"stroke-accent":"stroke-line",strokeWidth:c?2:1,opacity:n&&!c?.25:1},`${a.relation.from}-${a.relation.to}-${a.relation.label}`)}),t.edges.map(a=>i(a)?e.jsx("text",{x:a.mx,y:a.my,textAnchor:"middle",className:"fill-fg-dim text-[10px]",children:a.relation.label},`label-${a.relation.from}-${a.relation.to}-${a.relation.label}`):null)]}),t.boxes.map(a=>e.jsx(nn,{box:a,selected:a.id===n,dimmed:!!n&&a.id!==n&&!(r!=null&&r.has(a.id)),onClick:()=>s(a.id)},a.id))]})}function nn({box:t,selected:n,dimmed:s,onClick:r}){const i=be(t.id),a=Me(t.group),c=i.fields.slice(0,ye),p=i.fields.length-c.length;return e.jsxs("button",{type:"button","data-testid":`erd-box-${t.id}`,onClick:r,className:`absolute text-left rounded border overflow-hidden bg-bg-hi ${n?"border-accent ring-1 ring-accent":"border-line"} ${s?"opacity-30":""}`,style:{left:t.x,top:t.y,width:t.w,height:t.h},children:[e.jsxs("div",{className:"px-2 py-1 border-b border-line flex items-center gap-1.5",children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${a.tone.dot}`}),e.jsx("span",{className:"text-[11px] font-semibold text-fg truncate",children:i.name})]}),i.aka&&e.jsx("div",{className:"px-2 pt-0.5 text-[9.5px] text-fg-faint truncate",children:i.aka}),e.jsxs("div",{className:"px-2 py-0.5",children:[c.map(v=>e.jsxs("div",{className:"text-[9.5px] font-mono text-fg-dim truncate flex items-center gap-1",children:[v.key&&e.jsx("span",{className:"text-fg-faint",children:v.key}),e.jsx("span",{className:"truncate",children:v.name})]},v.name)),p>0&&e.jsxs("div",{className:"text-[9.5px] text-fg-faint italic",children:["+",p," more"]})]})]})}function Oe({fields:t}){return e.jsxs("table",{className:"w-full text-[11px] font-mono",children:[e.jsx("thead",{className:"text-fg-faint uppercase tracking-wide text-[9.5px]",children:e.jsxs("tr",{className:"border-b border-line",children:[e.jsx("th",{className:"text-left font-normal px-2 py-1",children:"name"}),e.jsx("th",{className:"text-left font-normal px-2 py-1",children:"type"}),e.jsx("th",{className:"text-left font-normal px-2 py-1",children:"key"}),e.jsx("th",{className:"text-left font-normal px-2 py-1",children:"note"})]})}),e.jsx("tbody",{children:t.map(n=>e.jsxs("tr",{className:"border-b border-line/50",children:[e.jsxs("td",{className:"px-2 py-1 text-fg",children:[n.name,n.optional&&e.jsx("span",{className:"text-fg-faint",children:"?"})]}),e.jsx("td",{className:"px-2 py-1 text-fg-dim",children:n.type}),e.jsx("td",{className:"px-2 py-1",children:n.key&&e.jsxs(U,{tone:n.key==="pk"?"accent":"dim",children:[n.key,n.ref?` → ${n.ref}`:""]})}),e.jsx("td",{className:"px-2 py-1 text-fg-faint",children:n.note})]},n.name))})]})}function _e({entity:t}){return e.jsxs("div",{className:"space-y-1 text-[11px]",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-fg-faint w-20 shrink-0",children:"path"}),e.jsx("span",{className:"font-mono text-fg-dim break-all",children:t.store.path})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-fg-faint w-20 shrink-0",children:"format"}),e.jsx("span",{className:"font-mono text-fg-dim",children:t.store.format})]}),t.store.writer&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-fg-faint w-20 shrink-0",children:"writer"}),e.jsxs(U,{tone:"accent",children:["single-writer: ",t.store.writer]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-fg-faint w-20 shrink-0",children:"definedIn"}),e.jsx("span",{className:"font-mono text-fg-dim break-all",children:t.store.definedIn})]})]})}function sn({entity:t,onSelectRelated:n}){const s=Me(t.group),r=De(t.id);return e.jsxs("div",{className:"p-3 space-y-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${s.tone.dot}`}),e.jsx("span",{className:"text-sm font-semibold text-fg",children:t.name})]}),t.aka&&e.jsx("div",{className:"text-[10.5px] text-fg-faint",children:t.aka}),e.jsx(U,{tone:"dim",className:"mt-1",children:s.label})]}),e.jsx("div",{className:"text-xs text-fg-dim leading-relaxed",children:t.summary}),e.jsxs("div",{children:[e.jsx(oe,{children:"storage"}),e.jsx(_e,{entity:t})]}),e.jsxs("div",{children:[e.jsx(oe,{children:"fields"}),e.jsx(Oe,{fields:t.fields})]}),t.notes&&t.notes.length>0&&e.jsxs("div",{children:[e.jsx(oe,{children:"notes"}),e.jsx("ul",{className:"list-disc pl-4 space-y-0.5 text-xs text-fg-dim",children:t.notes.map(i=>e.jsx("li",{children:i},i))})]}),e.jsxs("div",{children:[e.jsx(oe,{children:"relations"}),r.length===0?e.jsx("div",{className:"text-xs text-fg-faint italic",children:"no relations"}):e.jsx("ul",{className:"space-y-1",children:r.map(i=>{const a=i.from===t.id?i.to:i.from,c=be(a);return e.jsxs("li",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx("span",{className:"font-mono text-fg-faint w-10 shrink-0",children:Ut(i.cardinality)}),e.jsx("span",{className:"text-fg-dim",children:i.label}),i.via&&e.jsxs("span",{className:"font-mono text-[10px] text-fg-faint",children:["via ",i.via]}),e.jsx("button",{type:"button",onClick:()=>n(a),className:"ml-auto text-accent hover:underline font-mono",children:c.name})]},`${i.from}-${i.to}-${i.label}`)})})]})]})}function oe({children:t}){return e.jsx("div",{className:"text-[10.5px] uppercase tracking-wide text-fg-faint mb-1 font-mono",children:t})}function an(){return e.jsx("div",{className:"p-4 space-y-6",children:pe.map(t=>{const n=te.filter(s=>s.group===t.id);return n.length===0?null:e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${t.tone.dot}`}),e.jsx("span",{className:"text-xs font-semibold text-fg",children:t.label}),e.jsx("span",{className:"text-[10.5px] text-fg-faint",children:t.realm})]}),e.jsx("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-3",children:n.map(s=>e.jsxs("div",{className:"border border-line rounded bg-bg-hi p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-semibold text-fg",children:s.name}),s.aka&&e.jsx("span",{className:"text-[10.5px] text-fg-faint",children:s.aka})]}),e.jsx(U,{tone:"dim",className:"mt-1",children:t.label})]}),e.jsx("div",{className:"text-xs text-fg-dim leading-relaxed",children:s.summary}),e.jsx(_e,{entity:s}),e.jsx(Oe,{fields:s.fields}),s.notes&&s.notes.length>0&&e.jsx("ul",{className:"list-disc pl-4 space-y-0.5 text-xs text-fg-dim",children:s.notes.map(r=>e.jsx("li",{children:r},r))})]},s.id))})]},t.id)})})}const Re=[{key:"voice",label:"Voice"},{key:"appearance",label:"Appearance"},{key:"telemetry",label:"Telemetry"},{key:"remote",label:"Web remote"},{key:"updates",label:"Updates & retention"},{key:"startup",label:"Startup"},{key:"storage",label:"Storage map"}],rn={compact:"Compact",roomy:"Roomy"},on=".claude/session-manager";function ln({files:t}){const n=tt();return e.jsx("div",{className:"flex flex-wrap gap-2 px-4 pt-3","data-testid":"app-settings-chips",children:t.map(s=>{const r=s.path.startsWith("~/")?n?n+s.path.slice(1):null:s.path;return r?e.jsx(it,{path:r,keyPath:s.keyPath},s.path):null})})}function cn(){const[t,n]=o.useState(!1),[s,r]=o.useState(!1);o.useEffect(()=>{let a=!0;return at().then(c=>{a&&n(c.openToHomeOnLaunch===!0)}),()=>{a=!1}},[]);const i=async a=>{n(a),r(!0);try{await rt({openToHomeOnLaunch:a})}catch{n(!a),Q.error('Failed to save "Open to Home on launch" — try again.')}finally{r(!1)}};return e.jsxs("div",{className:"p-4 max-w-3xl space-y-3 text-sm",children:[e.jsx(V,{checked:t,onChange:i,disabled:s,label:"Open to Home on launch"}),e.jsx(Dt,{})]})}function dn(){const{density:t,setDensity:n}=nt();return e.jsxs("div",{className:"p-4 max-w-3xl space-y-5 text-sm",children:[e.jsx(yt,{}),e.jsxs("section",{className:"border border-line rounded p-3 space-y-1",children:[e.jsx("span",{className:"text-fg-dim text-xs",children:"Density"}),e.jsx(st,{options:["compact","roomy"],value:t,onChange:s=>n(s),labels:rn}),e.jsx("span",{className:"text-fg-faint text-[11px]",children:"Compact tightens spacing across the app's chrome; Roomy is the default."})]})]})}const W=(t,n)=>({path:`~/${on}/${t}`,keyPath:n}),pn={voice:[W("voice.json")],appearance:[{path:et,keyPath:["terminal"]},W("ui-chrome-prefs.json")],telemetry:[W("telemetry.json"),W("otel.json")],remote:[W("web-remote.json")],updates:[W("updater.json"),W("ops-retention.json")],startup:[{path:Qe,keyPath:["openToHomeOnLaunch"]}],storage:[]};function xn(){const[t,n]=o.useState("voice");return Ze("app-settings",s=>{Re.some(r=>r.key===s)&&n(s)}),e.jsxs("div",{className:"flex flex-col h-full min-h-0","data-testid":"app-settings",children:[e.jsx("div",{className:"flex items-center px-4 pt-3",children:e.jsx(Ae,{options:Re,active:t,onChange:n})}),e.jsx(ln,{files:pn[t]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto","data-testid":`app-settings-${t}`,children:[t==="voice"&&e.jsx(mt,{open:!0,onClose:()=>{},variant:"page"}),t==="appearance"&&e.jsx(dn,{}),t==="telemetry"&&e.jsx(wt,{}),t==="remote"&&e.jsx($t,{}),t==="updates"&&e.jsxs("div",{className:"p-4 max-w-3xl space-y-5",children:[e.jsx(Mt,{}),e.jsx(Bt,{})]}),t==="startup"&&e.jsx(cn,{}),t==="storage"&&e.jsx(Qt,{})]})]})}export{xn as AppSettings};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{aN as me,aV as Je,bG as et,aC as e,aS as p,bb as X,aO as D,aP as H,bz as Fe,bo as tt,bx as Ce,aI as st,bn as nt,m as ot}from"./index-Cn5E9958.js";import{P as at}from"./Panel-BjdJjhqt.js";import{p as _e,i as B,m as Oe,t as I,u as $,f as rt}from"./historyTotals-DDunb8Ch.js";import"./monaco-editor-BsIlgG7c.js";function ie(){return{promptCount:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,toolCallCount:0,sessionCount:0,errorCount:0,activeMinutes:0,estimatedCostUsd:0}}function we(t,s){t.promptCount+=s.promptCount,t.inputTokens+=s.inputTokens,t.outputTokens+=s.outputTokens,t.cacheReadTokens+=s.cacheReadTokens,t.cacheCreationTokens+=s.cacheCreationTokens,t.toolCallCount+=s.toolCallCount,t.sessionCount+=s.sessionCount,t.errorCount+=s.errorCount,t.activeMinutes+=s.activeMinutes,t.estimatedCostUsd+=s.estimatedCostUsd}function ct(t){return t.promptCount>0||t.sessionCount>0||t.toolCallCount>0||t.inputTokens>0||t.outputTokens>0}function it(t,s){const n=s===null,a=[],o=ie(),c={},r={};let i=0;for(const f of t.days){const l=ie();let d=!1;for(const[m,u]of Object.entries(f.byProject)){if(!n&&!s.has(m))continue;we(l,u),we(o,u),ct(u)&&(d=!0);for(const[y,v]of Object.entries(u.byModel)){const x=c[y]??(c[y]={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0});x.inputTokens+=v.inputTokens,x.outputTokens+=v.outputTokens,x.cacheReadTokens+=v.cacheReadTokens,x.cacheCreationTokens+=v.cacheCreationTokens,x.costUsd+=v.costUsd,v.estimated&&(x.estimated=!0)}const g=u.byLauncher??{};for(const[y,v]of Object.entries(g)){const x=r[y]??(r[y]={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,sessionCount:0});x.inputTokens+=v.inputTokens,x.outputTokens+=v.outputTokens,x.cacheReadTokens+=v.cacheReadTokens,x.cacheCreationTokens+=v.cacheCreationTokens,x.costUsd+=v.costUsd,x.sessionCount+=v.sessionCount}}d&&(i+=1),a.push({date:f.date,totals:l})}return{days:a,totals:o,prevTotals:n?t.prevTotals:ie(),prevAvailable:n,byModelTotals:c,byLauncherTotals:r,activeDays:i}}function He(t,s){if(!s)return{pct:null,direction:"flat"};const n=(t-s)/s*100,a=n>0?"up":n<0?"down":"flat";return{pct:n,direction:a}}function lt(t,s,n){return s<=0?0:t/s*n}const dt=["promptCount","inputTokens","outputTokens","cacheReadTokens","cacheCreationTokens","toolCallCount","sessionCount","errorCount","activeMinutes","estimatedCostUsd"],ut=["inputTokens","outputTokens","cacheReadTokens","cacheCreationTokens","costUsd"];function Re(t){const s={promptCount:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,toolCallCount:0,sessionCount:0,errorCount:0,activeMinutes:0,estimatedCostUsd:0,byModel:{}},n=a=>typeof a=="number"&&Number.isFinite(a)?a:0;for(const a of t){for(const o of dt)s[o]+=n(a[o]);for(const[o,c]of Object.entries(a.byModel??{})){const r=s.byModel[o]??(s.byModel[o]={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0});for(const i of ut)r[i]+=n(c==null?void 0:c[i])}}return s}const Be={in:"In tokens",out:"Out tokens",total:"Total tokens",prompts:"Prompts",sessions:"Sessions",time:"Time",spend:"Spend"};function E(t,s){const n=t.inputTokens+t.cacheReadTokens+t.cacheCreationTokens;switch(s){case"in":return n;case"out":return t.outputTokens;case"total":return n+t.outputTokens;case"prompts":return t.promptCount;case"sessions":return t.sessionCount;case"time":return t.activeMinutes;case"spend":return t.estimatedCostUsd}}function ft(t,s){const n=E(t.totals,s),a=t.prevAvailable?He(n,E(t.prevTotals,s)):null,o=t.days.map(c=>E(c.totals,s));return{value:n,delta:a,series:o}}function Se(t,s){const n=new Map,a=Math.ceil(t.length/2);t.forEach((r,i)=>{for(const[f,l]of Object.entries(r.byProject)){let d=n.get(f);d||(d={totals:{promptCount:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,toolCallCount:0,sessionCount:0,errorCount:0,activeMinutes:0,estimatedCostUsd:0},toolBreakdown:{},firstHalf:0,secondHalf:0},n.set(f,d)),d.totals.promptCount+=l.promptCount,d.totals.inputTokens+=l.inputTokens,d.totals.outputTokens+=l.outputTokens,d.totals.cacheReadTokens+=l.cacheReadTokens,d.totals.cacheCreationTokens+=l.cacheCreationTokens,d.totals.toolCallCount+=l.toolCallCount,d.totals.sessionCount+=l.sessionCount,d.totals.errorCount+=l.errorCount,d.totals.activeMinutes+=l.activeMinutes,d.totals.estimatedCostUsd+=l.estimatedCostUsd;for(const[u,g]of Object.entries(l.toolBreakdown))d.toolBreakdown[u]=(d.toolBreakdown[u]??0)+g;const m=E(l,s);i<a?d.firstHalf+=m:d.secondHalf+=m}});const o=Array.from(n.entries()).map(([r,i])=>{let f="",l=-1;for(const[d,m]of Object.entries(i.toolBreakdown))m>l&&(l=m,f=d);return{projectDir:r,value:E(i.totals,s),sharePct:0,trend:He(i.secondHalf,i.firstHalf),sessions:i.totals.sessionCount,topTool:f}}),c=o.reduce((r,i)=>r+i.value,0);for(const r of o)r.sharePct=c>0?r.value/c*100:0;return o.sort((r,i)=>i.value-r.value)}const xt=["date","cost_usd","input_tokens","output_tokens","cache_write_tokens","cache_read_tokens","total_tokens","cache_hit_pct","num_models","top_model"];function ht(t){return/[",\n]/.test(t)?`"${t.replace(/"/g,'""')}"`:t}function Me(t){return t.inputTokens+t.outputTokens+t.cacheReadTokens+t.cacheCreationTokens}function pt(t){const s=t.map(n=>{const a=n.inputTokens+n.outputTokens+n.cacheCreationTokens+n.cacheReadTokens,o=n.inputTokens+n.cacheReadTokens+n.cacheCreationTokens,c=o>0?n.cacheReadTokens/o*100:0,r=Object.entries(n.byModel).filter(([,d])=>Me(d)>0);let i="",f=-1;for(const[d,m]of r){const u=Me(m);u>f&&(f=u,i=d)}return[n.date,n.costUsd.toFixed(4),String(n.inputTokens),String(n.outputTokens),String(n.cacheCreationTokens),String(n.cacheReadTokens),String(a),c.toFixed(1),String(r.length),i?me(i):""].map(ht).join(",")});return[xt.join(","),...s].join(`
|
|
2
2
|
`)}const mt=["epic","job","task","other"],xe="sm-task:";function gt(t){return t.startsWith(xe)?"task":t.includes("session-manager-epic-worktrees")?"epic":t.includes("session-manager-job-worktrees")?"job":"other"}const jt={folderCount:0,sessionCount:0,promptCount:0,estimatedCostUsd:0,totalTokens:0};function Ie(t,s,n){const a=t.byLauncher[s]??(t.byLauncher[s]={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,sessionCount:0});a.inputTokens+=n.inputTokens,a.outputTokens+=n.outputTokens,a.cacheReadTokens+=n.cacheReadTokens,a.cacheCreationTokens+=n.cacheCreationTokens,a.costUsd+=n.estimatedCostUsd,a.sessionCount+=n.sessionCount}function $e(t,s,n){t.promptCount+=s.promptCount,t.inputTokens+=s.inputTokens,t.outputTokens+=s.outputTokens,t.cacheReadTokens+=s.cacheReadTokens,t.cacheCreationTokens+=s.cacheCreationTokens,t.toolCallCount+=s.toolCallCount,t.sessionCount+=s.sessionCount,t.errorCount+=s.errorCount,t.activeMinutes+=s.activeMinutes,t.estimatedCostUsd+=s.estimatedCostUsd;for(const[a,o]of Object.entries(s.toolBreakdown??{}))t.toolBreakdown[a]=(t.toolBreakdown[a]??0)+o;for(const[a,o]of Object.entries(s.byModel??{})){const c=t.byModel[a]??(t.byModel[a]={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0});c.inputTokens+=o.inputTokens,c.outputTokens+=o.outputTokens,c.cacheReadTokens+=o.cacheReadTokens,c.cacheCreationTokens+=o.cacheCreationTokens,c.costUsd+=o.costUsd,o.estimated&&(c.estimated=!0)}Ie(t,n,s)}function Ee(t,s,n){const a={};for(const[c,r]of Object.entries(t.byModel??{}))a[c]={...r};const o={...t,projectDir:s,toolBreakdown:{...t.toolBreakdown??{}},byModel:a,byLauncher:{}};return Ie(o,n,t),o}function vt(t,s){const n={...jt},a=new Set,o=t.map(c=>{const r={};for(const[i,f]of Object.entries(c.byProject)){if(i.startsWith(xe)){const u=i.slice(xe.length),g=r[u];g?$e(g,f,"task"):r[u]=Ee(f,u,"task");continue}const l=s[i];if(!l){a.add(i),n.sessionCount+=f.sessionCount,n.promptCount+=f.promptCount,n.estimatedCostUsd+=f.estimatedCostUsd,n.totalTokens+=f.inputTokens+f.outputTokens;continue}const d=gt(i),m=r[l];m?$e(m,f,d):r[l]=Ee(f,l,d)}return{...c,byProject:r}});return n.folderCount=a.size,{days:o,excluded:n}}function bt(t){return t.folderCount>0}function kt(t){const s=[`${t.folderCount} transcript folder${t.folderCount===1?"":"s"} with no resolvable working directory`];return t.sessionCount&&s.push(`${t.sessionCount.toLocaleString()} sessions`),t.promptCount&&s.push(`${t.promptCount.toLocaleString()} prompts`),t.estimatedCostUsd>=.005&&s.push(`$${t.estimatedCostUsd.toFixed(2)}`),`Excluded: ${s.join(" · ")}`}async function ge(){return(await Je()).history??{}}let De=Promise.resolve();function he(t){const s=De.then(async()=>{const n=await ge();await et({history:{...n,...t}})});return De=s.catch(()=>{}),s}const yt=["in","out","total","prompts","sessions","time","spend"],Nt=[{value:30,label:"30d"},{value:60,label:"60d"},{value:90,label:"90d"},{value:0,label:"All time"}];function Pe({value:t,options:s,onChange:n}){return e.jsx("div",{className:"flex gap-0.5 p-0.5 rounded bg-bg-elev shadow-[inset_0_0_0_1px_rgba(0,0,0,0.06)] text-[11px]",children:s.map(a=>e.jsx("button",{onClick:()=>n(a.value),className:`px-2 py-1 rounded whitespace-nowrap font-mono ${t===a.value?"bg-bg-hi text-fg shadow-sm":"text-fg-faint hover:text-fg"}`,children:a.label},String(a.value)))})}function Tt({measure:t,onMeasure:s,range:n,onRange:a,projectsShown:o,projectsTotal:c,fromDate:r,toDate:i,onRefresh:f,onExport:l,exportDisabled:d}){return e.jsxs("div",{className:"sticky top-0 z-10 border-b border-line px-4 py-2.5 flex flex-wrap items-center gap-3 backdrop-blur-sm",style:{backgroundColor:"rgba(246,239,225,0.93)"},children:[e.jsx(Pe,{value:t,options:yt.map(m=>({value:m,label:Be[m]})),onChange:s}),e.jsx(Pe,{value:n,options:Nt,onChange:a}),e.jsxs("span",{className:"text-[11px] text-fg-faint font-mono",children:[o," / ",c," projects"]}),e.jsxs("span",{className:"text-[11px] text-fg-faint font-mono",children:[r," → ",i]}),e.jsx("div",{className:"flex-1"}),e.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] border border-line rounded hover:text-fg hover:bg-bg-hi text-fg-faint",title:"Re-fetch the rollup (no scan)",children:"↻ Refresh"}),e.jsx("button",{onClick:l,disabled:d,className:"px-2 py-1 text-[11px] border border-line rounded hover:text-fg hover:bg-bg-hi text-fg-faint disabled:opacity-40 disabled:pointer-events-none",children:"Export CSV"})]})}const C="rounded-card bg-bg-hi border border-line",Ct="#ded2bd",wt="#6f7d52";function w({kicker:t,title:s,right:n}){return e.jsxs("div",{className:"flex items-baseline justify-between gap-3 mb-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wider text-accent font-mono",children:t}),e.jsx("h2",{className:"font-serif text-[25px] leading-tight tracking-tight text-fg",children:s})]}),n]})}function Q(t,s){switch(t){case"spend":return $(s);case"in":case"out":case"total":return I(s);case"time":return Oe(s);default:return B(s)}}function Rt({measure:t,headline:s,activeDays:n,projectsTouched:a,totalSessions:o}){const c=n>0?s.value/n:0,r=o>0?s.value/o:0,{delta:i}=s,f=i&&(t==="spend"?i.direction==="down":i.direction==="up"),l=i&&i.direction!=="flat"&&(t==="spend"?i.direction==="up":i.direction==="down"),d=f?"text-delta-good":l?"text-delta-bad":"text-fg-faint";return e.jsxs("div",{className:`${C} p-4`,children:[e.jsx(w,{kicker:"01 · overview",title:Be[t]}),e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[52px] leading-none font-mono tracking-tight text-fg",children:Q(t,s.value)}),i?e.jsxs("div",{className:`text-xs font-mono mt-2 ${d}`,children:[i.direction==="up"?"▲":i.direction==="down"?"▼":"·"," ",_e(Math.abs(i.pct??0))," vs prior period"]}):e.jsx("div",{className:"text-xs text-fg-faint mt-2",children:"no prior window to compare"})]}),e.jsx("div",{className:"flex-1 min-w-0 self-stretch",children:e.jsx(St,{series:s.series})})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-3 mt-4 pt-3 border-t border-line",children:[e.jsx(Y,{label:"per active day",value:Q(t,c)}),e.jsx(Y,{label:"per session",value:Q(t,r)}),e.jsx(Y,{label:"active days",value:B(n)}),e.jsx(Y,{label:"projects touched",value:B(a)})]})]})}function Y({label:t,value:s}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-fg-faint uppercase tracking-wider",children:t}),e.jsx("div",{className:"text-[17px] font-mono tracking-tight text-fg-dim",children:s})]})}function St({series:t}){if(t.length<2)return null;const a=Math.max(...t,0),o=Math.min(...t,0),c=a-o||1,r=160/(t.length-1),i=t.map((l,d)=>`${d*r},${48-(l-o)/c*48}`).join(" "),f=`0,48 ${i} 160,48`;return e.jsxs("svg",{viewBox:"0 0 160 48",preserveAspectRatio:"none",className:"w-full h-full min-h-[48px]",children:[e.jsx("polygon",{points:f,fill:"#b85c34",opacity:.15}),e.jsx("polyline",{points:i,fill:"none",stroke:"#b85c34",strokeWidth:1.5,vectorEffect:"non-scaling-stroke"})]})}const Mt=50;function $t({days:t}){const[s,n]=p.useState(Mt),a=p.useRef(!1);p.useEffect(()=>{let l=!1;return ge().then(d=>{l||a.current||typeof d.budgetCapUsd=="number"&&Number.isFinite(d.budgetCapUsd)&&d.budgetCapUsd>0&&n(d.budgetCapUsd)}),()=>{l=!0}},[]);const o=l=>{a.current=!0;const d=s;n(l),he({budgetCapUsd:l}).catch(()=>{n(d),X.error("Couldn't save the budget cap — reverted.")})},{mtdSpend:c,projectedSpend:r}=p.useMemo(()=>{const l=new Date,d=l.toLocaleDateString("en-CA").slice(0,7),m=new Date(l.getFullYear(),l.getMonth()+1,0).getDate(),u=l.getDate();let g=0;for(const y of t)if(y.date.startsWith(d))for(const v of Object.values(y.byProject))g+=v.estimatedCostUsd;return{mtdSpend:g,projectedSpend:lt(g,u,m)}},[t]),i=r>s,f=s>0?Math.min(100,c/s*100):0;return e.jsxs("div",{className:`${C} p-3`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h3",{className:"text-[10.5px] uppercase tracking-wider text-fg-faint font-mono",children:"Monthly budget"}),e.jsxs("label",{className:"flex items-center gap-1.5 text-[10px] text-fg-faint",children:["cap",e.jsx("span",{children:"$"}),e.jsx("input",{type:"number",min:1,step:1,value:s,onChange:l=>{const d=Number(l.target.value);Number.isFinite(d)&&d>0&&o(d)},className:"w-16 bg-bg border border-line rounded px-1.5 py-0.5 text-xs text-fg font-mono"})]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs font-mono mb-1.5",children:[e.jsxs("span",{className:"text-fg",children:[$(c)," ",e.jsx("span",{className:"text-fg-faint",children:"month-to-date"})]}),e.jsxs("span",{className:i?"text-delta-bad":"text-fg-dim",children:[$(r)," ",e.jsx("span",{className:"text-fg-faint",children:"projected"})]})]}),e.jsx("div",{className:"h-1.5 rounded bg-bg-hi overflow-hidden",children:e.jsx("div",{className:`h-full ${i?"bg-delta-bad":"bg-sage"}`,style:{width:`${Math.max(f,f>0?2:0)}%`}})}),e.jsx("div",{className:`text-[10px] mt-1 font-mono ${i?"text-delta-bad":"text-fg-faint"}`,children:i?`projected to exceed $${s.toFixed(0)} cap`:`${f.toFixed(0)}% of $${s.toFixed(0)} cap`})]})}function Et({chips:t,keep:s,onToggle:n,onIsolate:a,onShowAll:o}){const c=s===null;return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsxs("button",{onClick:o,className:`px-2 py-1 rounded text-[11px] font-mono border ${c?"bg-accent text-white border-accent":"border-line text-fg-faint hover:text-fg hover:bg-bg-hi"}`,children:["show all (",t.length,")"]}),t.map(r=>{const i=c||s.has(r.projectDir);return e.jsxs("button",{onClick:f=>f.shiftKey?a(r.projectDir):n(r.projectDir),title:r.projectDir,className:`inline-flex items-center gap-1.5 px-2 py-1 rounded text-[11px] font-mono border ${i?"border-line text-fg-dim bg-bg-hi":"border-line text-fg-faint opacity-40 hover:opacity-70"}`,children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:D(r.projectDir)}}),H(r.projectDir)]},r.projectDir)})]})}function Dt(t,s){const n=new Map;for(const o of t)for(const[c,r]of Object.entries(o.values))n.set(c,(n.get(c)??0)+r);const a=Array.from(n.entries()).sort((o,c)=>c[1]-o[1]).map(([o])=>o);return t.map(o=>{const c=a.reduce((f,l)=>f+(o.values[l]??0),0);let r=0;const i=a.map(f=>{const l=o.values[f]??0;if(c<=0)return{projectDir:f,value:l,y0:0,y1:0};const d=s==="share"?l/c:l,m=r,u=r+d;return r=u,{projectDir:f,value:l,y0:m,y1:u}});return{date:o.date,bands:i,total:c}})}const le=720,de=220,ue=44,Pt=20;function Ut(t,s){return t==="spend"?$(s):I(s)}function At({days:t,measure:s,selected:n,onSelect:a}){const[o,c]=p.useState("absolute"),r=p.useMemo(()=>Dt(t,o),[t,o]),i=p.useMemo(()=>{if(o==="share")return 1;let x=0;for(const b of r)x=Math.max(x,b.total);return x||1},[r,o]),f=le-ue,l=de-Pt,d=r.length>1?f/(r.length-1):f,m=x=>ue+x*d,u=x=>l-x/i*l,g=Math.max(1,Math.ceil(r.length/8)),y=4,v=Array.from({length:y+1},(x,b)=>i/y*b);return e.jsxs("div",{className:`${C} p-4`,children:[e.jsx(w,{kicker:"02 · over time",title:"Trend by project",right:e.jsx("div",{className:"flex border border-line rounded overflow-hidden text-[10px] font-mono",children:["absolute","share"].map(x=>e.jsx("button",{onClick:()=>c(x),className:`px-2 py-0.5 ${o===x?"bg-accent text-white":"text-fg-faint hover:text-fg"}`,children:x},x))})}),e.jsxs("svg",{width:"100%",viewBox:`0 0 ${le} ${de}`,className:"overflow-visible",children:[v.map((x,b)=>e.jsxs("g",{children:[e.jsx("line",{x1:ue,x2:le,y1:u(x),y2:u(x),stroke:"currentColor",className:"text-line",strokeWidth:1}),e.jsx("text",{x:0,y:u(x)+3,fontSize:9,className:"fill-fg-faint",children:o==="share"?`${Math.round(x*100)}%`:Ut(s,x)})]},b)),r.map((x,b)=>{if(b===0)return null;const P=r[b-1];return x.bands.map((j,ee)=>{const q=P.bands[ee],W=n!==null&&n!==j.projectDir,te=W?Ct:D(j.projectDir),se=[`${m(b-1)},${u(q.y0)}`,`${m(b)},${u(j.y0)}`,`${m(b)},${u(j.y1)}`,`${m(b-1)},${u(q.y1)}`].join(" ");return e.jsx("polygon",{points:se,fill:te,opacity:W?.6:.75,className:"cursor-pointer",onClick:()=>a(n===j.projectDir?null:j.projectDir),children:e.jsx("title",{children:H(j.projectDir)})},`${j.projectDir}-${b}`)})}),r.map((x,b)=>b%g!==0&&b!==r.length-1?null:e.jsx("text",{x:m(b),y:de-4,fontSize:9,textAnchor:"middle",className:"fill-fg-faint",children:x.date.slice(5)},x.date))]})]})}function Lt({rows:t,measure:s,selected:n,onSelect:a}){return t.length?e.jsxs("div",{className:`${C} overflow-hidden`,children:[e.jsx("div",{className:"p-4 pb-0",children:e.jsx(w,{kicker:"03 · by project",title:"Ranking"})}),e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"bg-bg-elev",children:e.jsx("tr",{children:["project","share","value","share %","trend","sessions","top tool"].map(o=>e.jsx("th",{className:"text-left px-3 py-2 text-fg-faint uppercase tracking-wider whitespace-nowrap",children:o},o))})}),e.jsx("tbody",{children:t.map(o=>{const c=D(o.projectDir),r=n===o.projectDir;return e.jsxs("tr",{onClick:()=>a(o.projectDir),className:`border-t border-line hover:bg-bg-elev cursor-pointer ${r?"bg-bg-elev":""}`,children:[e.jsx("td",{className:"px-3 py-2 font-mono text-fg-dim",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:c}}),H(o.projectDir)]})}),e.jsx("td",{className:"px-3 py-2 w-32",children:e.jsx("div",{className:"h-1.5 rounded bg-bg-hi overflow-hidden",children:e.jsx("div",{className:"h-full",style:{width:`${Math.max(o.sharePct,o.sharePct>0?2:0)}%`,backgroundColor:c}})})}),e.jsx("td",{className:"px-3 py-2 text-fg-faint font-mono",children:Q(s,o.value)}),e.jsxs("td",{className:"px-3 py-2 text-fg-faint font-mono",children:[o.sharePct.toFixed(1),"%"]}),e.jsx("td",{className:"px-3 py-2 font-mono",children:o.trend.pct===null?e.jsx("span",{className:"text-fg-faint",children:"—"}):e.jsxs("span",{className:o.trend.direction==="up"?"text-delta-good":o.trend.direction==="down"?"text-delta-bad":"text-fg-faint",children:[o.trend.direction==="up"?"▲":o.trend.direction==="down"?"▼":"·"," ",_e(Math.abs(o.trend.pct))]})}),e.jsx("td",{className:"px-3 py-2 text-fg-faint font-mono",children:B(o.sessions)}),e.jsx("td",{className:"px-3 py-2 text-fg-faint font-mono",children:o.topTool||"—"})]},o.projectDir)})})]})]}):e.jsxs("div",{className:`${C} p-4`,children:[e.jsx(w,{kicker:"03 · by project",title:"Ranking"}),e.jsx("div",{className:"text-xs text-fg-faint",children:"no projects in range"})]})}function Ft({projectDir:t,totals:s,byModel:n,toolBreakdown:a,onClear:o}){var d;const c=E(s,"in"),r=E(s,"out"),i=Object.entries(n).sort((m,u)=>u[1].costUsd-m[1].costUsd),f=Object.entries(a).sort((m,u)=>u[1]-m[1]),l=((d=f[0])==null?void 0:d[1])??0;return e.jsxs("div",{className:`${C} p-4`,children:[e.jsx(w,{kicker:"04 · drill in",title:H(t),right:e.jsx("button",{onClick:o,className:"text-[11px] text-fg-faint hover:text-fg font-mono",children:"clear ✕"})}),e.jsx("div",{className:"flex items-center gap-1.5 -mt-2 mb-3",children:e.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:D(t)}})}),e.jsxs("div",{className:"grid grid-cols-6 gap-3 mb-4",children:[e.jsx(O,{label:"prompts",value:B(s.promptCount)}),e.jsx(O,{label:"sessions",value:B(s.sessionCount)}),e.jsx(O,{label:"in tokens",value:I(c)}),e.jsx(O,{label:"out tokens",value:I(r)}),e.jsx(O,{label:"spend",value:$(s.estimatedCostUsd)}),e.jsx(O,{label:"time",value:Oe(s.activeMinutes)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-fg-faint uppercase tracking-wider mb-1.5",children:"model mix"}),i.length===0?e.jsx("div",{className:"text-xs text-fg-faint",children:"no model data"}):e.jsx("div",{className:"space-y-1",children:i.map(([m,u])=>e.jsxs("div",{className:"flex items-center justify-between text-[11px] font-mono text-fg-dim",children:[e.jsx("span",{children:me(m)}),e.jsx("span",{className:"text-fg-faint",children:$(u.costUsd)})]},m))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-fg-faint uppercase tracking-wider mb-1.5",children:"tool mix"}),f.length===0?e.jsx("div",{className:"text-xs text-fg-faint",children:"no tool data"}):e.jsx("div",{className:"space-y-1",children:f.slice(0,6).map(([m,u])=>e.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[e.jsx("span",{className:"w-20 shrink-0 truncate text-fg-dim font-mono",children:m}),e.jsx("div",{className:"flex-1 h-1.5 rounded bg-bg-hi overflow-hidden",children:e.jsx("div",{className:"h-full bg-hive-teal",style:{width:`${l>0?u/l*100:0}%`}})}),e.jsx("span",{className:"text-fg-faint font-mono w-8 text-right",children:u})]},m))})]})]})]})}function O({label:t,value:s}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-fg-faint uppercase tracking-wider",children:t}),e.jsx("div",{className:"text-[17px] font-mono tracking-tight text-fg",children:s})]})}function _t({byModelTotals:t}){const s=Object.entries(t).sort((a,o)=>o[1].costUsd-a[1].costUsd),n=s.reduce((a,[,o])=>a+o.costUsd,0);return e.jsxs("div",{className:`${C} p-4`,children:[e.jsx(w,{kicker:"05 · composition",title:"Model mix",right:e.jsxs("span",{className:"text-xs font-mono text-fg-faint",children:[$(n)," total"]})}),s.length===0?e.jsx("div",{className:"text-xs text-fg-faint",children:"no model data in range"}):e.jsx("div",{className:"space-y-2",children:s.map(([a,o])=>{const c=n>0?o.costUsd/n*100:0,r=D(a);return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-0.5",children:[e.jsxs("span",{className:"flex items-center gap-1.5 font-mono text-fg-dim truncate",children:[e.jsx("span",{className:"w-2 h-2 rounded-sm shrink-0",style:{backgroundColor:r}}),me(a),o.estimated&&e.jsx("span",{className:"text-fg-faint",children:"(est.)"})]}),e.jsxs("span",{className:"text-fg-faint whitespace-nowrap ml-2",children:[$(o.costUsd)," · ",c.toFixed(0),"%"]})]}),e.jsx("div",{className:"h-1.5 rounded bg-bg-hi overflow-hidden",children:e.jsx("div",{className:"h-full",style:{width:`${Math.max(c,c>0?2:0)}%`,backgroundColor:r}})})]},a)})})]})}const Ot={epic:"Epic sessions",job:"Scheduler jobs",task:"Tasks",other:"Other sessions"};function Ht({byLauncherTotals:t}){const s=mt.map(a=>{var o;return[a,((o=t[a])==null?void 0:o.costUsd)??0]}),n=s.reduce((a,[,o])=>a+o,0);return e.jsxs("div",{className:`${C} p-4`,children:[e.jsx(w,{kicker:"05 · composition",title:"Launcher mix",right:e.jsxs("span",{className:"text-xs font-mono text-fg-faint",children:[$(n)," total"]})}),n<=0?e.jsx("div",{className:"text-xs text-fg-faint",children:"no usage in range"}):e.jsx("div",{className:"space-y-2",children:s.map(([a,o])=>{const c=o/n*100,r=D(a);return e.jsxs("div",{"data-testid":`history-launcher-${a}`,children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-0.5",children:[e.jsxs("span",{className:"flex items-center gap-1.5 font-mono text-fg-dim truncate",children:[e.jsx("span",{className:"w-2 h-2 rounded-sm shrink-0",style:{backgroundColor:r}}),Ot[a]]}),e.jsxs("span",{className:"text-fg-faint whitespace-nowrap ml-2",children:[$(o)," · ",c.toFixed(0),"%"]})]}),e.jsx("div",{className:"h-1.5 rounded bg-bg-hi overflow-hidden",children:e.jsx("div",{className:"h-full",style:{width:`${Math.max(c,c>0?2:0)}%`,backgroundColor:r}})})]},a)})})]})}function Bt({rows:t}){const s=t.slice(0,3),n=s.reduce((c,r)=>c+r.sharePct,0),a=t.slice(3),o=a.reduce((c,r)=>c+r.sharePct,0);return e.jsxs("div",{className:`${C} p-4`,children:[e.jsx(w,{kicker:"05 · composition",title:"Concentration",right:e.jsxs("span",{className:"text-xs font-mono text-fg-faint",children:["top 3 = ",n.toFixed(0),"%"]})}),t.length===0?e.jsx("div",{className:"text-xs text-fg-faint",children:"no projects in range"}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex h-3 rounded overflow-hidden mb-2",children:t.map(c=>e.jsx("div",{style:{width:`${Math.max(c.sharePct,.5)}%`,backgroundColor:D(c.projectDir)},title:`${H(c.projectDir)} · ${c.sharePct.toFixed(1)}%`},c.projectDir))}),e.jsx("div",{className:"space-y-1 mb-2",children:s.map(c=>e.jsxs("div",{className:"flex items-center justify-between text-[11px] font-mono",children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-fg-dim truncate",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:D(c.projectDir)}}),H(c.projectDir)]}),e.jsxs("span",{className:"text-fg-faint",children:[c.sharePct.toFixed(1),"%"]})]},c.projectDir))}),a.length>0&&e.jsxs("p",{className:"text-[10px] text-fg-faint",children:[a.length," more project",a.length===1?"":"s"," account for ",o.toFixed(1),"% (long tail)."]})]})]})}const Z=30,pe=9,A=(Z+pe)*2;function It({totals:t}){const s=t.inputTokens+t.cacheReadTokens+t.cacheCreationTokens,n=s>0?t.cacheReadTokens/s*100:0,a=2*Math.PI*Z,o=A/2;return e.jsxs("div",{className:`${C} p-4`,children:[e.jsx(w,{kicker:"05 · composition",title:"Cache"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"relative shrink-0",style:{width:A,height:A},children:[e.jsxs("svg",{width:A,height:A,viewBox:`0 0 ${A} ${A}`,className:"-rotate-90",children:[e.jsx("circle",{cx:o,cy:o,r:Z,fill:"none",stroke:"currentColor",className:"text-bg-hi",strokeWidth:pe}),e.jsx("circle",{cx:o,cy:o,r:Z,fill:"none",stroke:wt,strokeWidth:pe,strokeDasharray:a,strokeDashoffset:a*(1-n/100),strokeLinecap:"round"})]}),e.jsxs("div",{className:"absolute inset-0 flex items-center justify-center text-[13px] font-mono text-fg",children:[n.toFixed(0),"%"]})]}),e.jsxs("div",{className:"text-[11px] space-y-1 font-mono",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-fg-faint",children:"reused (cache read)"}),e.jsx("span",{className:"text-fg-dim",children:I(t.cacheReadTokens)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-fg-faint",children:"written to cache"}),e.jsx("span",{className:"text-fg-dim",children:I(t.cacheCreationTokens)})]})]})]})]})}const Wt=.05,qt="—",Ue=t=>`$${t.toFixed(2)}`;function Kt(){const[t,s]=p.useState(null),[n,a]=p.useState(null),o=Fe(r=>r.show);p.useEffect(()=>{let r=!0;const i=()=>{window.api.history.loopEfficiency().then(l=>{r&&(s(l),a(null))}).catch(l=>{if(!r)return;const d=l instanceof Error?l.message:String(l);a(d),o("error",`Loop efficiency failed to load: ${d}`)})};i();const f=window.api.history.onUpdated(i);return()=>{r=!1,f()}},[o]);let c;if(n&&!t)c=e.jsxs("div",{"data-testid":"loop-eff-error",className:"text-[11px] font-mono text-fg-faint",children:["Failed to load: ",n]});else if(!t)c=e.jsx("div",{"data-testid":"loop-eff-loading",className:"text-[11px] font-mono text-fg-faint",children:"Loading…"});else if(t.rows.length===0)c=e.jsx("div",{"data-testid":"loop-eff-empty",className:"text-[11px] font-mono text-fg-faint",children:"No runs this week."});else{const r=t.totals.wastedRunRate>Wt;c=e.jsxs(e.Fragment,{children:[e.jsxs("table",{className:"w-full text-[11px] font-mono","data-testid":"loop-eff-table",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-fg-faint text-left",children:[e.jsx("th",{className:"font-normal",children:"Project"}),e.jsx("th",{className:"font-normal text-right",children:"Runs"}),e.jsx("th",{className:"font-normal text-right",children:"Wasted"}),e.jsx("th",{className:"font-normal text-right",children:"Verified"}),e.jsx("th",{className:"font-normal text-right",children:"Refuted"}),e.jsx("th",{className:"font-normal text-right",children:"List-price $"}),e.jsx("th",{className:"font-normal text-right",children:"$ / verified"})]})}),e.jsx("tbody",{className:"text-fg-dim",children:t.rows.map(i=>e.jsxs("tr",{"data-testid":"loop-eff-row",children:[e.jsx("td",{children:i.project}),e.jsx("td",{className:"text-right",children:i.runs}),e.jsx("td",{className:"text-right",children:i.wastedRuns}),e.jsx("td",{className:"text-right",children:i.verified}),e.jsx("td",{className:"text-right",children:i.refuted}),e.jsx("td",{className:"text-right",children:Ue(i.executorUsd)}),e.jsx("td",{className:"text-right","data-testid":"loop-eff-per-verified",children:i.usdPerVerified==null?qt:Ue(i.usdPerVerified)})]},i.cwd))})]}),e.jsxs("div",{"data-testid":"loop-eff-totals","data-warning":r?"true":"false",className:`mt-2 text-[11px] font-mono ${r?"text-amber-300":"text-fg-dim"}`,children:["wasted runs ",(t.totals.wastedRunRate*100).toFixed(1),"% (",t.totals.wastedRuns,"/",t.totals.runs,") · target ≤ 5%"]}),e.jsx("div",{"data-testid":"loop-eff-usage",className:"mt-1 text-[11px] font-mono text-fg-faint",children:t.verifiedPerUsagePct!=null?`${t.verifiedPerUsagePct} verified PRDs per 1% of weekly usage`:"weekly usage unavailable"})]})}return e.jsxs("div",{className:`${C} p-4`,"data-testid":"loop-efficiency",children:[e.jsx(w,{kicker:"06 · reliability",title:"Loop efficiency"}),c]})}const J="—",Vt=Object.freeze({"not-landed":"nothing or the wrong thing was committed","gate-red":"a gate command fails","behavior-wrong":"runs but does not do what a criterion says","not-checked-live":"passes tests, wrong against real data or the real UI","missing-test":"a criterion or change has no test that checks it",regression:"breaks something that worked","spec-gap":"every criterion met but the goal is not",security:"introduces a security problem","docs-drift":"docs no longer match the code",other:"none of the above"}),Gt="Proposed for a human to approve: add it to standards.md or the validator persona through /develop.",Ae=t=>t==null?J:`${t}%`;function zt(t,s){switch(s){case"firstPass":return Ae(t.firstPass.pct);case"refuted":return Ae(t.refuted.pct);case"fixWaves":return t.fixWaves.perPlan==null?J:String(t.fixWaves.perPlan);case"escapes":return String(t.escapes.length)}}function Yt(t,s){switch(s){case"firstPass":return t.firstPass.prds;case"refuted":return t.refuted.prds;case"fixWaves":return t.fixWaves.plans.filter(n=>n.fixWaves.length>0).map(n=>`${n.plan}: ${n.fixWaves.join(", ")}`);case"escapes":return t.escapes.map(n=>`${n.fixPrd} fixes ${n.escapedPrd} — ${n.reason??J}`)}}const fe=[{key:"firstPass",label:"First-pass verified"},{key:"refuted",label:"Refuted"},{key:"fixWaves",label:"Fix waves / plan"},{key:"escapes",label:"Escapes"}];function Xt(){var f;const[t,s]=p.useState(null),[n,a]=p.useState(null),[o,c]=p.useState(null),r=Fe(l=>l.show);p.useEffect(()=>{let l=!0;const d=g=>{l&&(a(g),r("error",`Validation quality failed to load: ${g}`))},m=()=>{window.api.history.validationQuality().then(g=>{if(l){if(!g.ok)return d(g.error);s(g.projects),a(null)}}).catch(g=>d(g instanceof Error?g.message:String(g)))};m();const u=window.api.history.onUpdated(m);return()=>{l=!1,u()}},[r]);let i;if(n&&!t)i=e.jsxs("div",{"data-testid":"val-q-error",className:"text-[11px] font-mono text-fg-faint",children:["Failed to load: ",n]});else if(!t)i=e.jsx("div",{"data-testid":"val-q-loading",className:"text-[11px] font-mono text-fg-faint",children:"Loading…"});else if(t.length===0)i=e.jsx("div",{"data-testid":"val-q-empty",className:"text-[11px] font-mono text-fg-faint",children:"No validated PRDs yet."});else{const l=o?t.find(u=>u.cwd===o.cwd):void 0,d=o&&l?Yt(l,o.metric):null,m=t.filter(u=>u.week.topMiss||u.week.unclassified.count>0);i=e.jsxs(e.Fragment,{children:[e.jsxs("table",{className:"w-full text-[11px] font-mono","data-testid":"val-q-table",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-fg-faint text-left",children:[e.jsx("th",{className:"font-normal",children:"Project"}),fe.map(u=>e.jsx("th",{className:"font-normal text-right",children:u.label},u.key))]})}),e.jsx("tbody",{className:"text-fg-dim",children:t.map(u=>e.jsxs("tr",{"data-testid":"val-q-row",children:[e.jsx("td",{children:u.project}),fe.map(g=>{const y=(o==null?void 0:o.cwd)===u.cwd&&o.metric===g.key;return e.jsx("td",{className:"text-right",children:e.jsx("button",{type:"button","data-testid":`val-q-${g.key}`,"aria-expanded":y,className:"underline decoration-dotted hover:text-fg",onClick:()=>c(y?null:{cwd:u.cwd,metric:g.key}),children:zt(u,g.key)})},g.key)})]},u.cwd))})]}),o&&l&&d&&e.jsxs("div",{"data-testid":"val-q-detail",className:"mt-2 text-[11px] font-mono text-fg-dim",children:[e.jsxs("div",{className:"text-fg-faint",children:[l.project," · ",(f=fe.find(u=>u.key===o.metric))==null?void 0:f.label]}),d.length===0?e.jsx("div",{className:"text-fg-faint",children:"No PRDs."}):e.jsx("ul",{children:d.map(u=>e.jsx("li",{"data-testid":"val-q-detail-item",children:u},u))})]}),e.jsxs("div",{"data-testid":"val-q-week",className:"mt-3 text-[11px] font-mono text-fg-dim",children:[e.jsx("div",{className:"text-fg-faint",children:"This week"}),m.length===0?e.jsx("div",{"data-testid":"val-q-week-empty",children:"No validator misses this week."}):m.map(u=>{const g=u.week.topMiss,y=u.week.unclassified;return e.jsxs("div",{children:[g&&e.jsxs("div",{"data-testid":"val-q-top-miss",className:"mt-1",children:[e.jsxs("div",{children:[u.project,": ",e.jsx("span",{className:"text-fg",children:g.missKind})," — ",Vt[g.missKind]??J," ·"," ",g.count,"×"]}),e.jsxs("div",{children:["PRDs: ",g.prds.join(", ")]}),g.reasons.length>0&&e.jsx("ul",{className:"list-disc pl-4",children:g.reasons.slice(0,5).map(v=>e.jsx("li",{"data-testid":"val-q-reason",children:v},v))}),e.jsxs("div",{"data-testid":"val-q-proposal",children:["Proposed check: ",g.proposal]}),e.jsx("div",{className:"text-fg-faint",children:Gt})]}),y.count>0&&e.jsxs("div",{"data-testid":"val-q-unclassified",className:"mt-1",children:[e.jsxs("div",{children:[u.project,": Not classified (recorded before checked verdicts): ",y.count]}),e.jsxs("div",{children:["PRDs: ",y.prds.join(", ")]}),y.reasons.length>0&&e.jsx("ul",{className:"list-disc pl-4",children:y.reasons.slice(0,5).map(v=>e.jsx("li",{"data-testid":"val-q-unclassified-reason",children:v},v))})]})]},u.cwd)})]})]})}return e.jsxs("div",{className:`${C} p-4`,"data-testid":"validation-quality",children:[e.jsx(w,{kicker:"07 · reliability",title:"Validation quality"}),i]})}const Qt=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function Zt({days:t,measure:s}){const{buckets:n,weekendShare:a,peakIdx:o}=p.useMemo(()=>{const r=new Array(7).fill(0);for(const d of t){const[m,u,g]=d.date.split("-").map(Number),y=new Date(m,u-1,g).getDay();r[y]+=E(d.totals,s)}const i=r.reduce((d,m)=>d+m,0),f=r[0]+r[6];let l=0;for(let d=1;d<7;d++)r[d]>r[l]&&(l=d);return{buckets:r,weekendShare:i>0?f/i*100:0,peakIdx:l}},[t,s]),c=Math.max(...n,1);return e.jsxs("div",{className:`${C} p-4`,children:[e.jsx(w,{kicker:"05 · composition",title:"Rhythm",right:e.jsxs("span",{className:"text-xs font-mono text-fg-faint",children:["weekend ",a.toFixed(0),"%"]})}),e.jsx("div",{className:"flex items-end gap-2 h-24",children:n.map((r,i)=>e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-end gap-1 h-full",children:[e.jsx("div",{className:`w-full rounded-t ${i===o?"bg-accent":"bg-rhythm"}`,style:{height:`${c>0?r/c*100:0}%`,minHeight:r>0?2:0}}),e.jsx("span",{className:"text-[9px] text-fg-faint font-mono",children:Qt[i]})]},i))})]})}const Jt=["in","out","total","prompts","sessions","time","spend"],es=[30,60,90,0],ts="spend",ss=30,ns=3e4,os=[];function as(){var Te;const[t,s]=p.useState(ts),[n,a]=p.useState(ss),o=p.useRef(!1),c=p.useRef(!1),r=h=>{o.current=!0;const k=t;s(h),he({measure:h}).catch(()=>{s(k),X.error("Couldn't save the measure preference — reverted.")})},i=h=>{c.current=!0;const k=n;a(h),he({range:h}).catch(()=>{a(k),X.error("Couldn't save the range preference — reverted.")})};p.useEffect(()=>{let h=!1;return ge().then(k=>{h||(!o.current&&k.measure&&Jt.includes(k.measure)&&s(k.measure),!c.current&&k.range!==void 0&&es.includes(k.range)&&a(k.range))}),()=>{h=!0}},[]);const f=tt(h=>h.navFace),l=Ce(h=>h.tabs),d=Ce(h=>h.activeTabId),m=((Te=l.find(h=>h.id===d))==null?void 0:Te.cwd)??null,u=p.useRef(f),g=m?st(m):null,[y,v]=p.useState(null),x=p.useMemo(()=>f==="project"&&g?new Set([g]):y,[f,g,y]),[b,P]=p.useState(null),[j,ee]=p.useState(null),[q,W]=p.useState(!0),[te,se]=p.useState(0),ne=p.useRef(n);ne.current=n;const K=p.useRef(!0),oe=p.useRef(0),je=p.useRef(0),L=p.useRef(null),V=p.useCallback(h=>{const k=ne.current;oe.current+=1,je.current=Date.now(),rt(k).then(N=>{if(oe.current-=1,!(!K.current||k!==ne.current)){if(W(!1),N.ok){ee(N.data);return}h||X.error(`History analytics failed to load: ${N.error}`)}})},[]);p.useEffect(()=>{K.current=!0,W(!0),V(!1)},[n,te,V]),p.useEffect(()=>{const h=()=>{if(!K.current)return;const R=je.current+ns-Date.now();if(oe.current===0&&R<=0){V(!0);return}L.current||(L.current=setTimeout(()=>{L.current=null,h()},Math.max(R,1e3)))},k=()=>{document.visibilityState==="visible"&&h()},N=window.api.history.onUpdated(h);return window.addEventListener("focus",h),document.addEventListener("visibilitychange",k),()=>{K.current=!1,N(),window.removeEventListener("focus",h),document.removeEventListener("visibilitychange",k),L.current&&(clearTimeout(L.current),L.current=null)}},[V]);const ve=p.useRef(!1);p.useEffect(()=>{if(!ve.current){ve.current=!0;return}v(null),P(null)},[n]),p.useEffect(()=>{u.current!==f&&(u.current=f,f==="home"&&v(null))},[f]);const{projects:be,resolving:ke}=nt(),ye=p.useMemo(()=>{const h={};for(const k of be)for(const N of k.encodedIds)h[N]=k.cwd;return h},[be]),F=p.useMemo(()=>j&&!ke?vt(j.days,ye):null,[j,ye,ke]),S=(F==null?void 0:F.days)??(j==null?void 0:j.days)??os,ae=(F==null?void 0:F.excluded)??null,M=p.useMemo(()=>j?it({days:S,totals:j.totals,prevTotals:j.prevTotals},x):null,[j,S,x]),_=p.useMemo(()=>x===null?S:S.map(h=>({date:h.date,byProject:Object.fromEntries(Object.entries(h.byProject).filter(([k])=>x.has(k)))})),[S,x]),G=p.useMemo(()=>Se(S,t),[S,t]),re=p.useMemo(()=>Se(_,t),[_,t]),We=p.useMemo(()=>_.map(h=>({date:h.date,values:Object.fromEntries(Object.entries(h.byProject).map(([k,N])=>[k,E(N,t)]))})),[_,t]),Ne=p.useMemo(()=>M?ft(M,t):null,[M,t]),z=p.useMemo(()=>{if(!j||!b)return null;const h=S.flatMap(T=>T.byProject[b]?[T.byProject[b]]:[]),{byModel:k,...N}=Re(h),R={};for(const T of h)for(const[U,ce]of Object.entries(T.toolBreakdown))R[U]=(R[U]??0)+ce;return{totals:N,byModel:k,toolBreakdown:R}},[j,S,b]);p.useEffect(()=>{b&&x!==null&&!x.has(b)&&P(null)},[b,x]);function qe(h){v(k=>{const N=new Set(G.map(U=>U.projectDir)),R=k??new Set(N),T=new Set(R);return T.has(h)?T.delete(h):T.add(h),T.size>=N.size?null:T})}function Ke(h){v(new Set([h]))}function Ve(){v(null)}function Ge(){if(!j)return;const h=_.map(U=>{const{byModel:ce,estimatedCostUsd:ze,inputTokens:Ye,outputTokens:Xe,cacheCreationTokens:Qe,cacheReadTokens:Ze}=Re(Object.values(U.byProject));return{date:U.date,costUsd:ze,inputTokens:Ye,outputTokens:Xe,cacheCreationTokens:Qe,cacheReadTokens:Ze,byModel:ce}}),k=pt(h),N=new Blob([k],{type:"text/csv"}),R=URL.createObjectURL(N),T=document.createElement("a");T.href=R,T.download=`usage-history-${j.from}-${j.to}.csv`,T.click(),URL.revokeObjectURL(R)}return q&&!j?e.jsx(Le,{}):j&&j.days.length===0?e.jsx(ot,{title:"no sessions in range",hint:"Widen the range or check back after your next session."}):!j||!M||!Ne?e.jsx(Le,{}):e.jsxs("div",{"data-testid":"history-dashboard",className:"flex flex-col h-full",children:[e.jsxs("h1",{className:"font-serif text-[42px] leading-tight tracking-tight text-fg px-4 pt-4",children:["Where your ",e.jsx("em",{className:"italic text-accent",children:"Claude time"})," goes"]}),e.jsx(Tt,{measure:t,onMeasure:r,range:n,onRange:i,projectsShown:x===null?G.length:x.size,projectsTotal:G.length,fromDate:j.from,toDate:j.to,onRefresh:()=>se(h=>h+1),onExport:Ge,exportDisabled:_.length===0}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-4 space-y-4",children:[e.jsx(Rt,{measure:t,headline:Ne,activeDays:M.activeDays,projectsTouched:re.length,totalSessions:M.totals.sessionCount}),e.jsx($t,{days:S}),ae&&bt(ae)&&e.jsx("div",{"data-testid":"history-excluded-note",className:"rounded-[10px] border border-line bg-bg-hi px-3 py-2 text-[11.5px] font-mono text-fg-faint",title:"A project is a working directory. ~/.claude/projects holds one folder per path the CLI was ever launched from — throwaway /tmp dirs and test fixtures included — and a folder whose cwd can't be recovered from its transcripts is not a project. Their totals are stated here rather than silently folded into the charts.",children:kt(ae)}),j.legacyDates&&j.legacyDates.length>0&&e.jsx("div",{"data-testid":"history-legacy-note",className:"rounded-[10px] border border-line bg-bg-hi px-3 py-2 text-[11.5px] font-mono text-fg-faint",children:rs(j.legacyDates)}),f==="home"&&e.jsx(Et,{chips:G.map(h=>({projectDir:h.projectDir,value:h.value})),keep:x,onToggle:qe,onIsolate:Ke,onShowAll:Ve}),e.jsx(At,{days:We,measure:t,selected:b,onSelect:P}),e.jsx(Lt,{rows:re,measure:t,selected:b,onSelect:P}),b&&z&&e.jsx(Ft,{projectDir:b,totals:z.totals,byModel:z.byModel,toolBreakdown:z.toolBreakdown,onClear:()=>P(null)}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(_t,{byModelTotals:M.byModelTotals}),e.jsx(Ht,{byLauncherTotals:M.byLauncherTotals}),e.jsx(Bt,{rows:re}),e.jsx(It,{totals:M.totals}),e.jsx(Zt,{days:M.days,measure:t})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsx(Kt,{}),e.jsx(Xt,{})]})]})]})}function rs(t){const s=t.reduce((a,o)=>o>a?o:a),n=t.length;return`${n} ${n===1?"day":"days"} in this range (last: ${s}) were counted with the older method and read about two to three times too high; they cannot be recounted because their transcripts are gone.`}function Le(){return e.jsxs("div",{className:"p-4 space-y-4 animate-pulse",children:[e.jsx("div",{className:"h-24 bg-bg-elev rounded"}),e.jsx("div",{className:"h-16 bg-bg-elev rounded"}),e.jsx("div",{className:"h-8 bg-bg-elev rounded"}),e.jsx("div",{className:"h-56 bg-bg-elev rounded"}),e.jsx("div",{className:"h-40 bg-bg-elev rounded"})]})}function cs(){return e.jsx(at,{children:e.jsx(as,{})})}const fs=p.memo(cs);export{fs as History};
|