clinkx 1.4.0 → 1.4.2
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/CHANGELOG.md +35 -0
- package/clinkx-workflows/dist/dashboard-ui/assets/{index-DSOtuS0p.js → index-CX4FrhYN.js} +1 -1
- package/clinkx-workflows/dist/dashboard-ui/index.html +1 -1
- package/clinkx-workflows/dist/settings/registry.js +5 -0
- package/clinkx-workflows/dist/settings/registry.js.map +1 -1
- package/dist/dashboard-cli.d.ts +11 -3
- package/dist/dashboard-cli.js +149 -32
- package/dist/dashboard-cli.js.map +1 -1
- package/dist/dashboard-companion/client.d.ts +14 -0
- package/dist/dashboard-companion/client.js +16 -0
- package/dist/dashboard-companion/client.js.map +1 -1
- package/dist/dashboard-companion/credential-expectation.d.ts +23 -0
- package/dist/dashboard-companion/credential-expectation.js +50 -0
- package/dist/dashboard-companion/credential-expectation.js.map +1 -0
- package/dist/dashboard-companion/host-channel.d.ts +36 -0
- package/dist/dashboard-companion/host-channel.js +78 -0
- package/dist/dashboard-companion/host-channel.js.map +1 -0
- package/dist/dashboard-companion/host-status.d.ts +179 -0
- package/dist/dashboard-companion/host-status.js +122 -0
- package/dist/dashboard-companion/host-status.js.map +1 -0
- package/dist/dashboard-companion/standalone-assets.d.ts +8 -0
- package/dist/dashboard-companion/standalone-assets.js +7 -1
- package/dist/dashboard-companion/standalone-assets.js.map +1 -1
- package/dist/dashboard-companion/standalone-entry.js +34 -13
- package/dist/dashboard-companion/standalone-entry.js.map +1 -1
- package/dist/desktop-host/child-env.d.ts +23 -0
- package/dist/desktop-host/child-env.js +70 -0
- package/dist/desktop-host/child-env.js.map +1 -0
- package/dist/desktop-host/daemon-entry.d.ts +2 -0
- package/dist/desktop-host/daemon-entry.js +50 -0
- package/dist/desktop-host/daemon-entry.js.map +1 -0
- package/dist/desktop-host/daemon-env.d.ts +12 -0
- package/dist/desktop-host/daemon-env.js +35 -0
- package/dist/desktop-host/daemon-env.js.map +1 -0
- package/dist/desktop-host/daemon-protocol.d.ts +210 -0
- package/dist/desktop-host/daemon-protocol.js +56 -0
- package/dist/desktop-host/daemon-protocol.js.map +1 -0
- package/dist/desktop-host/daemon.d.ts +50 -0
- package/dist/desktop-host/daemon.js +441 -0
- package/dist/desktop-host/daemon.js.map +1 -0
- package/dist/desktop-host/enrollment.d.ts +17 -0
- package/dist/desktop-host/enrollment.js +25 -0
- package/dist/desktop-host/enrollment.js.map +1 -0
- package/dist/desktop-host/import.d.ts +14 -0
- package/dist/desktop-host/import.js +95 -0
- package/dist/desktop-host/import.js.map +1 -0
- package/dist/desktop-host/profile.d.ts +130 -0
- package/dist/desktop-host/profile.js +176 -0
- package/dist/desktop-host/profile.js.map +1 -0
- package/dist/desktop-host/service.d.ts +6 -0
- package/dist/desktop-host/service.js +7 -0
- package/dist/desktop-host/service.js.map +1 -0
- package/dist/desktop-host/supervisor.d.ts +57 -0
- package/dist/desktop-host/supervisor.js +256 -0
- package/dist/desktop-host/supervisor.js.map +1 -0
- package/dist/desktop-host/view-state.d.ts +138 -0
- package/dist/desktop-host/view-state.js +27 -0
- package/dist/desktop-host/view-state.js.map +1 -0
- package/dist/registry.d.ts +7 -0
- package/dist/registry.js +21 -7
- package/dist/registry.js.map +1 -1
- package/docs/verification/README.md +28 -2
- package/docs/verification/workflow-handoff.md +86 -0
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,40 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## Unreleased
|
|
4
|
+
|
|
5
|
+
- Nothing yet.
|
|
6
|
+
|
|
7
|
+
## 1.4.2 — 2026-11-09
|
|
8
|
+
|
|
9
|
+
### Fixed
|
|
10
|
+
|
|
11
|
+
- The desktop app's in-window Quit button did nothing: it invoked a command name that does not exist (`quit` instead of `quit_command`), and the failed call was swallowed silently. A failed quit now surfaces in the notice bar. (Menu-bar Quit and ⌘Q were unaffected.)
|
|
12
|
+
|
|
13
|
+
## 1.4.1 — 2026-11-09
|
|
14
|
+
|
|
15
|
+
### Added
|
|
16
|
+
|
|
17
|
+
- ClinkX desktop app (`desktop/`, a thin Tauri 2 shell) that installs and supervises the dashboard companion without Docker: keychain-stored workstation key, validated folder setup, private enrollment-code display, connection status with tray lifecycle, explicit recovery actions, and Docker-state import. The same Node 26 executable runs the **host daemon** (`--host-daemon`), supervising a child of itself, so the shipped artifact is one binary for both roles and all launcher logic stays inside the repository's TypeScript tests. Docs in `docs/desktop-companion.md`; macOS arm64 first. Release artifacts are Developer ID signed and notarized (see the signed distribution entry below); local `npm run package` builds stay ad-hoc signed.
|
|
18
|
+
- `clinkx-workflows-dashboard --host-managed`: a versioned newline-delimited JSON status channel on stdout for a supervising launcher, including the transient enrollment code (stderr stays the log channel); graceful shutdown when the host closes stdin. Readers ignore unknown event types and refuse foreign versions.
|
|
19
|
+
- `clinkx-workflows-dashboard --credential-expectation <bootstrap|existing-enrolled>`: Docker's enrolled-store rule for native launches. A recorded enrolled profile whose store is missing — including loss of both credential and binding directories — fails closed instead of silently restarting enrollment. Docker's `DASHBOARD_CREDENTIAL_BOOTSTRAP_MODE` preflight is unchanged.
|
|
20
|
+
- Standalone companion qualification: the SEA build floor is official Node 26 LTS (Node 25 is EOL; Homebrew Node ships SEA disabled and now fails with guidance), postject runs through its JavaScript CLI so the Windows fallback needs no shell, and the build records `version/platform/node/sha256` beside the executable. A clean-room suite runs the real executable with an empty environment and no Node on `PATH`, and a hosted macOS CI job builds and retains it.
|
|
21
|
+
- `deploy/dashboard-companion/export-state.sh`: exports a stopped Docker companion's passkey store and workstation binding for the desktop app's import.
|
|
22
|
+
- Signed desktop distribution: a `release` CI job (on `v*` tags, or workflow_dispatch with `release`) builds the companion SEA with the Developer ID identity, packages, notarizes, and staples the .app and DMG, hard-verifies the result, and emits the `/download` channel documents (DMG, updater archive and signature, `latest.json`, `manifest.json` with per-file sha256 and the embedded Node version). Third-party notices ship inside the app. `scripts/release/sync-download-channel.mjs` verifies a release against its manifest and publishes it into the download volume with the updater pointer flipped last.
|
|
23
|
+
- Hosted static server: `CLINKX_DASHBOARD_DOWNLOAD_ROOT` serves a mounted volume under `/download` without authentication — per-request file admission (one safe path segment, regular files only), typed attachments, single byte ranges, `no-store` pointers, and a landing page rendered from the release manifest.
|
|
24
|
+
- In-app updates: the desktop app checks the channel at launch, prompts with the offered version, downloads and verifies on consent against the pinned ed25519 key, and installs at quit. Killed downloads and never-installed packages are swept at the next launch; a failed install is reported once and offered again. SIGTERM now quits gracefully (companion stop, then any consented install).
|
|
25
|
+
|
|
26
|
+
### Changed
|
|
27
|
+
|
|
28
|
+
- `scripts/build-dashboard-standalone.mjs --codesign-identity <name>` signs with the hardened runtime, a secure timestamp, and entitlements derived from the embedded Node runtime (V8 cannot reserve its code range under the hardened runtime without them; `get-task-allow` and DYLD injection are dropped), and every build now self-tests `--help` before its record is written. The build record gains `signing`.
|
|
29
|
+
- Desktop app: non-production bundle identifiers (QA builds) use their own keychain item, so a test copy can never read or replace the production workstation key; the production item is unchanged.
|
|
30
|
+
|
|
31
|
+
### Fixed
|
|
32
|
+
|
|
33
|
+
- A desktop shell started through a symlinked path fell back to a bare `clinkx-dashboard` on `PATH` and reported a misleading ENOENT. The PATH fallback is gone; the error now names the cause.
|
|
34
|
+
|
|
35
|
+
- The standalone executable ignored the user adapter tiers (`~/.clinkx/adapters`, XDG) and failed startup for any adapter override referencing a shipped `prompt_file`. Discovery and the shipped prompt fallback now resolve from the extracted runtime tree while `CLINKX_CONFIG_PATH` keeps its npm meaning.
|
|
36
|
+
- The gateway client exposes its connection progress to observers only (a refused upgrade carries its HTTP status); protocol behavior is unchanged.
|
|
37
|
+
|
|
3
38
|
## 1.4.0 — 2026-11-06
|
|
4
39
|
|
|
5
40
|
### Upgrade notes
|
|
@@ -119,4 +119,4 @@ ${t}
|
|
|
119
119
|
`).map(t=>t.trim()).filter(t=>t!=="")}function xL(e,t){return e===void 0?"unset":typeof e=="boolean"?e?"on":"off":typeof e=="string"?e===""?"unset":e:typeof e=="number"?t===""?String(e):`${String(e)} ${t}`:e.length===0?"empty list":`${String(e.length)} ${t===""?"entries":t}`}function wL(e,t,s){const i=new Map(s.map(m=>[m.key,m])),o=[],u=new Set,f=[];for(const[m,g]of Object.entries(t)){const h=i.get(m);if(h===void 0||h.settingClass==="secret")continue;const b=e.values[m];if(g.kind==="unset"){if(b===void 0)continue;o.push({key:m,action:"unset"}),u.add(h.settingClass),f.push(m);continue}Bs(g.value,b)||(o.push({key:m,action:"set",value:g.value}),u.add(h.settingClass),f.push(m))}return{ops:o,classesTouched:[...u],requiresStepUp:u.has("policy"),touchedKeys:f}}function d0(e,t){const s=new Map(t.map(i=>[i.key,i]));return e.map(i=>{const u=s.get(i.key)?.settingClass==="secret";return i.value===void 0||u?{key:i.key,action:i.action}:{key:i.key,action:i.action,value:i.value}})}function SL(e,t){return e==="policy"||e==="secret"?t==="passkey":!0}function og(e){return e==="none"?"This dashboard runs without authentication, so policy and secret changes are unavailable. Start the dashboard in passkey mode to edit them.":"Policy and secret changes need a passkey step-up, which is unavailable while signed in with a bearer token. Reconnect in passkey mode to edit them."}function jL(e,t){const s={},i={},o={},u=new Set,f=new Set,m=new Set;let g=0,h=0,b=0,x=!1;for(const N of e){N.liveness==="stale"&&(g+=1),N.liveness==="live"&&(h+=1),N.liveness==="live"&&!N.current&&(b+=1),N.settingsState==="unreadable"&&(x=!0);const w=new Set(N.shadowedKeys);for(const k of N.envEqualsFileKeys)w.add(k);if(N.liveness==="stale"){for(const k of N.shadowedKeys)o[k]=(o[k]??0)+1;for(const k of w)u.add(k)}else{for(const k of N.shadowedKeys)s[k]=(s[k]??0)+1;for(const k of w)i[k]=(i[k]??0)+1}for(const k of N.unknownEnvKeys)f.add(k);for(const k of N.invalidFallbackKeys)m.add(k)}return{shadowCounts:s,envOverrideCounts:i,envOverrideKeys:Object.keys(i).sort(),staleShadowCounts:Object.fromEntries(Object.entries(o).filter(([N])=>i[N]===void 0)),staleEnvOverrideKeys:[...u].filter(N=>i[N]===void 0).sort(),unknownEnvKeys:[...f].sort(),invalidFallbackKeys:[...m].sort(),staleProcessCount:g,liveProcessCount:h,restartRequiredCount:b,anyUnreadable:x,truncated:t}}function NL(e,t){return[...new Set([...Object.keys(e),...Object.keys(t)])].filter(i=>!Bs(e[i],t[i])).sort()}function kL({applicationRootId:e,onDiscard:t,onKeepEdits:s,open:i,remoteKeys:o}){return r.jsx(Ei,{applicationRootId:e,labelledBy:"settings-conflict-title",onClose:s,open:i,children:r.jsxs("section",{className:"settings-dialog",children:[r.jsx("h2",{id:"settings-conflict-title",children:"Settings changed elsewhere"}),r.jsx("p",{children:"Another writer saved the settings document before this save landed. Your edits are kept and listed against the new revision below."}),o.length===0?r.jsx("p",{children:"The revision moved but no tracked value differs."}):r.jsx("ul",{className:"settings-dialog__keys",children:o.map(u=>r.jsx("li",{children:r.jsx("code",{children:u})},u))}),r.jsxs("div",{className:"settings-dialog__actions",children:[r.jsx("button",{onClick:s,type:"button",children:"keep my edits on the new revision"}),r.jsx("button",{className:"settings-dialog__danger",onClick:t,type:"button",children:"discard my edits"})]})]})})}function AL(e){return e.liveness==="stale"?"stale — not observed recently":e.liveness==="unknown"?"liveness unknown (foreign host)":"live"}function EL(e){return e.current?"current":e.liveness==="live"?"older revision — restart to apply":"not current (not live)"}function RL(e){return[...new Set([...e.shadowedKeys,...e.envEqualsFileKeys])]}function TL({keys:e}){return e.length===0?null:r.jsxs("details",{className:"settings-processes__shadowed",children:[r.jsx("summary",{children:`env overrides: ${String(e.length)} key${e.length===1?"":"s"}`}),e.join(", ")]})}function CL({currentRevision:e,processes:t,projection:s}){const i=t.length-s.liveProcessCount-s.staleProcessCount;return r.jsxs("section",{className:"settings-processes","aria-labelledby":"settings-processes-title",children:[r.jsx("h2",{id:"settings-processes-title",children:"Processes"}),r.jsx("p",{className:"settings-processes__summary",children:`liveness ${String(s.liveProcessCount)} live · ${String(s.staleProcessCount)} stale · ${String(i)} unknown · current revision ${e===null?"none (no document)":String(e)}`}),s.staleProcessCount>0?r.jsx("p",{className:"settings-processes__stale",role:"note",children:`${String(s.staleProcessCount)} process${s.staleProcessCount===1?"":"es"} not observed recently — reconnect each in your MCP client (/mcp) if it should still be running`}):null,s.restartRequiredCount>0?r.jsx("p",{className:"settings-processes__restart",role:"note",children:`${String(s.restartRequiredCount)} live process${s.restartRequiredCount===1?"":"es"} running an older revision — restart required to apply newer settings`}):null,s.envOverrideKeys.length>0?r.jsx("p",{className:"settings-processes__overrides",role:"note",children:`env overrides in effect: ${s.envOverrideKeys.join(", ")}`}):null,s.staleEnvOverrideKeys.length>0?r.jsx("p",{className:"settings-processes__overrides",role:"note",children:`env overrides reported only by processes not observed recently, so they may no longer apply: ${s.staleEnvOverrideKeys.join(", ")}`}):null,t.length===0?r.jsx("p",{className:"settings-processes__empty",children:"no process heartbeats found yet"}):r.jsx("ul",{className:"settings-processes__list",children:t.map(o=>r.jsxs("li",{className:"settings-processes__row","data-current":o.current?"true":void 0,"data-liveness":o.liveness,children:[r.jsxs("span",{className:"settings-processes__id",children:[r.jsx("code",{children:o.entry}),` · ${o.host} · pid ${String(o.pid)}`]}),r.jsx("span",{className:"settings-processes__rev",children:o.loadedRevision===null?"no document loaded":`revision ${String(o.loadedRevision)}`}),r.jsx("span",{className:"settings-processes__freshness",children:EL(o)}),r.jsx("span",{className:"settings-processes__liveness",children:AL(o)}),o.settingsState==="off"?r.jsx("span",{className:"settings-processes__off",children:"settings loading disabled (CLINKX_SETTINGS=off)"}):null,r.jsx(TL,{keys:RL(o)}),o.invalidFallbackKeys.length>0?r.jsx("span",{className:"settings-processes__invalid",children:`invalid file value fell back: ${o.invalidFallbackKeys.join(", ")}`}):null,o.warnings.map((u,f)=>r.jsx("span",{className:"settings-processes__warning",children:u},f))]},o.id))}),s.unknownEnvKeys.length>0?r.jsx("p",{className:"settings-processes__unknown",role:"note",children:`unknown CLINKX_* env names (typos or dead vars): ${s.unknownEnvKeys.join(", ")}`}):null,s.truncated?r.jsx("p",{className:"settings-processes__truncated",children:"list truncated at the process cap"}):null]})}function OL({changeCount:e,classesTouched:t,checking:s,disabled:i,hasTextErrors:o,onDiscard:u,onSave:f,requiresStepUp:m,saving:g,stepUpBlocked:h}){const b=s?"checking whether the save landed…":g?"saving…":`save ${String(e)} change${e===1?"":"s"}`;return r.jsxs("div",{className:"settings-savebar","data-visible":e>0||s?"true":void 0,children:[r.jsx("span",{className:"settings-savebar__summary",children:e===0?"no pending changes":`${String(e)} pending · ${t.join(", ")}`}),m?r.jsx("span",{className:"settings-savebar__stepup",children:"passkey step-up required"}):null,r.jsx("span",{className:"settings-savebar__restart",children:"restart required to apply"}),o?r.jsx("span",{className:"settings-savebar__error",role:"alert",children:"fix the highlighted values before saving"}):null,r.jsx("button",{className:"settings-savebar__discard",disabled:g||s||e===0,onClick:u,type:"button",children:"discard edits"}),r.jsx("button",{className:"settings-savebar__save",disabled:i||g||s||e===0||o,onClick:f,type:"button",children:b}),h?r.jsx("span",{className:"settings-savebar__blocked",children:"policy/secret changes need passkey mode"}):null]})}function $L({disabled:e,labelId:t,onChange:s,value:i}){return r.jsxs("div",{"aria-labelledby":t,className:"settings-segmented",role:"group",children:[r.jsx("button",{"aria-pressed":i,className:"settings-segmented__option","data-state":i?"on":"off",disabled:e,onClick:()=>s(!0),type:"button",children:"on"}),r.jsx("button",{"aria-pressed":!i,className:"settings-segmented__option","data-state":i?"off":"on",disabled:e,onClick:()=>s(!1),type:"button",children:"off"})]})}function IL({choices:e,disabled:t,id:s,labelledBy:i,onChange:o,value:u}){return r.jsx("select",{"aria-labelledby":i,className:"settings-select",disabled:t,id:s,onChange:f=>o(f.currentTarget.value),value:u,children:e.map(f=>r.jsx("option",{value:f,children:f},f))})}function ML({describedBy:e,disabled:t,id:s,labelledBy:i,onChange:o,text:u}){return r.jsx("textarea",{"aria-describedby":e,"aria-labelledby":i,className:"settings-list",disabled:t,id:s,onChange:f=>o(f.currentTarget.value),rows:Math.min(6,Math.max(3,u.split(`
|
|
120
120
|
`).length)),spellCheck:!1,value:u,wrap:"off"})}function LL({describedBy:e,disabled:t,id:s,invalid:i,labelledBy:o,onChange:u,text:f,unit:m}){return r.jsxs("span",{className:"settings-number",children:[r.jsx("input",{"aria-describedby":e,"aria-invalid":i?!0:void 0,"aria-labelledby":o,className:"settings-number__input",disabled:t,id:s,inputMode:"numeric",onChange:g=>u(g.currentTarget.value),type:"text",value:f}),m===""?null:r.jsx("span",{"aria-hidden":"true",className:"settings-number__unit",children:m})]})}function DL({describedBy:e,disabled:t,busy:s,checking:i,error:o,id:u,isSet:f,labelledBy:m,onChange:g,onClear:h,onSet:b,updatedAt:x,value:N}){const w=`${u}-error`,k=o===void 0?e:e===void 0?w:`${e} ${w}`;return r.jsxs("div",{className:"settings-secret",children:[r.jsx("p",{className:"settings-secret__state","data-set":f?"true":"false",children:f?`set${x===void 0?"":` · updated ${x}`}`:"not set"}),r.jsxs("span",{className:"settings-secret__fields",children:[r.jsx("input",{"aria-describedby":k,"aria-invalid":o!==void 0?!0:void 0,"aria-labelledby":m,autoComplete:"new-password",className:"settings-secret__input",disabled:t||s,id:u,onChange:S=>g(S.currentTarget.value),placeholder:"write-only · paste a new value",type:"password",value:N}),r.jsx("button",{className:"settings-secret__action",disabled:t||s||N==="",onClick:b,type:"button",children:f?"replace value":"set value"}),f?r.jsx("button",{className:"settings-secret__action settings-secret__action--danger",disabled:t||s,onClick:h,type:"button",children:"clear"}):null]}),s?r.jsx("p",{className:"settings-secret__status",role:"status",children:i?"checking whether the secret save landed…":"saving secret…"}):null,o!==void 0?r.jsx("p",{className:"settings-secret__error",id:w,role:"alert",children:o}):null]})}function qL(e){return e==="file"?"file value":e==="draft"?"edited":"default"}function zL(e){return e===void 0?"":typeof e=="number"?String(e):typeof e=="string"?e:typeof e=="boolean"?"":e.join(`
|
|
121
121
|
`)}function UL({row:e,authBlocked:t,blockedMessage:s,busy:i,fieldError:o,textDraft:u,secretBusy:f,secretChecking:m,secretError:g,secretState:h,secretValue:b,onBool:x,onText:N,onReset:w,onSecretInput:k,onSecretSet:S,onSecretClear:A}){const{descriptor:$}=e,T=v.useId(),C=`${T}-label`,M=`${T}-control`,R=`${T}-hint`,O=`${T}-error`,G=$.settingClass==="secret",B=t||i||$.control==="unsupported",te=u??zL(e.effectiveValue),K=$.control==="unsupported"?xL(e.effectiveValue,$.unit):void 0;return r.jsxs("div",{className:"settings-row","data-dirty":e.dirty?"true":void 0,"data-key":$.key,children:[r.jsxs("div",{className:"settings-row__head",children:[r.jsx("span",{className:"settings-row__title",id:C,children:$.docs.title}),r.jsx("code",{className:"settings-row__key",children:$.key}),r.jsx("span",{className:"settings-row__source","data-source":e.source,children:qL(e.source)}),e.dirty?r.jsx("span",{className:"settings-row__dirty",children:"edited"}):null]}),r.jsx("p",{className:"settings-row__summary",children:$.docs.summary}),e.shadowedByEnvCount>0?r.jsx("p",{className:"settings-row__shadowed",children:`overridden by env in ${String(e.shadowedByEnvCount)} process${e.shadowedByEnvCount===1?"":"es"} — edit the environment to change it here`}):e.staleShadowedByEnvCount>0?r.jsx("p",{className:"settings-row__shadowed",children:`env override reported by ${String(e.staleShadowedByEnvCount)} process${e.staleShadowedByEnvCount===1?"":"es"} not observed recently — it may no longer apply`}):null,$.control==="unsupported"?r.jsx("p",{className:"settings-row__unsupported",children:`read-only in this dashboard: value ${K} (control type “${$.type}” needs a newer dashboard)`}):G?r.jsx(DL,{busy:f||i,checking:m,describedBy:R,disabled:t,error:g,id:M,isSet:h?.set??!1,labelledBy:C,onChange:k,onClear:A,onSet:S,...h?.updatedAt===void 0?{}:{updatedAt:h.updatedAt},value:b}):r.jsxs("div",{className:"settings-row__control",children:[$.control==="bool"?r.jsx($L,{disabled:B,labelId:C,onChange:x,value:e.effectiveValue===!0}):null,$.control==="enum"?r.jsx(IL,{choices:$.choices??[],disabled:B,id:M,labelledBy:C,onChange:N,value:typeof e.effectiveValue=="string"?e.effectiveValue:""}):null,$.control==="int"?r.jsx(LL,{describedBy:R,disabled:B,id:M,invalid:o!==void 0,labelledBy:C,onChange:N,text:te,unit:$.unit}):null,$.control==="string"||$.control==="url"?r.jsx("input",{"aria-describedby":R,"aria-invalid":o!==void 0?!0:void 0,"aria-labelledby":C,className:"settings-row__text",disabled:B,id:M,inputMode:$.control==="url"?"url":"text",onChange:se=>N(se.currentTarget.value),placeholder:$.control==="url"?"https://…":"",spellCheck:!1,type:"text",value:te}):null,$.control==="list"?r.jsx(ML,{describedBy:R,disabled:B,id:M,labelledBy:C,onChange:N,text:te}):null]}),r.jsx("p",{className:"settings-row__hint",id:R,children:[$.control==="list"?"one entry per line":null,$.min!==void 0||$.max!==void 0?`range ${String($.min??"…")}–${String($.max??"…")}${$.unit===""?"":` ${$.unit}`}`:null,e.warnings.resumeFingerprint?"affects the workflow resume fingerprint":null,e.warnings.readerFirst?"reader-first rollout flag":null,"restart required to apply"].filter(se=>se!==null).join(" · ")}),e.warnings.doc!==void 0?r.jsx("p",{className:"settings-row__warning",role:"note",children:e.warnings.doc}):null,t&&s!==void 0?r.jsx("p",{className:"settings-row__blocked",role:"note",children:s}):null,o!==void 0?r.jsx("p",{className:"settings-row__error",id:O,role:"alert",children:o}):null,!G&&$.control!=="unsupported"?r.jsx("button",{className:"settings-row__reset",disabled:t||i||!e.resetAvailable,onClick:w,type:"button",children:"reset to inherited"}):null]})}function BL({applicationRootId:e,message:t,onCancel:s,open:i,state:o}){return r.jsx(Ei,{applicationRootId:e,labelledBy:"settings-stepup-title",onClose:s,open:i,children:r.jsxs("section",{className:"settings-dialog",children:[r.jsx("h2",{id:"settings-stepup-title",children:"Confirm with your passkey"}),o==="active"?r.jsx("p",{role:"status",children:"Waiting for your passkey…"}):r.jsx("p",{className:"settings-dialog__error",role:"alert",children:t??"The passkey request could not be completed."}),r.jsx("p",{children:"Policy and secret changes need a fresh user-verification assertion bound to exactly these edits. Nothing is written until it succeeds."}),r.jsx("div",{className:"settings-dialog__actions",children:r.jsx("button",{onClick:s,type:"button",children:"cancel"})})]})})}const f0="clinkx-settings-save-v1",GL="clinkx-settings-secrets-save-v1",PL="clinkx-settings-step-up-v1",HL=400,VL=5;function p0(e){return new Promise(t=>{window.setTimeout(t,e)})}const FL={supports:()=>typeof window<"u"&&typeof window.PublicKeyCredential=="function",authenticate:async e=>{const{startAuthentication:t}=await w2(async()=>{const{startAuthentication:s}=await Promise.resolve().then(()=>iL);return{startAuthentication:s}},void 0);return t({optionsJSON:e})}};function cg(e){if(e instanceof Ar)switch(e.code){case"settings_unavailable":return"Settings storage is unavailable on this workstation. Check the settings directory and its permissions, then retry.";case"settings_locked":return e.message;case"settings_unreadable":return e.message;case"settings_auth_required":return"This dashboard session cannot write settings. Reconnect with an authorized session and retry.";case"step_up_required":case"step_up_failed":return`The passkey step-up did not complete (${e.code}). Nothing was written; retry the save.`;case"step_up_unavailable":return"Passkey step-up is unavailable in this auth mode; policy and secret changes need passkey mode.";case"settings_published_uncertain":return"The save may have landed, but its durability could not be confirmed. Checking whether it landed…";case"content_too_large_for_dashboard":return"The save payload is too large. Split the change into smaller saves.";default:return e.message}return e instanceof Error?e.message:"The settings request failed."}function KL(e,t){return e.every(s=>s.action==="set"?Bs(t[s.key],s.value):t[s.key]===void 0)}function ZL({api:e,applicationRootId:t="root",authMode:s,checkAttempts:i=VL,checkIntervalMs:o=HL,stepUpTransport:u,webauthn:f=FL}){const m=v.useMemo(()=>e??W2(),[e]),g=v.useMemo(()=>u??lL(m),[u,m]),h=s??tL(),[b,x]=v.useState("loading"),[N,w]=v.useState(null),[k,S]=v.useState(null),[A,$]=v.useState(null),[T,C]=v.useState({}),[M,R]=v.useState({}),[O,G]=v.useState(new Set),[B,te]=v.useState({}),[K,se]=v.useState({}),[ge,J]=v.useState(null),[we,ue]=v.useState("idle"),[L,Y]=v.useState(null),[de,oe]=v.useState({}),[Se,E]=v.useState(null),[U,P]=v.useState(null),[ne,be]=v.useState(!1),[q,re]=v.useState(null),Re=v.useRef(0),Te=v.useRef(null),xe=v.useCallback(()=>{const ye={id:Re.current+1,controller:new AbortController};return Re.current=ye.id,Te.current=ye,ye},[]),Me=v.useCallback(ye=>Te.current?.id===ye.id&&!ye.controller.signal.aborted,[]),ot=v.useCallback((ye,he)=>{re({key:ye,message:he})},[]),dt=v.useCallback(ye=>m.readSettings(ye).then(async he=>{S(he);const Ae=await m.readSettingsProcesses(ye).catch(()=>null);Ae!==null&&$(Ae)}),[m]),[Ot,tn]=v.useState(0);v.useEffect(()=>{const ye=new AbortController;return x("loading"),w(null),dt(ye.signal).then(()=>{ye.signal.aborted||x("ready")},he=>{ye.signal.aborted||(w(cg(he)),x("failed"))}),()=>ye.abort()},[dt,Ot]),v.useEffect(()=>()=>{Te.current?.controller.abort(),te({}),se({}),J(null)},[]);const $t=v.useMemo(()=>k===null?{state:"absent",revision:0,values:{}}:dL(k),[k]),wt=k?.descriptors??[],_n=v.useMemo(()=>hL(wt),[wt]),kt=v.useMemo(()=>vL(wt,$t,{boolDrafts:T,textDrafts:M,unsets:O}),[wt,$t,T,M,O]),st=v.useMemo(()=>wL($t,kt.draft,wt),[$t,kt.draft,wt]),en=A===null?null:jL(A.processes,A.truncated),ea=st.ops.length,zt=st.requiresStepUp,pt=zt&&h!=="passkey",on=Object.keys(kt.textErrors).length>0,pe=we!=="idle"||ge!==null,je=v.useRef(null);v.useLayoutEffect(()=>{if(je.current===$t)return;je.current=$t;const ye=kt.draft;R(he=>{const Ae={};let Pe=!1;for(const[Ze,Fe]of Object.entries(he))Ze in ye||Ze in kt.textErrors?Ae[Ze]=Fe:Pe=!0;return Pe?Ae:he}),C(he=>{const Ae={};let Pe=!1;for(const[Ze,Fe]of Object.entries(he))Ze in ye?Ae[Ze]=Fe:Pe=!0;return Pe?Ae:he}),G(he=>{const Ae=new Set;let Pe=!1;for(const Ze of he)Ze in ye?Ae.add(Ze):Pe=!0;return Pe?Ae:he})},[$t,kt.draft,kt.textErrors]);const Le=v.useCallback(()=>{C({}),R({}),G(new Set),te({}),se({})},[]),Oe=v.useCallback(ye=>{te(he=>{if(!(ye in he))return he;const Ae={...he};return delete Ae[ye],Ae})},[]),rt=v.useCallback(async()=>{try{const ye=await m.readSettings();return S(ye),ye}catch{return null}},[m]),ht=v.useCallback(async(ye,he,Ae,Pe,Ze)=>{P({state:"active",message:null});const Fe=await oL({transport:g,webauthn:f,signal:ye.controller.signal,request:{schemaVersion:PL,intent:Ze===void 0?{target:he,expectedRevision:Ae,ops:d0(Pe,wt)}:{target:"settings",expectedRevision:Ae,ops:d0(Pe,wt),recover:!0,expectedDigest:Ze.expectedDigest}}});return Me(ye)?Fe.kind==="verified"?(P(null),{kind:"proceed",stepUp:Fe.stepUp}):Fe.kind==="not_required"?(P(null),{kind:"proceed"}):(P({state:"failed",message:Fe.message}),{kind:"aborted"}):{kind:"aborted"}},[Me,wt,g,f]),Ut=v.useCallback(ye=>{Le(),ue("idle"),Y(null),ot("saved",`${ye} · restart required to apply`),dt()},[ot,Le,dt]),gt=v.useCallback((ye,he,Ae)=>{ue("checking"),ot("checking","Save outcome unknown — checking whether it landed…"),(async()=>{let Pe=!1,Ze=!1,Fe=!1;for(let Ye=0;Ye<i;Ye+=1){if(await p0(o),!Me(ye))return;const nn=await rt();if(!Me(ye))return;if(nn!==null&&(Fe=!0,nn.state==="ok"&&nn.revision>he&&(Ze=!0,KL(Ae,nn.values)))){Pe=!0;break}}if(Pe){Ut("save confirmed after re-check");return}ue("idle"),Y(Fe?Ze?"Save outcome unknown — the re-check found the revision moved but your change missing. Your edits are kept; review them and save again.":"Save outcome unknown — the re-check found no new revision yet. Your edits are kept; reload before saving again.":"Save outcome unknown — the re-check could not reach the server. Your edits are kept; reload before saving again.")})()},[ot,Me,i,o,Ut,rt]),Ve=v.useCallback((ye,he,Ae,Pe,Ze)=>{if(u0(he)){gt(ye,Ae,Ze);return}if(he instanceof Ar&&he.code==="settings_conflict"){(async()=>{const Fe=await rt(),Ye=Fe!==null&&Fe.state==="ok"?Fe.values:{};E({remoteKeys:NL(Pe,Ye)}),ue("idle")})();return}if(he instanceof Ar&&he.code==="settings_invalid"&&he.fieldErrors.length>0){const Fe={};for(const Ye of he.fieldErrors)Fe[Ye.key]=Ye.message;oe(Fe),ot("invalid","Some values were rejected; fix the highlighted rows.")}else Y(cg(he));ue("idle")},[ot,gt,rt]),cn=v.useCallback(()=>{if(pe||ea===0)return;const ye=$t.revision,he={...$t.values},Ae=st.ops,Pe=xe();ue("saving"),Y(null),oe({}),(async()=>{try{let Ze;if(st.requiresStepUp){if(h!=="passkey"){Y(og(h)),ue("idle");return}const Fe=await ht(Pe,"settings",ye,Ae.map(Ye=>Ye.action==="set"?{key:Ye.key,action:Ye.action,value:Ye.value}:{key:Ye.key,action:Ye.action}));if(Fe.kind==="aborted"){Me(Pe)&&ue("idle");return}Ze=Fe.stepUp}if(!Me(Pe)||(await m.saveSettings({schemaVersion:f0,expectedRevision:ye,ops:Ae,...Ze===void 0?{}:{stepUp:Ze}}),!Me(Pe)))return;Ut(`${String(Ae.length)} change${Ae.length===1?"":"s"} saved`)}catch(Ze){if(!Me(Pe))return;Ve(Pe,Ze,ye,he,Ae)}})()},[ot,m,Me,h,$t,xe,pe,ea,Ve,Ut,ht,st.ops,st.requiresStepUp]),Bt=v.useCallback((ye,he,Ae,Pe)=>{J({key:he,phase:"checking"}),ot("secretChecking","Secret save outcome unknown — checking…"),(async()=>{let Ze=!1,Fe=!1,Ye=!1,nn=!1;for(let oa=0;oa<i;oa+=1){if(await p0(o),!Me(ye))return;const va=await rt();if(va!==null&&(Fe=!0,!(va.secretsRevision<=Ae))){if(Ye=!0,nn=va.secrets[he]?.set===!0,!Pe){if(!nn){Ze=!0;break}continue}break}}if(Me(ye)){if(J(null),Ze){ot("secret","Secret cleared"),dt();return}se(oa=>({...oa,[he]:Pe&&Ye&&nn?"Save outcome unknown — a value is set, but this page cannot confirm it is the one you entered. Replace it to be certain.":Fe?"Save outcome unknown — the re-check could not confirm the secret save. Retry the action.":"Secret save outcome unknown — the re-check could not reach the server. Retry the action."}))}})()},[ot,Me,i,o,dt,rt]),Rn=v.useCallback((ye,he)=>{const Ae=B[ye]??"";if(pe||he==="set"&&Ae==="")return;if(h!=="passkey"){se(Fe=>({...Fe,[ye]:og(h)}));return}const Pe=k?.secretsRevision??0,Ze=xe();se(Fe=>{if(!(ye in Fe))return Fe;const Ye={...Fe};return delete Ye[ye],Ye}),J({key:ye,phase:"saving"}),(async()=>{try{const Fe=await ht(Ze,"secrets",Pe,[{key:ye,action:he}]);if(Fe.kind==="aborted"){Me(Ze)&&J(null);return}if(!Me(Ze))return;const Ye=await m.saveSettingsSecrets({schemaVersion:GL,expectedRevision:Pe,ops:he==="set"?[{key:ye,action:"set",value:Ae}]:[{key:ye,action:"unset"}],...Fe.stepUp===void 0?{}:{stepUp:Fe.stepUp}});if(!Me(Ze))return;Ye.revision>Pe&&Ye.applied.some(nn=>nn.key===ye&&nn.action===he)?(J(null),ot("secret",he==="set"?"Secret saved · the value is never displayed":"Secret cleared"),dt()):Bt(Ze,ye,Pe,he==="set")}catch(Fe){if(!Me(Ze))return;if(u0(Fe)){Bt(Ze,ye,Pe,he==="set");return}J(null),se(Ye=>({...Ye,[ye]:cg(Fe)}))}finally{Me(Ze)&&Oe(ye)}})()},[ot,m,Me,h,xe,Bt,pe,Oe,k,ht,B]),Da=v.useCallback(()=>{if(k===null||k.state!=="unreadable"||st.ops.length===0)return;const ye=k.digest;be(!1);const he=xe();ue("saving"),Y(null),(async()=>{try{const Ae=await ht(he,"settings",0,st.ops.map(Pe=>Pe.action==="set"?{key:Pe.key,action:Pe.action,value:Pe.value}:{key:Pe.key,action:Pe.action}),{expectedDigest:ye});if(Ae.kind==="aborted"){Me(he)&&ue("idle");return}if(!Me(he)||(await m.saveSettings({schemaVersion:f0,expectedRevision:0,ops:st.ops,recover:!0,expectedDigest:ye,...Ae.stepUp===void 0?{}:{stepUp:Ae.stepUp}}),!Me(he)))return;Ut("corrupt document replaced — old bytes kept as a corrupt backup")}catch(Ae){if(!Me(he))return;Ve(he,Ae,0,{},st.ops)}})()},[m,Me,xe,k,Ve,Ut,ht,st.ops]),Ya=v.useCallback(()=>{Te.current?.controller.abort(),ge!==null&&Oe(ge.key),P(null),ue("idle"),J(null)},[Oe,ge]),un=v.useCallback(ye=>{G(he=>{if(!he.has(ye))return he;const Ae=new Set(he);return Ae.delete(ye),Ae})},[]),Gt=v.useCallback((ye,he)=>{C(Ae=>({...Ae,[ye]:he})),un(ye)},[un]),Tn=v.useCallback((ye,he)=>{R(Ae=>({...Ae,[ye]:he})),un(ye)},[un]),rn=v.useCallback(ye=>{G(he=>new Set(he).add(ye)),C(he=>{if(!(ye in he))return he;const Ae={...he};return delete Ae[ye],Ae}),R(he=>{if(!(ye in he))return he;const Ae={...he};return delete Ae[ye],Ae})},[]),In=ye=>kt.textErrors[ye]??de[ye],ct=h==="passkey"?void 0:og(h);return r.jsxs("section",{className:"settings-view","aria-labelledby":"dashboard-page-title",children:[r.jsx("h1",{className:"visually-hidden",id:"dashboard-page-title",children:"Settings"}),r.jsxs("header",{className:"settings-view__head",children:[r.jsx("p",{className:"settings-view__eyebrow",children:"workstation"}),r.jsx("h2",{className:"settings-view__title",children:"Settings"}),r.jsxs("p",{className:"settings-view__facts",children:[$t.state==="ok"?`revision ${String($t.revision)}${k?.state==="ok"?` · saved ${k.updatedAt}`:""}`:$t.state==="absent"?"no settings document yet — the first save creates it":"settings document unreadable",` · auth ${h}`]})]}),r.jsx(sp,{announcement:q}),b==="loading"?r.jsx("p",{className:"settings-view__state",role:"status",children:"Loading settings…"}):null,b==="failed"?r.jsxs("div",{className:"settings-view__state",role:"alert",children:[r.jsx("p",{children:N??"The settings document could not be loaded."}),r.jsx("button",{onClick:()=>tn(ye=>ye+1),type:"button",children:"[ retry settings ]"})]}):null,b==="ready"&&k!==null?r.jsxs(r.Fragment,{children:[k.state==="unreadable"?r.jsxs("div",{className:"settings-view__unreadable",role:"alert",children:[r.jsxs("p",{children:["The settings document on this workstation is unreadable (",k.reason,"). A routine save never overwrites it — recovering replaces the corrupt file with the edits staged below."]}),r.jsx("p",{children:r.jsx("code",{children:`digest ${k.digest}`})}),h==="passkey"?r.jsxs(r.Fragment,{children:[r.jsx("button",{disabled:st.ops.length===0||on||pe,onClick:()=>be(!0),type:"button",children:"Recover (replace corrupt file)"}),st.ops.length===0?r.jsx("span",{className:"settings-view__note",children:"stage at least one edit to recover"}):null]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{children:"Recovery always needs a passkey step-up, which is unavailable in this auth mode. Run this command on the workstation instead:"}),r.jsx("code",{className:"settings-view__recover-cmd",children:`clinkx settings recover --digest ${k.digest}`})]})]}):null,k.state!=="unreadable"&&(k.settingsState?.status==="unreadable"||k.secretsState==="unreadable")?r.jsxs("div",{className:"settings-view__unreadable",role:"alert",children:[r.jsx("p",{children:k.settingsState?.status==="unreadable"?"The settings document health reports unreadable even though this read succeeded. Reload the page; if it stays unreadable, recover it with clinkx settings recover.":"The secrets document on this workstation is unreadable. Secret changes may fail until it is recovered; a settings save is not affected. Recover it with:"}),k.settingsState?.status!=="unreadable"?r.jsx("p",{children:r.jsx("code",{className:"settings-view__recover-cmd",children:"clinkx settings recover --secrets"})}):null]}):null,en!==null&&en.anyUnreadable?r.jsx("div",{className:"settings-view__degraded",role:"alert",children:r.jsx("p",{children:"At least one observed process reports its settings document as unreadable and is running on shipped defaults. Check its settings directory, then restart it."})}):null,L!==null?r.jsx("p",{className:"settings-view__error",role:"alert",children:L}):null,_n.map(ye=>r.jsxs("section",{"aria-labelledby":`settings-group-${ye.settingClass}`,className:"settings-group",children:[r.jsx("h3",{id:`settings-group-${ye.settingClass}`,children:ye.title}),ye.descriptors.map(he=>{const Ae=gL({descriptor:he,baseline:$t,draft:kt.draft,shadowedByEnvCount:en?.shadowCounts[he.key]??0,staleShadowedByEnvCount:en?.staleShadowCounts[he.key]??0}),Pe=!SL(he.settingClass,h);return r.jsx(UL,{authBlocked:Pe,blockedMessage:ct,busy:pe,fieldError:In(he.key),onBool:Ze=>Gt(he.key,Ze),onReset:()=>rn(he.key),onSecretClear:()=>Rn(he.key,"unset"),onSecretInput:Ze=>te(Fe=>({...Fe,[he.key]:Ze})),onSecretSet:()=>Rn(he.key,"set"),onText:Ze=>Tn(he.key,Ze),row:Ae,secretBusy:ge?.key===he.key,secretChecking:ge?.key===he.key&&ge.phase==="checking",secretError:K[he.key],secretState:k.secrets[he.key],secretValue:B[he.key]??"",textDraft:M[he.key]},he.key)})]},ye.settingClass)),en!==null?r.jsx(CL,{currentRevision:A?.currentRevision??null,processes:A?.processes??[],projection:en}):null,r.jsx(OL,{changeCount:ea,checking:we==="checking",classesTouched:st.classesTouched,disabled:pt,hasTextErrors:on,onDiscard:()=>{Le(),ot("discarded","Edits discarded")},onSave:cn,requiresStepUp:zt,saving:we==="saving",stepUpBlocked:pt})]}):null,r.jsx(kL,{applicationRootId:t,onDiscard:()=>{E(null),Le(),ot("discarded","Edits discarded after conflict")},onKeepEdits:()=>{E(null),ot("kept","Edits kept on the new revision")},open:Se!==null,remoteKeys:Se?.remoteKeys??[]}),r.jsx(BL,{applicationRootId:t,message:U?.message??null,onCancel:Ya,open:U!==null,state:U?.state??"active"}),r.jsx(Ei,{applicationRootId:t,labelledBy:"settings-recover-title",onClose:()=>be(!1),open:ne,children:r.jsxs("section",{className:"settings-dialog",children:[r.jsx("h2",{id:"settings-recover-title",children:"Replace the corrupt file?"}),r.jsx("p",{children:"The unreadable settings document will be replaced by a new document holding exactly the edits staged below. If the old bytes can still be read they are kept beside it as a corrupt backup; if they cannot be read the recover is refused and nothing is overwritten. You will be asked to confirm with your passkey."}),r.jsxs("div",{className:"settings-dialog__actions",children:[r.jsx("button",{onClick:Da,type:"button",children:"replace and save"}),r.jsx("button",{onClick:()=>be(!1),type:"button",children:"cancel"})]})]})})]})}const XL=e=>(document.addEventListener("visibilitychange",e),()=>{document.removeEventListener("visibilitychange",e)}),h0=()=>document.visibilityState==="visible";function nN(){return v.useSyncExternalStore(XL,h0,h0)}function xp(e,t,s,i){const o=nN(),f=t||s&&!i&&o;v.useEffect(()=>{if(!f)return;let m=!1;return e.start().finally(()=>{!m&&!t&&e.stop()}),()=>{m=!0,e.stop()}},[t,e,f])}function YL(e,t=!0,s=!1){const i=v.useSyncExternalStore(e.subscribe,e.getState,e.getState);return xp(e,t,s,i.lastRefreshAtMs!==null),i}function QL(e,t=!0,s=!1){const i=v.useSyncExternalStore(e.subscribe,e.getState,e.getState);return xp(e,t,s,i.lastRefreshAtMs!==null),i}function JL(e,t=!0,s=!1){const i=v.useSyncExternalStore(e.subscribe,e.getState,e.getState);return xp(e,t,s,i.lastRefreshAtMs!==null),i}function WL(e,t=!0,s=!1){const i=v.useSyncExternalStore(e.subscribe,e.getState,e.getState);return xp(e,t,s,i.lastRefreshAtMs!==null),i}function el(){return window.location.pathname}function m0(e){return{clinkxRoute:e}}function eD(e){const t=v.useRef(e);t.current=e;const[s,i]=v.useState(()=>qc(el())),o=v.useRef(0),u=v.useRef(0),f=v.useRef(void 0),m=v.useRef(void 0),g=v.useRef(s);g.current=s,v.useEffect(()=>{const S=el(),A=qc(S);A.kind==="resolved"&&A.canonicalPath!==S&&window.history.replaceState(m0(A.canonicalPath),"",A.canonicalPath),i(A)},[]),v.useEffect(()=>{const S=()=>{o.current++,u.current=o.current,f.current=void 0,t.current?.(el()),i(qc(el()))};return window.addEventListener("popstate",S),()=>window.removeEventListener("popstate",S)},[]);const h=v.useCallback((S,A,$)=>{if(o.current++,u.current=o.current,f.current=$,t.current?.(S),S===el()){i(qc(S));return}const T=m0(S);A==="push"?window.history.pushState(T,"",S):window.history.replaceState(T,"",S),i(qc(S))},[]),b=v.useCallback(S=>{h(c1(S),"push")},[h]),x=v.useCallback(S=>{h(yo(S),"push")},[h]),N=v.useCallback(S=>{h(yo(S),"replace")},[h]),w=v.useCallback(S=>{const A=el(),$=f.current,T=yo(vS(S));return h(T,"push","runGeneration"in S?S.runGeneration:void 0),m.current={intent:o.current,path:T,previousPath:A,previousGeneration:$},o.current},[h]),k=v.useCallback(S=>{if(o.current!==S)return;const A=m.current;m.current=void 0,A?.intent===S&&el()===A.path?h(A.previousPath,"replace",A.previousGeneration):o.current++},[h]);return{resolution:s,navigateToDestination:b,pushRoute:x,replaceRoute:N,getIntent:()=>o.current,getRouteIntent:()=>u.current,cancelIntent:k,back:()=>{o.current++,f.current=void 0,t.current?.(null),window.history.back()},getExpectedGeneration:()=>f.current,beginAgentNavigation:w}}function g0(e){return e??new AbortController().signal}async function v0(e,t,s){let i;try{i=await e(t,{signal:s})}catch(o){throw o instanceof Ct?new Ee("connection_changed",409,"agent_instance_changed"):s.aborted||o instanceof DOMException&&o.name==="AbortError"?new Ee("aborted"):new Ee("offline")}if(i.status===401)throw new Ee("auth_expired",401,"unauthorized");if(!i.ok)throw new Ee("request_error",i.status);try{return await xn(i)}catch(o){throw o instanceof Ct?new Ee("connection_changed",409,"agent_instance_changed"):new Ee("request_error",i.status)}}function tD(e=Ka){return{async listWorkflows(t){return await v0(e,"/api/workflows",g0(t))},async listAdapters(t){return await v0(e,"/api/adapters",g0(t))}}}const nD=2e3;function aD(e){return{phase:"initial_loading",live:[],history:[],nextBefore:void 0,historyPage:0,canGoNewer:!1,canGoOlder:!1,selected:null,detail:null,lastRefreshAtMs:null,displayNowMs:e,serverOffsetMs:0,announcement:null}}function _0(e,t){const s=e instanceof Ee?e.kind:"request_error";return s==="auth_expired"?"auth_expired":s==="connection_changed"||Kf(s)?"connection_changed":s==="offline"?"offline":t?"stale":"error"}function sD(e){let t=aD(Date.now()),s=null,i=null,o=!1,u=!1,f=0,m=[void 0],g=0,h=0;const b=new Set,x=_o(),N=R=>{t=R;for(const O of b)O()},w=()=>{s!==null&&clearTimeout(s),s=null},k=()=>{w(),!(o||t.phase==="auth_expired"||t.phase==="connection_changed"||t.phase==="error"||document.visibilityState!=="visible")&&(s=setTimeout(()=>{$()},nD))},S=R=>({runId:R.runId,runGeneration:R.runGeneration,stateRevision:R.stateRevision}),A=async(R,O=!1)=>{const G=x.begin(R);try{const B=O&&e.getRunDetailForPolling!==void 0?await e.getRunDetailForPolling(R,G.signal):await e.getRunDetail(R,G.signal);return x.acceptsDetail(G.identity,B)?B:null}catch(B){if(!x.isActive(G.identity))return null;throw B}},$=async(R=m)=>{if(o||document.visibilityState!=="visible")return!1;w(),i?.abort(),x.cancel();const O=++f,G=g,B=++h,te=new AbortController;i=te;const K=Date.now(),se=[...R];try{let ge=se[se.length-1],J=await e.listRuns(ge===void 0?{signal:te.signal}:{before:ge,signal:te.signal}),we=!1;for(;J.history.length===0&&se.length>1;)se.pop(),we=!0,ge=se[se.length-1],J=await e.listRuns(ge===void 0?{signal:te.signal}:{before:ge,signal:te.signal});if(o||te.signal.aborted||O!==f)return!1;const ue=Date.now(),L=Date.parse(J.serverNow),Y=K+(ue-K)/2,de=Number.isFinite(L)?L-Y:t.serverOffsetMs,oe=ue+de,Se=[...J.live,...J.history];let E=t.selected,U=t.detail,P=!1,ne=we?"The previous page was pruned. Showing the nearest newer history page.":null;const be=t.selected!==null&&t.live.some(re=>re.runId===t.selected?.runId&&re.runGeneration===t.selected.runGeneration);if(E!==null&&G===g){const re=Se.find(Te=>Te.runId===E?.runId&&Te.runGeneration===E.runGeneration),Re=Se.find(Te=>Te.runId===E?.runId);if(re!==void 0?E=S(re):Re!==void 0&&(E=null,U=null,ne="Run generation changed. Select the replacement deliberately to inspect it."),E!==null)try{P=!0;const Te=await A(E,!0);if(Te===null||o||te.signal.aborted||O!==f||B!==h)return!1;U=Te,E=S(Te);const xe=J.live.some(Me=>Me.runId===Te.runId&&Me.runGeneration===Te.runGeneration);be&&!xe&&Te.availability==="available"&&Te.status!=="pending"&&Te.status!=="running"&&(ne="Selected run moved to history.")}catch(Te){if(B!==h)return!1;if(Te instanceof Ee&&Te.code==="run_generation_changed")E=null,U=null,ne="Run generation changed. Select the replacement deliberately to inspect it.";else if(Te instanceof Ee&&Te.status===404)E=null,U=null,ne="The selected run is no longer available.";else throw Te}}if(o||te.signal.aborted||O!==f||P&&B!==h)return!1;m=se;const q=G!==g;return N({...t,phase:q?t.phase:"current",live:J.live,history:J.history,nextBefore:J.nextBefore,canGoOlder:J.nextBefore!==void 0,historyPage:se.length-1,canGoNewer:se.length>1,selected:q?t.selected:E,detail:q?t.detail:U,lastRefreshAtMs:oe,displayNowMs:oe,serverOffsetMs:de,announcement:q?t.announcement:ne}),!0}catch(ge){return o||te.signal.aborted||O!==f||B!==h||G!==g||N({...t,phase:_0(ge,t.lastRefreshAtMs!==null)}),!1}finally{!o&&O===f&&k()}},T=()=>{document.visibilityState==="visible"?$():(w(),i?.abort(),h+=1,x.cancel())},C=()=>{document.visibilityState==="visible"&&$()},M=()=>{u&&(u=!1,f+=1,h+=1,w(),i?.abort(),i=null,x.cancel(),document.removeEventListener("visibilitychange",T),window.removeEventListener("focus",C))};return{async start(){u||o||(u=!0,document.addEventListener("visibilitychange",T),window.addEventListener("focus",C),await $())},stop:M,dispose(){o||(M(),o=!0,b.clear())},getState(){return t},subscribe(R){return b.add(R),()=>b.delete(R)},async retry(){await $()},runGenerationChanged(){o||t.selected===null||(g+=1,h+=1,x.cancel(),N({...t,phase:"current",selected:null,detail:null,announcement:"Run generation changed. Select the replacement deliberately to inspect it."}))},async select(R){if(o)return;g+=1;const O=++h,G=S(R);N({...t,selected:G,detail:null,announcement:null});try{const B=await A(G);B!==null&&!o&&O===h&&N({...t,selected:S(B),detail:B})}catch(B){if(o||O!==h||B instanceof Ee&&B.kind==="aborted")return;if(B instanceof Ee&&B.code==="run_generation_changed"){N({...t,phase:"current",selected:null,detail:null,announcement:"Run generation changed. Select the replacement deliberately to inspect it."});return}if(B instanceof Ee&&B.status===404){N({...t,phase:"current",selected:null,detail:null,announcement:"The selected run is no longer available."});return}N({...t,phase:_0(B,t.lastRefreshAtMs!==null)})}},async older(){o||t.nextBefore===void 0||await $([...m,t.nextBefore])},async newer(){o||m.length<=1||await $(m.slice(0,-1))}}}function rD(e){return e??new AbortController().signal}function b0(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fi(e){if(typeof e!="string"||e.length===0)throw new Ee("request_error",200);return e}function iD(e){if(!b0(e)||!b0(e.childConfig))throw new Ee("request_error",200);const t=e.childConfig,s=t.source==="ambient"&&t.configured===!1?{source:"ambient",configured:!1}:t.source==="explicit"&&t.configured===!0?{source:"explicit",configured:!0,path:fi(t.path)}:(()=>{throw new Ee("request_error",200)})();return{stateDir:fi(e.stateDir),...e.activitiesRoot===void 0?{}:{activitiesRoot:fi(e.activitiesRoot)},...e.progressReportsRoot===void 0?{}:{progressReportsRoot:fi(e.progressReportsRoot)},runsRoot:fi(e.runsRoot),workspaceRoot:fi(e.workspaceRoot),workflowsPath:fi(e.workflowsPath),templatesPath:fi(e.templatesPath),childConfig:s}}function lD(e=Ka){return{async getEnvironment(t){const s=rD(t);let i;try{i=await e("/api/env",{signal:s})}catch(o){throw o instanceof Ct?new Ee("connection_changed",409,"agent_instance_changed"):s.aborted||o instanceof DOMException&&o.name==="AbortError"?new Ee("aborted"):new Ee("offline")}if(i.status===401)throw new Ee("auth_expired",401,"unauthorized");if(!i.ok)throw new Ee("request_error",i.status);try{return iD(await xn(i))}catch(o){throw o instanceof Ee?o:o instanceof Ct?new Ee("connection_changed",409,"agent_instance_changed"):new Ee("request_error",i.status)}}}}const oD=2e3,cD=Object.freeze({phase:"current",detailPhase:"idle",activities:Object.freeze([]),selected:null,detail:null,lastRefreshAtMs:null,announcement:null,displayNowMs:0,serverOffsetMs:0});function uD(){return Object.freeze({async start(){},stop(){},dispose(){},getState:()=>cD,subscribe:()=>()=>{},async retry(){},async select(){},clearSelection(){}})}function ef(e){return{activityId:e.activityId,activityGeneration:e.activityGeneration,stateRevision:e.stateRevision}}function y0(e,t){const s=e instanceof Ee?e.kind:"request_error";return s==="auth_expired"?"auth_expired":s==="connection_changed"||Kf(s)?"connection_changed":s==="offline"?"offline":t?"stale":"error"}function dD(e){let t={phase:"initial_loading",detailPhase:"idle",activities:[],selected:null,detail:null,lastRefreshAtMs:null,announcement:null,displayNowMs:0,serverOffsetMs:0},s=!1,i=!1,o=0,u=0,f=null,m=null;const g=new Set,h=T=>{t=T;for(const C of g)C()},b=()=>{f!==null&&clearTimeout(f),f=null},x=()=>{b(),!(i||t.phase==="auth_expired"||t.phase==="connection_changed"||t.phase==="error"||document.visibilityState!=="visible")&&(f=setTimeout(()=>{k()},oD))},N=(T,C)=>!i&&m===C&&!C.signal.aborted&&T===o,w=(T,C)=>!i&&m===C&&!C.signal.aborted&&T===u,k=async()=>{if(i||document.visibilityState!=="visible")return!1;b(),m?.abort();const T=++o,C=u,M=new AbortController;m=M;const R=Date.now();try{const O=await e.listActivities({signal:M.signal});if(!N(T,M))return!1;const G=Date.now();let B=t.selected,te=t.detail,K=t.detailPhase,se=null;if(B!==null&&C===u){const L=O.activities.find(de=>de.activityId===B?.activityId&&de.activityGeneration===B.activityGeneration),Y=O.activities.find(de=>de.activityId===B?.activityId);if(L===void 0&&Y!==void 0)B=null,te=null,K="idle",se="Activity generation changed. Select the replacement deliberately.";else{L!==void 0&&(B=ef(L));try{if(te=await(e.getActivityDetailForPolling??e.getActivityDetail)(B,M.signal),!N(T,M))return!1;B=ef(te),K="loaded"}catch(de){if(!N(T,M))return!1;if(de instanceof Ee&&(de.code==="activity_generation_changed"||de.code==="activity_state_changed"||de.status===404))B=null,te=null,K="idle",se="The selected activity changed or is no longer retained.";else throw de}}}if(!N(T,M))return!1;const ge=Date.parse(O.serverNow),J=R+(G-R)/2,we=Number.isFinite(ge)?ge-J:t.serverOffsetMs,ue=G+we;return h({phase:"current",detailPhase:K,activities:O.activities,selected:B,detail:te,lastRefreshAtMs:ue,displayNowMs:ue,serverOffsetMs:we,announcement:se}),!0}catch(O){return N(T,M)&&h({...t,phase:y0(O,t.lastRefreshAtMs!==null)}),!1}finally{!i&&T===o&&x()}},S=()=>{document.visibilityState==="visible"?k():(b(),m?.abort(),m=null)},A=()=>{document.visibilityState==="visible"&&k()},$=()=>{s&&(s=!1,o+=1,u+=1,b(),m?.abort(),m=null,document.removeEventListener("visibilitychange",S),window.removeEventListener("focus",A))};return{async start(){s||i||(s=!0,document.addEventListener("visibilitychange",S),window.addEventListener("focus",A),await k())},stop:$,dispose(){i||($(),i=!0,g.clear())},getState(){return t},subscribe(T){return g.add(T),()=>g.delete(T)},async retry(){await k()},async select(T){if(i)return;m?.abort();const C=++u,M=new AbortController;m=M;const R=ef(T);h({...t,selected:R,detail:null,detailPhase:"loading",announcement:null});try{const O=await e.getActivityDetail(R,M.signal);w(C,M)&&h({...t,selected:ef(O),detail:O,detailPhase:"loaded"})}catch(O){if(!w(C,M)||O instanceof Ee&&O.kind==="aborted")return;if(O instanceof Ee&&(O.code==="activity_generation_changed"||O.code==="activity_state_changed"||O.status===404)){h({...t,selected:null,detail:null,detailPhase:"idle",announcement:"The selected activity changed or is no longer retained."});return}h({...t,phase:y0(O,t.lastRefreshAtMs!==null),detailPhase:"error"})}},clearSelection(){u+=1,m?.abort(),m=null,h({...t,selected:null,detail:null,detailPhase:"idle",announcement:null})}}}const fD=3e3,pD=Object.freeze({phase:"current",detailPhase:"idle",contextRuns:Object.freeze([]),selectedId:null,detail:null,lastRefreshAtMs:null,displayNowMs:0,serverOffsetMs:0,announcement:null});function hD(){return Object.freeze({async start(){},stop(){},dispose(){},getState:()=>pD,subscribe:()=>()=>{},async retry(){},async select(){},clearSelection(){}})}function x0(e,t){const s=e instanceof Ee?e.kind:"request_error";return s==="auth_expired"?"auth_expired":s==="connection_changed"||Kf(s)?"connection_changed":s==="offline"?"offline":t?"stale":"error"}function Ls(e,t){if(t!==null)return e.find(s=>s.id===t)}function w0(e,t){return js(e.lifecycle?.status)&&!js(t.lifecycle?.status)?e:Object.freeze({...e,lifecycle:t.lifecycle,orphaned:t.orphaned,liveness:t.liveness})}function S0(e,t,s){const i=e?.contextGeneration===s.contextGeneration?e.lifecycle?.status:t?.contextGeneration===s.contextGeneration?t.lifecycle?.status:void 0,o=s.lifecycle?.status;return Ff(i)&&o!==void 0&&!Ff(o)}function Ff(e){return e==="pending"||e==="running"}function js(e){return e!==void 0&&!Ff(e)}function mD(e){let t={phase:"initial_loading",detailPhase:"idle",contextRuns:[],selectedId:null,detail:null,lastRefreshAtMs:null,displayNowMs:0,serverOffsetMs:0,announcement:null},s=!1,i=!1,o=0,u=0,f=null,m=null,g=null,h=0,b,x,N,w=!0;const k=new Set,S=G=>{t=G;for(const B of k)B()},A=()=>{f!==null&&clearTimeout(f),f=null},$=()=>{A(),!(i||t.phase==="auth_expired"||t.phase==="connection_changed"||t.phase==="error"||document.visibilityState!=="visible")&&(f=setTimeout(()=>{C()},fD))},T=async(G,B,te,K)=>{const se=Ls(t.contextRuns,G),ge=u,J=N,we=se?.contextGeneration===B&&js(se?.lifecycle?.status)||te?.contextGeneration===B&&js(te?.lifecycle?.status)||J?.contextRunId===G&&J.expectedGeneration===B&&J.requiresTerminalAudit,ue=++h;g?.abort();const L=new AbortController;g=L;const Y=oe=>{if(oe===null||u<=ge)return oe;const Se=Ls(t.contextRuns,G);return Se?.contextGeneration===oe.contextGeneration?w0(oe,Se):oe},de=oe=>{if(oe===void 0)return!1;const Se=Ls(t.contextRuns,G),E=t.detail?.id===G?t.detail:null;return B===oe&&we||Se?.contextGeneration===oe&&js(Se.lifecycle?.status)||E?.contextGeneration===oe&&js(E.lifecycle?.status)};try{const oe=await e.getContextRunDetail(G,L.signal);if(i||L.signal.aborted||ue!==h||t.selectedId!==G)return;const E=Ls(t.contextRuns,G)?.contextGeneration??b??B;if(E!==void 0&&oe.contextGeneration!==E){if(E!==B){const ne=t.detail?.id===G&&t.detail.contextGeneration===E?t.detail:null;if(b=E,N={contextRunId:G,expectedGeneration:E,requiresTerminalAudit:de(E)},K&&w){w=!1,await T(G,E,ne,!1);return}S({...t,detail:ne,detailPhase:"error",announcement:"Context run generation changed again. Retry to inspect the current incarnation."});return}N={contextRunId:G,expectedGeneration:E,requiresTerminalAudit:de(E)},S({...t,detail:null,detailPhase:"error",announcement:"Context run generation changed again. Retry to inspect the current incarnation."});return}const U=t.detail?.id===G&&t.detail.contextGeneration===oe.contextGeneration?t.detail:te?.contextGeneration===oe.contextGeneration?te:null;if(de(oe.contextGeneration)&&Ff(oe.lifecycle?.status)){if(b=oe.contextGeneration,N={contextRunId:G,expectedGeneration:oe.contextGeneration,requiresTerminalAudit:!0},!we&&K&&w){w=!1,await T(G,oe.contextGeneration,te,!1);return}S({...t,detail:Y(U),detailPhase:"error",announcement:"Context run reached a terminal state, but its audited detail is not available yet. Retry to inspect it."});return}const P=Y(oe)??oe;b=oe.contextGeneration,x=void 0,N=void 0,w=!0,S({...t,selectedId:P.id,detail:P,detailPhase:"loaded",announcement:null})}catch(oe){if(L.signal.aborted||ue!==h||oe instanceof Ee&&oe.kind==="aborted")return;if(oe instanceof Ee&&(oe.code==="not_found"||oe.status===404)){x=t.lastRefreshAtMs!==null&&Ls(t.contextRuns,G)===void 0?u:void 0,N=void 0,w=!0,S({...t,selectedId:G,detail:null,detailPhase:"not_found",announcement:"The selected context run is no longer retained."});return}const E=Ls(t.contextRuns,G)?.contextGeneration??b??B,U=te!==null&&(E===void 0||te.contextGeneration===E)?te:null,P=t.detail?.id===G&&(E===void 0||t.detail.contextGeneration===E)?t.detail:U,ne=Y(P);N={contextRunId:G,expectedGeneration:E,requiresTerminalAudit:de(E)},S({...t,phase:x0(oe,t.lastRefreshAtMs!==null),detail:ne,detailPhase:"error",announcement:null})}},C=async(G=!0)=>{if(i||document.visibilityState!=="visible")return!1;A(),m?.abort();const B=++o,te=new AbortController;m=te;try{const K=Date.now(),se=await e.listContextRuns({signal:te.signal});if(i||te.signal.aborted||B!==o)return!1;u=B;const ge=Date.now(),J=Date.parse(se.serverNow),we=K+(ge-K)/2,ue=Number.isFinite(J)?J-we:t.serverOffsetMs,L=ge+ue;let Y=null,de=t.detail,oe=t.detailPhase;const Se=t.selectedId;let E;if(Se!==null){const U=Ls(se.contextRuns,Se);if(U!==void 0){const P=Ls(t.contextRuns,Se),ne=de?.contextGeneration??P?.contextGeneration??b;b=U.contextGeneration;const be=N;if(js(U.lifecycle?.status)&&be?.contextRunId===Se&&(be.expectedGeneration===void 0||be.expectedGeneration===U.contextGeneration)&&(N={contextRunId:Se,expectedGeneration:U.contextGeneration,requiresTerminalAudit:!0}),oe==="not_found")x!==void 0?B>x?(x=void 0,h+=1,g?.abort(),de=null,oe="loading",E={expectedGeneration:U.contextGeneration,retainedDetail:null,requiresTerminalAudit:js(U.lifecycle?.status)}):B===x&&(x=void 0):ne!==void 0&&ne!==U.contextGeneration&&(h+=1,g?.abort(),de=null,oe="loading",E={expectedGeneration:U.contextGeneration,retainedDetail:null,requiresTerminalAudit:js(U.lifecycle?.status)});else if(ne!==void 0&&ne!==U.contextGeneration)h+=1,g?.abort(),de=null,oe="loading",E={expectedGeneration:U.contextGeneration,retainedDetail:null,requiresTerminalAudit:js(U.lifecycle?.status)},Y="Context run generation changed. Reloading the current incarnation.";else if(de!==null&&de.contextGeneration===U.contextGeneration){const q=oe==="loaded"&&S0(P,de,U);de=w0(de,U);const re=N?.contextRunId===Se&&(N.expectedGeneration===void 0||N.expectedGeneration===U.contextGeneration);oe=oe==="loading"&&re?"loading":re?"error":"loaded",q&&(h+=1,g?.abort(),E={expectedGeneration:U.contextGeneration,retainedDetail:de,requiresTerminalAudit:!0})}else de===null&&oe==="loading"&&(S0(P,null,U)||P===void 0&&t.lastRefreshAtMs!==null)&&(h+=1,g?.abort(),E={expectedGeneration:U.contextGeneration,retainedDetail:null,requiresTerminalAudit:js(U.lifecycle?.status)})}}if(E!==void 0&&Se!==null){const U=E;b=U.expectedGeneration,G&&w?(w=!1,N=void 0):(N={contextRunId:Se,expectedGeneration:U.expectedGeneration,requiresTerminalAudit:U.requiresTerminalAudit},de=U.retainedDetail,oe="error",Y="Context run detail changed. Retry to inspect the current incarnation.",E=void 0)}return S({phase:"current",detailPhase:oe,contextRuns:se.contextRuns,selectedId:Se,detail:de,lastRefreshAtMs:L,displayNowMs:L,serverOffsetMs:ue,announcement:Y}),Se!==null&&t.selectedId===Se&&E!==void 0&&await T(Se,E.expectedGeneration,E.retainedDetail,!1),!0}catch(K){return i||te.signal.aborted||B!==o||S({...t,phase:x0(K,t.lastRefreshAtMs!==null)}),!1}finally{!i&&B===o&&$()}},M=()=>{document.visibilityState==="visible"?C():(A(),m?.abort())},R=()=>{document.visibilityState==="visible"&&C()},O=()=>{s&&(s=!1,o+=1,A(),m?.abort(),m=null,h+=1,g?.abort(),g=null,document.removeEventListener("visibilitychange",M),window.removeEventListener("focus",R))};return{async start(){s||i||(s=!0,document.addEventListener("visibilitychange",M),window.addEventListener("focus",R),await C())},stop:O,dispose(){i||(O(),i=!0,k.clear())},getState(){return t},subscribe(G){return k.add(G),()=>k.delete(G)},async retry(){if(!await C(!1))return;const G=N;if(G===void 0||t.selectedId!==G.contextRunId)return;const te=Ls(t.contextRuns,G.contextRunId)?.contextGeneration??b??G.expectedGeneration,K=G.requiresTerminalAudit&&G.expectedGeneration===te;b=te,N={contextRunId:G.contextRunId,expectedGeneration:te,requiresTerminalAudit:K};const se=t.detail?.id===G.contextRunId&&(te===void 0||t.detail.contextGeneration===te)?t.detail:null;S({...t,detail:se,detailPhase:"loading",announcement:null}),await T(G.contextRunId,te,se,!1)},async select(G){if(i)return;const B=t.selectedId,te=t.detail?.id===G?t.detail:null,K=Ls(t.contextRuns,G)?.contextGeneration??te?.contextGeneration??(B===G?b:void 0);(B!==G||b!==void 0&&K!==void 0&&b!==K)&&(N=void 0),b=K,x=void 0,w=!0,S({...t,selectedId:G,detail:te,detailPhase:te===null?"loading":"loaded",announcement:null}),await T(G,b,te,!0)},clearSelection(){h+=1,g?.abort(),b=void 0,x=void 0,N=void 0,w=!0,S({...t,selectedId:null,detail:null,detailPhase:"idle",announcement:null})}}}const gD=3e3,vD=Object.freeze({phase:"current",progressReports:Object.freeze([]),truncated:!1,selectedId:null,detail:null,detailPhase:"idle",omittedSections:Object.freeze([]),publishedSessionStatus:null,unreadableReason:null,lastRefreshAtMs:null,displayNowMs:0,serverOffsetMs:0,announcement:null});function _D(){return Object.freeze({async start(){},stop(){},dispose(){},getState:()=>vD,subscribe:()=>()=>{},async retry(){},async select(){},clearSelection(){},async setStatusOverride(){}})}function tf(e,t){const s=e instanceof Ee?e.kind:"request_error";return s==="auth_expired"?"auth_expired":s==="connection_changed"||Kf(s)?"connection_changed":s==="offline"?"offline":t?"stale":"error"}function ug(e,t,s,i){const o=Date.parse(e),u=t+(s-t)/2,f=Number.isFinite(o)?o-u:i;return{serverOffsetMs:f,alignedNowMs:s+f}}function bD(e){let t={phase:"initial_loading",progressReports:[],truncated:!1,selectedId:null,detail:null,detailPhase:"idle",omittedSections:[],publishedSessionStatus:null,unreadableReason:null,lastRefreshAtMs:null,displayNowMs:0,serverOffsetMs:0,announcement:null},s=!1,i=!1,o=0,u=null,f=null;const m=new Set,g=T=>{t=T;for(const C of m)C()},h=()=>{u!==null&&clearTimeout(u),u=null},b=()=>{h(),!(i||t.phase==="auth_expired"||t.phase==="connection_changed"||t.phase==="error"||document.visibilityState!=="visible")&&(u=setTimeout(()=>{w()},gD))},x=async()=>{if(i||document.visibilityState!=="visible")return!1;h(),f?.abort();const T=++o,C=new AbortController;f=C;try{const M=Date.now(),R=await e.listProgressReports({signal:C.signal});if(i||C.signal.aborted||T!==o)return!1;const O=Date.now(),{serverOffsetMs:G,alignedNowMs:B}=ug(R.serverNow,M,O,t.serverOffsetMs);return g({phase:"current",progressReports:R.progressReports,truncated:R.truncated,selectedId:t.selectedId,detail:t.detail,detailPhase:t.detailPhase,omittedSections:t.omittedSections,publishedSessionStatus:t.publishedSessionStatus,unreadableReason:t.unreadableReason,lastRefreshAtMs:B,displayNowMs:B,serverOffsetMs:G,announcement:null}),!0}catch(M){return i||C.signal.aborted||T!==o||g({...t,phase:tf(M,t.lastRefreshAtMs!==null)}),!1}finally{!i&&T===o&&b()}},N=async()=>{if(i||document.visibilityState!=="visible"||t.selectedId===null)return!1;h(),f?.abort();const T=++o,C=new AbortController;f=C;const M=t.selectedId;try{const R=Date.now(),O=await e.getProgressReportDetail(M,C.signal);if(i||C.signal.aborted||T!==o)return!1;const G=Date.now(),{serverOffsetMs:B,alignedNowMs:te}=ug(O.serverNow,R,G,t.serverOffsetMs);return g({phase:"current",progressReports:t.progressReports,truncated:t.truncated,selectedId:O.progressReport.session.id,detail:O.progressReport,detailPhase:"loaded",omittedSections:O.omittedSections,publishedSessionStatus:O.publishedSessionStatus??null,unreadableReason:null,lastRefreshAtMs:te,displayNowMs:te,serverOffsetMs:B,announcement:null}),!0}catch(R){if(i||C.signal.aborted||T!==o)return!1;const O=Cw(R);return O!==void 0?(g({...t,selectedId:M,detail:null,detailPhase:"not_found",unreadableReason:O,announcement:j0(O)}),!1):(g({...t,phase:tf(R,t.lastRefreshAtMs!==null),detailPhase:t.detail===null?"error":"stale"}),!1)}finally{!i&&T===o&&t.unreadableReason===null&&b()}},w=async()=>t.unreadableReason!==null?!1:t.selectedId===null?x():N(),k=()=>{document.visibilityState==="visible"?w():(h(),f?.abort())},S=()=>{document.visibilityState==="visible"&&w()},A=()=>{s&&(s=!1,o+=1,h(),f?.abort(),f=null,document.removeEventListener("visibilitychange",k),window.removeEventListener("focus",S))};return{async start(){s||i||(s=!0,(t.phase==="error"||t.phase==="offline")&&g({...t,phase:"initial_loading"}),document.addEventListener("visibilitychange",k),window.addEventListener("focus",S),await w())},stop:A,dispose(){i||(A(),i=!0,m.clear())},getState(){return t},subscribe(T){return m.add(T),()=>m.delete(T)},async retry(){t.unreadableReason!==null&&g({...t,detailPhase:t.selectedId===null?"idle":"loading",unreadableReason:null,announcement:null}),await w()},async select(T){if(i)return;h(),f?.abort(),o+=1;const C=++o,M=new AbortController;f=M,g({...t,selectedId:T,detail:null,detailPhase:"loading",omittedSections:[],publishedSessionStatus:null,unreadableReason:null,announcement:null});try{const R=Date.now(),O=await e.getProgressReportDetail(T,M.signal);if(!i&&!M.signal.aborted&&C===o){const G=Date.now(),{serverOffsetMs:B,alignedNowMs:te}=ug(O.serverNow,R,G,t.serverOffsetMs);g({phase:"current",progressReports:t.progressReports,truncated:t.truncated,selectedId:O.progressReport.session.id,detail:O.progressReport,detailPhase:"loaded",omittedSections:O.omittedSections,publishedSessionStatus:O.publishedSessionStatus??null,unreadableReason:null,lastRefreshAtMs:te,displayNowMs:te,serverOffsetMs:B,announcement:null})}}catch(R){if(M.signal.aborted||C!==o||R instanceof Ee&&R.kind==="aborted")return;const O=Cw(R);if(O!==void 0){g({...t,selectedId:T,detail:null,detailPhase:"not_found",unreadableReason:O,announcement:j0(O)});return}g({...t,phase:tf(R,t.lastRefreshAtMs!==null),detailPhase:"error"})}finally{!i&&C===o&&t.unreadableReason===null&&b()}},clearSelection(){o+=1,h(),f?.abort(),g({...t,selectedId:null,detail:null,detailPhase:"idle",omittedSections:[],publishedSessionStatus:null,unreadableReason:null,announcement:null}),!i&&document.visibilityState==="visible"&&x()},async setStatusOverride(T,C){if(!i){h(),f?.abort(),o+=1;try{const M=await e.setStatusOverride(T,C);if(i)return;M.kind==="detail"&&$(T,M),await w()}catch(M){if(i)return;g({...t,phase:tf(M,t.lastRefreshAtMs!==null)}),t.unreadableReason===null&&b()}}}};function $(T,C){if(C.progressReport.session.id!==T)return;const M=C.publishedSessionStatus;g({...t,progressReports:t.progressReports.map(R=>R.id===T?yD(R,C.progressReport.session.status,M):R),...t.selectedId===T?{detail:C.progressReport,detailPhase:"loaded",omittedSections:C.omittedSections,publishedSessionStatus:M??null,unreadableReason:null}:{}})}}function yD(e,t,s){return Object.freeze({id:e.id,title:e.title,status:t,projectFolder:e.projectFolder,startedAt:e.startedAt,updatedAt:e.updatedAt,agentCount:e.agentCount,...e.taskCounts===void 0?{}:{taskCounts:e.taskCounts},...s===void 0?{}:{publishedStatus:s}})}function j0(e){switch(e){case"removed":return"The selected progress report is no longer available.";case"malformed":return"The selected progress report could not be parsed.";case"oversized":return"The selected progress report is too large to display in the dashboard."}}const xD=3e3,po={runs:"Run monitor",activities:"Single calls",context_runs:"Context runs",progress_reports:"Progress reports",workflows:"Workflows",adapters:"Adapters",artifacts:"Artifacts",prompt_builder:"Prompt builder",settings:"Settings"};function N0(e,t){const[s,i]=v.useState(0),[o,u]=v.useState({phase:"loading",rows:[]}),f=v.useRef(!1);return v.useEffect(()=>{if(!t||f.current)return;const m=new AbortController;return u(g=>({phase:"loading",rows:g.rows})),e(m.signal).then(g=>{m.signal.aborted||(f.current=!0,u({phase:"current",rows:g.rows}))}).catch(g=>{if(m.signal.aborted)return;f.current=!0;const h=g instanceof Ee&&(g.kind==="auth_expired"||g.kind==="connection_changed"||g.kind==="offline")?g.kind:"error";u(b=>({phase:h,rows:b.rows}))}),()=>m.abort()},[t,s,e]),{state:o,retry:()=>{f.current=!1,i(m=>m+1)}}}function k0({kind:e,phase:t,retry:s}){if(t==="current")return null;if(t==="loading")return r.jsx(Gf,{message:`Loading ${e} catalog…`,role:"status"});const i=t==="auth_expired"?`Authentication expired; the ${e} catalog was not loaded.`:t==="connection_changed"?`Connection changed; rebootstrap before loading the ${e} catalog.`:t==="offline"?`Offline; the ${e} catalog could not be loaded.`:`The ${e} catalog request failed.`,o=t==="auth_expired"||t==="connection_changed"?void 0:{label:`[ retry ${e} catalog ]`,run:s};return r.jsx(Gf,{message:i,...o===void 0?{}:{retry:o},role:"alert"})}function Av({accountActions:e,applicationRootId:t="root",activityApi:s,activityController:i,artifactApi:o,catalogApi:u,contextRunsApi:f,contextRunsController:m,progressReportsApi:g,progressReportsController:h,controller:b,environmentApi:x,inspectorApi:N,resultApi:w,routeHydrationApi:k,sessionLogApi:S}){const[A]=v.useState(AR),$=eD(W=>A.setVisible(W==="/prompt-builder"));v.useLayoutEffect(()=>{A.setVisible(window.location.pathname==="/prompt-builder")});const T=$.resolution,C=T.kind==="not_found",M=T.kind==="resolved"?T:null,R=M?.destination??"runs",O=M?.selection??null,[G,B]=v.useState(!1),[te,K]=v.useState(!1),[se,ge]=v.useState(!1),[J,we]=v.useState(!1),[ue]=v.useState(()=>av()),[L]=v.useState(()=>sD(ue)),[Y]=v.useState(()=>dD(ue)),[de]=v.useState(()=>uD()),[oe]=v.useState(()=>f??Ej()),[Se]=v.useState(()=>mD(oe)),[E]=v.useState(()=>hD()),[U]=v.useState(()=>g??pM()),[P]=v.useState(()=>bD(U)),[ne]=v.useState(()=>_D()),[be]=v.useState(()=>tD()),[q]=v.useState(()=>mO()),[re]=v.useState(()=>lD()),[Re]=v.useState(()=>nj()),Te=x??re,[xe,Me]=v.useState(null),[ot,dt]=v.useState(0),[Ot,tn]=v.useState(!1),$t=nN(),wt=b??L,_n=i??(b===void 0?Y:de),kt=m??(b===void 0?Se:E),st=h??(b===void 0?P:ne),en=k??(b===void 0?ue:void 0),ea=s??ue,zt=S??(b===void 0&&i===void 0&&m===void 0&&h===void 0?Re:void 0),pt=xe!==null,on=W=>pt&&(W.lastRefreshAtMs!==null||W.phase==="error"||W.phase==="offline"||W.phase==="stale"),pe=WL(st,R==="progress_reports",pt),je=YL(wt,R==="runs",on(pe)),Le=QL(_n,R==="activities",on(je)),Oe=JL(kt,R==="context_runs",on(Le)),rt=v.useRef(je.phase);v.useEffect(()=>{const W=new AbortController;return tn(!1),Te.getEnvironment(W.signal).then(De=>{W.signal.aborted||Me({stateDir:De.stateDir,...De.activitiesRoot===void 0?{}:{activitiesRoot:De.activitiesRoot},...De.progressReportsRoot===void 0?{}:{progressReportsRoot:De.progressReportsRoot},runsRoot:De.runsRoot,workspaceRoot:De.workspaceRoot,workflowsPath:De.workflowsPath,templatesPath:De.templatesPath,childConfig:De.childConfig.source==="explicit"?`explicit · ${De.childConfig.path}`:"ambient · not configured"})}).catch(()=>{W.signal.aborted||tn(!0)}),()=>W.abort()},[Te,ot]),v.useEffect(()=>{if(!Ot||!$t)return;const W=window.setTimeout(()=>{dt(De=>De+1)},xD);return()=>window.clearTimeout(W)},[$t,Ot]),v.useEffect(()=>{const W=rt.current;rt.current=je.phase,je.phase==="current"&&W!=="current"&&Ot&&dt(De=>De+1)},[je.phase,Ot]);const ht=u??be,Ut=b===void 0||u!==void 0,gt=N0(v.useCallback(async W=>({rows:(await ht.listWorkflows(W)).workflows}),[ht]),R==="workflows"||R==="prompt_builder"||Ut),Ve=N0(v.useCallback(async W=>({rows:(await ht.listAdapters(W)).adapters}),[ht]),R==="adapters"||R==="prompt_builder"||Ut),[cn,Bt]=v.useState(null),Rn=BS(je),Da=[...je.live,...je.history].reduce((W,De)=>(De.availability!=="available"||(W[De.workflowName]=(W[De.workflowName]??0)+1),W),{}),Ya=[...je.live,...je.history].reduce((W,De)=>W+(De.availability==="available"?De.reportedRunningCalls:0),0),un=je.selected,Gt=Le.selected,Tn=O?.kind==="run"||O?.kind==="run_call"?O.runId:null,rn=$.getExpectedGeneration(),In=$.getRouteIntent();v.useEffect(()=>{if(R!=="runs"||Tn===null||$.getIntent()!==In)return;const W=new AbortController,De=wt.getState();if(De.selected?.runId===Tn&&(rn===void 0||De.selected.runGeneration===rn))return;const fe=[...De.live,...De.history].find(fn=>fn.availability==="available"&&fn.runId===Tn&&(rn===void 0||fn.runGeneration===rn));if(fe!==void 0){wt.select(fe);return}if(en!==void 0)return en.getRunDetailCurrent(Tn,W.signal).then(fn=>{W.signal.aborted||$.getIntent()!==In||fn.availability==="available"&&(rn===void 0||fn.runGeneration===rn)&&wt.select(fn)}).catch(()=>{}),()=>W.abort()},[R,en,wt,Tn,rn,In]);const ct=O?.kind==="activity"?O.activityId:null,ye=v.useRef(null);v.useEffect(()=>{if(R!=="activities")return;if(ct===null){ye.current=null,K(!1);return}if(ye.current===ct||(ye.current=ct,K(!0),Le.selected?.activityId===ct))return;const W=Le.activities.find(De=>De.activityId===ct);if(W!==void 0){_n.select(W);return}en!==void 0&&en.getActivityDetailCurrent(ct).then(De=>{ye.current===ct&&_n.select(De)}).catch(()=>{})},[_n,R,en,Le.activities,Le.selected,ct]);const he=O?.kind==="context_run"?O.contextRunId:null;v.useEffect(()=>{if(R!=="context_runs"){Oe.selectedId!==null&&kt.clearSelection();return}if(he===null){K(!1),Oe.selectedId!==null&&kt.clearSelection();return}K(!0),Oe.selectedId!==he&&kt.select(he)},[kt,R,Oe.selectedId,he]);const Ae=O?.kind==="progress_report"?O.progressReportId:null,Pe=v.useRef(Ae);v.useEffect(()=>{if(R==="progress_reports"){if(Ae===null){K(!1),pe.selectedId!==null&&st.clearSelection();return}K(!0),pe.selectedId!==Ae&&st.select(Ae)}},[st,R,pe.selectedId,Ae]),v.useEffect(()=>{const W=Pe.current;Pe.current=Ae,!(R!=="progress_reports"||W===null||Ae!==null)&&window.setTimeout(()=>{const De=document.querySelector(`.dashboard-layout__run-list [role="option"][data-item-id="${CSS.escape(W)}"]`),fe=document.querySelector(".dashboard-layout__run-list #progress-report-list-title"),fn=document.querySelector('.dashboard-layout__run-list [role="option"]');(De??fe??fn)?.focus()},0)},[R,Ae]);const Ze=Tn??je.selected?.runId??null,Fe=O?.kind==="run_call"?{stageId:O.stageId,callId:O.callId}:null,Ye=O?.kind==="artifact_reference"?{runId:O.runId,stageId:O.stageId,callId:O.callId}:null,nn=v.useRef(!1);v.useEffect(()=>{O?.kind!=="run_call"&&(nn.current=!1)},[O]);const oa=v.useCallback((W,De)=>{const fe=Ze;fe!==null&&(De==="open"&&W!==null?(nn.current=!0,$.pushRoute(Ax(fe,W.stageId,W.callId))):De==="switch"&&W!==null?$.replaceRoute(Ax(fe,W.stageId,W.callId)):nn.current?(nn.current=!1,$.back()):$.replaceRoute(Ud(fe)))},[$,Ze]),va=v.useCallback(()=>{wt.runGenerationChanged()},[wt]),z=v.useCallback(()=>{_n.clearSelection(),$.replaceRoute({kind:"activities"})},[_n,$.replaceRoute]),Ne=v.useCallback(()=>{kt.clearSelection(),$.replaceRoute({kind:"context_runs"})},[kt,$.replaceRoute]),Ce=v.useRef({path:"",run:je.detail});v.useLayoutEffect(()=>{Ce.current={path:M?.canonicalPath??"",run:je.detail}});const Ue=v.useRef($);Ue.current=$;const[Qe]=v.useState(()=>e1({dashboard:ue,readVisibleRun:()=>{const W=Ce.current.run;return W?.availability==="available"?{runId:W.runId,runGeneration:W.runGeneration}:null},openView:async(W,De)=>{const fe=await JE(W,De,{api:ue,getIntent:()=>Ue.current.getIntent()}),fn=Ue.current;fe();const vs=fn.beginAgentNavigation(W),xa=W.kind==="council"?ER(A):null,wa=yo(vS(W));K("runId"in W||"workflowName"in W||"adapterName"in W);const Xs=()=>fn.cancelIntent(vs);De.addEventListener("abort",Xs,{once:!0});try{await f1({signal:De,isCurrent:()=>Ue.current.getIntent()===vs,isVisible:()=>{const Sa=Ce.current;if(Sa.path!==wa)return!1;if(W.kind==="council")return xa()&&document.querySelector('[data-agent-builder-target="workflow"]')!==null;const ja=document.getElementById("persisted-call-inspector-title");if(W.kind!=="run_call"&&ja!==null)return!1;if("runId"in W){if(Sa.run?.availability!=="available"||Sa.run.runId!==W.runId||Sa.run.runGeneration!==W.runGeneration)return!1;if(W.kind==="run_call")return Sa.run.stages.some(Lr=>Lr.stageId===W.stageId&&Lr.calls.some(Al=>Al.callId===W.callId))&&ja?.dataset.runId===W.runId&&ja.dataset.runGeneration===W.runGeneration&&ja.dataset.stageId===W.stageId&&ja.dataset.callId===W.callId;if(W.kind==="run_result")return document.getElementById("run-result-heading")!==null}return W.kind==="workflow_detail"?document.querySelector("[data-agent-workflow]")?.getAttribute("data-agent-workflow")===W.workflowName:W.kind==="adapter_detail"?document.querySelector("[data-agent-adapter]")?.getAttribute("data-agent-adapter")===W.adapterName:!0}})}catch(Sa){throw Sa instanceof Error&&Sa.message==="view_changed"?new qt("view_changed"):Sa}finally{De.removeEventListener("abort",Xs)}return W.kind==="run_result"&&document.getElementById("run-result-heading")?.scrollIntoView?.(),{outcome:"opened",view:W}}})),At=SR(C?"not_found":R,Qe,A),Dt=v.useRef(un);v.useEffect(()=>{const W=Dt.current;Dt.current=un,!(R!=="runs"||!te||W===null||un!==null)&&(K(!1),window.setTimeout(()=>{const De=document.querySelector(".dashboard-layout__run-list [data-selection-loss-announcement]"),fe=document.querySelector('.dashboard-layout__run-list [role="option"]');(De??fe)?.focus()},0))},[R,te,un]);const Yt=v.useRef(Gt);v.useEffect(()=>{const W=Yt.current;Yt.current=Gt,!(R!=="activities"||!te||W===null||Gt!==null)&&(K(!1),window.setTimeout(()=>{const De=document.querySelector(".dashboard-layout__run-list [data-selection-loss-announcement]"),fe=document.querySelector('.dashboard-layout__run-list [role="option"]');(De??fe)?.focus()},0))},[R,te,Gt]);const Cn=O?.kind==="workflow"?O.workflowName:null,Je=O?.kind==="adapter"?O.adapterName:null;v.useEffect(()=>{R!=="adapters"&&(ge(!1),we(!1))},[R]);const wn=v.useRef(null);v.useEffect(()=>{const W=R==="runs"?un?.runId??null:R==="activities"?Gt?.activityId??null:R==="context_runs"?he:R==="progress_reports"?Ae:R==="workflows"?Cn:R==="adapters"?Je:R==="artifacts"?Ye===null?null:`${Ye.runId}:${Ye.callId}`:null;W===null||W===wn.current||(wn.current=W,document.querySelector(".dashboard-layout__detail")?.scrollTo?.({top:0}))},[R,un,Gt,he,Ae,Cn,Je,Ye]);const Mn=R==="activities"?Le.phase:R==="context_runs"?Oe.phase:R==="progress_reports"?pe.phase:je.phase,ca=R==="runs"||R==="activities"||R==="context_runs"||R==="progress_reports",Ln=W=>{W==="artifacts"&&B(!0),K(!1),$.navigateToDestination(W)},Ft=()=>{K(!1),window.setTimeout(()=>{document.querySelector('.dashboard-layout__run-list [role="option"][aria-selected="true"]')?.focus()},0)},Sn=()=>{$.pushRoute({kind:"activities"}),Ft()},jt=()=>{$.pushRoute({kind:"workflows"}),Ft()},Mr=()=>{$.pushRoute({kind:"adapters"}),Ft()},Nl=()=>{$.pushRoute({kind:"artifacts"}),Ft()},_a=()=>{$.pushRoute({kind:"progress_reports"})},Dn=je.detail!==null&&je.detail.availability==="available"?je.detail:null,ms=Dn!==null||Le.lastRefreshAtMs!==null,gs=W=>zO(W,Dn,Le.activities),ba=ms&&Ve.state.phase==="current"?Object.fromEntries(Ve.state.rows.map(W=>[W.name,gs(W.name).length])):void 0,kl=vv(),ua=se&&!kl,ya=yj(Ve.state.rows,Je??void 0),Qt=ms&&ya!==void 0?gs(ya.name):void 0,dn={...je.lastRefreshAtMs===null?{}:{runs:je.live.length+je.history.length},...Le.lastRefreshAtMs===null?{}:{activities:Le.activities.length},...Oe.lastRefreshAtMs===null?{}:{context_runs:Oe.contextRuns.length},...pe.lastRefreshAtMs===null?{}:{progress_reports:pe.progressReports.length},...gt.state.phase==="current"?{workflows:gt.state.rows.length}:{},...Ve.state.phase==="current"?{adapters:Ve.state.rows.length}:{},...cn===null?{}:{artifacts:cn}},[ta,Hn]=v.useState(0),Ti=v.useMemo(()=>{const W=(fe,fn)=>{if(fe===void 0)return"";const vs=Date.parse(fe);if(!Number.isFinite(vs))return"";const xa=fn===void 0?Number.NaN:Date.parse(fn),wa=Number.isFinite(xa)?xa-vs:je.displayNowMs-vs;return wa>=0?Eo(wa):""},De=[];for(const fe of je.live)fe.availability==="available"&&De.push({group:"runs",id:`run:${fe.runId}`,name:fe.workflowName,sub:`run ${fe.runId}`,meta:W(fe.startedAt,fe.completedAt),status:fe.status,searchTerms:[fe.runId,fe.workflowName,fe.status,`v${fe.workflowVersion}`],targetId:fe.runId});for(const fe of je.history)fe.availability==="available"&&De.push({group:"runs",id:`run:${fe.runId}`,name:fe.workflowName,sub:`run ${fe.runId}`,meta:W(fe.startedAt,fe.completedAt),status:fe.status,searchTerms:[fe.runId,fe.workflowName,fe.status,`v${fe.workflowVersion}`],targetId:fe.runId});for(const fe of Le.activities)De.push({group:"calls",id:`call:${fe.activityId}`,name:`${fe.kind} · ${fe.adapter} / ${fe.role}`,sub:`activity ${fe.activityId}`,meta:W(fe.startedAt,fe.completedAt),status:fe.status,searchTerms:[fe.activityId,fe.kind,fe.adapter,fe.role,fe.status],targetId:fe.activityId});for(const fe of Oe.contextRuns)fe.lifecycle!==null&&De.push({group:"context",id:`ctx:${fe.id}`,name:fe.operationKind,sub:fe.id,meta:fe.lifecycle.durationMs===null?"":Eo(fe.lifecycle.durationMs),status:fe.lifecycle.status,searchTerms:[fe.id,fe.operationKind,fe.source,fe.lifecycle.status],targetId:fe.id});for(const fe of pe.progressReports)De.push({group:"progress",id:`report:${fe.id}`,name:fe.title,sub:fe.id,meta:$n(fe.updatedAt,pe.displayNowMs),status:fe.status,searchTerms:[fe.id,fe.title,fe.status],targetId:fe.id});if(gt.state.phase==="current")for(const fe of gt.state.rows)De.push({group:"workflows",id:`workflow:${fe.name}`,name:fe.name,sub:`workflow · v${fe.version}`,meta:`${String(fe.stageCount)} stages · ${String(fe.callCount)} calls`,status:"",searchTerms:[fe.name,"workflow",`v${fe.version}`,fe.description],targetId:fe.name});if(Ve.state.phase==="current")for(const fe of Ve.state.rows)De.push({group:"adapters",id:`adapter:${fe.name}`,name:fe.name,sub:`adapter · $ ${fe.command}`,meta:fe.parser,status:"",searchTerms:[fe.name,"adapter",fe.parser,fe.command,fe.backend],targetId:fe.name});return De},[je,Le.activities,Oe.contextRuns,pe,gt.state,Ve.state]);if(!C&&R==="progress_reports"&&Ae!==null)return r.jsx(Lw,{detail:pe.detail,detailPhase:pe.detailPhase,nowMs:pe.displayNowMs,onBack:_a,onRetry:()=>{st.retry()},onSetStatusOverride:W=>{st.setStatusOverride(Ae,W)},omittedSections:pe.omittedSections,pollingPhase:pe.phase,...pe.publishedSessionStatus===null?{}:{publishedSessionStatus:pe.publishedSessionStatus},selectedId:Ae,unreadableReason:pe.unreadableReason});const Qa=W=>{switch(Hn(De=>De+1),W.group){case"runs":K(!0),$.pushRoute(Ud(W.targetId));return;case"calls":K(!0),$.pushRoute(Om(W.targetId));return;case"context":$.pushRoute(Ex(W.targetId));return;case"progress":$.pushRoute(Rx(W.targetId));return;case"workflows":$.pushRoute(Tx(W.targetId));return;case"adapters":$.pushRoute($m(W.targetId));return}};return r.jsxs(GR,{webMcp:At,...e===void 0?{}:{accountActions:e},activeDestination:C?null:R,applicationRootId:t,environment:xe,jumpItems:Ti,navigationCounts:dn,observationAvailable:C?!1:ca,onJumpOpen:Qa,onNavigate:Ln,pageTitle:C?"Not found":po[R],pollingPhase:Mn,reportedRunningCalls:{count:je.lastRefreshAtMs===null?null:Ya,refreshedLabel:je.lastRefreshAtMs===null?null:Rn.lastRefreshLabel},children:[C?r.jsxs("section",{className:"app-shell__view","aria-labelledby":"dashboard-page-title",children:[r.jsx("h1",{id:"dashboard-page-title",className:"app-shell__title",children:"Page not found"}),r.jsxs("p",{className:"app-shell__note",role:"status",children:["No dashboard view matches ",r.jsx("code",{children:T.rawPath}),"."]}),r.jsx("button",{className:"app-shell__not-found-action",onClick:()=>Ln("runs"),type:"button",children:"Go to run monitor"})]}):null,!C&&R==="runs"?r.jsx(yr,{detail:r.jsx(N$,{applicationRootId:t,...N===void 0?{}:{inspectorApi:N},onBack:Ft,onInspectorRouteChange:oa,onRetry:()=>{wt.retry()},onRunGenerationChanged:va,...je.detail?.availability!=="available"?{}:{contextPreflight:je.detail.contextPreflight??null},...w===void 0?{}:{resultApi:w},routeCall:Fe,...zt===void 0?{}:{sessionLogApi:zt},state:je}),mobileView:un!==null&&te?"detail":"list",runList:r.jsxs("section",{className:"app-shell__view","aria-live":"off",children:[r.jsx("h1",{id:"dashboard-page-title",className:"visually-hidden",children:po[R]}),r.jsx(B$,{filterResetKey:ta,onNewer:()=>{wt.newer()},onOlder:()=>{wt.older()},onRetry:()=>{wt.retry()},onSelect:W=>{K(!0),$.pushRoute(Ud(W.runId)),wt.select(W)},state:je})]})}):null,!C&&R==="activities"?r.jsx(yr,{detailAriaLabel:"Single-call detail",listAriaLabel:"Single-call list",detail:r.jsx(M$,{api:ea,detail:ct===null?null:Le.detail,detailPhase:ct===null?"idle":Le.detailPhase,nowMs:Le.displayNowMs,onBack:Sn,onGenerationChanged:z,selection:ct===null?null:Gt,...zt===void 0?{}:{sessionLogApi:zt}},ct===null||Gt===null?"activity:none":[Gt.activityId,Gt.activityGeneration].join(":")),mobileView:Gt!==null&&te?"detail":"list",runList:r.jsxs("section",{className:"app-shell__view","aria-live":"off",children:[r.jsx("h1",{id:"dashboard-page-title",className:"visually-hidden",children:po[R]}),r.jsx(P$,{filterResetKey:ta,activities:Le.activities,announcement:Le.announcement,hasSnapshot:Le.lastRefreshAtMs!==null,onRetry:()=>{_n.retry()},onSelect:W=>{K(!0),ye.current=W.activityId,$.pushRoute(Om(W.activityId)),_n.select(W)},phase:Le.phase,selected:Le.selected,nowMs:Le.displayNowMs})]})}):null,!C&&R==="context_runs"?r.jsx(yr,{detailAriaLabel:"Context run detail",listAriaLabel:"Context run list",detail:r.jsx(NI,{canRetry:Oe.phase==="current"||Oe.phase==="stale"||Oe.phase==="offline"||Oe.phase==="error",detail:Oe.detail,detailPhase:Oe.detailPhase,onBack:()=>{$.pushRoute({kind:"context_runs"})},onGenerationChanged:Ne,onRetry:()=>{kt.retry()},selectedId:he,contextRunsApi:oe,...zt===void 0?{}:{sessionLogApi:zt}}),mobileView:he!==null?"detail":"list",runList:r.jsxs("section",{className:"app-shell__view","aria-live":"off",children:[r.jsx("h1",{id:"dashboard-page-title",className:"visually-hidden",children:po[R]}),r.jsx(AI,{filterResetKey:ta,announcement:Oe.announcement,contextRuns:Oe.contextRuns,hasSnapshot:Oe.lastRefreshAtMs!==null,nowMs:Oe.displayNowMs,onRetry:()=>{kt.retry()},onSelect:W=>{$.pushRoute(Ex(W))},phase:Oe.phase,selectedId:Oe.selectedId})]})}):null,!C&&R==="progress_reports"?r.jsx(yr,{detailAriaLabel:"Progress report detail",listAriaLabel:"Progress report list",detail:r.jsx(Lw,{detail:pe.detail,detailPhase:pe.detailPhase,nowMs:pe.displayNowMs,onBack:_a,onRetry:()=>{st.retry()},onSetStatusOverride:W=>{Ae!==null&&st.setStatusOverride(Ae,W)},omittedSections:pe.omittedSections,pollingPhase:pe.phase,...pe.publishedSessionStatus===null?{}:{publishedSessionStatus:pe.publishedSessionStatus},selectedId:Ae,unreadableReason:pe.unreadableReason}),mobileView:Ae!==null?"detail":"list",runList:r.jsxs("section",{className:"app-shell__view","aria-live":"off",children:[r.jsx("h1",{id:"dashboard-page-title",className:"visually-hidden",children:po[R]}),r.jsx(TI,{announcement:pe.announcement,filterResetKey:ta,progressReports:pe.progressReports,hasSnapshot:pe.lastRefreshAtMs!==null,nowMs:pe.displayNowMs,onRetry:()=>{st.retry()},onSelect:W=>{$.pushRoute(Rx(W))},phase:pe.phase,...xe?.progressReportsRoot===void 0?{}:{progressReportsRoot:xe.progressReportsRoot},selectedId:pe.selectedId,truncated:pe.truncated})]})}):null,!C&&R==="workflows"?r.jsx(yr,{detailAriaLabel:"Workflow detail",listAriaLabel:"Workflow index",detail:gt.state.phase==="current"?r.jsx(QO,{onBack:jt,runCounts:Da,workflow:_j(gt.state.rows,Cn??void 0)}):null,mobileView:Cn!==null?"detail":"list",runList:r.jsxs("section",{className:"app-shell__view","aria-live":"off",children:[r.jsx("h1",{id:"dashboard-page-title",className:"visually-hidden",children:po[R]}),r.jsx(k0,{kind:"workflow",phase:gt.state.phase,retry:gt.retry}),gt.state.phase==="current"?r.jsx(ZO,{onSelect:W=>$.pushRoute(Tx(W)),...xe?.workflowsPath===void 0?{}:{sourcePath:xe.workflowsPath},runCounts:Da,...Cn===null?{}:{selectedName:Cn},workflows:gt.state.rows}):null]})}):null,!C&&R==="adapters"?r.jsx(yr,{detailAriaLabel:"Adapter detail",listAriaLabel:"Adapter index",detail:Ve.state.phase==="current"?ua?r.jsx(s$,{adapters:Ve.state.rows,differencesOnly:J,onClose:()=>ge(!1),onDifferencesToggle:()=>we(W=>!W),onOpenAdapter:W=>{ge(!1),$.pushRoute($m(W))},...Je===null?{}:{selectedName:Je},...ba===void 0?{}:{useCounts:ba}}):r.jsx(a$,{adapter:ya,adapters:Ve.state.rows,onBack:Mr,onOpenUse:W=>{W.kind==="workflow"?$.pushRoute(Ud(W.runId)):$.pushRoute(Om(W.activityId))},...Qt===void 0?{}:{uses:Qt}}):null,mobileView:Je!==null?"detail":"list",runList:r.jsxs("section",{className:"app-shell__view","aria-live":"off",children:[r.jsx("h1",{id:"dashboard-page-title",className:"visually-hidden",children:"Adapters"}),r.jsx(k0,{kind:"adapter",phase:Ve.state.phase,retry:Ve.retry}),Ve.state.phase==="current"?r.jsx(WO,{adapters:Ve.state.rows,compareOn:ua,onCompareToggle:()=>ge(W=>!W),onSelect:W=>$.pushRoute($m(W)),...Je===null?{}:{selectedName:Je},...ba===void 0?{}:{useCounts:ba}}):null]})}):null,!C&&(G||je.lastRefreshAtMs!==null&&(b===void 0||o!==void 0))?r.jsx("div",{className:"app-shell__catalog-frame",hidden:R!=="artifacts",children:r.jsx(p$,{active:R==="artifacts",api:o??q,mobileView:Ye!==null?"detail":"list",onBackToList:Nl,onLoadedCount:Bt,onSelectReference:W=>{$.pushRoute(d1(W.runId,W.stageId,W.callId))},runs:[...je.live,...je.history],selection:Ye,...xe?.runsRoot===void 0?{}:{runsRoot:xe.runsRoot}})}):null,!C&&R==="prompt_builder"?r.jsx(b2,{agentHost:A,adapters:{phase:Ve.state.phase,rows:Ve.state.rows,retry:Ve.retry},workflows:{phase:gt.state.phase,rows:gt.state.rows,retry:gt.retry}}):null,!C&&R==="settings"?r.jsx(ZL,{applicationRootId:t}):null]})}class Jn extends Error{status;code;constructor(t,s){super(s),this.name="DashboardAuthApiError",this.status=t,this.code=s}}const wD=`{"error":{"code":"not_found"}}
|
|
122
|
-
`,SD="no-store",jD="application/json; charset=utf-8",ND=/^[A-Za-z0-9_-]{43}$/,aN=new WeakSet;function kD(){const e=new Jn(404,"not_found");return aN.add(e),e}async function AD(e,t){try{return(await e.status()).mode}catch(s){if(t&&s instanceof Jn&&aN.has(s))return"bearer";throw s}}function $o(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sN(e,t){if(!e.ok){const s=$o(t)&&$o(t.error)&&typeof t.error.code=="string"?t.error.code:"request_failed";throw new Jn(e.status,s)}return t}function rN(e,t){return Y0()?aS(e,t):fetch(e,t)}async function iN(e){ha(e);let t;try{t=await e.json()}catch{throw ha(e),new Jn(e.status,"invalid_response")}return ha(e),sN(e,t)}async function ED(e){if(e.status!==404)return iN(e);ha(e);let t;try{t=await e.text()}catch{throw ha(e),new Jn(e.status,"invalid_response")}if(ha(e),t===wD&&e.headers.get("cache-control")===SD&&e.headers.get("content-type")===jD)throw kD();let s;try{s=JSON.parse(t)}catch{throw new Jn(e.status,"invalid_response")}return sN(e,s)}async function tl(e,t,s){const i=Jg(),o=await rN(e,{method:"POST",credentials:"same-origin",redirect:"error",referrerPolicy:"no-referrer",headers:{"Content-Type":"application/json",...s==null?{}:{"X-Enrollment-Code":s},...i==null?{}:{[Cf]:i}},body:JSON.stringify(t)});try{return await iN(o)}catch(u){throw u instanceof Jn&&u.status===401&&Fs(),u}}function RD(e){if(!$o(e))throw new Jn(200,"invalid_response");if(Object.keys(e).sort().join("\0")!==["authenticated","enrolled","mode"].sort().join("\0")||typeof e.enrolled!="boolean"||typeof e.authenticated!="boolean"||e.mode!=="passkey"&&e.mode!=="bearer"&&e.mode!=="none")throw new Jn(200,"invalid_response");return e}function bf(e){if(!$o(e)||typeof e.challenge!="string")throw new Jn(200,"invalid_response");return e}function TD(e){if(!$o(e)||typeof e.challengeId!="string"||!/^[A-Za-z0-9_-]{43}$/.test(e.challengeId))throw new Jn(200,"invalid_response");return{challengeId:e.challengeId,options:bf(e.options)}}function CD(e){if(!$o(e))throw Fs(),new Jn(200,"invalid_response");const t=Object.keys(e).sort().join("\0");if(wu()){if(t!==["originProof","verified"].sort().join("\0")||e.verified!==!0||typeof e.originProof!="string"||!ND.test(e.originProof))throw Fs(),new Jn(200,"invalid_response");try{DA(e.originProof)}catch{throw Fs(),new Jn(200,"invalid_response")}return}if(t!=="verified"||e.verified!==!0)throw new Jn(200,"invalid_response")}function wp(){return{async status(e){try{const t=Jg(),s=await rN("/api/auth/status",{method:"GET",credentials:"same-origin",redirect:"error",referrerPolicy:"no-referrer",...t==null?{}:{headers:{[Cf]:t}},...e==null?{}:{signal:e}}),i=RD(await ED(s));return i.authenticated||Fs(),i}catch(t){throw wu()&&t instanceof Jn&&Fs(),t}},async registrationOptions(e){return bf(await tl("/api/auth/register/options",{},e))},async verifyRegistration(e,t,s){await tl("/api/auth/register/verify",{response:e,...s==null?{}:{label:s}},t)},async registerAssertionOptions(){return TD(await tl("/api/auth/register/assert/options",{}))},async verifyRegisterAssertion(e,t){return bf(await tl("/api/auth/register/assert/verify",{challengeId:e,response:t}))},async authenticationOptions(){return bf(await tl("/api/auth/login/options",{}))},async verifyAuthentication(e){CD(await tl("/api/auth/login/verify",{response:e}))},async logout(){try{await tl("/api/auth/logout",{})}finally{Fs()}}}}const OD=/^[A-Za-z0-9_-]{32}$/,$D={supports:ku,register:async e=>Wj({optionsJSON:e}),authenticate:async e=>tN({optionsJSON:e})};function dg(e){if(e instanceof Jn){if(e.status===401)return"Authorization was rejected.";if(e.code==="not_enrolled")return"Register a passkey before signing in.";if(e.code==="passkey_assertion_required")return"Adding a passkey needs a passkey that is already enrolled. Refresh the status and try again.";if(e.code==="state_conflict")return"Enrollment changed. Refresh the status and try again."}return e instanceof DOMException&&e.name==="NotAllowedError"?"The passkey request was cancelled or timed out.":"The passkey request could not be completed."}function lN({api:e,webauthn:t,authenticatedContent:s,preAuthActions:i}){const o=v.useMemo(()=>e??wp(),[e]),u=t??$D,[f,m]=v.useState(null),[g,h]=v.useState(""),b=v.useRef(""),x=v.useRef(!0),[N,w]=v.useState(null),[k,S]=v.useState(null);v.useEffect(()=>{x.current=!0,Yc("passkey");const C=new AbortController;o.status(C.signal).then(R=>{C.signal.aborted||m(R)},R=>{C.signal.aborted||S(dg(R))});const M=()=>{m(R=>R==null?R:{...R,authenticated:!1}),S("Your dashboard session expired. Sign in again.")};return window.addEventListener(cu,M),()=>{x.current=!1,C.abort(),window.removeEventListener(cu,M),b.current="",h("")}},[o]);const A=C=>{if(N!=null)return;const M=C?void 0:b.current.trim();if(!C&&!OD.test(M??"")){S("Enter the 32-character enrollment code from the launch output.");return}S(null),w("register");const R=gl(),O=()=>x.current&&Ks(R);(async()=>{try{let B;if(C){const K=await o.registerAssertionOptions();if(!O())return;const se=await u.authenticate(K.options);if(!O())return;B=await o.verifyRegisterAssertion(K.challengeId,se)}else B=await o.registrationOptions(M);if(!O())return;const te=await u.register(B);if(!O())return;await o.verifyRegistration(te,C?void 0:b.current.trim()||void 0)}finally{b.current=""}if(!O())return;h("");const G=await o.status();O()&&m(G)})().catch(G=>{O()&&(h(""),S(dg(G)))}).finally(()=>{x.current&&w(null)})},$=()=>{if(N!=null)return;S(null),w("login");const C=gl(),M=()=>x.current&&Ks(C);(async()=>{const R=await o.authenticationOptions();if(!M())return;const O=await u.authenticate(R);if(!M()||(await o.verifyAuthentication(O),!M()))return;const G=await o.status();M()&&m(G)})().catch(R=>{M()&&S(dg(R))}).finally(()=>{x.current&&w(null)})},T=()=>{N==null&&(S(null),w("logout"),window.dispatchEvent(new CustomEvent(Of)),o.logout().then(async()=>{if(x.current){m(C=>C==null?C:{...C,authenticated:!1});try{const C=await o.status();x.current&&m(C)}catch{x.current&&S("Signed out locally, but authentication status could not be refreshed.")}}}).catch(()=>{x.current&&(m(C=>C==null?C:{...C,authenticated:!1}),S("Sign-out could not be confirmed. You were signed out locally."))}).finally(()=>{x.current&&w(null)}))};if(f===null)return r.jsx("main",{className:"auth-gate",children:r.jsxs("section",{className:"auth-gate__card",children:[r.jsx("h1",{children:"ClinkX field station"}),r.jsx("p",{"aria-live":"polite",children:k??"Checking passkey status…"}),i]})});if(!u.supports())return r.jsx("main",{className:"auth-gate",children:r.jsxs("section",{className:"auth-gate__card",children:[r.jsx("h1",{children:"Passkeys unavailable"}),r.jsx("p",{children:"This browser does not support WebAuthn. Open the dashboard in a supported browser."}),i]})});if(f.authenticated){const C={error:k,onAddPasskey:()=>A(!0),onSignOut:T,pending:N==="register"||N==="logout"?N:null};return r.jsx("div",{className:"auth-gate__authenticated",children:s?.(C)??r.jsx(Av,{accountActions:C})})}return r.jsx("main",{className:"auth-gate",children:r.jsxs("section",{className:"auth-gate__card","aria-labelledby":"auth-gate-title",children:[r.jsx("span",{"aria-hidden":"true",className:"auth-gate__mark"}),r.jsx("h1",{id:"auth-gate-title",children:"ClinkX field station"}),f.enrolled?r.jsxs(r.Fragment,{children:[r.jsx("p",{children:"Use your passkey to open the run monitor."}),r.jsx("button",{type:"button",disabled:N!==null,onClick:$,children:N==="login"?"Waiting for passkey…":"Sign in"})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{children:"Register the first passkey with the one-time enrollment code."}),r.jsx("label",{htmlFor:"enrollment-code",children:"Enrollment code"}),r.jsx("input",{id:"enrollment-code",value:g,disabled:N!==null,autoComplete:"off",autoCapitalize:"off",spellCheck:!1,onChange:C=>{b.current=C.target.value,h(C.target.value),k!=null&&S(null)}}),r.jsx("button",{type:"button",disabled:N!==null,onClick:()=>A(!1),children:N==="register"?"Waiting for passkey…":"Register this device"})]}),k==null?null:r.jsx("p",{className:"auth-gate__error",role:"alert",children:k}),i]})})}const ID=/^[A-Za-z0-9_-]{43}$/;function MD({onSubmit:e}){const[t,s]=v.useState(""),[i,o]=v.useState(null),[u,f]=v.useState(!1),m=v.useId(),g=v.useId(),h=b=>{if(b.preventDefault(),u)return;const x=t.trim();if(!ID.test(x)){o("Enter the 43-character access token from the launch output.");return}o(null),f(!0),e(x).then(N=>{N||(o("That token was rejected. Check the launch output and try again."),f(!1))},()=>{o("Could not reach the dashboard. Is it still running?"),f(!1)})};return r.jsx("main",{className:"login",children:r.jsxs("section",{className:"login__card","aria-labelledby":"login-title",children:[r.jsx("span",{"aria-hidden":"true",className:"login__mark",children:r.jsx("span",{className:"login__mark-dot"})}),r.jsx("h1",{className:"login__title",id:"login-title",children:"ClinkX field station"}),r.jsx("p",{className:"login__lede",children:"Paste the access token printed when the dashboard started to open the run monitor."}),r.jsxs("form",{className:"login__form",onSubmit:h,noValidate:!0,children:[r.jsx("label",{className:"login__label op-caption",htmlFor:m,children:"Access token"}),r.jsx("input",{id:m,className:"login__input",type:"password",autoComplete:"off",autoCapitalize:"off",spellCheck:!1,autoFocus:!0,value:t,disabled:u,"aria-invalid":i!==null,...i===null?{}:{"aria-describedby":g},onChange:b=>{s(b.target.value),i!==null&&o(null)}}),i===null?null:r.jsx("p",{className:"login__error op-caption",id:g,role:"alert",children:i}),r.jsx("button",{className:"login__submit",type:"submit",disabled:u,children:u?"Opening…":"Open dashboard"})]})]})})}const LD="clinkx-dashboard-public-origin",A0=2;function DD(e){try{const t=new URL(e);return t.protocol==="https:"&&t.origin===e}catch{return!1}}function qD(e=document,t=window.location.origin){const s=e.querySelectorAll(`meta[name="${LD}"]`);if(s.length===0)return{kind:"standalone"};const i=s.length===1?s[0]?.getAttribute("content")??"":"";return!DD(i)||i!==t?{kind:"misconfigured"}:{kind:"hosted",publicOrigin:i}}const bi=et().datetime(),Ev=et().max(4096).refine(e=>{try{const t=new URL(e);return t.protocol==="https:"&&t.username===""&&t.password===""}catch{return!1}});function Sp(e){return et().regex(new RegExp(`^${e}_[A-Za-z0-9_-]{16,64}$`))}const zD=lt(["owner"]),Rv=Sp("cmp"),oN=et().regex(/^clxd_[A-Za-z0-9_-]{43}$/),UD=lt(["paid_period","past_due_grace","period_ended","grace_expired","no_purchase","payment_pending","subscription_inactive","unknown_state","suspended","operator_grant"]),BD=lt(["none","active","trialing","past_due","incomplete","incomplete_expired","unpaid","canceled","paused","unknown"]),cN=$e({access:lt(["granted","denied"]),reason:UD,subscription_state:BD,access_until:bi.nullable(),grant_until:bi.nullable(),grace_deadline:bi.nullable(),suspended:lu(),last_reconciled_at:bi.nullable(),stale:lu()}).strict().refine(e=>e.access==="denied"||e.access_until!==null).refine(e=>!e.suspended||e.access==="denied"),uN=$e({companion_id:Rv,label:et().min(1).max(64).regex(/^[\x20-\x7e]+$/),created_at:bi,key_issued_at:bi.nullable(),connection:$e({state:lt(["offline","online"]),connection_generation:Ia().int().nonnegative().nullable()}).strict().refine(e=>e.state==="online"==(e.connection_generation!==null))}).strict(),GD=$e({workspace:$e({id:Sp("ten")}).strict(),role:zD,billing_enabled:lu(),entitlement:cN,max_workstations:nt(A0),workstations:Qn(uN).max(A0)}).strict(),PD=$e({workstation:uN,api_key:oN}).strict(),HD=$e({companion_id:Rv,api_key:oN,revoked_credential_id:Sp("cred").nullable(),closed_connections:Ia().int().nonnegative()}).strict(),VD=$e({companion_id:Rv,revoked_at:bi,closed_connections:Ia().int().nonnegative()}).strict(),FD=$e({entitlement:cN}).strict(),KD=$e({checkout_url:Ev}).strict(),ZD=$e({portal_url:Ev}).strict(),XD=$e({logged_out:nt(!0)}).strict(),YD=$e({account:$e({id:Sp("acc"),display_name:et().min(1).max(200).nullable()}).strict(),expires_at:bi}).strict(),QD=$e({authorization_url:Ev}).strict(),dN=["unauthenticated","auth_failed","forbidden","not_member","not_found","method_not_allowed","misdirected_request","credential_revoked","entitlement_inactive","context_mismatch","not_active","workstation_limit","workstation_not_found","workstation_required","subscription_active","payload_too_large","invalid_request","webhook_signature_invalid","rate_limited","outcome_unknown","store_unavailable","provider_unavailable","companion_offline"],JD=$e({error:$e({code:lt(dN),message:et().min(1).max(500).optional()}).strict()}).strict();class Hs extends Error{status;code;constructor(t,s){super(s),this.name="ControlApiError",this.status=t,this.code=s}}function WD(e){const t=JD.safeParse(e);if(t.success)return t.data.error.code;const s=B0(e);return dN.includes(s??"")?s:"invalid_response"}const fN={credentials:"same-origin",redirect:"error",referrerPolicy:"no-referrer",cache:"no-store"};function nl(e,t){return{...fN,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}}function fg(e){return{...fN,method:"GET",...e===void 0?{}:{signal:e}}}async function Ds(e,t,s){try{return await e(t,s)}catch(i){throw i instanceof TypeError?new Hs(0,"network_error"):i}}async function e4(e,t){try{return await t(e)}catch(s){throw s instanceof Ct?s:new Hs(e.status,"invalid_response")}}async function qs(e,t,s=i=>i.json()){const i=await e4(e,s);if(!e.ok)throw new Hs(e.status,WD(i));const o=t.safeParse(i);if(!o.success)throw new Hs(e.status,"invalid_response");return o.data}const pN="CLINKX_DASHBOARD_GATEWAY_TOKEN=";function t4(e){return`${pN}${e}`}function n4(e=(s,i)=>fetch(s,i),t=aS){return{async session(s){const i=await Ds(e,"/api/control/auth/session",fg(s));try{return await qs(i,YD)}catch(o){if(o instanceof Hs&&o.code==="unauthenticated")return null;throw o}},async startSignIn(){const s=await Ds(e,"/api/control/auth/start",nl({}));return(await qs(s,QD)).authorization_url},async readWorkspace(s){const i=await Ds(e,"/api/control/workspace",fg(s)),o=await qs(i,GD),u=ou(i.headers.get(z0));if(u===null||u.tenantId!==o.workspace.id||u.companionId!==null)throw new Hs(i.status,"invalid_response");return{workspace:o,context:u}},async createWorkstation(s){const i=await Ds(t,"/api/control/workstations",nl({label:s}));return qs(i,PD,xn)},async rotateWorkstation(s){const i=await Ds(t,"/api/control/workstations/rotate",nl({companion_id:s})),o=await qs(i,HD,xn);if(o.companion_id!==s)throw new Hs(i.status,"invalid_response");return o},async revokeWorkstation(s){const i=await Ds(t,"/api/control/workstations/revoke",nl({companion_id:s})),o=await qs(i,VD,xn);if(o.companion_id!==s)throw new Hs(i.status,"invalid_response");return o},async billingStatus(s){const i=await Ds(t,"/api/control/billing/status",fg(s));return(await qs(i,FD,xn)).entitlement},async startCheckout(){const s=await Ds(t,"/api/control/billing/checkout",nl({}));return(await qs(s,KD,xn)).checkout_url},async openPortal(){const s=await Ds(t,"/api/control/billing/portal",nl({}));return(await qs(s,ZD,xn)).portal_url},async logout(){const s=await Ds(e,"/api/control/auth/logout",nl({}));await qs(s,XD)}}}const a4=new Set(["unauthenticated","forbidden","not_member","misdirected_request"]),s4=new Set(["network_error","store_unavailable","rate_limited","invalid_response"]);function r4(e,t){return a4.has(e)?!1:s4.has(e)||t>=500}async function i4(e,t){const s=Qc();try{const{workspace:i,context:o}=await e.readWorkspace(t);if(t?.aborted===!0)throw new DOMException("aborted","AbortError");const u=J0(o,s);return u===null?{kind:"superseded"}:{kind:"ready",workspace:i,context:o,epoch:u}}catch(i){if(!(i instanceof Hs))throw i;return s!==Qc()?{kind:"superseded"}:i.code==="unauthenticated"?{kind:"signed_out"}:{kind:"unavailable",code:i.code,status:i.status}}}function pg(e,t,s){const i=t.connection.connection_generation;if(t.connection.state!=="online"||i===null)return{kind:"offline"};const o={tenantId:e.context.tenantId,companionId:t.companion_id,generation:i},u=J0(o,s);return u===null?{kind:"superseded"}:{kind:"selected",context:o,epoch:u}}const hg="billing";function l4(e=window){const t=new URLSearchParams(e.location.search);if(!t.has(hg))return"none";const s=t.getAll(hg);t.delete(hg);const i=t.toString();e.history.replaceState(e.history.state,"",e.location.pathname+(i===""?"":`?${i}`)+e.location.hash);const[o]=s;return s.length!==1?"invalid":o==="checkout_complete"||o==="checkout_canceled"?o:"invalid"}const Vg="This workspace has no active access. Ask the operator to grant access.";function Fg(e,t,s=!0){if(e instanceof ds&&e.failure==="entitlement_inactive")return s?"An active subscription is required to create an API key.":Vg;if(e instanceof Hs){if(e.code==="forbidden"||e.code==="not_member")return"Only the workspace owner can do this.";if(e.code==="provider_unavailable")return"Billing is not available yet. Try again later.";if(e.code==="rate_limited")return"Too many requests. Wait a moment and try again.";if(e.code==="entitlement_inactive")return s?"An active subscription is required to create an API key.":Vg;if(e.code==="workstation_limit")return`This ${s?"subscription":"workspace"} already has its maximum number of workstations. Revoke one first.`;if(e.code==="subscription_active")return"This workspace already has a subscription. Use Manage billing to change it.";if(e.code==="workstation_not_found"||e.code==="not_active")return"That workstation is no longer active. Reload the workspace and try again.";if(e.code==="invalid_request")return"Use 1-64 printable characters for the workstation name."}return t}function o4({issued:e,onDone:t}){const s=t4(e.apiKey),i=v.useRef(null);return v.useEffect(()=>{i.current?.focus()},[e]),r.jsxs("section",{className:"hosted-owner__section hosted-owner__section--key","aria-labelledby":"hosted-key-title",children:[r.jsxs("div",{className:"hosted-owner__section-head",children:[r.jsxs("h2",{id:"hosted-key-title",ref:i,tabIndex:-1,children:["API key for ",e.label]}),r.jsx("span",{className:"hosted-owner__stamp",children:"shown once"})]}),r.jsxs("p",{className:"hosted-owner__hint",children:["This key is shown once. Put this line in ",r.jsx("code",{children:"deploy/dashboard-companion/.env"})," on that workstation, then start the companion."]}),r.jsxs("output",{className:"hosted-owner__secret","aria-label":"Companion .env line",children:[r.jsx("span",{className:"hosted-owner__secret-var",children:pN}),e.apiKey]}),r.jsxs("div",{className:"hosted-owner__actions",children:[r.jsx(ma,{label:"Copy .env line",idleLabel:"[ copy .env line ]",text:s}),r.jsx(ma,{label:"Copy API key",idleLabel:"[ copy api key ]",text:e.apiKey}),r.jsx("button",{type:"button",className:"hosted-btn hosted-btn--outline",onClick:t,children:"Done"})]})]})}function c4({workspace:e,api:t,onSelect:s,onIssued:i,onChanged:o}){const[u,f]=v.useState(""),[m,g]=v.useState(null),[h,b]=v.useState(null),[x,N]=v.useState(null),w=x!==null,[k,S]=v.useState(null),A=v.useRef(null),$=v.useRef(null),T=v.useRef(!1),C=e.workstations.length>=e.max_workstations,M=e.entitlement.access==="granted",R=M&&!e.entitlement.suspended,O=e.billing_enabled,G=M&&e.workstations.some(J=>J.connection.state==="online"),B=J=>{J.preventDefault();const we=u.trim();w||we===""||(N("create"),S(null),t.createWorkstation(we).then(ue=>{f(""),i({label:ue.workstation.label,apiKey:ue.api_key}),o()},ue=>S(Fg(ue,"The API key could not be created.",O))).finally(()=>N(null)))},te=(J,we)=>{if(w)return;N("workstation"),S(null),(J.kind==="rotate"?t.rotateWorkstation(J.companionId).then(L=>{i({label:we.label,apiKey:L.api_key})}):t.revokeWorkstation(J.companionId).then(()=>{})).then(()=>{J.kind==="revoke"?(b(null),A.current?.focus()):b(J),g(null),o()},L=>{T.current=!0,S(Fg(L,J.kind==="rotate"?"The API key could not be rotated.":"The workstation could not be revoked.",O))}).finally(()=>N(null))};v.useEffect(()=>{if(x!==null||!T.current)return;T.current=!1;const J=document.activeElement;(J===null||J===document.body)&&$.current?.focus()},[x]);const K=J=>{b(null),g(J)},se=()=>{b(m),g(null)},ge=(J,we)=>h?.kind===J&&h.companionId===we;return r.jsxs("section",{className:"hosted-owner__section","aria-labelledby":"hosted-workstations-title",children:[r.jsxs("div",{className:"hosted-owner__section-head",children:[r.jsx("h2",{id:"hosted-workstations-title",ref:A,tabIndex:-1,children:"Workstations"}),r.jsxs("p",{className:"hosted-owner__section-meta",children:[e.workstations.length," of ",e.max_workstations," workstations"]})]}),e.workstations.length===0?r.jsx("p",{className:"hosted-owner__hint",children:"No workstations yet."}):r.jsx("ul",{className:"hosted-gate__workstations",children:e.workstations.map(J=>{const we=J.connection.state==="online";return r.jsxs("li",{className:"hosted-owner__row","data-companion-state":J.connection.state,children:[r.jsx("span",{"aria-hidden":"true",className:we?"hosted-owner__dot":"hosted-owner__dot hosted-owner__dot--off"}),r.jsxs("div",{className:"hosted-owner__row-name",children:[r.jsx("strong",{children:J.label})," ",r.jsx("span",{className:we?"hosted-owner__row-state hosted-owner__row-state--on":"hosted-owner__row-state",children:we?"Online":"Offline"})]}),r.jsxs("div",{className:"hosted-owner__row-actions",children:[r.jsx("button",{type:"button",className:G&&we?"hosted-btn hosted-btn--fill":"hosted-btn hosted-btn--outline","aria-label":`Open ${J.label}`,disabled:!we,onClick:()=>s(J),children:"Open"}),m?.companionId===J.companion_id?null:r.jsxs(r.Fragment,{children:[r.jsx("button",{type:"button",className:"hosted-link hosted-link--muted","aria-label":`Rotate key for ${J.label}`,autoFocus:ge("rotate",J.companion_id),disabled:w,onClick:()=>K({kind:"rotate",companionId:J.companion_id}),children:"[ rotate key ]"}),r.jsx("button",{type:"button",className:"hosted-link hosted-link--muted","aria-label":`Revoke ${J.label}`,autoFocus:ge("revoke",J.companion_id),disabled:w,onClick:()=>K({kind:"revoke",companionId:J.companion_id}),children:"[ revoke ]"})]})]}),m?.companionId===J.companion_id?r.jsxs("div",{className:"hosted-owner__confirm",children:[r.jsx("p",{children:m.kind==="rotate"?"Rotating disconnects this workstation now and shows its new key once.":"Revoking disconnects this workstation now and frees its slot."}),r.jsxs("div",{className:"hosted-owner__actions",children:[r.jsx("button",{type:"button",ref:$,className:m.kind==="rotate"?"hosted-btn hosted-btn--outline":"hosted-btn hosted-btn--danger",disabled:w,"data-busy":x==="workstation"?"true":void 0,onClick:()=>te(m,J),children:m.kind==="rotate"?x==="workstation"?"Rotating…":"Rotate now":x==="workstation"?"Revoking…":"Revoke now"}),r.jsx("button",{type:"button",className:"hosted-link hosted-link--muted","aria-label":"Cancel",autoFocus:!0,disabled:w,onClick:se,children:"[ cancel ]"})]})]}):null]},J.companion_id)})}),R&&e.workstations.some(J=>J.connection.state==="offline")?r.jsx("p",{className:"hosted-owner__hint",children:"Start the ClinkX companion on an offline workstation. This page refreshes automatically."}):null,C?r.jsxs("p",{className:"hosted-owner__hint",children:[O?"This subscription covers":"This workspace allows"," at most ",e.max_workstations," workstations."]}):r.jsxs("form",{className:"hosted-owner__form",onSubmit:B,children:[r.jsxs("label",{className:"hosted-owner__field",children:[r.jsx("span",{className:"hosted-owner__field-label",children:"Workstation name"}),r.jsx("input",{className:"hosted-owner__input",value:u,maxLength:64,disabled:!M||w,onChange:J=>f(J.currentTarget.value),placeholder:"e.g. studio-mac",autoComplete:"off",spellCheck:!1})]}),r.jsx("button",{type:"submit",className:G?"hosted-btn hosted-btn--outline":"hosted-btn hosted-btn--fill",disabled:!M||w||u.trim()==="","data-busy":x==="create"?"true":void 0,children:x==="create"?"Creating…":"Create API key"})]}),!M&&!C?r.jsx("p",{className:"hosted-owner__hint",children:O?"Subscribe to create API keys.":Vg}):null,k===null?null:r.jsx("p",{className:"hosted-gate__error",role:"alert",children:k})]})}const u4={checkout_complete:"Checkout finished. Access starts once the payment is confirmed, which can take a moment.",checkout_canceled:"Checkout was canceled. Nothing was charged."};function d4({billingReturn:e,onDismiss:t}){return e==="none"||e==="invalid"?null:r.jsxs("div",{className:"hosted-owner__notice",role:"status",children:[r.jsx("p",{children:u4[e]}),r.jsx("button",{type:"button",className:"hosted-link hosted-link--muted","aria-label":"Dismiss",onClick:t,children:"[ dismiss ]"})]})}const mg={paid_period:"Paid period",past_due_grace:"Payment past due (grace period)",period_ended:"Paid period ended",grace_expired:"Grace period ended",no_purchase:"No subscription",payment_pending:"Payment pending",subscription_inactive:"Subscription inactive",unknown_state:"Subscription state unknown",suspended:"Workspace suspended",operator_grant:"Access granted by operator"},f4=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"});function yf({iso:e}){const t=Date.parse(e);return r.jsx("time",{dateTime:e,children:Number.isNaN(t)?e:f4.format(t)})}function p4(e,t){if(e.reason==="operator_grant"){const s=e.grant_until??e.access_until;return s===null?mg.operator_grant:r.jsxs(r.Fragment,{children:[mg.operator_grant," until ",r.jsx(yf,{iso:s})]})}return!t&&e.reason==="no_purchase"?"Not granted":mg[e.reason]}function hN({entitlement:e,billingEnabled:t}){return r.jsxs("dl",{className:"hosted-owner__facts",children:[r.jsx("dt",{children:"Access"}),r.jsx("dd",{"data-access":e.access,children:e.access==="granted"?"Active":"Inactive"}),r.jsx("dt",{children:"Reason"}),r.jsx("dd",{children:p4(e,t)}),e.access_until===null?null:r.jsxs(r.Fragment,{children:[r.jsx("dt",{children:"Access until"}),r.jsx("dd",{children:r.jsx(yf,{iso:e.access_until})})]}),e.grant_until===null||e.reason==="operator_grant"?null:r.jsxs(r.Fragment,{children:[r.jsx("dt",{children:"Operator grant until"}),r.jsx("dd",{children:r.jsx(yf,{iso:e.grant_until})})]}),!t||e.grace_deadline===null?null:r.jsxs(r.Fragment,{children:[r.jsx("dt",{children:"Grace deadline"}),r.jsx("dd",{children:r.jsx(yf,{iso:e.grace_deadline})})]})]})}function h4({entitlement:e}){return r.jsxs("section",{className:"hosted-owner__section","aria-labelledby":"hosted-access-title",children:[r.jsx("h2",{id:"hosted-access-title",children:"Access"}),r.jsx(hN,{entitlement:e,billingEnabled:!1}),e.suspended?r.jsx("p",{className:"hosted-owner__hint",children:"This workspace is suspended. Ask the operator to lift the suspension."}):null]})}function m4({entitlement:e,api:t,navigate:s}){const[i,o]=v.useState(null),[u,f]=v.useState(null),m=g=>{if(i!==null)return;o(g),f(null),(g==="checkout"?t.startCheckout():t.openPortal()).then(b=>s(b),b=>{f(Fg(b,"Billing could not be opened.")),o(null)})};return r.jsxs("section",{className:"hosted-owner__section","aria-labelledby":"hosted-billing-title",children:[r.jsx("h2",{id:"hosted-billing-title",children:"Billing"}),r.jsx(hN,{entitlement:e,billingEnabled:!0}),e.suspended?r.jsx("p",{className:"hosted-owner__hint",children:"This workspace is suspended. Payment does not lift a suspension."}):null,r.jsxs("div",{className:"hosted-owner__actions",children:[e.access==="granted"?null:r.jsx("button",{type:"button",className:"hosted-btn hosted-btn--fill",disabled:i!==null,"data-busy":i==="checkout"?"true":void 0,onClick:()=>m("checkout"),children:i==="checkout"?"Opening checkout…":"Subscribe"}),r.jsx("button",{type:"button",className:"hosted-btn hosted-btn--outline",disabled:i!==null,"data-busy":i==="portal"?"true":void 0,onClick:()=>m("portal"),children:i==="portal"?"Opening billing…":"Manage billing"})]}),u===null?null:r.jsx("p",{className:"hosted-gate__error",role:"alert",children:u})]})}const Tv="/workspace",Cv="clinkx.hosted.workstation",Ov="clinkx.hosted.lastWorkstation",$v={tab:()=>window.sessionStorage,last:()=>window.localStorage};function E0(e,t,s){try{const i=JSON.parse(e().getItem(t)??"null");if(typeof i!="object"||i===null)return null;const{tenantId:o,companionId:u}=i;return o===s&&typeof u=="string"&&u!==""?u:null}catch{return null}}function R0(e,t,s){try{e().setItem(t,JSON.stringify(s))}catch{}}function T0(e,t){try{e().removeItem(t)}catch{}}function g4(e,t=$v){return E0(t.tab,Cv,e)??E0(t.last,Ov,e)}function v4(e,t,s=$v){R0(s.tab,Cv,{tenantId:e,companionId:t}),R0(s.last,Ov,{tenantId:e,companionId:t})}function C0(e=$v){T0(e.tab,Cv),T0(e.last,Ov)}function nf(e=window){return e.location.pathname===Tv}const _4=1e4,b4=1e4,y4=15e3;function x4(e){window.location.assign(e)}function w4(e,t){return t()*Math.min(b4,250*2**Math.max(0,e-1))}function S4(e){return typeof e=="object"&&e!==null&&e.name==="AbortError"}function j4(e){return e==="misdirected_request"?"This address does not serve ClinkX workspaces.":e==="forbidden"||e==="not_member"?"This ClinkX account has no workspace it can manage.":"The workspace service could not be reached."}function mN({workspace:e}){return r.jsx("button",{type:"button",className:"hosted-link hosted-link--muted","aria-label":e.signingOut?"Signing out…":"Sign out of ClinkX account",disabled:e.signingOut,onClick:e.signOut,children:e.signingOut?"signing out…":"[ sign out of ClinkX account ]"})}function N4({workspace:e}){return r.jsxs("div",{className:"hosted-gate__pre-auth",children:[e.isOwner?r.jsx("button",{type:"button",className:"hosted-link","aria-label":"Workspace",onClick:e.openWorkspace,children:"[ workspace ]"}):null,r.jsx(mN,{workspace:e})]})}const k4={filled:"hosted-gate__mark",hollow:"hosted-gate__mark hosted-gate__mark--hollow",pulse:"hosted-gate__mark hosted-gate__mark--live",fail:"hosted-gate__mark hosted-gate__mark--fail"},A4=["account","workspace","passkey"];function E4({at:e,mark:t,drawing:s}){const i=u=>u<e?"hosted-gate__node hosted-gate__node--done":u===e?`hosted-gate__node ${k4[t]}`:"hosted-gate__node",o=u=>s&&u===e-1?"hosted-gate__track-line hosted-gate__track-line--busy":u<e?"hosted-gate__track-line hosted-gate__track-line--done":"hosted-gate__track-line";return r.jsxs("div",{className:"hosted-gate__track","aria-hidden":"true",children:[r.jsxs("div",{className:"hosted-gate__track-row",children:[r.jsx("span",{className:i(1)}),r.jsx("span",{className:o(1)}),r.jsx("span",{className:i(2)}),r.jsx("span",{className:o(2)}),r.jsx("span",{className:i(3)})]}),r.jsx("div",{className:"hosted-gate__track-labels",children:A4.map((u,f)=>r.jsx("span",{className:f+1===e?"is-current":void 0,children:u},u))})]})}function mo({title:e,at:t,mark:s,drawing:i=!1,workspace:o=!1,children:u}){return r.jsx("main",{className:o?"auth-gate hosted-gate hosted-gate--workspace":"auth-gate hosted-gate",children:r.jsxs("section",{className:o?"hosted-gate__card hosted-gate__card--workspace":"hosted-gate__card","aria-labelledby":"hosted-gate-title",children:[r.jsxs("div",{className:"hosted-gate__head",children:[r.jsx(E4,{at:t,mark:s,drawing:i}),r.jsx("h1",{id:"hosted-gate-title",children:e})]}),u]})})}function R4({billingReturn:e,api:t,localAuth:s,navigate:i,renderLocal:o,statusPollMs:u,random:f}){const[m,g]=v.useState({phase:"connecting"}),[h,b]=v.useState(0),[x,N]=v.useState(e),[w,k]=v.useState(null),[S,A]=v.useState(!1),[$,T]=v.useState(!1),[C,M]=v.useState(!1),R=v.useRef(!1),O=v.useRef(null),G=v.useRef(null),B=v.useRef(m),te=v.useRef(!1),K=v.useRef(null),se=v.useRef(null),ge=v.useRef({consecutive:0,committedAt:0}),J=v.useCallback(q=>{O.current??=g4(q.context.tenantId);const re=O.current===null?void 0:q.workspace.workstations.find(Te=>Te.companion_id===O.current);if(O.current!==null&&re===void 0&&(O.current=null,C0()),nf()){g({phase:"workspace",read:q,offlineSelection:!1});return}const Re=q.workspace.entitlement.access==="granted"?re:void 0;if(Re!==void 0){const Te=pg(q,Re,Qc());if(Te.kind==="selected"){g({phase:"local",read:q,workstation:Re,epoch:Te.epoch});return}if(Te.kind==="superseded")return}g({phase:"workspace",read:q,offlineSelection:Re!==void 0})},[]);v.useEffect(()=>{const q=new AbortController,re=()=>!q.signal.aborted,Re=()=>{ge.current.consecutive+=1,b(dt=>dt+1)},Te=dt=>{if(K.current===q&&(K.current=null),!(!re()||dt.kind==="superseded")){if(dt.kind==="signed_out"){g({phase:"signed_out"});return}if(dt.kind==="unavailable"){const Ot=r4(dt.code,dt.status);g({phase:"unavailable",retrying:Ot,code:dt.code}),Ot&&Re();return}J({workspace:dt.workspace,context:dt.context})}},xe=dt=>{K.current===q&&(K.current=null),!(!re()||S4(dt))&&(g({phase:"unavailable",retrying:!0,code:null}),Re())},Me=h===0||te.current?0:w4(ge.current.consecutive,f);te.current=!1,se.current=q;const ot=window.setTimeout(()=>{q.signal.aborted||(K.current=q,i4(t,q.signal).then(Te,xe))},Me);return()=>{window.clearTimeout(ot),q.abort(),se.current===q&&(se.current=null)}},[t,J,f,h]),v.useEffect(()=>{if(B.current=m,m.phase!=="local")return;const q=Date.now();q-ge.current.committedAt>y4&&(ge.current.consecutive=0),ge.current.committedAt=q},[m]);const we=v.useCallback(()=>{te.current=!0,b(q=>q+1)},[]);v.useEffect(()=>ev(q=>{if(q.type==="lost"){if(K.current?.abort(),q.cause==="cloud_unauthenticated"){se.current?.abort(),O.current=null,g({phase:"signed_out"});return}if(q.cause==="entitlement_inactive"&&B.current.phase==="workspace"){te.current=!0,b(re=>re+1);return}ge.current.consecutive+=1,g({phase:"connecting"}),b(re=>re+1)}}),[]);const ue=()=>{const q=K.current;R.current||q!==null&&!q.signal.aborted||we()},L=m.phase==="unavailable"&&m.retrying;v.useEffect(()=>{if(!L)return;const q=()=>{document.visibilityState==="visible"&&ue()};return window.addEventListener("online",ue),document.addEventListener("visibilitychange",q),()=>{window.removeEventListener("online",ue),document.removeEventListener("visibilitychange",q)}},[L]),v.useEffect(()=>{if(m.phase!=="workspace")return;const q=window.setTimeout(we,u);return()=>window.clearTimeout(q)},[we,m,u]),v.useEffect(()=>{const q=()=>{const re=B.current;if(nf())re.phase==="local"&&g({phase:"workspace",read:re.read,offlineSelection:!1});else if(re.phase==="workspace")G.current=null;else return;we()};return window.addEventListener("popstate",q),()=>window.removeEventListener("popstate",q)},[we]);const Y=v.useCallback(()=>{nf()||(G.current=`${window.location.pathname}${window.location.search}${window.location.hash}`,window.history.pushState(null,"",Tv)),g(q=>q.phase==="local"?{phase:"workspace",read:q.read,offlineSelection:!1}:q),we()},[we]),de=v.useCallback(()=>{if(R.current)return;R.current=!0,window.dispatchEvent(new CustomEvent(Of)),M(!0),K.current?.abort(),se.current?.abort();let q=m.phase==="local";if(m.phase==="workspace"&&O.current!==null){const re=m.read.workspace.workstations.find(Re=>Re.companion_id===O.current);q=re!==void 0&&pg(m.read,re,Qc()).kind==="selected"}(async()=>(q&&await s.logout().catch(()=>{}),await t.logout().catch(()=>{}),O.current=null,C0(),Ag("cloud_unauthenticated"),R.current=!1,M(!1)))()},[t,s,m]),oe=(m.phase==="local"||m.phase==="workspace")&&m.read.workspace.role==="owner",Se=v.useMemo(()=>({openWorkspace:Y,isOwner:oe,signOut:de,signingOut:C}),[oe,Y,de,C]),E=()=>{S||(A(!0),T(!1),t.startSignIn().then(i,()=>{A(!1),T(!0)}))},U=(q,re)=>{O.current=re.companion_id,v4(q.context.tenantId,re.companion_id),nf()&&(window.history.pushState(null,"",G.current??"/runs"),G.current=null);const Re=pg(q,re,Qc());Re.kind==="selected"?g({phase:"local",read:q,workstation:re,epoch:Re.epoch}):Re.kind==="offline"&&g({phase:"workspace",read:q,offlineSelection:!0})},P=r.jsx(d4,{billingReturn:x,onDismiss:()=>N("none")}),ne=r.jsx(mN,{workspace:Se}),be=w===null?null:r.jsx(o4,{issued:w,onDone:()=>k(null)});switch(m.phase){case"connecting":return r.jsx(mo,{title:"ClinkX workspace",at:2,mark:"pulse",drawing:!0,children:r.jsx("p",{className:"hosted-gate__lede","aria-live":"polite",children:"Connecting to your workspace…"})});case"signed_out":return r.jsxs(mo,{title:"Sign in to ClinkX",at:1,mark:"hollow",children:[r.jsx("p",{className:"hosted-gate__lede",children:"Sign in with your ClinkX account to open your workspace. Each workstation then asks for its own passkey."}),r.jsx("div",{className:"hosted-gate__actions",children:r.jsx("button",{type:"button",className:"hosted-btn hosted-btn--fill hosted-btn--wide",disabled:S,"data-busy":S?"true":void 0,onClick:E,children:S?"Redirecting…":"Sign in"})}),$?r.jsx("p",{className:"hosted-gate__error",role:"alert",children:"Sign-in could not be started. Try again."}):null]});case"unavailable":return m.retrying?r.jsxs(mo,{title:"ClinkX workspace",at:2,mark:"pulse",drawing:!0,children:[r.jsx("p",{className:"hosted-gate__lede","aria-live":"polite",children:"Reconnecting…"}),r.jsxs("div",{className:"hosted-gate__actions",children:[r.jsx("button",{type:"button",className:"hosted-btn hosted-btn--outline",onClick:ue,children:"Try now"}),ne]})]}):r.jsxs(mo,{title:"Workspace unavailable",at:2,mark:"fail",children:[r.jsx("p",{className:"hosted-gate__lede",children:j4(m.code)}),r.jsxs("div",{className:"hosted-gate__actions",children:[r.jsx("button",{type:"button",className:"hosted-btn hosted-btn--fill hosted-btn--wide",onClick:()=>{g({phase:"connecting"}),we()},children:"Try again"}),ne]})]});case"workspace":{const{read:q}=m,re=q.workspace;return r.jsxs(mo,{title:"Your ClinkX workspace",at:2,mark:"filled",workspace:!0,children:[m.offlineSelection?r.jsxs("div",{className:"hosted-owner__notice",role:"status",children:[r.jsx("span",{"aria-hidden":"true",className:"hosted-owner__dot hosted-owner__dot--off"}),r.jsx("p",{children:"That workstation is offline. Start its companion, or open another workstation."})]}):null,re.billing_enabled?P:null,be,r.jsx(c4,{workspace:re,api:t,onSelect:Re=>U(q,Re),onIssued:k,onChanged:we}),re.billing_enabled?r.jsx(m4,{entitlement:re.entitlement,api:t,navigate:i}):r.jsx(h4,{entitlement:re.entitlement}),r.jsx("div",{className:"hosted-gate__foot",children:ne})]})}}return r.jsx("div",{className:"hosted-gate__local","data-authority-epoch":m.epoch,"data-workstation":m.workstation.companion_id,children:o(Se)},m.epoch)}function T4({hosting:e,renderLocal:t,billingReturn:s="none",api:i,localAuth:o,navigate:u=x4,statusPollMs:f=_4,random:m=Math.random}){const g=v.useMemo(()=>i??n4(),[i]),h=v.useMemo(()=>o??wp(),[o]);return e.kind==="hosted"?r.jsx(R4,{billingReturn:s,api:g,localAuth:h,navigate:u,renderLocal:t,statusPollMs:f,random:m}):r.jsx(mo,{title:"ClinkX workspace",at:1,mark:"fail",children:r.jsx("p",{className:"hosted-gate__lede",role:"alert",children:"This dashboard's hosting configuration is invalid."})})}function C4(e,t=window.location.origin){return e.mode==="local"&&!e.authenticated&&wu(t)}const gN=document.getElementById("root");if(!gN)throw new Error("Root element #root not found");const Xc=Qk.createRoot(gN),O0=qD(),O4=e=>{const t=e.kind==="hosted"?l4():void 0;t!==void 0&&t!=="none"&&window.history.replaceState(window.history.state,"",Tv),e.kind==="hosted"&&(KA(),Yc("passkey"));const s=wp();Xc.render(r.jsx(v.StrictMode,{children:r.jsx(T4,{hosting:e,...t===void 0?{}:{billingReturn:t},localAuth:s,renderLocal:i=>r.jsx(lN,{api:s,preAuthActions:r.jsx(N4,{workspace:i}),authenticatedContent:o=>r.jsx(Av,{accountActions:{...o,onOpenWorkspace:i.openWorkspace}})})})}))},$4=()=>{const e=Z0(),t=()=>{Xc.render(r.jsx(v.StrictMode,{children:r.jsx(Av,{})}))},s=async m=>{if(!HA(m))return!1;try{return(await Eg()).authenticated?(t(),!0):(kg(),!1)}catch(g){const h=VA();if(kg(),h)throw g;return!1}},i=()=>{Xc.render(r.jsx(v.StrictMode,{children:r.jsx(MD,{onSubmit:s})}))},o=()=>C4(wr(),window.location.origin),u=()=>{if(Yc("bearer"),o()){i();return}Eg().then(()=>o()?i():t(),()=>o()?i():t())},f=wp();AD(f,e.mode==="remote").then(m=>{if(m==="passkey"){Yc("passkey"),Xc.render(r.jsx(v.StrictMode,{children:r.jsx(lN,{api:f})}));return}if(m==="none"){Yc("none"),t();return}u()},()=>{Xc.render(r.jsx(v.StrictMode,{children:r.jsx("main",{className:"auth-gate",children:r.jsxs("section",{className:"auth-gate__card",role:"alert",children:[r.jsx("h1",{children:"ClinkX field station"}),r.jsx("p",{children:"Could not load dashboard authentication status."})]})})}))})};O0.kind==="standalone"?$4():O4(O0);
|
|
122
|
+
`,SD="no-store",jD="application/json; charset=utf-8",ND=/^[A-Za-z0-9_-]{43}$/,aN=new WeakSet;function kD(){const e=new Jn(404,"not_found");return aN.add(e),e}async function AD(e,t){try{return(await e.status()).mode}catch(s){if(t&&s instanceof Jn&&aN.has(s))return"bearer";throw s}}function $o(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sN(e,t){if(!e.ok){const s=$o(t)&&$o(t.error)&&typeof t.error.code=="string"?t.error.code:"request_failed";throw new Jn(e.status,s)}return t}function rN(e,t){return Y0()?aS(e,t):fetch(e,t)}async function iN(e){ha(e);let t;try{t=await e.json()}catch{throw ha(e),new Jn(e.status,"invalid_response")}return ha(e),sN(e,t)}async function ED(e){if(e.status!==404)return iN(e);ha(e);let t;try{t=await e.text()}catch{throw ha(e),new Jn(e.status,"invalid_response")}if(ha(e),t===wD&&e.headers.get("cache-control")===SD&&e.headers.get("content-type")===jD)throw kD();let s;try{s=JSON.parse(t)}catch{throw new Jn(e.status,"invalid_response")}return sN(e,s)}async function tl(e,t,s){const i=Jg(),o=await rN(e,{method:"POST",credentials:"same-origin",redirect:"error",referrerPolicy:"no-referrer",headers:{"Content-Type":"application/json",...s==null?{}:{"X-Enrollment-Code":s},...i==null?{}:{[Cf]:i}},body:JSON.stringify(t)});try{return await iN(o)}catch(u){throw u instanceof Jn&&u.status===401&&Fs(),u}}function RD(e){if(!$o(e))throw new Jn(200,"invalid_response");if(Object.keys(e).sort().join("\0")!==["authenticated","enrolled","mode"].sort().join("\0")||typeof e.enrolled!="boolean"||typeof e.authenticated!="boolean"||e.mode!=="passkey"&&e.mode!=="bearer"&&e.mode!=="none")throw new Jn(200,"invalid_response");return e}function bf(e){if(!$o(e)||typeof e.challenge!="string")throw new Jn(200,"invalid_response");return e}function TD(e){if(!$o(e)||typeof e.challengeId!="string"||!/^[A-Za-z0-9_-]{43}$/.test(e.challengeId))throw new Jn(200,"invalid_response");return{challengeId:e.challengeId,options:bf(e.options)}}function CD(e){if(!$o(e))throw Fs(),new Jn(200,"invalid_response");const t=Object.keys(e).sort().join("\0");if(wu()){if(t!==["originProof","verified"].sort().join("\0")||e.verified!==!0||typeof e.originProof!="string"||!ND.test(e.originProof))throw Fs(),new Jn(200,"invalid_response");try{DA(e.originProof)}catch{throw Fs(),new Jn(200,"invalid_response")}return}if(t!=="verified"||e.verified!==!0)throw new Jn(200,"invalid_response")}function wp(){return{async status(e){try{const t=Jg(),s=await rN("/api/auth/status",{method:"GET",credentials:"same-origin",redirect:"error",referrerPolicy:"no-referrer",...t==null?{}:{headers:{[Cf]:t}},...e==null?{}:{signal:e}}),i=RD(await ED(s));return i.authenticated||Fs(),i}catch(t){throw wu()&&t instanceof Jn&&Fs(),t}},async registrationOptions(e){return bf(await tl("/api/auth/register/options",{},e))},async verifyRegistration(e,t,s){await tl("/api/auth/register/verify",{response:e,...s==null?{}:{label:s}},t)},async registerAssertionOptions(){return TD(await tl("/api/auth/register/assert/options",{}))},async verifyRegisterAssertion(e,t){return bf(await tl("/api/auth/register/assert/verify",{challengeId:e,response:t}))},async authenticationOptions(){return bf(await tl("/api/auth/login/options",{}))},async verifyAuthentication(e){CD(await tl("/api/auth/login/verify",{response:e}))},async logout(){try{await tl("/api/auth/logout",{})}finally{Fs()}}}}const OD=/^[A-Za-z0-9_-]{32}$/,$D={supports:ku,register:async e=>Wj({optionsJSON:e}),authenticate:async e=>tN({optionsJSON:e})};function dg(e){if(e instanceof Jn){if(e.status===401)return"Authorization was rejected.";if(e.code==="not_enrolled")return"Register a passkey before signing in.";if(e.code==="passkey_assertion_required")return"Adding a passkey needs a passkey that is already enrolled. Refresh the status and try again.";if(e.code==="state_conflict")return"Enrollment changed. Refresh the status and try again."}return e instanceof DOMException&&e.name==="NotAllowedError"?"The passkey request was cancelled or timed out.":"The passkey request could not be completed."}function lN({api:e,webauthn:t,authenticatedContent:s,preAuthActions:i}){const o=v.useMemo(()=>e??wp(),[e]),u=t??$D,[f,m]=v.useState(null),[g,h]=v.useState(""),b=v.useRef(""),x=v.useRef(!0),[N,w]=v.useState(null),[k,S]=v.useState(null);v.useEffect(()=>{x.current=!0,Yc("passkey");const C=new AbortController;o.status(C.signal).then(R=>{C.signal.aborted||m(R)},R=>{C.signal.aborted||S(dg(R))});const M=()=>{m(R=>R==null?R:{...R,authenticated:!1}),S("Your dashboard session expired. Sign in again.")};return window.addEventListener(cu,M),()=>{x.current=!1,C.abort(),window.removeEventListener(cu,M),b.current="",h("")}},[o]);const A=C=>{if(N!=null)return;const M=C?void 0:b.current.trim();if(!C&&!OD.test(M??"")){S("Enter the 32-character enrollment code from the launch output.");return}S(null),w("register");const R=gl(),O=()=>x.current&&Ks(R);(async()=>{try{let B;if(C){const K=await o.registerAssertionOptions();if(!O())return;const se=await u.authenticate(K.options);if(!O())return;B=await o.verifyRegisterAssertion(K.challengeId,se)}else B=await o.registrationOptions(M);if(!O())return;const te=await u.register(B);if(!O())return;await o.verifyRegistration(te,C?void 0:b.current.trim()||void 0)}finally{b.current=""}if(!O())return;h("");const G=await o.status();O()&&m(G)})().catch(G=>{O()&&(h(""),S(dg(G)))}).finally(()=>{x.current&&w(null)})},$=()=>{if(N!=null)return;S(null),w("login");const C=gl(),M=()=>x.current&&Ks(C);(async()=>{const R=await o.authenticationOptions();if(!M())return;const O=await u.authenticate(R);if(!M()||(await o.verifyAuthentication(O),!M()))return;const G=await o.status();M()&&m(G)})().catch(R=>{M()&&S(dg(R))}).finally(()=>{x.current&&w(null)})},T=()=>{N==null&&(S(null),w("logout"),window.dispatchEvent(new CustomEvent(Of)),o.logout().then(async()=>{if(x.current){m(C=>C==null?C:{...C,authenticated:!1});try{const C=await o.status();x.current&&m(C)}catch{x.current&&S("Signed out locally, but authentication status could not be refreshed.")}}}).catch(()=>{x.current&&(m(C=>C==null?C:{...C,authenticated:!1}),S("Sign-out could not be confirmed. You were signed out locally."))}).finally(()=>{x.current&&w(null)}))};if(f===null)return r.jsx("main",{className:"auth-gate",children:r.jsxs("section",{className:"auth-gate__card",children:[r.jsx("h1",{children:"ClinkX field station"}),r.jsx("p",{"aria-live":"polite",children:k??"Checking passkey status…"}),i]})});if(!u.supports())return r.jsx("main",{className:"auth-gate",children:r.jsxs("section",{className:"auth-gate__card",children:[r.jsx("h1",{children:"Passkeys unavailable"}),r.jsx("p",{children:"This browser does not support WebAuthn. Open the dashboard in a supported browser."}),i]})});if(f.authenticated){const C={error:k,onAddPasskey:()=>A(!0),onSignOut:T,pending:N==="register"||N==="logout"?N:null};return r.jsx("div",{className:"auth-gate__authenticated",children:s?.(C)??r.jsx(Av,{accountActions:C})})}return r.jsx("main",{className:"auth-gate",children:r.jsxs("section",{className:"auth-gate__card","aria-labelledby":"auth-gate-title",children:[r.jsx("span",{"aria-hidden":"true",className:"auth-gate__mark"}),r.jsx("h1",{id:"auth-gate-title",children:"ClinkX field station"}),f.enrolled?r.jsxs(r.Fragment,{children:[r.jsx("p",{children:"Use your passkey to open the run monitor."}),r.jsx("button",{type:"button",disabled:N!==null,onClick:$,children:N==="login"?"Waiting for passkey…":"Sign in"})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{children:"Register the first passkey with the one-time enrollment code."}),r.jsx("label",{htmlFor:"enrollment-code",children:"Enrollment code"}),r.jsx("input",{id:"enrollment-code",value:g,disabled:N!==null,autoComplete:"off",autoCapitalize:"off",spellCheck:!1,onChange:C=>{b.current=C.target.value,h(C.target.value),k!=null&&S(null)}}),r.jsx("button",{type:"button",disabled:N!==null,onClick:()=>A(!1),children:N==="register"?"Waiting for passkey…":"Register this device"})]}),k==null?null:r.jsx("p",{className:"auth-gate__error",role:"alert",children:k}),i]})})}const ID=/^[A-Za-z0-9_-]{43}$/;function MD({onSubmit:e}){const[t,s]=v.useState(""),[i,o]=v.useState(null),[u,f]=v.useState(!1),m=v.useId(),g=v.useId(),h=b=>{if(b.preventDefault(),u)return;const x=t.trim();if(!ID.test(x)){o("Enter the 43-character access token from the launch output.");return}o(null),f(!0),e(x).then(N=>{N||(o("That token was rejected. Check the launch output and try again."),f(!1))},()=>{o("Could not reach the dashboard. Is it still running?"),f(!1)})};return r.jsx("main",{className:"login",children:r.jsxs("section",{className:"login__card","aria-labelledby":"login-title",children:[r.jsx("span",{"aria-hidden":"true",className:"login__mark",children:r.jsx("span",{className:"login__mark-dot"})}),r.jsx("h1",{className:"login__title",id:"login-title",children:"ClinkX field station"}),r.jsx("p",{className:"login__lede",children:"Paste the access token printed when the dashboard started to open the run monitor."}),r.jsxs("form",{className:"login__form",onSubmit:h,noValidate:!0,children:[r.jsx("label",{className:"login__label op-caption",htmlFor:m,children:"Access token"}),r.jsx("input",{id:m,className:"login__input",type:"password",autoComplete:"off",autoCapitalize:"off",spellCheck:!1,autoFocus:!0,value:t,disabled:u,"aria-invalid":i!==null,...i===null?{}:{"aria-describedby":g},onChange:b=>{s(b.target.value),i!==null&&o(null)}}),i===null?null:r.jsx("p",{className:"login__error op-caption",id:g,role:"alert",children:i}),r.jsx("button",{className:"login__submit",type:"submit",disabled:u,children:u?"Opening…":"Open dashboard"})]})]})})}const LD="clinkx-dashboard-public-origin",A0=2;function DD(e){try{const t=new URL(e);return t.protocol==="https:"&&t.origin===e}catch{return!1}}function qD(e=document,t=window.location.origin){const s=e.querySelectorAll(`meta[name="${LD}"]`);if(s.length===0)return{kind:"standalone"};const i=s.length===1?s[0]?.getAttribute("content")??"":"";return!DD(i)||i!==t?{kind:"misconfigured"}:{kind:"hosted",publicOrigin:i}}const bi=et().datetime(),Ev=et().max(4096).refine(e=>{try{const t=new URL(e);return t.protocol==="https:"&&t.username===""&&t.password===""}catch{return!1}});function Sp(e){return et().regex(new RegExp(`^${e}_[A-Za-z0-9_-]{16,64}$`))}const zD=lt(["owner"]),Rv=Sp("cmp"),oN=et().regex(/^clxd_[A-Za-z0-9_-]{43}$/),UD=lt(["paid_period","past_due_grace","period_ended","grace_expired","no_purchase","payment_pending","subscription_inactive","unknown_state","suspended","operator_grant"]),BD=lt(["none","active","trialing","past_due","incomplete","incomplete_expired","unpaid","canceled","paused","unknown"]),cN=$e({access:lt(["granted","denied"]),reason:UD,subscription_state:BD,access_until:bi.nullable(),grant_until:bi.nullable(),grace_deadline:bi.nullable(),suspended:lu(),last_reconciled_at:bi.nullable(),stale:lu()}).strict().refine(e=>e.access==="denied"||e.access_until!==null).refine(e=>!e.suspended||e.access==="denied"),uN=$e({companion_id:Rv,label:et().min(1).max(64).regex(/^[\x20-\x7e]+$/),created_at:bi,key_issued_at:bi.nullable(),connection:$e({state:lt(["offline","online"]),connection_generation:Ia().int().nonnegative().nullable()}).strict().refine(e=>e.state==="online"==(e.connection_generation!==null))}).strict(),GD=$e({workspace:$e({id:Sp("ten")}).strict(),role:zD,billing_enabled:lu(),entitlement:cN,max_workstations:nt(A0),workstations:Qn(uN).max(A0)}).strict(),PD=$e({workstation:uN,api_key:oN}).strict(),HD=$e({companion_id:Rv,api_key:oN,revoked_credential_id:Sp("cred").nullable(),closed_connections:Ia().int().nonnegative()}).strict(),VD=$e({companion_id:Rv,revoked_at:bi,closed_connections:Ia().int().nonnegative()}).strict(),FD=$e({entitlement:cN}).strict(),KD=$e({checkout_url:Ev}).strict(),ZD=$e({portal_url:Ev}).strict(),XD=$e({logged_out:nt(!0)}).strict(),YD=$e({account:$e({id:Sp("acc"),display_name:et().min(1).max(200).nullable()}).strict(),expires_at:bi}).strict(),QD=$e({authorization_url:Ev}).strict(),dN=["unauthenticated","auth_failed","forbidden","not_member","not_found","method_not_allowed","misdirected_request","credential_revoked","entitlement_inactive","context_mismatch","not_active","workstation_limit","workstation_not_found","workstation_required","subscription_active","payload_too_large","invalid_request","webhook_signature_invalid","rate_limited","outcome_unknown","store_unavailable","provider_unavailable","companion_offline"],JD=$e({error:$e({code:lt(dN),message:et().min(1).max(500).optional()}).strict()}).strict();class Hs extends Error{status;code;constructor(t,s){super(s),this.name="ControlApiError",this.status=t,this.code=s}}function WD(e){const t=JD.safeParse(e);if(t.success)return t.data.error.code;const s=B0(e);return dN.includes(s??"")?s:"invalid_response"}const fN={credentials:"same-origin",redirect:"error",referrerPolicy:"no-referrer",cache:"no-store"};function nl(e,t){return{...fN,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}}function fg(e){return{...fN,method:"GET",...e===void 0?{}:{signal:e}}}async function Ds(e,t,s){try{return await e(t,s)}catch(i){throw i instanceof TypeError?new Hs(0,"network_error"):i}}async function e4(e,t){try{return await t(e)}catch(s){throw s instanceof Ct?s:new Hs(e.status,"invalid_response")}}async function qs(e,t,s=i=>i.json()){const i=await e4(e,s);if(!e.ok)throw new Hs(e.status,WD(i));const o=t.safeParse(i);if(!o.success)throw new Hs(e.status,"invalid_response");return o.data}const pN="CLINKX_DASHBOARD_GATEWAY_TOKEN=";function t4(e){return`${pN}${e}`}function n4(e=(s,i)=>fetch(s,i),t=aS){return{async session(s){const i=await Ds(e,"/api/control/auth/session",fg(s));try{return await qs(i,YD)}catch(o){if(o instanceof Hs&&o.code==="unauthenticated")return null;throw o}},async startSignIn(){const s=await Ds(e,"/api/control/auth/start",nl({}));return(await qs(s,QD)).authorization_url},async readWorkspace(s){const i=await Ds(e,"/api/control/workspace",fg(s)),o=await qs(i,GD),u=ou(i.headers.get(z0));if(u===null||u.tenantId!==o.workspace.id||u.companionId!==null)throw new Hs(i.status,"invalid_response");return{workspace:o,context:u}},async createWorkstation(s){const i=await Ds(t,"/api/control/workstations",nl({label:s}));return qs(i,PD,xn)},async rotateWorkstation(s){const i=await Ds(t,"/api/control/workstations/rotate",nl({companion_id:s})),o=await qs(i,HD,xn);if(o.companion_id!==s)throw new Hs(i.status,"invalid_response");return o},async revokeWorkstation(s){const i=await Ds(t,"/api/control/workstations/revoke",nl({companion_id:s})),o=await qs(i,VD,xn);if(o.companion_id!==s)throw new Hs(i.status,"invalid_response");return o},async billingStatus(s){const i=await Ds(t,"/api/control/billing/status",fg(s));return(await qs(i,FD,xn)).entitlement},async startCheckout(){const s=await Ds(t,"/api/control/billing/checkout",nl({}));return(await qs(s,KD,xn)).checkout_url},async openPortal(){const s=await Ds(t,"/api/control/billing/portal",nl({}));return(await qs(s,ZD,xn)).portal_url},async logout(){const s=await Ds(e,"/api/control/auth/logout",nl({}));await qs(s,XD)}}}const a4=new Set(["unauthenticated","forbidden","not_member","misdirected_request"]),s4=new Set(["network_error","store_unavailable","rate_limited","invalid_response"]);function r4(e,t){return a4.has(e)?!1:s4.has(e)||t>=500}async function i4(e,t){const s=Qc();try{const{workspace:i,context:o}=await e.readWorkspace(t);if(t?.aborted===!0)throw new DOMException("aborted","AbortError");const u=J0(o,s);return u===null?{kind:"superseded"}:{kind:"ready",workspace:i,context:o,epoch:u}}catch(i){if(!(i instanceof Hs))throw i;return s!==Qc()?{kind:"superseded"}:i.code==="unauthenticated"?{kind:"signed_out"}:{kind:"unavailable",code:i.code,status:i.status}}}function pg(e,t,s){const i=t.connection.connection_generation;if(t.connection.state!=="online"||i===null)return{kind:"offline"};const o={tenantId:e.context.tenantId,companionId:t.companion_id,generation:i},u=J0(o,s);return u===null?{kind:"superseded"}:{kind:"selected",context:o,epoch:u}}const hg="billing";function l4(e=window){const t=new URLSearchParams(e.location.search);if(!t.has(hg))return"none";const s=t.getAll(hg);t.delete(hg);const i=t.toString();e.history.replaceState(e.history.state,"",e.location.pathname+(i===""?"":`?${i}`)+e.location.hash);const[o]=s;return s.length!==1?"invalid":o==="checkout_complete"||o==="checkout_canceled"?o:"invalid"}const Vg="This workspace has no active access. Ask the operator to grant access.";function Fg(e,t,s=!0){if(e instanceof ds&&e.failure==="entitlement_inactive")return s?"An active subscription is required to create an API key.":Vg;if(e instanceof Hs){if(e.code==="forbidden"||e.code==="not_member")return"Only the workspace owner can do this.";if(e.code==="provider_unavailable")return"Billing is not available yet. Try again later.";if(e.code==="rate_limited")return"Too many requests. Wait a moment and try again.";if(e.code==="entitlement_inactive")return s?"An active subscription is required to create an API key.":Vg;if(e.code==="workstation_limit")return`This ${s?"subscription":"workspace"} already has its maximum number of workstations. Revoke one first.`;if(e.code==="subscription_active")return"This workspace already has a subscription. Use Manage billing to change it.";if(e.code==="workstation_not_found"||e.code==="not_active")return"That workstation is no longer active. Reload the workspace and try again.";if(e.code==="invalid_request")return"Use 1-64 printable characters for the workstation name."}return t}function o4({issued:e,onDone:t}){const s=t4(e.apiKey),i=v.useRef(null);return v.useEffect(()=>{i.current?.focus()},[e]),r.jsxs("section",{className:"hosted-owner__section hosted-owner__section--key","aria-labelledby":"hosted-key-title",children:[r.jsxs("div",{className:"hosted-owner__section-head",children:[r.jsxs("h2",{id:"hosted-key-title",ref:i,tabIndex:-1,children:["API key for ",e.label]}),r.jsx("span",{className:"hosted-owner__stamp",children:"shown once"})]}),r.jsxs("p",{className:"hosted-owner__hint",children:["This key is shown once. On that workstation, install the ClinkX desktop app and enter it during setup — or put this line in ",r.jsx("code",{children:"deploy/dashboard-companion/.env"})," and start the Docker companion."]}),r.jsxs("output",{className:"hosted-owner__secret","aria-label":"Companion .env line",children:[r.jsx("span",{className:"hosted-owner__secret-var",children:pN}),e.apiKey]}),r.jsxs("div",{className:"hosted-owner__actions",children:[r.jsx(ma,{label:"Copy .env line",idleLabel:"[ copy .env line ]",text:s}),r.jsx(ma,{label:"Copy API key",idleLabel:"[ copy api key ]",text:e.apiKey}),r.jsx("button",{type:"button",className:"hosted-btn hosted-btn--outline",onClick:t,children:"Done"})]})]})}function c4({workspace:e,api:t,onSelect:s,onIssued:i,onChanged:o}){const[u,f]=v.useState(""),[m,g]=v.useState(null),[h,b]=v.useState(null),[x,N]=v.useState(null),w=x!==null,[k,S]=v.useState(null),A=v.useRef(null),$=v.useRef(null),T=v.useRef(!1),C=e.workstations.length>=e.max_workstations,M=e.entitlement.access==="granted",R=M&&!e.entitlement.suspended,O=e.billing_enabled,G=M&&e.workstations.some(J=>J.connection.state==="online"),B=J=>{J.preventDefault();const we=u.trim();w||we===""||(N("create"),S(null),t.createWorkstation(we).then(ue=>{f(""),i({label:ue.workstation.label,apiKey:ue.api_key}),o()},ue=>S(Fg(ue,"The API key could not be created.",O))).finally(()=>N(null)))},te=(J,we)=>{if(w)return;N("workstation"),S(null),(J.kind==="rotate"?t.rotateWorkstation(J.companionId).then(L=>{i({label:we.label,apiKey:L.api_key})}):t.revokeWorkstation(J.companionId).then(()=>{})).then(()=>{J.kind==="revoke"?(b(null),A.current?.focus()):b(J),g(null),o()},L=>{T.current=!0,S(Fg(L,J.kind==="rotate"?"The API key could not be rotated.":"The workstation could not be revoked.",O))}).finally(()=>N(null))};v.useEffect(()=>{if(x!==null||!T.current)return;T.current=!1;const J=document.activeElement;(J===null||J===document.body)&&$.current?.focus()},[x]);const K=J=>{b(null),g(J)},se=()=>{b(m),g(null)},ge=(J,we)=>h?.kind===J&&h.companionId===we;return r.jsxs("section",{className:"hosted-owner__section","aria-labelledby":"hosted-workstations-title",children:[r.jsxs("div",{className:"hosted-owner__section-head",children:[r.jsx("h2",{id:"hosted-workstations-title",ref:A,tabIndex:-1,children:"Workstations"}),r.jsxs("p",{className:"hosted-owner__section-meta",children:[e.workstations.length," of ",e.max_workstations," workstations"]})]}),e.workstations.length===0?r.jsx("p",{className:"hosted-owner__hint",children:"No workstations yet."}):r.jsx("ul",{className:"hosted-gate__workstations",children:e.workstations.map(J=>{const we=J.connection.state==="online";return r.jsxs("li",{className:"hosted-owner__row","data-companion-state":J.connection.state,children:[r.jsx("span",{"aria-hidden":"true",className:we?"hosted-owner__dot":"hosted-owner__dot hosted-owner__dot--off"}),r.jsxs("div",{className:"hosted-owner__row-name",children:[r.jsx("strong",{children:J.label})," ",r.jsx("span",{className:we?"hosted-owner__row-state hosted-owner__row-state--on":"hosted-owner__row-state",children:we?"Online":"Offline"})]}),r.jsxs("div",{className:"hosted-owner__row-actions",children:[r.jsx("button",{type:"button",className:G&&we?"hosted-btn hosted-btn--fill":"hosted-btn hosted-btn--outline","aria-label":`Open ${J.label}`,disabled:!we,onClick:()=>s(J),children:"Open"}),m?.companionId===J.companion_id?null:r.jsxs(r.Fragment,{children:[r.jsx("button",{type:"button",className:"hosted-link hosted-link--muted","aria-label":`Rotate key for ${J.label}`,autoFocus:ge("rotate",J.companion_id),disabled:w,onClick:()=>K({kind:"rotate",companionId:J.companion_id}),children:"[ rotate key ]"}),r.jsx("button",{type:"button",className:"hosted-link hosted-link--muted","aria-label":`Revoke ${J.label}`,autoFocus:ge("revoke",J.companion_id),disabled:w,onClick:()=>K({kind:"revoke",companionId:J.companion_id}),children:"[ revoke ]"})]})]}),m?.companionId===J.companion_id?r.jsxs("div",{className:"hosted-owner__confirm",children:[r.jsx("p",{children:m.kind==="rotate"?"Rotating disconnects this workstation now and shows its new key once.":"Revoking disconnects this workstation now and frees its slot."}),r.jsxs("div",{className:"hosted-owner__actions",children:[r.jsx("button",{type:"button",ref:$,className:m.kind==="rotate"?"hosted-btn hosted-btn--outline":"hosted-btn hosted-btn--danger",disabled:w,"data-busy":x==="workstation"?"true":void 0,onClick:()=>te(m,J),children:m.kind==="rotate"?x==="workstation"?"Rotating…":"Rotate now":x==="workstation"?"Revoking…":"Revoke now"}),r.jsx("button",{type:"button",className:"hosted-link hosted-link--muted","aria-label":"Cancel",autoFocus:!0,disabled:w,onClick:se,children:"[ cancel ]"})]})]}):null]},J.companion_id)})}),R&&e.workstations.some(J=>J.connection.state==="offline")?r.jsx("p",{className:"hosted-owner__hint",children:"Start the ClinkX companion on an offline workstation. This page refreshes automatically."}):null,C?r.jsxs("p",{className:"hosted-owner__hint",children:[O?"This subscription covers":"This workspace allows"," at most ",e.max_workstations," workstations."]}):r.jsxs("form",{className:"hosted-owner__form",onSubmit:B,children:[r.jsxs("label",{className:"hosted-owner__field",children:[r.jsx("span",{className:"hosted-owner__field-label",children:"Workstation name"}),r.jsx("input",{className:"hosted-owner__input",value:u,maxLength:64,disabled:!M||w,onChange:J=>f(J.currentTarget.value),placeholder:"e.g. studio-mac",autoComplete:"off",spellCheck:!1})]}),r.jsx("button",{type:"submit",className:G?"hosted-btn hosted-btn--outline":"hosted-btn hosted-btn--fill",disabled:!M||w||u.trim()==="","data-busy":x==="create"?"true":void 0,children:x==="create"?"Creating…":"Create API key"})]}),!M&&!C?r.jsx("p",{className:"hosted-owner__hint",children:O?"Subscribe to create API keys.":Vg}):null,k===null?null:r.jsx("p",{className:"hosted-gate__error",role:"alert",children:k})]})}const u4={checkout_complete:"Checkout finished. Access starts once the payment is confirmed, which can take a moment.",checkout_canceled:"Checkout was canceled. Nothing was charged."};function d4({billingReturn:e,onDismiss:t}){return e==="none"||e==="invalid"?null:r.jsxs("div",{className:"hosted-owner__notice",role:"status",children:[r.jsx("p",{children:u4[e]}),r.jsx("button",{type:"button",className:"hosted-link hosted-link--muted","aria-label":"Dismiss",onClick:t,children:"[ dismiss ]"})]})}const mg={paid_period:"Paid period",past_due_grace:"Payment past due (grace period)",period_ended:"Paid period ended",grace_expired:"Grace period ended",no_purchase:"No subscription",payment_pending:"Payment pending",subscription_inactive:"Subscription inactive",unknown_state:"Subscription state unknown",suspended:"Workspace suspended",operator_grant:"Access granted by operator"},f4=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"});function yf({iso:e}){const t=Date.parse(e);return r.jsx("time",{dateTime:e,children:Number.isNaN(t)?e:f4.format(t)})}function p4(e,t){if(e.reason==="operator_grant"){const s=e.grant_until??e.access_until;return s===null?mg.operator_grant:r.jsxs(r.Fragment,{children:[mg.operator_grant," until ",r.jsx(yf,{iso:s})]})}return!t&&e.reason==="no_purchase"?"Not granted":mg[e.reason]}function hN({entitlement:e,billingEnabled:t}){return r.jsxs("dl",{className:"hosted-owner__facts",children:[r.jsx("dt",{children:"Access"}),r.jsx("dd",{"data-access":e.access,children:e.access==="granted"?"Active":"Inactive"}),r.jsx("dt",{children:"Reason"}),r.jsx("dd",{children:p4(e,t)}),e.access_until===null?null:r.jsxs(r.Fragment,{children:[r.jsx("dt",{children:"Access until"}),r.jsx("dd",{children:r.jsx(yf,{iso:e.access_until})})]}),e.grant_until===null||e.reason==="operator_grant"?null:r.jsxs(r.Fragment,{children:[r.jsx("dt",{children:"Operator grant until"}),r.jsx("dd",{children:r.jsx(yf,{iso:e.grant_until})})]}),!t||e.grace_deadline===null?null:r.jsxs(r.Fragment,{children:[r.jsx("dt",{children:"Grace deadline"}),r.jsx("dd",{children:r.jsx(yf,{iso:e.grace_deadline})})]})]})}function h4({entitlement:e}){return r.jsxs("section",{className:"hosted-owner__section","aria-labelledby":"hosted-access-title",children:[r.jsx("h2",{id:"hosted-access-title",children:"Access"}),r.jsx(hN,{entitlement:e,billingEnabled:!1}),e.suspended?r.jsx("p",{className:"hosted-owner__hint",children:"This workspace is suspended. Ask the operator to lift the suspension."}):null]})}function m4({entitlement:e,api:t,navigate:s}){const[i,o]=v.useState(null),[u,f]=v.useState(null),m=g=>{if(i!==null)return;o(g),f(null),(g==="checkout"?t.startCheckout():t.openPortal()).then(b=>s(b),b=>{f(Fg(b,"Billing could not be opened.")),o(null)})};return r.jsxs("section",{className:"hosted-owner__section","aria-labelledby":"hosted-billing-title",children:[r.jsx("h2",{id:"hosted-billing-title",children:"Billing"}),r.jsx(hN,{entitlement:e,billingEnabled:!0}),e.suspended?r.jsx("p",{className:"hosted-owner__hint",children:"This workspace is suspended. Payment does not lift a suspension."}):null,r.jsxs("div",{className:"hosted-owner__actions",children:[e.access==="granted"?null:r.jsx("button",{type:"button",className:"hosted-btn hosted-btn--fill",disabled:i!==null,"data-busy":i==="checkout"?"true":void 0,onClick:()=>m("checkout"),children:i==="checkout"?"Opening checkout…":"Subscribe"}),r.jsx("button",{type:"button",className:"hosted-btn hosted-btn--outline",disabled:i!==null,"data-busy":i==="portal"?"true":void 0,onClick:()=>m("portal"),children:i==="portal"?"Opening billing…":"Manage billing"})]}),u===null?null:r.jsx("p",{className:"hosted-gate__error",role:"alert",children:u})]})}const Tv="/workspace",Cv="clinkx.hosted.workstation",Ov="clinkx.hosted.lastWorkstation",$v={tab:()=>window.sessionStorage,last:()=>window.localStorage};function E0(e,t,s){try{const i=JSON.parse(e().getItem(t)??"null");if(typeof i!="object"||i===null)return null;const{tenantId:o,companionId:u}=i;return o===s&&typeof u=="string"&&u!==""?u:null}catch{return null}}function R0(e,t,s){try{e().setItem(t,JSON.stringify(s))}catch{}}function T0(e,t){try{e().removeItem(t)}catch{}}function g4(e,t=$v){return E0(t.tab,Cv,e)??E0(t.last,Ov,e)}function v4(e,t,s=$v){R0(s.tab,Cv,{tenantId:e,companionId:t}),R0(s.last,Ov,{tenantId:e,companionId:t})}function C0(e=$v){T0(e.tab,Cv),T0(e.last,Ov)}function nf(e=window){return e.location.pathname===Tv}const _4=1e4,b4=1e4,y4=15e3;function x4(e){window.location.assign(e)}function w4(e,t){return t()*Math.min(b4,250*2**Math.max(0,e-1))}function S4(e){return typeof e=="object"&&e!==null&&e.name==="AbortError"}function j4(e){return e==="misdirected_request"?"This address does not serve ClinkX workspaces.":e==="forbidden"||e==="not_member"?"This ClinkX account has no workspace it can manage.":"The workspace service could not be reached."}function mN({workspace:e}){return r.jsx("button",{type:"button",className:"hosted-link hosted-link--muted","aria-label":e.signingOut?"Signing out…":"Sign out of ClinkX account",disabled:e.signingOut,onClick:e.signOut,children:e.signingOut?"signing out…":"[ sign out of ClinkX account ]"})}function N4({workspace:e}){return r.jsxs("div",{className:"hosted-gate__pre-auth",children:[e.isOwner?r.jsx("button",{type:"button",className:"hosted-link","aria-label":"Workspace",onClick:e.openWorkspace,children:"[ workspace ]"}):null,r.jsx(mN,{workspace:e})]})}const k4={filled:"hosted-gate__mark",hollow:"hosted-gate__mark hosted-gate__mark--hollow",pulse:"hosted-gate__mark hosted-gate__mark--live",fail:"hosted-gate__mark hosted-gate__mark--fail"},A4=["account","workspace","passkey"];function E4({at:e,mark:t,drawing:s}){const i=u=>u<e?"hosted-gate__node hosted-gate__node--done":u===e?`hosted-gate__node ${k4[t]}`:"hosted-gate__node",o=u=>s&&u===e-1?"hosted-gate__track-line hosted-gate__track-line--busy":u<e?"hosted-gate__track-line hosted-gate__track-line--done":"hosted-gate__track-line";return r.jsxs("div",{className:"hosted-gate__track","aria-hidden":"true",children:[r.jsxs("div",{className:"hosted-gate__track-row",children:[r.jsx("span",{className:i(1)}),r.jsx("span",{className:o(1)}),r.jsx("span",{className:i(2)}),r.jsx("span",{className:o(2)}),r.jsx("span",{className:i(3)})]}),r.jsx("div",{className:"hosted-gate__track-labels",children:A4.map((u,f)=>r.jsx("span",{className:f+1===e?"is-current":void 0,children:u},u))})]})}function mo({title:e,at:t,mark:s,drawing:i=!1,workspace:o=!1,children:u}){return r.jsx("main",{className:o?"auth-gate hosted-gate hosted-gate--workspace":"auth-gate hosted-gate",children:r.jsxs("section",{className:o?"hosted-gate__card hosted-gate__card--workspace":"hosted-gate__card","aria-labelledby":"hosted-gate-title",children:[r.jsxs("div",{className:"hosted-gate__head",children:[r.jsx(E4,{at:t,mark:s,drawing:i}),r.jsx("h1",{id:"hosted-gate-title",children:e})]}),u]})})}function R4({billingReturn:e,api:t,localAuth:s,navigate:i,renderLocal:o,statusPollMs:u,random:f}){const[m,g]=v.useState({phase:"connecting"}),[h,b]=v.useState(0),[x,N]=v.useState(e),[w,k]=v.useState(null),[S,A]=v.useState(!1),[$,T]=v.useState(!1),[C,M]=v.useState(!1),R=v.useRef(!1),O=v.useRef(null),G=v.useRef(null),B=v.useRef(m),te=v.useRef(!1),K=v.useRef(null),se=v.useRef(null),ge=v.useRef({consecutive:0,committedAt:0}),J=v.useCallback(q=>{O.current??=g4(q.context.tenantId);const re=O.current===null?void 0:q.workspace.workstations.find(Te=>Te.companion_id===O.current);if(O.current!==null&&re===void 0&&(O.current=null,C0()),nf()){g({phase:"workspace",read:q,offlineSelection:!1});return}const Re=q.workspace.entitlement.access==="granted"?re:void 0;if(Re!==void 0){const Te=pg(q,Re,Qc());if(Te.kind==="selected"){g({phase:"local",read:q,workstation:Re,epoch:Te.epoch});return}if(Te.kind==="superseded")return}g({phase:"workspace",read:q,offlineSelection:Re!==void 0})},[]);v.useEffect(()=>{const q=new AbortController,re=()=>!q.signal.aborted,Re=()=>{ge.current.consecutive+=1,b(dt=>dt+1)},Te=dt=>{if(K.current===q&&(K.current=null),!(!re()||dt.kind==="superseded")){if(dt.kind==="signed_out"){g({phase:"signed_out"});return}if(dt.kind==="unavailable"){const Ot=r4(dt.code,dt.status);g({phase:"unavailable",retrying:Ot,code:dt.code}),Ot&&Re();return}J({workspace:dt.workspace,context:dt.context})}},xe=dt=>{K.current===q&&(K.current=null),!(!re()||S4(dt))&&(g({phase:"unavailable",retrying:!0,code:null}),Re())},Me=h===0||te.current?0:w4(ge.current.consecutive,f);te.current=!1,se.current=q;const ot=window.setTimeout(()=>{q.signal.aborted||(K.current=q,i4(t,q.signal).then(Te,xe))},Me);return()=>{window.clearTimeout(ot),q.abort(),se.current===q&&(se.current=null)}},[t,J,f,h]),v.useEffect(()=>{if(B.current=m,m.phase!=="local")return;const q=Date.now();q-ge.current.committedAt>y4&&(ge.current.consecutive=0),ge.current.committedAt=q},[m]);const we=v.useCallback(()=>{te.current=!0,b(q=>q+1)},[]);v.useEffect(()=>ev(q=>{if(q.type==="lost"){if(K.current?.abort(),q.cause==="cloud_unauthenticated"){se.current?.abort(),O.current=null,g({phase:"signed_out"});return}if(q.cause==="entitlement_inactive"&&B.current.phase==="workspace"){te.current=!0,b(re=>re+1);return}ge.current.consecutive+=1,g({phase:"connecting"}),b(re=>re+1)}}),[]);const ue=()=>{const q=K.current;R.current||q!==null&&!q.signal.aborted||we()},L=m.phase==="unavailable"&&m.retrying;v.useEffect(()=>{if(!L)return;const q=()=>{document.visibilityState==="visible"&&ue()};return window.addEventListener("online",ue),document.addEventListener("visibilitychange",q),()=>{window.removeEventListener("online",ue),document.removeEventListener("visibilitychange",q)}},[L]),v.useEffect(()=>{if(m.phase!=="workspace")return;const q=window.setTimeout(we,u);return()=>window.clearTimeout(q)},[we,m,u]),v.useEffect(()=>{const q=()=>{const re=B.current;if(nf())re.phase==="local"&&g({phase:"workspace",read:re.read,offlineSelection:!1});else if(re.phase==="workspace")G.current=null;else return;we()};return window.addEventListener("popstate",q),()=>window.removeEventListener("popstate",q)},[we]);const Y=v.useCallback(()=>{nf()||(G.current=`${window.location.pathname}${window.location.search}${window.location.hash}`,window.history.pushState(null,"",Tv)),g(q=>q.phase==="local"?{phase:"workspace",read:q.read,offlineSelection:!1}:q),we()},[we]),de=v.useCallback(()=>{if(R.current)return;R.current=!0,window.dispatchEvent(new CustomEvent(Of)),M(!0),K.current?.abort(),se.current?.abort();let q=m.phase==="local";if(m.phase==="workspace"&&O.current!==null){const re=m.read.workspace.workstations.find(Re=>Re.companion_id===O.current);q=re!==void 0&&pg(m.read,re,Qc()).kind==="selected"}(async()=>(q&&await s.logout().catch(()=>{}),await t.logout().catch(()=>{}),O.current=null,C0(),Ag("cloud_unauthenticated"),R.current=!1,M(!1)))()},[t,s,m]),oe=(m.phase==="local"||m.phase==="workspace")&&m.read.workspace.role==="owner",Se=v.useMemo(()=>({openWorkspace:Y,isOwner:oe,signOut:de,signingOut:C}),[oe,Y,de,C]),E=()=>{S||(A(!0),T(!1),t.startSignIn().then(i,()=>{A(!1),T(!0)}))},U=(q,re)=>{O.current=re.companion_id,v4(q.context.tenantId,re.companion_id),nf()&&(window.history.pushState(null,"",G.current??"/runs"),G.current=null);const Re=pg(q,re,Qc());Re.kind==="selected"?g({phase:"local",read:q,workstation:re,epoch:Re.epoch}):Re.kind==="offline"&&g({phase:"workspace",read:q,offlineSelection:!0})},P=r.jsx(d4,{billingReturn:x,onDismiss:()=>N("none")}),ne=r.jsx(mN,{workspace:Se}),be=w===null?null:r.jsx(o4,{issued:w,onDone:()=>k(null)});switch(m.phase){case"connecting":return r.jsx(mo,{title:"ClinkX workspace",at:2,mark:"pulse",drawing:!0,children:r.jsx("p",{className:"hosted-gate__lede","aria-live":"polite",children:"Connecting to your workspace…"})});case"signed_out":return r.jsxs(mo,{title:"Sign in to ClinkX",at:1,mark:"hollow",children:[r.jsx("p",{className:"hosted-gate__lede",children:"Sign in with your ClinkX account to open your workspace. Each workstation then asks for its own passkey."}),r.jsx("div",{className:"hosted-gate__actions",children:r.jsx("button",{type:"button",className:"hosted-btn hosted-btn--fill hosted-btn--wide",disabled:S,"data-busy":S?"true":void 0,onClick:E,children:S?"Redirecting…":"Sign in"})}),$?r.jsx("p",{className:"hosted-gate__error",role:"alert",children:"Sign-in could not be started. Try again."}):null]});case"unavailable":return m.retrying?r.jsxs(mo,{title:"ClinkX workspace",at:2,mark:"pulse",drawing:!0,children:[r.jsx("p",{className:"hosted-gate__lede","aria-live":"polite",children:"Reconnecting…"}),r.jsxs("div",{className:"hosted-gate__actions",children:[r.jsx("button",{type:"button",className:"hosted-btn hosted-btn--outline",onClick:ue,children:"Try now"}),ne]})]}):r.jsxs(mo,{title:"Workspace unavailable",at:2,mark:"fail",children:[r.jsx("p",{className:"hosted-gate__lede",children:j4(m.code)}),r.jsxs("div",{className:"hosted-gate__actions",children:[r.jsx("button",{type:"button",className:"hosted-btn hosted-btn--fill hosted-btn--wide",onClick:()=>{g({phase:"connecting"}),we()},children:"Try again"}),ne]})]});case"workspace":{const{read:q}=m,re=q.workspace;return r.jsxs(mo,{title:"Your ClinkX workspace",at:2,mark:"filled",workspace:!0,children:[m.offlineSelection?r.jsxs("div",{className:"hosted-owner__notice",role:"status",children:[r.jsx("span",{"aria-hidden":"true",className:"hosted-owner__dot hosted-owner__dot--off"}),r.jsx("p",{children:"That workstation is offline. Start its companion, or open another workstation."})]}):null,re.billing_enabled?P:null,be,r.jsx(c4,{workspace:re,api:t,onSelect:Re=>U(q,Re),onIssued:k,onChanged:we}),re.billing_enabled?r.jsx(m4,{entitlement:re.entitlement,api:t,navigate:i}):r.jsx(h4,{entitlement:re.entitlement}),r.jsx("div",{className:"hosted-gate__foot",children:ne})]})}}return r.jsx("div",{className:"hosted-gate__local","data-authority-epoch":m.epoch,"data-workstation":m.workstation.companion_id,children:o(Se)},m.epoch)}function T4({hosting:e,renderLocal:t,billingReturn:s="none",api:i,localAuth:o,navigate:u=x4,statusPollMs:f=_4,random:m=Math.random}){const g=v.useMemo(()=>i??n4(),[i]),h=v.useMemo(()=>o??wp(),[o]);return e.kind==="hosted"?r.jsx(R4,{billingReturn:s,api:g,localAuth:h,navigate:u,renderLocal:t,statusPollMs:f,random:m}):r.jsx(mo,{title:"ClinkX workspace",at:1,mark:"fail",children:r.jsx("p",{className:"hosted-gate__lede",role:"alert",children:"This dashboard's hosting configuration is invalid."})})}function C4(e,t=window.location.origin){return e.mode==="local"&&!e.authenticated&&wu(t)}const gN=document.getElementById("root");if(!gN)throw new Error("Root element #root not found");const Xc=Qk.createRoot(gN),O0=qD(),O4=e=>{const t=e.kind==="hosted"?l4():void 0;t!==void 0&&t!=="none"&&window.history.replaceState(window.history.state,"",Tv),e.kind==="hosted"&&(KA(),Yc("passkey"));const s=wp();Xc.render(r.jsx(v.StrictMode,{children:r.jsx(T4,{hosting:e,...t===void 0?{}:{billingReturn:t},localAuth:s,renderLocal:i=>r.jsx(lN,{api:s,preAuthActions:r.jsx(N4,{workspace:i}),authenticatedContent:o=>r.jsx(Av,{accountActions:{...o,onOpenWorkspace:i.openWorkspace}})})})}))},$4=()=>{const e=Z0(),t=()=>{Xc.render(r.jsx(v.StrictMode,{children:r.jsx(Av,{})}))},s=async m=>{if(!HA(m))return!1;try{return(await Eg()).authenticated?(t(),!0):(kg(),!1)}catch(g){const h=VA();if(kg(),h)throw g;return!1}},i=()=>{Xc.render(r.jsx(v.StrictMode,{children:r.jsx(MD,{onSubmit:s})}))},o=()=>C4(wr(),window.location.origin),u=()=>{if(Yc("bearer"),o()){i();return}Eg().then(()=>o()?i():t(),()=>o()?i():t())},f=wp();AD(f,e.mode==="remote").then(m=>{if(m==="passkey"){Yc("passkey"),Xc.render(r.jsx(v.StrictMode,{children:r.jsx(lN,{api:f})}));return}if(m==="none"){Yc("none"),t();return}u()},()=>{Xc.render(r.jsx(v.StrictMode,{children:r.jsx("main",{className:"auth-gate",children:r.jsxs("section",{className:"auth-gate__card",role:"alert",children:[r.jsx("h1",{children:"ClinkX field station"}),r.jsx("p",{children:"Could not load dashboard authentication status."})]})})}))})};O0.kind==="standalone"?$4():O4(O0);
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
<meta name="referrer" content="no-referrer" />
|
|
7
7
|
<title>ClinkX workflow dashboard</title>
|
|
8
8
|
<script src="/theme-init.js"></script>
|
|
9
|
-
<script type="module" crossorigin src="/assets/index-
|
|
9
|
+
<script type="module" crossorigin src="/assets/index-CX4FrhYN.js"></script>
|
|
10
10
|
<link rel="stylesheet" crossorigin href="/assets/style-C5guUjwN.css">
|
|
11
11
|
</head>
|
|
12
12
|
<body>
|
|
@@ -1207,6 +1207,8 @@ const ENV_ONLY = [
|
|
|
1207
1207
|
{ name: "CLINKX_DASHBOARD_STANDALONE_ENTRY", reason: "internal channel: marks the companion standalone entry process" },
|
|
1208
1208
|
{ name: "CLINKX_SETTINGS_DIR", reason: "bootstrap locator: overrides the settings directory itself (OQ-4)" },
|
|
1209
1209
|
{ name: "CLINKX_SETTINGS", reason: "bootstrap switch: disables settings loading entirely (OQ-4)" },
|
|
1210
|
+
{ name: "CLINKX_DESKTOP_WORKSTATION_KEY", reason: "launcher secret channel: keychain-held workstation key injected by the desktop shell at spawn; never file-writable and never in argv" },
|
|
1211
|
+
{ name: "CLINKX_DESKTOP_COMPANION_EXECUTABLE", reason: "code execution: development/test override choosing the companion executable the host daemon supervises (daemon-entry.ts)" },
|
|
1210
1212
|
{ name: "CLINKX_RUN_CODEX_SCHEMA_DRIFT", reason: "test/dev-only opt-in for the live codex schema drift check (tests/codex)" },
|
|
1211
1213
|
{ name: "CLINKX_REQUIRE_CROSS_REPO", reason: "test/dev-only cross-repo assertion flag (tests/integration)" },
|
|
1212
1214
|
{ name: "CLINKX_IDLE_TIMEOUT_SECONDS", reason: "adapter-overridable knob: optional adapter idle_timeout_seconds (src/config.ts) wins when pinned; this env is the live fallback for adapters that pin none (src/runner.ts)" },
|
|
@@ -1251,6 +1253,9 @@ const DEPLOYMENT_ONLY = [
|
|
|
1251
1253
|
{ name: "CLINKX_DASHBOARD_GATEWAY_REQUIRE_PERSISTENT_DB", reason: "gateway self-config: image-set persistent DB requirement" },
|
|
1252
1254
|
{ name: "CLINKX_DASHBOARD_GATEWAY_ACCOUNT_ORIGIN", reason: "retired gateway name: set means reject" },
|
|
1253
1255
|
{ name: "CLINKX_DASHBOARD_GATEWAY_TENANT_BASE_DOMAIN", reason: "retired gateway name: set means reject" },
|
|
1256
|
+
{ name: "CLINKX_DESKTOP_APP_DATA", reason: "launcher self-config: desktop app-data directory holding the daemon profile (shell owned)" },
|
|
1257
|
+
{ name: "CLINKX_DESKTOP_VAULT", reason: "launcher self-config: shell-reported OS keychain availability for the workstation key" },
|
|
1258
|
+
{ name: "CLINKX_DESKTOP_SERVICE", reason: "launcher self-config: self-hosted service override the shell passes to the host daemon (origin|gatewayUrl|mode)" },
|
|
1254
1259
|
];
|
|
1255
1260
|
/**
|
|
1256
1261
|
* DEAD: still read by consumers but effectively unreachable — every shipped
|