@rubytech/create-maxy-code 0.1.501 → 0.1.503

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/package.json +1 -1
  2. package/payload/platform/docs/superpowers/plans/2026-07-25-task-1974-uploads-intake-inbox.md +235 -0
  3. package/payload/platform/docs/superpowers/plans/2026-07-25-task-1976-intra-folder-hygiene.md +215 -0
  4. package/payload/platform/plugins/admin/PLUGIN.md +1 -0
  5. package/payload/platform/plugins/admin/hooks/__tests__/quote-engine-gate.test.sh +98 -0
  6. package/payload/platform/plugins/admin/hooks/quote-engine-gate.sh +68 -0
  7. package/payload/platform/plugins/admin/skills/platform-architecture/SKILL.md +2 -2
  8. package/payload/platform/plugins/admin/skills/whats-new/SKILL.md +13 -0
  9. package/payload/platform/plugins/docs/references/internals.md +1 -1
  10. package/payload/platform/scripts/lib/provision-account-dir.sh +2 -1
  11. package/payload/platform/services/telegram-channel/dist/instructions.js +2 -2
  12. package/payload/platform/services/telegram-channel/dist/instructions.js.map +1 -1
  13. package/payload/platform/services/webchat-channel/dist/instructions.js +2 -2
  14. package/payload/platform/services/webchat-channel/dist/instructions.js.map +1 -1
  15. package/payload/platform/services/whatsapp-channel/dist/notification.js +2 -2
  16. package/payload/platform/services/whatsapp-channel/dist/notification.js.map +1 -1
  17. package/payload/platform/templates/account-schema/SCHEMA.md +36 -1
  18. package/payload/platform/templates/specialists/agents/data-manager.md +4 -2
  19. package/payload/server/public/activity.html +5 -5
  20. package/payload/server/public/assets/AdminLoginScreens-Bv_bKKeL.js +1 -0
  21. package/payload/server/public/assets/AdminShell-Gq8DU_ig.js +2 -0
  22. package/payload/server/public/assets/{activity-CVdVSw5V.js → activity-DZFYDHNA.js} +1 -1
  23. package/payload/server/public/assets/{admin-If1QLlS3.js → admin-DLUOixl6.js} +1 -1
  24. package/payload/server/public/assets/{bot-8b26IlQY.js → bot-CrEhKW1l.js} +1 -1
  25. package/payload/server/public/assets/{browser-F40DXfKA.js → browser-Bt4-LKLU.js} +1 -1
  26. package/payload/server/public/assets/calendar-B8ujkn_K.js +1 -0
  27. package/payload/server/public/assets/chat-lQXd6gsM.js +1 -0
  28. package/payload/server/public/assets/chevron-left-CQ8rcBoO.js +1 -0
  29. package/payload/server/public/assets/chevron-right-CSRSqblN.js +1 -0
  30. package/payload/server/public/assets/clock-B7Ba8AZL.js +1 -0
  31. package/payload/server/public/assets/data-BdlGqjKM.js +1 -0
  32. package/payload/server/public/assets/{file-text-B1HjPFbM.js → file-text-BpLcZKld.js} +1 -1
  33. package/payload/server/public/assets/{graph-CIC-mgKR.js → graph-HB0199x-.js} +3 -3
  34. package/payload/server/public/assets/{graph-labels-BnpHCHaQ.js → graph-labels-Bx19ZYvJ.js} +1 -1
  35. package/payload/server/public/assets/{maximize-2-BL7QVTcQ.js → maximize-2-BhR-Ec21.js} +1 -1
  36. package/payload/server/public/assets/operator-Bf3hP3qo.js +1 -0
  37. package/payload/server/public/assets/page-Bs24tO-C.js +32 -0
  38. package/payload/server/public/assets/page-FnCmAeHc.js +1 -0
  39. package/payload/server/public/assets/{public-BI21tOkm.js → public-DZHPsyKX.js} +1 -1
  40. package/payload/server/public/assets/{rotate-ccw-C_20Bc3E.js → rotate-ccw-D9qOBLig.js} +1 -1
  41. package/payload/server/public/assets/{routines-Ci3N8wqV.js → routines-lGiYaMiX.js} +1 -1
  42. package/payload/server/public/assets/skills-y-h0P9rC.js +1 -0
  43. package/payload/server/public/assets/{tasks-DC2Yf2Ev.js → tasks-Cyc1EfLA.js} +1 -1
  44. package/payload/server/public/assets/{time-entry-format-CNcjs2HV.js → time-entry-format-RkCW7hKu.js} +1 -1
  45. package/payload/server/public/assets/{triangle-alert-CngnWtjD.js → triangle-alert-k8ulav-N.js} +1 -1
  46. package/payload/server/public/assets/{useCopyFeedback-DZ9Bw5CI.js → useCopyFeedback-DN1WA5vU.js} +1 -1
  47. package/payload/server/public/assets/useSubAccountSwitcher-fvBunpOC.css +1 -0
  48. package/payload/server/public/assets/useSubAccountSwitcher-iQGqNJhI.js +9 -0
  49. package/payload/server/public/assets/useVoiceRecorder-v--TIxaM.js +2 -0
  50. package/payload/server/public/assets/{wrench-dky2-13x.js → wrench-CKhz8KnQ.js} +1 -1
  51. package/payload/server/public/browser.html +4 -4
  52. package/payload/server/public/calendar.html +7 -7
  53. package/payload/server/public/chat.html +14 -14
  54. package/payload/server/public/data.html +11 -11
  55. package/payload/server/public/graph.html +9 -9
  56. package/payload/server/public/index.html +15 -15
  57. package/payload/server/public/operator.html +15 -15
  58. package/payload/server/public/public.html +14 -14
  59. package/payload/server/public/routines.html +6 -6
  60. package/payload/server/public/skills.html +5 -5
  61. package/payload/server/public/tasks.html +6 -6
  62. package/payload/server/server.js +840 -748
  63. package/payload/server/public/assets/AdminLoginScreens-C3LZOPIY.js +0 -1
  64. package/payload/server/public/assets/AdminShell-BlbUNAPc.js +0 -2
  65. package/payload/server/public/assets/calendar-DZiHiBwV.js +0 -1
  66. package/payload/server/public/assets/chat-uD28FVCS.js +0 -1
  67. package/payload/server/public/assets/chevron-left-lBxD57tD.js +0 -1
  68. package/payload/server/public/assets/chevron-right-C-lDig9Y.js +0 -1
  69. package/payload/server/public/assets/clock-DqRNsY40.js +0 -1
  70. package/payload/server/public/assets/data-BsFyBN85.js +0 -1
  71. package/payload/server/public/assets/operator-B62h_TaC.js +0 -1
  72. package/payload/server/public/assets/page-BUUBseJZ.js +0 -32
  73. package/payload/server/public/assets/page-Bw-tYjw7.js +0 -1
  74. package/payload/server/public/assets/skills-CiflzOko.js +0 -1
  75. package/payload/server/public/assets/useSubAccountSwitcher-CHwQhkaI.js +0 -9
  76. package/payload/server/public/assets/useSubAccountSwitcher-yFQqnpQ8.css +0 -1
  77. package/payload/server/public/assets/useVoiceRecorder-C3G6aqZr.js +0 -2
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: platform-architecture
3
3
  description: Use when grounding any documented-surface claim about what Maxy ships — plugins, skills, specialists, install/deploy flows, internals. This is the install catalogue, not evidence of what is enabled on the current account. For install state on this account, call `capabilities-here`; for documented surface, cite the `Source:` URL inline.
4
- content-hash: sha256:70e0125f4ead8ba83c01b87f6a9ccc15f51d9492c5dd55bd4f83106769280a7e
4
+ content-hash: sha256:f78dfe81d9832fd7197627e1cf770c730bb2d16b4b640f1a47558e86acfe0db8
5
5
  brand: maxy-code
6
6
  product-name: Maxy
7
7
  ---
@@ -4354,7 +4354,7 @@ Standing rules the operator gives over a channel are `Preference` nodes. Two mec
4354
4354
 
4355
4355
  **Observability.** `[preference-write] op=reconcile … mode=<reinforce|update|contradict|new> similarity=…` — a stream of `mode=new` for subjects that already exist is the duplicate-minting signature. `[preference-inject] op=inject channel=<wa|tg|web> injected=<N> owner=<8> source=<owner|no-owner|owner-error|fetch-error>` — injection selects only the account owner's admin preferences, so `source=owner injected=0` is a genuinely empty owner, `source=no-owner` is an account with no seeded owner (injects nothing, a missed owner seeding), and `injected=0 source=owner` on an account whose owner holds rules is the write-only regression re-appearing. `[preference-inject] op=reconcile accountId=… stored=… injected=…` — the standing reconciliation audit (claude-session-manager, 5-minute tick) flags any account whose stored active count diverges from what injection surfaces; injection now surfaces every stored active preference verbatim, so `stored == injected` is the healthy signal and any gap is a dropped-row regression (a reintroduced cap, filter, or truncation). A clean pass logs `op=reconcile drifted=0`, the no-event detector.
4356
4356
 
4357
- **Consult-before-send gate.** Injection (above) puts the owner's active rules in front of every channel turn, but the growing layer-2 `Preference` set is read on demand with `profile-read`, a per-turn judgement the agent can skip, the miss that dropped a customer signature on a delivered document. `hooks/preference-consult-gate.sh` (admin plugin) is the deliverable-boundary enforcement: a PreToolUse gate on customer-facing document deliverables (`browser-pdf-save`/`SendUserFile` to `memory/users/<phone>/documents/`, and email/Outlook sends carrying attachments) that blocks (exit 2) when no `profile-read` ran after the last user message in the transcript. It fires on documents only, never on casual replies. **Observability:** `[preference-gate] op=allow tool=<name> consulted=true` on an allowed document deliverable, `op=bypass tool=<name> detail=no profile-read this turn` on a block; a stream of `op=bypass` is the un-consulted-send signature. The advisory companion `hooks/preference-consult-directive.sh` injects the two-layer architecture reminder every turn (`[pref-wrapper] op=inject`). The placement half, promoting finished deliverables out of `output/` scratch, is counted by the `data-manager` reconcile audit (`scratch-refs`, `stranded`); making that audit run on a standing periodic cadence is a filed follow-up.
4357
+ **Consult-before-send gate.** Injection (above) puts the owner's active rules in front of every channel turn, but the growing layer-2 `Preference` set is read on demand with `profile-read`, a per-turn judgement the agent can skip, the miss that dropped a customer signature on a delivered document. `hooks/preference-consult-gate.sh` (admin plugin) is the deliverable-boundary enforcement: a PreToolUse gate on customer-facing document deliverables (`browser-pdf-save`/`SendUserFile` to `memory/users/<phone>/documents/`, and email/Outlook sends carrying attachments) that blocks (exit 2) when no `profile-read` ran after the last user message in the transcript. It fires on documents only, never on casual replies. **Observability:** `[preference-gate] op=allow tool=<name> consulted=true` on an allowed document deliverable, `op=bypass tool=<name> detail=no profile-read this turn` on a block; a stream of `op=bypass` is the un-consulted-send signature. The advisory companion `hooks/preference-consult-directive.sh` injects the two-layer architecture reminder every turn (`[pref-wrapper] op=inject`). The placement half, promoting finished deliverables out of `output/` scratch, is counted by the `data-manager` reconcile audit (`scratch-refs`, `stranded`); making that audit run on a standing periodic cadence is a filed follow-up. The inbound mirror is the `uploads/` intake inbox: an uploaded file lands at `uploads/<attachmentId>/` and is promoted to its canonical entity bucket when its graph node is created, so a persisted node reference resolving into `uploads/` is intake drift, counted by the same reconcile audit as `stranded-intake`. Unlike `output/`, `uploads/` is never rebuilt by a tool, so the `data-manager` may promote a file out of it. Beyond placement and intake, the same audit counts intra-folder sprawl inside each operator-data entity folder from disk structure alone: superseded version copies (`<base>.ext` and `<base>-vN.ext` are one deliverable, all but the newest counted `versioned`), format twins (a source `.html`/`.md` render kept beside its delivered `.pdf` of the same basename, counted `format-twins`), and subfolders nested under `projects/<name>/` or `contacts/<name>/` that the flat rule forbids (counted `stray-subdir`). These are read-only counts; removal or flattening happens only on a `data-manager` stewardship dispatch, each paired with a `database-operator` reference update. The reconcile output contract is `unreachable=N broken-refs=M scratch-refs=P stranded=Q stranded-intake=R versioned=S format-twins=T stray-subdir=U`.
4358
4358
 
4359
4359
  ---
4360
4360
 
@@ -9,6 +9,19 @@ Invoked by the admin agent directly.
9
9
 
10
10
  This is the platform's release timeline, newest first. Each entry shows the date it shipped and the version it shipped in, so you can tell the operator how current their install is. To compare, read the installed version from `capabilities-here` and match it against the versions below. Keep answers high level and in plain English; this is a summary, not a full commit log.
11
11
 
12
+ ## 2026-07-25 (0.1.503)
13
+
14
+ - The "stalled" indicator in chat now only shows when a turn is genuinely stuck, not during a normal pause.
15
+ - Quote price changes always go through the proper pricing engine now, closing a path that could skip its checks.
16
+ - The Skills and Calendar detail views are wider and no longer show an unnecessary scrollbar.
17
+
18
+ ## 2026-07-25 (0.1.502)
19
+
20
+ - Uploading a file from the phone or desktop app now shows as a proper thumbnail in chat, not a raw file path.
21
+ - Switching accounts now shows a loading screen and lands you on the dashboard instead of a blank page.
22
+ - Uploaded files are automatically filed into the right folder instead of sitting in a temporary holding area.
23
+ - Searching your files is more reliable and no longer times out on larger accounts.
24
+
12
25
  ## 2026-07-21 (0.1.482)
13
26
 
14
27
  - WhatsApp now runs a separate connection for each client account, so one client's messages never mix with another's.
@@ -408,7 +408,7 @@ Standing rules the operator gives over a channel are `Preference` nodes. Two mec
408
408
 
409
409
  **Observability.** `[preference-write] op=reconcile … mode=<reinforce|update|contradict|new> similarity=…` — a stream of `mode=new` for subjects that already exist is the duplicate-minting signature. `[preference-inject] op=inject channel=<wa|tg|web> injected=<N> owner=<8> source=<owner|no-owner|owner-error|fetch-error>` — injection selects only the account owner's admin preferences, so `source=owner injected=0` is a genuinely empty owner, `source=no-owner` is an account with no seeded owner (injects nothing, a missed owner seeding), and `injected=0 source=owner` on an account whose owner holds rules is the write-only regression re-appearing. `[preference-inject] op=reconcile accountId=… stored=… injected=…` — the standing reconciliation audit (claude-session-manager, 5-minute tick) flags any account whose stored active count diverges from what injection surfaces; injection now surfaces every stored active preference verbatim, so `stored == injected` is the healthy signal and any gap is a dropped-row regression (a reintroduced cap, filter, or truncation). A clean pass logs `op=reconcile drifted=0`, the no-event detector.
410
410
 
411
- **Consult-before-send gate.** Injection (above) puts the owner's active rules in front of every channel turn, but the growing layer-2 `Preference` set is read on demand with `profile-read`, a per-turn judgement the agent can skip, the miss that dropped a customer signature on a delivered document. `hooks/preference-consult-gate.sh` (admin plugin) is the deliverable-boundary enforcement: a PreToolUse gate on customer-facing document deliverables (`browser-pdf-save`/`SendUserFile` to `memory/users/<phone>/documents/`, and email/Outlook sends carrying attachments) that blocks (exit 2) when no `profile-read` ran after the last user message in the transcript. It fires on documents only, never on casual replies. **Observability:** `[preference-gate] op=allow tool=<name> consulted=true` on an allowed document deliverable, `op=bypass tool=<name> detail=no profile-read this turn` on a block; a stream of `op=bypass` is the un-consulted-send signature. The advisory companion `hooks/preference-consult-directive.sh` injects the two-layer architecture reminder every turn (`[pref-wrapper] op=inject`). The placement half, promoting finished deliverables out of `output/` scratch, is counted by the `data-manager` reconcile audit (`scratch-refs`, `stranded`); making that audit run on a standing periodic cadence is a filed follow-up.
411
+ **Consult-before-send gate.** Injection (above) puts the owner's active rules in front of every channel turn, but the growing layer-2 `Preference` set is read on demand with `profile-read`, a per-turn judgement the agent can skip, the miss that dropped a customer signature on a delivered document. `hooks/preference-consult-gate.sh` (admin plugin) is the deliverable-boundary enforcement: a PreToolUse gate on customer-facing document deliverables (`browser-pdf-save`/`SendUserFile` to `memory/users/<phone>/documents/`, and email/Outlook sends carrying attachments) that blocks (exit 2) when no `profile-read` ran after the last user message in the transcript. It fires on documents only, never on casual replies. **Observability:** `[preference-gate] op=allow tool=<name> consulted=true` on an allowed document deliverable, `op=bypass tool=<name> detail=no profile-read this turn` on a block; a stream of `op=bypass` is the un-consulted-send signature. The advisory companion `hooks/preference-consult-directive.sh` injects the two-layer architecture reminder every turn (`[pref-wrapper] op=inject`). The placement half, promoting finished deliverables out of `output/` scratch, is counted by the `data-manager` reconcile audit (`scratch-refs`, `stranded`); making that audit run on a standing periodic cadence is a filed follow-up. The inbound mirror is the `uploads/` intake inbox: an uploaded file lands at `uploads/<attachmentId>/` and is promoted to its canonical entity bucket when its graph node is created, so a persisted node reference resolving into `uploads/` is intake drift, counted by the same reconcile audit as `stranded-intake`. Unlike `output/`, `uploads/` is never rebuilt by a tool, so the `data-manager` may promote a file out of it. Beyond placement and intake, the same audit counts intra-folder sprawl inside each operator-data entity folder from disk structure alone: superseded version copies (`<base>.ext` and `<base>-vN.ext` are one deliverable, all but the newest counted `versioned`), format twins (a source `.html`/`.md` render kept beside its delivered `.pdf` of the same basename, counted `format-twins`), and subfolders nested under `projects/<name>/` or `contacts/<name>/` that the flat rule forbids (counted `stray-subdir`). These are read-only counts; removal or flattening happens only on a `data-manager` stewardship dispatch, each paired with a `database-operator` reference update. The reconcile output contract is `unreachable=N broken-refs=M scratch-refs=P stranded=Q stranded-intake=R versioned=S format-twins=T stray-subdir=U`.
412
412
 
413
413
  ---
414
414
 
@@ -92,7 +92,8 @@ provision_account_dir() {
92
92
  "matcher": "Bash",
93
93
  "hooks": [
94
94
  { "type": "command", "command": "bash $HOOKS_PATH/archive-ingest-surface-gate.sh" },
95
- { "type": "command", "command": "bash $HOOKS_PATH/fs-schema-guard-bash-pre.sh" }
95
+ { "type": "command", "command": "bash $HOOKS_PATH/fs-schema-guard-bash-pre.sh" },
96
+ { "type": "command", "command": "bash $HOOKS_PATH/quote-engine-gate.sh" }
96
97
  ]
97
98
  },
98
99
  {
@@ -72,8 +72,8 @@ export function replyTextDescription(role) {
72
72
  // NO_INTERNALS violation. The public role keeps plain delivery and relies on the
73
73
  // server-level PUBLIC_INSTRUCTIONS.
74
74
  export const ADMIN_REFRAME_INSTRUCTION = 'Dispatch the owning specialist with the Agent tool. ' +
75
- 'Any deliverable artefact email, letter, quote, order, report, PDF, image, page ' +
76
- 'is content-producer work, without exception, including follow-up edits to one already produced. ' +
75
+ 'Every deliverable artefact (email, letter, quote, order, report, PDF, image, page) goes to the installed specialist that owns that artefact type, never produced inline, including follow-up edits to one already produced; ' +
76
+ 'only when no specialist owns the artefact type is it content-producer work. ' +
77
77
  'Else load the owning skill; else (a greeting, quick question, confirmation) just answer. ' +
78
78
  'Artefact work with neither is the violation signal — reconsider. ' +
79
79
  'Your capabilities here are very well defined: before telling the operator something cannot be done, ' +
@@ -1 +1 @@
1
- {"version":3,"file":"instructions.js","sourceRoot":"","sources":["../src/instructions.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,+EAA+E;AAC/E,+EAA+E;AAC/E,qEAAqE;AACrE,8EAA8E;AAC9E,kCAAkC;AAIlC;mEACmE;AACnE,MAAM,UAAU,kBAAkB,CAAC,GAAuB;IACxD,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAA;AAC9C,CAAC;AAED,MAAM,YAAY,GAChB,gGAAgG;IAChG,iGAAiG;IACjG,mGAAmG;IACnG,iGAAiG;IACjG,0EAA0E,CAAA;AAE5E,yEAAyE;AACzE,gFAAgF;AAChF,wEAAwE;AACxE,yEAAyE;AACzE,8EAA8E;AAC9E,iFAAiF;AACjF,6EAA6E;AAC7E,mFAAmF;AACnF,6EAA6E;AAC7E,MAAM,mBAAmB,GACvB,6FAA6F;IAC7F,mGAAmG;IACnG,yFAAyF;IACzF,sGAAsG,CAAA;AAExG,MAAM,kBAAkB,GACtB,mBAAmB;IACnB,iEAAiE;IACjE,mGAAmG;IACnG,+FAA+F;IAC/F,8FAA8F;IAC9F,kGAAkG;IAClG,6FAA6F;IAC7F,wFAAwF;IACxF,YAAY,CAAA;AAEd,MAAM,mBAAmB,GACvB,mBAAmB;IACnB,uEAAuE;IACvE,oGAAoG;IACpG,iGAAiG;IACjG,4FAA4F;IAC5F,kGAAkG;IAClG,iGAAiG;IACjG,oCAAoC;IACpC,YAAY,CAAA;AAEd,MAAM,UAAU,mBAA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ACzE,0EAA0E;AAC1E,2EAA2E;AAC3E,2EAA2E;AAC3E,2EAA2E;AAC3E,+EAA+E;AAC/E,wEAAwE;AACxE,gFAAgF;AAChF,wEAAwE;AACxE,EAAE;AACF,8EAA8E;AAC9E,2EAA2E;AAC3E,uEAAuE;AACvE,iFAAiF;AACjF,oCAAoC;AACpC,MAAM,CAAC,MAAM,yBAAyB,GACpC,sDAAsD;IACtD,8NAA8N;IAC9N,8EAA8E;IAC9E,2FAA2F;IAC3F,mEAAmE;IACnE,sGAAsG;IACtG,oHAAoH;IACpH,+IAA+I;IAC/I,gFAAgF;IAChF,+EAA+E;IAC/E,8DAA8D;IAC9D,0EAA0E;IAC1E,4DAA4D;IAC5D,8EAA8E;IAC9E,0EAA0E;IAC1E,uGAAuG;IACvG,iDAAiD;IACjD,gFAAgF;IAChF,mFAAmF;IACnF,oHAAoH;IACpH,yBAAyB;IACzB,+EAA+E;IAC/E,iFAAiF;IACjF,iFAAiF;IACjF,mBAAmB;IACnB,8GAA8G;IAC9G,gHAAgH;IAChH,4BAA4B,CAAA"}
@@ -96,8 +96,8 @@ export function connectorAuthenticateToolDescription() {
96
96
  // routing language to the visitor — a NO_INTERNALS violation. The public role
97
97
  // keeps plain delivery and relies on the server-level PUBLIC_INSTRUCTIONS.
98
98
  export const ADMIN_REFRAME_INSTRUCTION = 'Dispatch the owning specialist with the Agent tool. ' +
99
- 'Any deliverable artefact email, letter, quote, order, report, PDF, image, page ' +
100
- 'is content-producer work, without exception, including follow-up edits to one already produced. ' +
99
+ 'Every deliverable artefact (email, letter, quote, order, report, PDF, image, page) goes to the installed specialist that owns that artefact type, never produced inline, including follow-up edits to one already produced; ' +
100
+ 'only when no specialist owns the artefact type is it content-producer work. ' +
101
101
  'Else load the owning skill; else (a greeting, quick question, confirmation) just answer. ' +
102
102
  'Artefact work with neither is the violation signal — reconsider. ' +
103
103
  'Your capabilities here are very well defined: before telling the operator something cannot be done, ' +
@@ -1 +1 @@
1
- {"version":3,"file":"instruct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47
47
  export const REFRAME_INSTRUCTION = 'Dispatch the owning specialist with the Agent tool. ' +
48
- 'Any deliverable artefact email, letter, quote, order, report, PDF, image, page ' +
49
- 'is content-producer work, without exception, including follow-up edits to one already produced. ' +
48
+ 'Every deliverable artefact (email, letter, quote, order, report, PDF, image, page) goes to the installed specialist that owns that artefact type, never produced inline, including follow-up edits to one already produced; ' +
49
+ 'only when no specialist owns the artefact type is it content-producer work. ' +
50
50
  'Else load the owning skill; else (a greeting, quick question, confirmation) just answer. ' +
51
51
  'Artefact work with neither is the violation signal — reconsider. ' +
52
52
  'Your capabilities here are very well defined: before telling the sender something cannot be done, ' +
@@ -1 +1 @@
1
- {"version":3,"file":"notification.js","sourceRoot":"","sources":["../src/notification.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,yEAAyE;AACzE,yEAAyE;AAiEzE;;;gFAGgF;AAChF,MAAM,CAAC,MAAM,eAAe,GAAG,GAAG,CAAA;AAElC;;;;;;;;;;GAUG;AACH,MAAM,UAAU,gBAAgB,CAAC,EAAgB;IAC/C,IAAI,CAAC,EAAE,CAAC,IAAI;QAAE,OAAO,wDAAwD,CAAA;IAC7E,8EAA8E;IAC9E,8EAA8E;IAC9E,+BAA+B;IAC/B,MAAM,KAAK,GAAG,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAA;IAC1B,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,GAAG,eAAe,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,eAAe,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAA;IACxG,OAAO,0DAA0D,MAAM,IAAI,CAAA;AAC7E,CAAC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAC9B,sDAAsD;IACtD,qFAAqF;IACrF,kGAAkG;IAClG,2FAA2F;IAC3F,mEAAmE;IACnE,oGAAoG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AAE,EAAE,EAAE,2BAA2B,EAAE;IACxD,EAAE,IAAI,EAAE,SAAS,EAAE,EAAE,EAAE,yBAAyB,EAAE;IAClD,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE,EAAE,sBAAsB,EAAE;CAC/C,CAAA;AAOD,MAAM,UAAU,mBAAmB,CAAC,IAAY;IAC9C,MAAM,UAAU,GAAgB,EAAE,CAAA;IAClC,IAAI,KAAK,GAAG,IAAI,CAAA;IAChB,KAAK,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,IAAI,sBAAsB,EAAE,CAAC;QAClD,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,EAAE;YAC9B,UAAU,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAA;YAC5C,OAAO,YAAY,CAAA;QACrB,CAAC,CAAC,CAAA;IACJ,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,CAAA;AAC9B,CAAC"}
@@ -26,6 +26,32 @@ the client data portal, and case-sensitive matching. The write guard blocks a ba
26
26
  name as you create it, and the standing reconcile counts any that predate the
27
27
  rule. Renaming an existing bad name goes through the `data-manager` specialist.
28
28
 
29
+ ## Intra-folder hygiene
30
+
31
+ The `projects/<name>/` and `contacts/<name>/` entity folders hold one current
32
+ copy of each deliverable, in one canonical format, with no subtree. Three rules
33
+ keep them that way; the standing reconcile counts any that predate them, and
34
+ `data-manager` clears them on a stewardship dispatch. (`documents/` is exempt: it
35
+ may hold one document-folder deep per the buckets above, so these rules do not
36
+ apply there.)
37
+
38
+ - **Current version only.** `<base>.ext` and `<base>-vN.ext` (for example
39
+ `charlotte-deck.pdf` and `charlotte-deck-v2.pdf` through
40
+ `charlotte-deck-v6.pdf`) are versions of one deliverable, not separate files.
41
+ Keep the highest-numbered version (the unsuffixed base is the original, so any
42
+ `-vN` supersedes it); the superseded copies are removed through `data-manager`.
43
+ - **One canonical format.** A delivered `.pdf` and its source render sharing the
44
+ same basename (`charlotte-deck.html` beside `charlotte-deck.pdf`,
45
+ `invoice-rbt-2026-005.html` beside `invoice-rbt-2026-005.pdf`) are one
46
+ deliverable in two formats. The pdf is the deliverable; the `.html` or `.md`
47
+ render that produced it is not a second one and is removed through
48
+ `data-manager`.
49
+ - **No subfolder.** No folder nests under `projects/<name>/` or
50
+ `contacts/<name>/`; files live directly inside the entity folder. This is the
51
+ flat rule from the buckets above, restated as a standing invariant: the write
52
+ guard blocks the depth as you create it, and the reconcile counts any subtree
53
+ that predates the guard or was created off-path.
54
+
29
55
  ## Tool-owned (off-limits — never reorganise)
30
56
 
31
57
  Finished deliverables must be promoted out of `output/` into `documents/` or
@@ -33,8 +59,17 @@ Finished deliverables must be promoted out of `output/` into `documents/` or
33
59
  last resort, and a graph reference must never point into it (the next tool write
34
60
  rebuilds the tree and the reference dangles).
35
61
 
62
+ `uploads/` is a temporary intake inbox, not rebuilt scratch. A file lands at
63
+ `uploads/<attachmentId>/` on upload and is promoted to its canonical entity
64
+ bucket when its graph node is created: a Person or Organization file to
65
+ `contacts/<name>/`, a Project file to `projects/<name>/`, anything else to
66
+ `documents/`. A persisted graph reference must never point into `uploads/`.
67
+ Unlike `output/`, each upload writes its own `uploads/<attachmentId>/` dir and no
68
+ tool walks or rebuilds the subtree, so promoting a file out of it through the
69
+ `data-manager` specialist is safe.
70
+
36
71
  The internal structure of these is owned by the writing tool and is recreated on
37
- the next write: `url-get/`, `output/`, `generated/`, `extracted/`, `uploads/`,
72
+ the next write: `url-get/`, `output/`, `generated/`, `extracted/`,
38
73
  any published/served tree (`sites/`, `public/`), `agents/`, `specialists/`, and
39
74
  platform-internal areas (`cache/`, `secrets/`, `state/`, `logs/`, `tmp/`).
40
75
  `.quarantine/` is a historical store. An earlier version of the schema reconcile
@@ -14,6 +14,8 @@ You are the steward of this account's data directory. Admin dispatches you throu
14
14
  - The account data directory is organised consistently with the graph ontology. Before the first move of a session, Read `platform/plugins/memory/references/schema-base.md`; when `brand.json#vertical` is set, also Read `platform/plugins/memory/references/schema-<vertical>.md`. Directory structure and file placement should make sense to someone navigating by the graph: files that belong to a Project, Person, or document node live where the node's references say they live.
15
15
  - Every operator file is reachable from a graph node, and every graph file-reference resolves to a real path. `memory-search` is how you resolve which nodes reference a file — search for the filename and the path before deciding anything about it.
16
16
  - A file is never moved without the referencing nodes being updated in the same pass. Moves and reference updates are paired operations: for each move, dispatch `database-operator` via the Task tool with a brief naming the node (elementId from your `memory-search`), the property holding the old path, and the new path. You have no graph-write tools by design — every graph mutation flows through database-operator.
17
+ - A file in the `uploads/` intake inbox whose graph node exists is promoted to its canonical bucket (Person or Organization to `contacts/<name>/`, Project to `projects/<name>/`, else `documents/`), paired with a `database-operator` `sourcePath` update in the same pass, exactly as any other move. `uploads/` is a temporary landing area, not a tool-owned tree, so moving a file out of it is not a reorganisation of a system-convention directory.
18
+ - Superseded versions and redundant format twins are removed, and a subfolder nested under `projects/<name>/` or `contacts/<name>/` is flattened or re-filed, when a stewardship brief asks for it. Each removal or move pairs with a `database-operator` reference update in the same pass, exactly as any other move: the surviving current render keeps the node reference, and a removed file's node is repointed or its reference dropped. Removal is destructive, so it happens only on an explicit stewardship dispatch, never in the read-only reconcile audit.
17
19
 
18
20
  ## Off-limits: system-convention directories
19
21
 
@@ -21,13 +23,13 @@ Directories whose layout is owned by tools are not yours to reorganise — a too
21
23
 
22
24
  ## The reconcile audit brief
23
25
 
24
- When admin's brief names a reconcile audit, the pass is read-only: walk the operator-file areas of the account directory, resolve each file against the graph via `memory-search`, and count (a) files unreachable from any graph node, (b) graph file-references that do not resolve to a real path, (c) graph file-references that resolve into a tool-owned scratch dir (`output/`, `generated/`, `extracted/`, `url-get/`), which the next tool write rebuilds so the reference is fragile by construction, and (d) deliverables a node references that resolve only under a scratch dir and were never promoted to `documents/` or `projects/`. Move nothing, dispatch nothing. The audit exists so a rising count is visible before anyone asks for a cleanup.
26
+ When admin's brief names a reconcile audit, the pass is read-only: walk the operator-file areas of the account directory, resolve each file against the graph via `memory-search`, and count (a) files unreachable from any graph node, (b) graph file-references that do not resolve to a real path, (c) graph file-references that resolve into a tool-owned scratch dir (`output/`, `generated/`, `extracted/`, `url-get/`), which the next tool write rebuilds so the reference is fragile by construction, (d) deliverables a node references that resolve only under a scratch dir and were never promoted to `documents/` or `projects/`, and (e) graph file-references that resolve into the `uploads/` intake inbox, which is a temporary landing area a file should have been promoted out of when its node was created. The walk now includes `uploads/`; a file under `uploads/` that no node references counts under (a) unreachable. Then, per operator-data entity folder (`projects/<name>/`, `contacts/<name>/`), count three intra-folder drifts from disk structure alone, no graph resolution needed: (f) files in a version group, where `<base>.ext` and `<base>-vN.ext` share a basename stem and extension and all but the newest are superseded, counting every superseded copy as `versioned`; (g) format twins, a source-render file (`.html`, `.md`) whose delivered `.pdf` twin of the same basename sits in the same folder, counting each such render as `format-twins`; (h) stray subfolders nested under an entity folder, which the flat rule forbids, counting each subfolder as `stray-subdir`. Move nothing, dispatch nothing. The audit exists so a rising count is visible before anyone asks for a cleanup.
25
27
 
26
28
  When the vertical's `schema-<vertical>.md` declares a **published / served tree** with a Filesystem ↔ graph section (e.g. the per-listing site target with a URL ↔ path rule and an artefact → graph-reference table), the audit also walks that tree. The graph references it by hosted URL, not local path, so resolution runs through the section's URL ↔ path rule: for each served file, derive its hosted URL and check that some node references it; for each node URL **that matches the section's hosted-URL prefix**, derive its local path and check the file exists. Count served files matching no node reference in `unreachable` and prefix-matching node URLs resolving to no served file in `broken-refs`. Node URLs the rule cannot resolve — externally-hosted URLs (a CDN image, a third-party portal link) carry no served-tree prefix — are outside this audit and are never counted as broken. Honour the section's "served but intentionally unreferenced (tool / collateral)" list — those classes carry no reference by design and are never orphans, the same exclusion you already apply to the `url-get/` cache. This walk is still read-only: the served tree is a publish write target (off-limits to moves, above); the audit only counts drift, it never reorganises.
27
29
 
28
30
  ## Output contract
29
31
 
30
- End every dispatch with a one-line machine-greppable summary as the last line of your reply. For stewardship work: `moves=N ref-updates=M skipped=<reason|none>`. For the reconcile audit: `unreachable=N broken-refs=M scratch-refs=P stranded=Q`. If a brief is ambiguous about whether a directory is operator data or a system convention, name the ambiguity in your reply instead of guessing.
32
+ End every dispatch with a one-line machine-greppable summary as the last line of your reply. For stewardship work: `moves=N ref-updates=M skipped=<reason|none>`. For the reconcile audit: `unreachable=N broken-refs=M scratch-refs=P stranded=Q stranded-intake=R versioned=S format-twins=T stray-subdir=U`. If a brief is ambiguous about whether a directory is operator data or a system convention, name the ambiguity in your reply instead of guessing.
31
33
 
32
34
  ## Review gates
33
35
 
@@ -5,12 +5,12 @@
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
6
  <title>Activity — Maxy</title>
7
7
  <link rel="icon" href="/favicon.ico">
8
- <script type="module" crossorigin src="/assets/activity-CVdVSw5V.js"></script>
8
+ <script type="module" crossorigin src="/assets/activity-DZFYDHNA.js"></script>
9
9
  <link rel="modulepreload" crossorigin href="/assets/chunk-CCr-iYLO.js">
10
- <link rel="modulepreload" crossorigin href="/assets/useSubAccountSwitcher-CHwQhkaI.js">
11
- <link rel="modulepreload" crossorigin href="/assets/AdminShell-BlbUNAPc.js">
12
- <link rel="modulepreload" crossorigin href="/assets/triangle-alert-CngnWtjD.js">
13
- <link rel="stylesheet" crossorigin href="/assets/useSubAccountSwitcher-yFQqnpQ8.css">
10
+ <link rel="modulepreload" crossorigin href="/assets/useSubAccountSwitcher-iQGqNJhI.js">
11
+ <link rel="modulepreload" crossorigin href="/assets/AdminShell-Gq8DU_ig.js">
12
+ <link rel="modulepreload" crossorigin href="/assets/triangle-alert-k8ulav-N.js">
13
+ <link rel="stylesheet" crossorigin href="/assets/useSubAccountSwitcher-fvBunpOC.css">
14
14
  <link rel="stylesheet" href="/brand-defaults.css">
15
15
  </head>
16
16
  <body>
@@ -0,0 +1 @@
1
+ import{o as e}from"./chunk-CCr-iYLO.js";import{H as t,I as n,K as r,L as i,V as a,z as o}from"./useSubAccountSwitcher-iQGqNJhI.js";import{D as s}from"./useVoiceRecorder-v--TIxaM.js";import{C as c,S as l,x as u}from"./AdminShell-Gq8DU_ig.js";var d=`admin-landing-redirected`,f=`/graph`;function p(e){return e.variant===`operator`?!1:e.appState===`chat`&&!e.alreadyRedirected}var m=e(r(),1);function h(e=`admin`){let[n,r]=(0,m.useState)(`loading`),[i,a]=(0,m.useState)(``),[o,l]=(0,m.useState)(``),[u,h]=(0,m.useState)(``),[g,_]=(0,m.useState)(!1),[v,y]=(0,m.useState)(!1),[b,x]=(0,m.useState)(!1),[S,C]=(0,m.useState)(!1),[w,T]=(0,m.useState)(!1),[E,D]=(0,m.useState)(null),[O,k]=(0,m.useState)(null),[A,j]=(0,m.useState)(void 0),[M,N]=(0,m.useState)(null),[P,F]=(0,m.useState)(void 0),[I,L]=(0,m.useState)(null),[R,z]=(0,m.useState)(null),[B,V]=(0,m.useState)(void 0),H=(0,m.useRef)(void 0),[U,W]=(0,m.useState)(!1),[G,K]=(0,m.useState)(!0);(0,m.useEffect)(()=>{typeof window>`u`||fetch(`/api/remote-auth/status`).then(e=>e.ok?e.json():null).then(e=>{e?.configured&&W(!0)}).catch(()=>{})},[]);let q=(0,m.useRef)(null),J=(0,m.useRef)(null);(0,m.useEffect)(()=>{async function e(){let e=null;try{e=sessionStorage.getItem(`maxy-admin-session-key`)}catch{}if(!e)return!1;try{let t=await fetch(`/api/admin/session?session_key=${encodeURIComponent(e)}`);if(t.status===401){try{sessionStorage.removeItem(`maxy-admin-session-key`)}catch{}return!1}if(!t.ok)return!1;let n=await t.json();D(n.session_key),z(n.sessionId??null),j(n.businessName),N(n.role??null),F(n.userName===void 0?null:n.userName),L(n.avatar??null);let i=s(n.thinkingView);return H.current=i,V(i),r(`chat`),!0}catch(e){return console.error(`[admin] session restore failed:`,e),!1}}async function t(n=2){try{let i=await fetch(`/api/health`);if(!i.ok){if(n>0)return await new Promise(e=>setTimeout(e,1500)),t(n-1);console.error(`[admin] health check returned ${i.status} after retries`),r(`set-pin`);return}let a=await i.json();if(!a.pin_configured){r(`set-pin`);return}K(!!a.claude_authenticated);let o=!1;try{o=new URLSearchParams(window.location.search).get(`connect`)===`claude`}catch{}if(o){try{let e=new URL(window.location.href);e.searchParams.delete(`connect`),window.history.replaceState(null,``,e.pathname+e.search+e.hash)}catch{}if(!a.claude_authenticated){r(`connect-claude`);return}}if(await e())return;r(`enter-pin`)}catch(e){if(n>0)return await new Promise(e=>setTimeout(e,1500)),t(n-1);console.error(`[admin] health check failed:`,e),r(`set-pin`)}}t()},[]),(0,m.useEffect)(()=>{n===`chat`&&fetch(`/api/admin/claude-info`).then(e=>{if(e.ok)return e.json()}).then(e=>{e&&k(e)}).catch(()=>{})},[n]),(0,m.useEffect)(()=>{if(typeof window>`u`)return;let t=!1;try{t=sessionStorage.getItem(d)===`1`}catch{}if(p({appState:n,alreadyRedirected:t,variant:e})){try{sessionStorage.setItem(d,`1`)}catch{}console.info(`[admin-ui] landing-redirect target=${f}`),window.location.replace(f)}},[n,e]);let Y=(0,m.useRef)(null);(0,m.useEffect)(()=>{if(n!==`chat`)return;let e=setInterval(async()=>{try{let e=await fetch(`/api/health`);if(e.ok){let t=await e.json();K(t.auth_status!==`dead`&&t.auth_status!==`missing`)}}catch{}if(E)try{let e=await fetch(`/api/admin/session?session_key=${encodeURIComponent(E)}`);if(e.status!==401)return;let n=(await e.clone().json().catch(()=>null))?.code??`unknown-401`;if(n===`remote-auth-required`){t(`heartbeat`,`/api/admin/session`);return}console.warn(`[admin-auth] outcome=heartbeat-detected-expiry code=${n}`),Y.current?.()}catch{}},300*1e3);return()=>clearInterval(e)},[n,E]),(0,m.useEffect)(()=>{n===`connect-claude`&&fetch(`/api/health`).then(e=>e.ok?e.json():null).then(e=>{e?.claude_authenticated&&(K(!0),r(`enter-pin`))}).catch(()=>{})},[n]);async function X(e,n){y(!0);try{let i=await fetch(`/api/admin/session`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pin:e,...n?{accountId:n}:{}})});if(!i.ok){let e=await i.json().catch(()=>({}));if(i.status===401&&e?.code===`remote-auth-required`){t(`enter-pin`,`/api/admin/session`);return}h(e.error||`Invalid PIN`);return}let o=await i.json();D(o.session_key),z(o.sessionId??null),j(o.businessName),N(o.role??null),F(o.userName===void 0?null:o.userName),L(o.avatar??null);let c=s(o.thinkingView);H.current=c,V(c);try{sessionStorage.setItem(`maxy-admin-session-key`,o.session_key)}catch{}a(``),r(`chat`)}catch(e){console.error(`[admin] connection error:`,e),h(`Could not connect.`)}finally{y(!1)}}let Z=(0,m.useCallback)(async e=>{if(e.preventDefault(),v)return;h(``);let n=o.trim();if(!n){h(`Please enter your name.`);return}if(i.length<4){h(`PIN must be at least 4 characters.`);return}let s=i;y(!0);try{let e=await fetch(`/api/onboarding/set-pin`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pin:s,name:n})});if(!e.ok){let n=await e.json().catch(()=>({}));if(e.status===401&&n?.code===`remote-auth-required`){t(`set-pin`,`/api/onboarding/set-pin`);return}if(e.status===409){console.log(`[admin] PIN already configured — re-checking health`);try{let e=await fetch(`/api/health`);if(e.ok){let t=await e.json();t.pin_configured&&t.claude_authenticated?r(`enter-pin`):t.pin_configured?r(`connect-claude`):h(n.error||`Failed to set PIN.`)}else r(`enter-pin`)}catch{r(`enter-pin`)}return}h(n.error||`Failed to set PIN.`);return}let i=await fetch(`/api/health`);if((i.ok?await i.json():null)?.claude_authenticated){await X(s);return}a(``),r(`connect-claude`)}catch(e){console.error(`[admin] connection error:`,e),h(`Could not connect.`)}finally{y(!1)}},[i,v,o]),Q=(0,m.useCallback)(async e=>{e.preventDefault(),h(``),await X(i)},[i]),ee=(0,m.useCallback)(async()=>{T(!0);try{if(!await c())return console.warn(`[admin-ui] claude-disconnect not verified — credentials may persist; staying put`),!1;K(!1),D(null),N(null),F(void 0),L(null);try{sessionStorage.removeItem(`maxy-admin-session-key`),sessionStorage.removeItem(d)}catch{}return r(`connect-claude`),!0}finally{T(!1)}},[]),$=(0,m.useCallback)(()=>{D(null),N(null),F(void 0),L(null);try{sessionStorage.removeItem(`maxy-admin-session-key`),sessionStorage.removeItem(d)}catch{}a(``),h(``),r(`enter-pin`)},[]);return(0,m.useEffect)(()=>{Y.current=$},[$]),{appState:n,setAppState:r,pin:i,setPin:a,operatorName:o,setOperatorName:l,pinError:u,setPinError:h,showPin:g,setShowPin:_,pinLoading:v,authPolling:b,setAuthPolling:x,authLoading:S,setAuthLoading:C,disconnecting:w,cacheKey:E,setCacheKey:D,claudeInfo:O,setClaudeInfo:k,businessName:A,role:M,userName:P,userAvatar:I,sessionId:R,setSessionId:z,expandAll:B,setExpandAll:V,expandAllDefaultRef:H,remoteAuthEnabled:U,claudeConnected:G,pinInputRef:q,setPinFormRef:J,handleSetPin:Z,handleLogin:Q,handleDisconnect:ee,handleLogout:$}}var g=a();function _({inputRef:e,value:t,onChange:n,onComplete:r,showPin:i,autoFocus:a}){let o=(0,m.useRef)([]);function s(e,r){r.key===`Backspace`?(r.preventDefault(),t[e]?n(t.slice(0,e)+t.slice(e+1)):e>0&&(n(t.slice(0,e-1)+t.slice(e)),o.current[e-1]?.focus())):r.key===`ArrowLeft`&&e>0?o.current[e-1]?.focus():r.key===`ArrowRight`&&e<5?o.current[e+1]?.focus():r.key===`Enter`&&(r.preventDefault(),r.currentTarget.form?.requestSubmit())}function c(e,i){let a=i.nativeEvent.data;if(!a||!/^\d$/.test(a))return;let s=t.split(``);for(s[e]=a;s.length<e;)s.push(``);let c=s.join(``).replace(/\D/g,``).slice(0,6);n(c),c.length===6?r?.(c):e<5&&o.current[e+1]?.focus()}function l(e){e.preventDefault();let t=e.clipboardData.getData(`text`).replace(/\D/g,``).slice(0,6);t&&(n(t),t.length===6?r?.(t):o.current[t.length]?.focus())}return(0,g.jsx)(`div`,{className:`pin-field`,children:Array.from({length:6}).map((n,r)=>(0,g.jsx)(`input`,{ref:t=>{o.current[r]=t,r===0&&e&&(e.current=t)},type:`text`,inputMode:`numeric`,className:`pin-box${t[r]?` pin-box-filled`:``}`,value:t[r]?i?t[r]:`•`:``,onKeyDown:e=>s(r,e),onInput:e=>c(r,e),onPaste:l,onFocus:e=>e.target.select(),autoFocus:a&&r===0,autoComplete:`off`,maxLength:1,"aria-label":`PIN digit ${r+1}`},r))})}function v(e){let{pin:t,setPin:n,showPin:r,setShowPin:a,pinLoading:s,pinError:c,pinInputRef:d,setPinFormRef:f,onSubmit:p,operatorName:m,setOperatorName:h}=e;return(0,g.jsx)(`div`,{className:`connect-page`,children:(0,g.jsxs)(`div`,{className:`connect-content`,children:[(0,g.jsx)(`img`,{src:o,alt:i.productName,className:`connect-logo connect-logo--maxy`}),!i.logoContainsName&&(0,g.jsxs)(`h1`,{className:`connect-title`,children:[`Welcome to `,i.productName]}),(0,g.jsxs)(`p`,{className:`connect-subtitle`,children:[`Tell `,i.productName,` who you are, then choose a PIN.`]}),(0,g.jsxs)(`form`,{ref:f,onSubmit:p,className:`connect-pin-form`,children:[(0,g.jsxs)(`div`,{className:`pin-input-row`,children:[(0,g.jsx)(`input`,{type:`text`,className:`connect-name-input`,placeholder:`Your full name`,value:m,onChange:e=>h(e.target.value),autoComplete:`name`,autoFocus:!0,required:!0,"aria-label":`Your full name`}),(0,g.jsx)(`div`,{style:{width:38,flexShrink:0},"aria-hidden":`true`})]}),(0,g.jsxs)(`div`,{className:`pin-input-row`,children:[(0,g.jsx)(_,{inputRef:d,value:t,onChange:n,onComplete:()=>{},showPin:r}),(0,g.jsx)(u,{variant:`send`,type:`submit`,disabled:!t||!m.trim(),loading:s,"aria-label":`Set PIN`,children:(0,g.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,g.jsx)(`line`,{x1:`5`,y1:`12`,x2:`19`,y2:`12`}),(0,g.jsx)(`polyline`,{points:`12 5 19 12 12 19`})]})})]}),(0,g.jsx)(l,{checked:r,onChange:()=>a(e=>!e),label:`Show PIN`})]}),c&&(0,g.jsx)(`p`,{className:`admin-pin-error`,children:c})]})})}function y(e){let{pin:t,setPin:n,showPin:r,setShowPin:a,pinLoading:s,pinError:c,pinInputRef:d,onSubmit:f,remoteAuthEnabled:p,onSignOutRemote:m}=e;return(0,g.jsxs)(`div`,{className:`connect-page`,children:[p&&m&&(0,g.jsx)(`button`,{type:`button`,className:`connect-signout`,onClick:m,children:`Sign out`}),(0,g.jsxs)(`div`,{className:`connect-content`,children:[(0,g.jsx)(`img`,{src:o,alt:i.productName,className:`connect-logo connect-logo--maxy`}),!i.logoContainsName&&(0,g.jsx)(`h1`,{className:`connect-title`,children:i.productName}),(0,g.jsxs)(`form`,{onSubmit:f,className:`connect-pin-form`,children:[(0,g.jsxs)(`div`,{className:`pin-input-row`,children:[(0,g.jsx)(_,{inputRef:d,value:t,onChange:n,onComplete:()=>{},showPin:r,autoFocus:!0}),(0,g.jsx)(u,{variant:`send`,type:`submit`,disabled:!t,loading:s,children:(0,g.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,g.jsx)(`line`,{x1:`5`,y1:`12`,x2:`19`,y2:`12`}),(0,g.jsx)(`polyline`,{points:`12 5 19 12 12 19`})]})})]}),(0,g.jsx)(`div`,{className:`pin-options`,children:(0,g.jsx)(l,{checked:r,onChange:()=>a(e=>!e),label:`Show PIN`})})]}),c&&(0,g.jsx)(`p`,{className:`admin-pin-error`,children:c})]})]})}function b(e){let{authPolling:t,setAuthPolling:n,authLoading:r,setAuthLoading:a,pinError:s,setPinError:c,setAppState:l}=e,[d,f]=(0,m.useState)(!1),[p,h]=(0,m.useState)(!1),[_,v]=(0,m.useState)(``),[y,b]=(0,m.useState)(``),[x,S]=(0,m.useState)(``);async function C(){S(``);try{let e=await(await fetch(`/api/onboarding/claude-auth`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`paste-code`,code:y})})).json();e.accepted?(S(`Code submitted. Finishing sign-in…`),b(``)):S(e.error||`Could not submit code.`)}catch(e){console.error(`[admin] paste-code error:`,e),S(`Could not submit code.`)}}async function w(){h(!0),c(``);try{let e=await(await fetch(`/api/onboarding/claude-auth`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`launch-browser`})})).json();e.launched?f(!0):e.error&&c(e.error)}catch(e){console.error(`[admin] browser launch error:`,e),c(`Could not launch browser.`)}h(!1)}async function T(){a(!0),c(``);try{let e=await(await fetch(`/api/onboarding/claude-auth`,{method:`POST`})).json();if(e.started){n(!0),f(!0),a(!1),v(e.transport||``);for(let e=0;e<120;e++)if(await new Promise(e=>setTimeout(e,2e3)),(await(await fetch(`/api/onboarding/claude-auth`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`wait`})})).json()).authenticated){await fetch(`/api/onboarding/claude-auth`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`stop`})}),l(`enter-pin`);return}c(`Timed out waiting for sign-in. Try again.`),n(!1)}else e.error&&c(e.error)}catch(e){console.error(`[admin] auth flow error:`,e),c(`Could not start auth flow.`)}a(!1)}async function E(){await fetch(`/api/onboarding/claude-auth`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`stop`})}),n(!1),c(``)}return t||d?(0,g.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,height:`100dvh`,overflow:`auto`},children:[(0,g.jsxs)(`header`,{className:`chat-header`,style:{paddingBottom:`12px`,flexShrink:0,position:`relative`,maxWidth:`680px`,width:`100%`,margin:`0 auto`,padding:`24px 20px 12px`},children:[t?(0,g.jsx)(`button`,{onClick:E,style:{position:`absolute`,top:`12px`,right:`12px`,background:`none`,border:`none`,color:`#999`,fontSize:`13px`,cursor:`pointer`,padding:`4px 8px`},"aria-label":`Cancel`,children:`✕`}):(0,g.jsx)(`button`,{onClick:()=>f(!1),style:{position:`absolute`,top:`12px`,right:`12px`,background:`none`,border:`none`,color:`#999`,fontSize:`13px`,cursor:`pointer`,padding:`4px 8px`},"aria-label":`Close browser`,children:`✕`}),(0,g.jsx)(`img`,{src:`/brand/claude.png`,alt:`Claude`,className:`chat-logo`}),(0,g.jsx)(`h1`,{className:`chat-tagline`,children:`Connect Claude`}),(0,g.jsx)(`p`,{className:`chat-intro`,children:t?`Sign in and authorize in the browser below.`:`Open your email or prepare your accounts, then sign in.`}),!t&&(0,g.jsx)(`div`,{style:{marginTop:`12px`},children:(0,g.jsx)(u,{variant:`primary`,onClick:T,disabled:r,children:r?(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(`span`,{className:`spin`,style:{display:`inline-block`},children:`✱`}),` Connecting…`]}):`Sign in to Claude`})}),t&&_===`native`&&(0,g.jsxs)(`div`,{style:{marginTop:`14px`,maxWidth:`420px`,margin:`14px auto 0`,display:`flex`,flexDirection:`column`,gap:`8px`},children:[(0,g.jsx)(`label`,{style:{fontSize:`12px`,color:`#999`,lineHeight:1.4},children:`If the browser didn't finish sign-in, paste the code or full redirect URL from Claude's page:`}),(0,g.jsxs)(`div`,{style:{display:`flex`,gap:`8px`},children:[(0,g.jsx)(`input`,{type:`text`,value:y,onChange:e=>b(e.target.value),placeholder:`Paste code or redirect URL`,style:{flex:1,padding:`8px 10px`,fontSize:`13px`,border:`1px solid #ccc`,borderRadius:`6px`}}),(0,g.jsx)(u,{variant:`primary`,onClick:C,disabled:!y.trim(),children:`Submit`})]}),x&&(0,g.jsx)(`p`,{style:{fontSize:`12px`,color:`#999`,margin:0},children:x})]})]}),(0,g.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,gap:`10px`,padding:`0 0 16px`},children:(0,g.jsx)(`iframe`,{src:`/vnc-viewer.html`,style:{flex:1,width:`100%`,minHeight:0,border:`none`,background:`#111`,display:`block`},title:`Claude Sign-in`})}),s&&(0,g.jsx)(`p`,{className:`admin-pin-error`,style:{textAlign:`center`,padding:`0 20px 16px`},children:s})]}):(0,g.jsx)(`div`,{className:`connect-page`,children:(0,g.jsxs)(`div`,{className:`connect-content`,children:[(0,g.jsxs)(`div`,{className:`connect-logos`,children:[(0,g.jsx)(`div`,{className:`connect-logo-wrap`,children:(0,g.jsx)(`img`,{src:`/brand/claude.png`,alt:`Claude`,className:`connect-logo`})}),(0,g.jsx)(`svg`,{className:`connect-arrow`,viewBox:`0 0 48 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,g.jsx)(`path`,{d:`M0 12h44m0 0l-8-8m8 8l-8 8`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})}),(0,g.jsxs)(`div`,{className:`connect-logo-wrap`,children:[(0,g.jsx)(`img`,{src:o,alt:i.productName,className:`connect-logo connect-logo--maxy`}),!i.logoContainsName&&(0,g.jsx)(`span`,{className:`connect-logo-label`,children:i.productName})]})]}),(0,g.jsxs)(`h1`,{className:`connect-title`,children:[`Connect Claude to power `,i.productName]}),(0,g.jsx)(`p`,{className:`connect-subtitle`,children:`Sign in with your Anthropic account to get started.`}),(0,g.jsx)(u,{variant:`primary`,onClick:T,disabled:r,children:r?(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(`span`,{className:`spin`,style:{display:`inline-block`},children:`✱`}),` Connecting…`]}):`Sign in to Claude`}),(0,g.jsx)(`p`,{style:{marginTop:`6px`,fontSize:`11px`,color:`#999`,maxWidth:`300px`,textAlign:`center`,lineHeight:`1.4`},children:`First time? You may need to sign into your email and Anthropic account in the browser before connecting.`}),(0,g.jsx)(`button`,{onClick:w,disabled:p,style:{marginTop:`12px`,background:`none`,border:`none`,color:`var(--color-primary, #666)`,fontSize:`13px`,cursor:`pointer`,textDecoration:`underline`,textUnderlineOffset:`3px`},children:p?`Launching…`:`Open browser first`}),s&&(0,g.jsx)(`p`,{className:`admin-pin-error`,children:s})]})})}function x({auth:e}){return e.appState===`loading`?(0,g.jsx)(n,{surface:`gate`}):e.appState===`set-pin`?(0,g.jsx)(v,{pin:e.pin,setPin:e.setPin,showPin:e.showPin,setShowPin:e.setShowPin,pinLoading:e.pinLoading,pinError:e.pinError,pinInputRef:e.pinInputRef,setPinFormRef:e.setPinFormRef,onSubmit:e.handleSetPin,operatorName:e.operatorName,setOperatorName:e.setOperatorName}):e.appState===`connect-claude`?(0,g.jsx)(b,{authPolling:e.authPolling,setAuthPolling:e.setAuthPolling,authLoading:e.authLoading,setAuthLoading:e.setAuthLoading,pinError:e.pinError,setPinError:e.setPinError,setAppState:e.setAppState}):e.appState===`enter-pin`?(0,g.jsx)(y,{pin:e.pin,setPin:e.setPin,showPin:e.showPin,setShowPin:e.setShowPin,pinLoading:e.pinLoading,pinError:e.pinError,pinInputRef:e.pinInputRef,onSubmit:e.handleLogin,remoteAuthEnabled:e.remoteAuthEnabled,onSignOutRemote:()=>{console.info(`[admin-ui] remote-auth sign-out → /__remote-auth/logout`),window.location.href=`/__remote-auth/logout`}}):null}export{h as n,x as t};
@@ -0,0 +1,2 @@
1
+ import{o as e}from"./chunk-CCr-iYLO.js";import{A as t,B as n,C as r,D as i,E as a,F as o,G as s,I as c,K as l,L as u,N as d,O as f,P as p,R as m,S as h,T as g,V as _,_ as ee,a as v,b as y,d as te,f as ne,g as b,h as x,j as S,k as re,m as C,o as ie,r as w,t as ae,u as oe,v as se,w as T,x as ce}from"./useSubAccountSwitcher-iQGqNJhI.js";async function le(){try{let e=await fetch(`/api/onboarding/claude-auth`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`logout`})});return e.ok?(await e.json().catch(()=>({})))?.logged_out===!0:(console.error(`[admin-ui] claude-logout http-status=${e.status}`),!1)}catch(e){return console.error(`[admin-ui] claude-logout fetch failed: ${e instanceof Error?e.message:String(e)}`),!1}}var E=_();function ue({checked:e,onChange:t,label:n,disabled:r,ariaLabel:i=n}){return(0,E.jsxs)(`label`,{className:`maxy-checkbox${r?` maxy-checkbox--disabled`:``}`,children:[(0,E.jsx)(`input`,{type:`checkbox`,"aria-label":i,checked:e,onChange:e=>t(e.target.checked),disabled:r}),(0,E.jsx)(`span`,{className:`maxy-checkbox__box`,children:`✱`}),n&&(0,E.jsx)(`span`,{className:`maxy-checkbox__label`,children:n})]})}var D=e(l(),1),de={sm:14,md:16,lg:18},O={sm:30,md:38,lg:46};function k({variant:e=`primary`,size:t=`md`,icon:n,iconPosition:r=`leading`,loading:i=!1,fullWidth:a=!1,disabled:o=!1,type:s=`button`,onClick:c,"aria-label":l,"aria-pressed":u,style:d,className:f,children:p}){let m=[`btn`,`btn--${e}`,t===`md`?``:`btn--${t}`,a?`btn--full`:``,f].filter(Boolean).join(` `),h=de[t],g={...e===`send`?{width:O[t],height:O[t]}:{},...d},_=Object.keys(g).length>0;return(0,E.jsxs)(`button`,{type:s,className:m,disabled:i||o,onClick:c,"aria-label":l,"aria-pressed":u,style:_?g:void 0,children:[(0,E.jsxs)(`span`,{className:`btn__content`,style:{visibility:i?`hidden`:`visible`},children:[n&&r===`leading`&&(0,E.jsx)(n,{size:h}),p,n&&r===`trailing`&&(0,E.jsx)(n,{size:h})]}),i&&(0,E.jsx)(`span`,{className:`btn__spinner`,children:`✱`})]})}var fe=o(`archive-restore`,[[`rect`,{width:`20`,height:`5`,x:`2`,y:`3`,rx:`1`,key:`1wp1u1`}],[`path`,{d:`M4 8v11a2 2 0 0 0 2 2h2`,key:`tvwodi`}],[`path`,{d:`M20 8v11a2 2 0 0 1-2 2h-2`,key:`1gkqxj`}],[`path`,{d:`m9 15 3-3 3 3`,key:`1pd0qc`}],[`path`,{d:`M12 12v9`,key:`192myk`}]]),pe=o(`archive`,[[`rect`,{width:`20`,height:`5`,x:`2`,y:`3`,rx:`1`,key:`1wp1u1`}],[`path`,{d:`M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8`,key:`1s80jp`}],[`path`,{d:`M10 12h4`,key:`a56b0p`}]]),A=o(`chevron-down`,[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]),me=o(`ellipsis-vertical`,[[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}],[`circle`,{cx:`12`,cy:`5`,r:`1`,key:`gxeob9`}],[`circle`,{cx:`12`,cy:`19`,r:`1`,key:`lyex9k`}]]),he=o(`gauge`,[[`path`,{d:`m12 14 4-4`,key:`9kzdfg`}],[`path`,{d:`M3.34 19a10 10 0 1 1 17.32 0`,key:`19p75a`}]]),j=o(`list-todo`,[[`path`,{d:`M13 5h8`,key:`a7qcls`}],[`path`,{d:`M13 12h8`,key:`h98zly`}],[`path`,{d:`M13 19h8`,key:`c3s6r1`}],[`path`,{d:`m3 17 2 2 4-4`,key:`1jhpwq`}],[`rect`,{x:`3`,y:`4`,width:`6`,height:`6`,rx:`1`,key:`cif1o7`}]]),ge=o(`message-square`,[[`path`,{d:`M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z`,key:`18887p`}]]),_e=o(`panel-left`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M9 3v18`,key:`fh3hqa`}]]),ve=o(`sliders-horizontal`,[[`path`,{d:`M10 5H3`,key:`1qgfaw`}],[`path`,{d:`M12 19H3`,key:`yhmn1j`}],[`path`,{d:`M14 3v4`,key:`1sua03`}],[`path`,{d:`M16 17v4`,key:`1q0r14`}],[`path`,{d:`M21 12h-9`,key:`1o4lsq`}],[`path`,{d:`M21 19h-5`,key:`1rlt1p`}],[`path`,{d:`M21 5h-7`,key:`1oszz2`}],[`path`,{d:`M8 10v4`,key:`tgpxqk`}],[`path`,{d:`M8 12H3`,key:`a7s4jb`}]]),ye=o(`wand-sparkles`,[[`path`,{d:`m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72`,key:`ul74o6`}],[`path`,{d:`m14 7 3 3`,key:`1r5n42`}],[`path`,{d:`M5 6v4`,key:`ilb8ba`}],[`path`,{d:`M19 14v4`,key:`blhpug`}],[`path`,{d:`M10 2v2`,key:`7u0qdc`}],[`path`,{d:`M7 8H3`,key:`zfb6yr`}],[`path`,{d:`M21 16h-4`,key:`1cnmox`}],[`path`,{d:`M11 3H9`,key:`1obp7u`}]]),be=o(`waypoints`,[[`path`,{d:`m10.586 5.414-5.172 5.172`,key:`4mc350`}],[`path`,{d:`m18.586 13.414-5.172 5.172`,key:`8c96vv`}],[`path`,{d:`M6 12h12`,key:`8npq4p`}],[`circle`,{cx:`12`,cy:`20`,r:`2`,key:`144qzu`}],[`circle`,{cx:`12`,cy:`4`,r:`2`,key:`muu5ef`}],[`circle`,{cx:`20`,cy:`12`,r:`2`,key:`1xzzfp`}],[`circle`,{cx:`4`,cy:`12`,r:`2`,key:`1hvhnz`}]]),xe=o(`zap`,[[`path`,{d:`M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z`,key:`1xq2db`}]]);function Se({connected:e,onConnectClaude:t}){return e?(0,E.jsxs)(`span`,{className:`claude-status-pill`,"data-connected":`true`,title:`Claude is connected`,children:[(0,E.jsx)(`img`,{src:`/brand/claude.png`,alt:``,className:`claude-status-pill__mark`}),(0,E.jsx)(`span`,{className:`claude-status-pill__label`,children:`Connected`}),(0,E.jsx)(`span`,{className:`claude-status-pill__dot claude-status-pill__dot--live`,"aria-hidden":`true`})]}):(0,E.jsxs)(`button`,{type:`button`,className:`claude-status-pill claude-status-pill--action`,"data-connected":`false`,onClick:t,title:`Connect Claude`,children:[(0,E.jsx)(`img`,{src:`/brand/claude.png`,alt:``,className:`claude-status-pill__mark`}),(0,E.jsx)(`span`,{className:`claude-status-pill__label`,children:`Connect`}),(0,E.jsx)(`span`,{className:`claude-status-pill__dot claude-status-pill__dot--down`,"aria-hidden":`true`})]})}function Ce(e){return e===`/`||e===``?`Dashboard`:e.startsWith(`/chat`)?`Chat`:e.startsWith(`/tasks`)?`Tasks`:e.startsWith(`/data`)?`Data`:e.startsWith(`/calendar`)?`Calendar`:e.startsWith(`/graph`)?`Graph`:e.startsWith(`/activity`)?`Activity`:e.startsWith(`/browser`)?`Browser`:`Dashboard`}function we({title:e,sidebarOpen:t,onToggleSidebar:n,claudeConnected:r,onConnectClaude:i}){let a=e??Ce(typeof window<`u`?window.location.pathname:`/`),o=r!==void 0&&i!==void 0;return(0,E.jsxs)(`header`,{className:`admin-page-header`,children:[(0,E.jsxs)(`button`,{type:`button`,className:`admin-page-header__toggle`,"aria-label":t?`Hide sidebar`:`Show sidebar`,title:t?`Hide sidebar`:`Show sidebar`,"aria-expanded":t,onClick:n,children:[(0,E.jsx)(_e,{className:`admin-page-header__toggle-desktop`,size:18,strokeWidth:1.75}),(0,E.jsx)(T,{className:`admin-page-header__toggle-mobile`,size:22,strokeWidth:1.75})]}),(0,E.jsx)(`h1`,{className:`admin-page-header__title`,children:a}),o&&(0,E.jsx)(`div`,{className:`admin-page-header__right`,children:(0,E.jsx)(Se,{connected:r,onConnectClaude:i})})]})}var M=[{label:`Home`,href:`/`,Icon:a,match:e=>e===`/`||e===``},{label:`Chat`,href:`/chat`,Icon:r,match:e=>e.startsWith(`/chat`)},{label:`Tasks`,href:`/tasks`,Icon:j,match:e=>e.startsWith(`/tasks`)},{label:`Data`,href:`/data`,Icon:S,match:e=>e.startsWith(`/data`)},{label:`Calendar`,href:`/calendar`,Icon:d,match:e=>e.startsWith(`/calendar`)}],Te=[{label:`Chat`,href:`/`,Icon:r,match:e=>e===`/`||e===``||e.startsWith(`/chat`)},{label:`Data`,href:`/data`,Icon:S,match:e=>e.startsWith(`/data`)}];function Ee(e){let t=M.find(t=>t.match(e));return t?t.href:`/`}function N({variant:e=`admin`,onOpenConversations:t}={}){let n=typeof window<`u`?window.location.pathname:`/`,i=e===`operator`?Te:M,a=e===`operator`?Te.find(e=>e.match(n))?.href??`/`:Ee(n),o=e=>{let t=e.href===a,{Icon:n}=e;return(0,E.jsxs)(`a`,{href:e.href,className:`bottom-tab${t?` is-active`:``}`,"aria-current":t?`page`:void 0,children:[(0,E.jsx)(n,{size:19,strokeWidth:1.75}),(0,E.jsx)(`span`,{className:`bottom-tab__label`,children:e.label})]},e.href)};return(0,E.jsxs)(`nav`,{className:`bottom-tab-bar`,"aria-label":`Primary`,children:[i.slice(0,1).map(o),e===`operator`&&t&&(0,E.jsxs)(`button`,{type:`button`,className:`bottom-tab`,onClick:t,children:[(0,E.jsx)(r,{size:19,strokeWidth:1.75}),(0,E.jsx)(`span`,{className:`bottom-tab__label`,children:`Conversations`})]}),i.slice(1).map(o)]})}var De=`maxy-shell-side-px`;function Oe(){if(typeof window>`u`)return 0;let e=document.querySelector(`.platform > .artefact`)?.getBoundingClientRect();return e&&e.width>0?Math.round(e.width):0}function P(e){if(typeof window>`u`)return e;let t=window.innerWidth,n=Math.max(248,t-480-Oe());return Math.min(Math.max(e,248),n)}function ke(){if(typeof window>`u`)return 264;try{let e=window.localStorage.getItem(De);if(!e)return 264;let t=parseInt(e,10);if(!Number.isFinite(t))return console.warn(`[admin-ui] sidebar-width-parse-failed stored=${JSON.stringify(e)} fallback=264`),264;if(t>=248)return P(t)}catch{}return 264}function Ae({targetSelector:e=`.platform`}){let t=(0,D.useRef)(null),[n,r]=(0,D.useState)(()=>ke()),i=(0,D.useRef)(n);(0,D.useLayoutEffect)(()=>{let t=document.querySelector(e);!t||!(t instanceof HTMLElement)||(t.style.setProperty(`--side-px`,`${n}px`),i.current=n)},[n,e]);let a=(0,D.useCallback)(()=>{r(e=>{let t=P(e);return t===e?e:t})},[]);(0,D.useEffect)(()=>{a(),window.addEventListener(`resize`,a);let t=document.querySelector(e),n=null;return t instanceof HTMLElement&&(n=new MutationObserver(a),n.observe(t,{attributes:!0,attributeFilter:[`data-artefact`,`class`]})),()=>{window.removeEventListener(`resize`,a),n?.disconnect()}},[a,e]);let o=e=>{e.preventDefault();let n=t.current;if(!n)return;n.setPointerCapture(e.pointerId),n.classList.add(`dragging`);let a=!1,o=e=>{a=!0,r(P(Math.round(e.clientX)))},s=()=>{if(n.releasePointerCapture(e.pointerId),n.classList.remove(`dragging`),window.removeEventListener(`pointermove`,o),window.removeEventListener(`pointerup`,s),!a)return;let t=i.current;try{window.localStorage.setItem(De,String(t))}catch{}console.info(`[admin-ui] sidebar-resize px=${t}`)};window.addEventListener(`pointermove`,o),window.addEventListener(`pointerup`,s)},s=()=>{let e=P(264);r(e);try{window.localStorage.removeItem(De)}catch{}console.info(`[admin-ui] sidebar-resize px=${e}`)};return(0,E.jsx)(`div`,{ref:t,className:`side-resize-handle`,role:`separator`,"aria-orientation":`vertical`,"aria-label":`Resize sidebar`,onPointerDown:o,onDoubleClick:s})}var je=s();function Me(e){return Math.max(14,e/2-386)}function Ne(e){return e.left===0&&e.top===0&&e.width===0&&e.height===0}var Pe={position:`fixed`,visibility:`hidden`};function F({anchorRef:e,onClose:t,className:n,role:r,ariaLabel:i,anchorId:a,children:o}){let s=(0,D.useRef)(null),[c,l]=(0,D.useState)(Pe),u=(0,D.useRef)(null),d=(0,D.useCallback)(()=>{let t=s.current;if(!t)return;let r=e.current,i=[n,a].filter(Boolean).join(`:`)||`unknown`,o=t.getBoundingClientRect(),c=window.innerWidth,d=window.innerHeight,f=o.width>0&&o.height>0,p=r?r.getBoundingClientRect():null,m=(e,t)=>console.error(`[anchored-popover] op=offscreen id=${i} left=${e} top=${t} w=${o.width} h=${o.height} viewport=${c},${d}`),h=e=>{e!==u.current&&(u.current=e,console.log(e))};if(h(`[anchored-popover] op=anchor id=${i} present=${!!r} rect=${p?`${p.left},${p.top},${p.width},${p.height}`:`none`}`),!p){let e=Math.max(4,c-o.width-Me(c)),t=Math.max(4,d-o.height-14);l({position:`fixed`,left:e,top:t,visibility:`visible`}),h(`[anchored-popover] op=placed id=${i} left=${e} top=${t} w=${o.width} h=${o.height} flipped=false clampedLeft=false clampedRight=false`);return}if(f&&Ne(p)){l(Pe),m(p.left,p.top);return}let g=p.right-o.width,_=c-o.width-4,ee=!1,v=!1;g>_&&(g=_,ee=!0),g<4&&(g=4,v=!0);let y=d-p.bottom-4,te=p.top-4,ne=o.height+8<=y?!1:o.height+8<=te?!0:te>y,b=Math.max(0,ne?te:y),x=ne?Math.max(4,p.top-Math.min(o.height,b)):p.bottom;l({position:`fixed`,left:g,top:x,maxHeight:b,visibility:`visible`}),h(`[anchored-popover] op=placed id=${i} left=${g} top=${x} w=${o.width} h=${o.height} maxH=${b} flipped=${ne} clampedLeft=${v} clampedRight=${ee}`);let S=Math.min(o.height,b);f&&(g+o.width<=0||g>=c||x+S<=0||x>=d)&&m(g,x)},[e,a,n]);return(0,D.useLayoutEffect)(()=>{if(d(),typeof ResizeObserver>`u`)return;let e=new ResizeObserver(()=>d());return s.current&&e.observe(s.current),()=>e.disconnect()},[d]),(0,D.useEffect)(()=>{let n=e=>{e.key===`Escape`&&t()},r=n=>{let r=n.target;e.current?.contains(r)||s.current?.contains(r)||t()},i=n=>{let r=e.current;r&&n.target instanceof Node&&n.target.contains(r)&&t()},a=()=>t();return document.addEventListener(`keydown`,n),document.addEventListener(`pointerdown`,r),window.addEventListener(`scroll`,i,!0),window.addEventListener(`resize`,a),()=>{document.removeEventListener(`keydown`,n),document.removeEventListener(`pointerdown`,r),window.removeEventListener(`scroll`,i,!0),window.removeEventListener(`resize`,a)}},[e,t]),(0,je.createPortal)((0,E.jsx)(`div`,{ref:s,className:n,role:r,"aria-label":i,style:c,children:o}),document.body)}function Fe({actions:e,disabled:t}){let[n,r]=(0,D.useState)(!1),[i,a]=(0,D.useState)(null),o=(0,D.useRef)(null),s=(0,D.useCallback)(()=>{r(!1),a(null)},[]);return(0,E.jsxs)(`div`,{className:`conv-actions`,children:[(0,E.jsx)(`button`,{ref:o,type:`button`,className:`conv-action conv-actions-overflow`,onClick:()=>r(e=>!e),disabled:t,"aria-haspopup":`menu`,"aria-expanded":n,"aria-label":`Session actions`,title:`Session actions`,children:(0,E.jsx)(T,{size:12})}),n&&(0,E.jsx)(F,{anchorRef:o,onClose:s,className:`conv-actions-menu`,role:`menu`,children:e.map(e=>e.panel?(0,E.jsxs)(`div`,{className:`conv-actions-menu-disclosure`,children:[(0,E.jsxs)(`button`,{type:`button`,role:`menuitem`,"aria-haspopup":`dialog`,"aria-expanded":i===e.key,disabled:t,onClick:()=>a(t=>t===e.key?null:e.key),children:[e.icon,(0,E.jsx)(`span`,{children:e.menuLabel})]}),i===e.key&&(0,E.jsx)(`div`,{className:`conv-actions-menu-panel`,children:e.panel()})]},e.key):(0,E.jsxs)(`button`,{type:`button`,role:`menuitem`,className:e.danger?`conv-action-danger`:void 0,"aria-busy":e.busy,disabled:t,onClick:t=>{e.onClick?.(t),s()},children:[e.icon,(0,E.jsx)(`span`,{children:e.menuLabel})]},e.key))})]})}var I=`claude-opus-4-8[1m]`,Ie=`claude-sonnet-5`,L=`claude-haiku-4-5`,Le={[I]:`Opus 4.8 (1M context)`,[Ie]:`Sonnet 5`,[L]:`Haiku 4.5`};function R(e){return Le[e]??e}var z=[I,Ie,L];function Re(e){return e.replace(/\[1m\]$/,``)}function ze(e){return z.find(t=>Re(t)===Re(e))??e}var Be=[`default`,`acceptEdits`,`plan`,`auto`,`bypassPermissions`],Ve=[`low`,`medium`,`high`,`xhigh`];[...Be],[...Ve],[...Ve];var B=[I,Ie,L],He={default:`Ask permissions`,acceptEdits:`Accept edits`,plan:`Plan mode`,auto:`Auto mode`,bypassPermissions:`Bypass permissions`},V=Be.map(e=>({value:e,label:He[e]??e})),H={low:`Low`,medium:`Medium`,high:`High`,xhigh:`Highest`},Ue=Ve.map(e=>({value:e,label:H[e]??e}));function We(e){if(e){let t=B.find(t=>Re(t)===Re(e));if(t)return t}return I}function Ge({row:e,adminFetch:t,onError:n}){let[r,i]=(0,D.useState)(()=>We(e.model)),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(``),[l,u]=(0,D.useState)(!1),d=(0,D.useRef)(!1);(0,D.useEffect)(()=>{i(We(e.model))},[e.model]);let f=async()=>{if(!d.current){d.current=!0,u(!0);try{let i=await t(`/api/admin/session-reseat`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({fromSessionId:e.sessionId,model:r,...a?{permissionMode:a}:{},...s?{effort:s}:{}})});if(!i.ok){n(`Could not reset ${e.title} (status ${i.status})`),console.error(`[admin-ui] dashboard-reseat-failed sessionId=${e.sessionId} status=${i.status}`),d.current=!1,u(!1);return}let o=await i.json().catch(()=>({}));o.target?window.location.assign(o.target):(n(`Reset of ${e.title} returned no target`),d.current=!1,u(!1))}catch(t){n(`Could not reset ${e.title} (network error)`),console.error(`[admin-ui] dashboard-reseat-failed sessionId=${e.sessionId} error=${t instanceof Error?t.message:String(t)}`),d.current=!1,u(!1)}}};return(0,E.jsxs)(E.Fragment,{children:[(0,E.jsxs)(`label`,{className:`reseat-field`,children:[(0,E.jsx)(`span`,{children:`Model`}),(0,E.jsx)(`select`,{"data-kind":`model`,value:r,disabled:l,onChange:e=>i(e.target.value),children:B.map(e=>(0,E.jsx)(`option`,{value:e,children:R(e)},e))})]}),(0,E.jsxs)(`label`,{className:`reseat-field`,children:[(0,E.jsx)(`span`,{children:`Mode`}),(0,E.jsxs)(`select`,{"data-kind":`mode`,value:a,disabled:l,onChange:e=>o(e.target.value),children:[(0,E.jsx)(`option`,{value:``,children:`Keep current`}),V.map(e=>(0,E.jsx)(`option`,{value:e.value,children:e.label},e.value))]})]}),(0,E.jsxs)(`label`,{className:`reseat-field`,children:[(0,E.jsx)(`span`,{children:`Effort`}),(0,E.jsxs)(`select`,{"data-kind":`effort`,value:s,disabled:l,onChange:e=>c(e.target.value),children:[(0,E.jsx)(`option`,{value:``,children:`Keep current`}),Ue.map(e=>(0,E.jsx)(`option`,{value:e.value,children:e.label},e.value))]})]}),(0,E.jsx)(`button`,{type:`button`,className:`reseat-apply`,disabled:l,"aria-busy":l,onClick:()=>void f(),children:l?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(g,{size:12,className:`spin`,"aria-hidden":`true`}),`Resetting…`]}):`Reset`})]})}function Ke(e){if(e<60)return`${e}s`;let t=Math.floor(e/60),n=e%60;return n>0?`${t}m ${n}s`:`${t}m`}function qe(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function Je({target:e,anchorEl:t,onConfirm:n,onCancel:r}){let i=(0,D.useRef)(null);return i.current=t,e?(0,E.jsxs)(F,{anchorRef:i,onClose:r,className:`conv-delete-confirm`,role:`alertdialog`,ariaLabel:`Confirm delete session`,children:[(0,E.jsxs)(`div`,{className:`claude-info-header`,children:[(0,E.jsx)(`span`,{children:`Delete this conversation?`}),(0,E.jsx)(`button`,{className:`claude-info-close`,onClick:r,"aria-label":`Close`,children:`✕`})]}),(0,E.jsxs)(`div`,{className:`claude-info-section`,style:{padding:`12px 14px`,fontSize:`11px`,color:`var(--text-secondary)`},children:[(0,E.jsxs)(`div`,{className:`conv-delete-target`,children:[(0,E.jsx)(`span`,{className:`conv-delete-label`,title:e.title,children:e.title||`Untitled session`}),(0,E.jsx)(`code`,{className:`conv-delete-id`,title:e.sessionId,children:e.sessionId.slice(0,8)})]}),(0,E.jsx)(`div`,{style:{marginTop:`8px`},children:`This permanently removes the transcript. It is not moved to Archive and cannot be recovered.`}),e.live&&(0,E.jsx)(`div`,{style:{marginTop:`8px`},children:`This session is running; deleting stops it first.`})]}),(0,E.jsxs)(`div`,{className:`claude-info-section`,style:{display:`flex`,gap:`8px`,padding:`10px 14px`},children:[(0,E.jsx)(k,{variant:`danger`,size:`sm`,style:{flex:1},onClick:n,children:`Delete`}),(0,E.jsx)(k,{variant:`secondary`,size:`sm`,style:{flex:1},onClick:r,children:`Cancel`})]})]}):null}function Ye({open:e,count:t,liveCount:n,onConfirm:r,onCancel:i}){if(!e)return null;let a=t===1?``:`s`;return(0,E.jsx)(`div`,{className:`claude-info-overlay`,onClick:i,children:(0,E.jsxs)(`div`,{className:`claude-info-modal`,onClick:e=>e.stopPropagation(),role:`alertdialog`,"aria-label":`Confirm delete sessions`,children:[(0,E.jsxs)(`div`,{className:`claude-info-header`,children:[(0,E.jsxs)(`span`,{children:[`Delete `,t,` conversation`,a,`?`]}),(0,E.jsx)(`button`,{className:`claude-info-close`,onClick:i,"aria-label":`Close`,children:`✕`})]}),(0,E.jsxs)(`div`,{className:`claude-info-section`,style:{padding:`12px 14px`,fontSize:`11px`,color:`var(--text-secondary)`},children:[`This permanently removes `,t,` transcript`,a,`. `,t===1?`It is`:`They are`,` not moved to Archive and cannot be recovered.`,n>0&&(0,E.jsxs)(`div`,{style:{marginTop:`8px`},children:[n,` `,n===1?`is`:`are`,` running and will be stopped first.`]})]}),(0,E.jsxs)(`div`,{className:`claude-info-section`,style:{display:`flex`,gap:`8px`,padding:`10px 14px`},children:[(0,E.jsxs)(k,{variant:`danger`,size:`sm`,style:{flex:1},onClick:r,children:[`Delete `,t]}),(0,E.jsx)(k,{variant:`secondary`,size:`sm`,style:{flex:1},onClick:i,children:`Cancel`})]})]})})}var Xe=`auth-refresh-failed`;function Ze({error:e,onClose:t}){if(!e)return null;let n=e.reason===Xe,r=n?`Claude sign-in expired`:`Session didn’t open`,i=n?`Your claude.ai login has expired. Re-authenticate to resume sessions.`:`The session did not bind within 60 seconds, so there is no live conversation to open.`;return(0,E.jsx)(`div`,{className:`claude-info-overlay`,onClick:t,children:(0,E.jsxs)(`div`,{className:`claude-info-modal`,onClick:e=>e.stopPropagation(),role:`alertdialog`,"aria-label":`Session could not be opened`,children:[(0,E.jsxs)(`div`,{className:`claude-info-header`,children:[(0,E.jsx)(`span`,{children:r}),(0,E.jsx)(`button`,{className:`claude-info-close`,onClick:t,"aria-label":`Close`,children:`✕`})]}),(0,E.jsxs)(`div`,{className:`claude-info-section`,style:{padding:`12px 14px`,fontSize:`11px`,color:`var(--text-secondary)`},children:[i,(0,E.jsxs)(`div`,{className:`claude-info-row`,style:{marginTop:`8px`},children:[(0,E.jsx)(`span`,{className:`claude-info-label`,children:`Reason`}),(0,E.jsx)(`span`,{className:`claude-info-value`,children:e.reason})]}),e.sessionId&&(0,E.jsxs)(`div`,{className:`claude-info-row`,children:[(0,E.jsx)(`span`,{className:`claude-info-label`,children:`Session`}),(0,E.jsxs)(`span`,{className:`claude-info-value`,children:[e.sessionId.slice(0,8),`…`]})]})]})]})})}function Qe(e){let{show:t,onClose:n,claudeInfo:r,messages:i,sessionElapsed:a,sessionId:o,cacheKey:s}=e,[c,l]=(0,D.useState)(null);if(!t)return null;let u=i.flatMap(e=>e.events?.filter(e=>e.type===`usage`)??[]),d=u.at(-1),f=d?.peak_request_pct==null?d?.context_window?Math.round((d.input_tokens+d.cache_creation_tokens+d.cache_read_tokens)/d.context_window*100):0:Math.round(d.peak_request_pct*100),p=u.reduce((e,t)=>e+t.input_tokens+t.cache_creation_tokens+t.cache_read_tokens+t.output_tokens,0),m=i.flatMap(e=>e.events?.filter(e=>e.type===`rate_limit`)??[]).at(-1),h=u.reduce((e,t)=>e+(t.total_cost_usd??0),0),g=r?.account?.subscriptionType,_=e=>{let t=e*1e3-Date.now();if(t<=0)return`now`;let n=Math.floor(t/36e5),r=Math.floor(t%36e5/6e4);return n>0?`${n}h ${r}m`:`${r}m`};return(0,E.jsx)(`div`,{className:`claude-info-overlay`,onClick:n,children:(0,E.jsxs)(`div`,{className:`claude-info-modal`,onClick:e=>e.stopPropagation(),children:[(0,E.jsxs)(`div`,{className:`claude-info-header`,children:[(0,E.jsx)(`img`,{src:`/brand/claude.png`,alt:`Claude`,className:`claude-info-icon`}),(0,E.jsx)(`span`,{children:`Claude Code`}),(0,E.jsx)(`button`,{className:`claude-info-close`,onClick:n,"aria-label":`Close`,children:`✕`})]}),(0,E.jsxs)(`div`,{className:`claude-info-section`,children:[(0,E.jsxs)(`div`,{className:`claude-info-row`,children:[(0,E.jsx)(`span`,{className:`claude-info-label`,children:`Version`}),(0,E.jsx)(`span`,{className:`claude-info-value`,children:r?r.version:`…`})]}),(0,E.jsxs)(`div`,{className:`claude-info-row`,children:[(0,E.jsx)(`span`,{className:`claude-info-label`,children:`Email`}),(0,E.jsx)(`span`,{className:`claude-info-value`,children:r?.account?.email??`…`})]})]}),(g||m||h>0)&&(0,E.jsxs)(`div`,{className:`claude-info-section`,children:[g&&(0,E.jsxs)(`div`,{className:`claude-info-row`,children:[(0,E.jsx)(`span`,{className:`claude-info-label`,children:`Plan`}),(0,E.jsx)(`span`,{className:`claude-info-value`,style:{textTransform:`capitalize`},children:g})]}),m&&(0,E.jsxs)(E.Fragment,{children:[(0,E.jsxs)(`div`,{className:`claude-info-row`,children:[(0,E.jsx)(`span`,{className:`claude-info-label`,children:`Usage`}),(0,E.jsxs)(`span`,{className:`claude-info-value`,children:[Math.round(m.utilization*100),`%`]})]}),(0,E.jsxs)(`div`,{className:`claude-info-row`,children:[(0,E.jsx)(`span`,{className:`claude-info-label`,children:`Resets in`}),(0,E.jsx)(`span`,{className:`claude-info-value`,children:_(m.resetsAt)})]}),m.isUsingOverage&&(0,E.jsxs)(`div`,{className:`claude-info-row`,children:[(0,E.jsx)(`span`,{className:`claude-info-label`,children:`Overage`}),(0,E.jsx)(`span`,{className:`claude-info-value`,children:`Active`})]})]}),h>0&&(0,E.jsxs)(`div`,{className:`claude-info-row`,children:[(0,E.jsx)(`span`,{className:`claude-info-label`,children:`Session cost`}),(0,E.jsxs)(`span`,{className:`claude-info-value`,children:[`$`,h<.01?h.toFixed(4):h.toFixed(2)]})]})]}),(0,E.jsxs)(`div`,{className:`claude-info-section`,children:[(0,E.jsxs)(`div`,{className:`claude-info-row`,children:[(0,E.jsx)(`span`,{className:`claude-info-label`,children:`Model`}),(0,E.jsx)(`span`,{className:`claude-info-value`,children:r?.model??`…`})]}),(0,E.jsxs)(`div`,{className:`claude-info-row`,children:[(0,E.jsx)(`span`,{className:`claude-info-label`,children:`Context used`}),(0,E.jsx)(`span`,{className:`claude-info-value`,children:f>0?`${f}%`:`—`})]}),(0,E.jsxs)(`div`,{className:`claude-info-row`,children:[(0,E.jsx)(`span`,{className:`claude-info-label`,children:`Tokens`}),(0,E.jsx)(`span`,{className:`claude-info-value`,children:p>0?qe(p):`—`})]}),(0,E.jsxs)(`div`,{className:`claude-info-row`,children:[(0,E.jsx)(`span`,{className:`claude-info-label`,children:`Session`}),(0,E.jsx)(`span`,{className:`claude-info-value`,children:Ke(a)})]}),(o||s)&&(()=>{let e=o??s??``;return(0,E.jsxs)(`div`,{className:`claude-info-row`,children:[(0,E.jsx)(`span`,{className:`claude-info-label`,children:`Session`}),(0,E.jsx)(`button`,{type:`button`,className:`claude-info-value claude-info-id-copy`,title:`${e} (${o?`flushed`:`pre-flush`}) — click to copy`,onClick:async()=>{l(await w(e)?`copied`:`failed`),setTimeout(()=>l(null),1200)},children:c===`copied`?`copied ✓`:c===`failed`?`copy failed ✕`:`${e.slice(0,8)}…`})]})})()]})]})})}function $e({open:e,onConnect:t,onClose:n}){return e?(0,E.jsx)(`div`,{className:`claude-info-overlay`,onClick:n,children:(0,E.jsxs)(`div`,{className:`claude-info-modal`,onClick:e=>e.stopPropagation(),role:`alertdialog`,"aria-label":`Claude is not connected`,children:[(0,E.jsxs)(`div`,{className:`claude-info-header`,children:[(0,E.jsx)(`span`,{children:`Claude isn’t connected`}),(0,E.jsx)(`button`,{className:`claude-info-close`,onClick:n,"aria-label":`Close`,children:`✕`})]}),(0,E.jsxs)(`div`,{className:`claude-info-section`,style:{padding:`12px 14px`,fontSize:`11px`,color:`var(--text-secondary)`,display:`flex`,flexDirection:`column`,gap:`10px`},children:[(0,E.jsx)(`span`,{children:`This needs Claude, which is currently disconnected. Connect to continue — the rest of the dashboard stays available either way.`}),(0,E.jsxs)(`div`,{style:{display:`flex`,gap:`8px`,alignItems:`center`},children:[(0,E.jsx)(k,{variant:`primary`,size:`sm`,onClick:t,children:`Connect Claude`}),(0,E.jsx)(`button`,{type:`button`,className:`claude-info-close`,style:{fontSize:`11px`},onClick:n,children:`Not now`})]})]})]})}):null}function et(e){let t=Math.round(e/6e4),n=Math.floor(t/60),r=t%60;return`${n}h ${String(r).padStart(2,`0`)}m`}function U(e){return e.activeMs.thinking+e.activeMs.messaging+e.activeMs.toolUse}function tt(e){return e.toLocaleString(`en-GB`)}function nt(e){return`£${e.toFixed(2)}`}function rt(e){let t=[`Day`,`Active`,`Output tokens`,`Input tokens`,`Cache write`,`Cache read`,`Opus 4.8 (GBP)`,`Sonnet 4.6 (GBP)`],n=(e,t)=>[e,et(U(t)),String(t.tokens.output),String(t.tokens.input),String(t.tokens.cacheWrite),String(t.tokens.cacheRead),t.costGBP.opus.toFixed(2),t.costGBP.sonnet.toFixed(2)];return[t,...e.days.map(e=>n(e.date,e)),n(`TOTAL (${e.days.length} d)`,e.totals)].map(e=>e.join(`,`)).join(`
2
+ `)}function it({label:e,d:t,bold:n}){let r=n?`th`:`td`;return(0,E.jsxs)(`tr`,{className:n?`usage-total-row`:void 0,children:[(0,E.jsx)(r,{className:`usage-day`,children:e}),(0,E.jsx)(r,{children:et(U(t))}),(0,E.jsx)(r,{children:tt(t.tokens.output)}),(0,E.jsx)(r,{children:tt(t.tokens.input)}),(0,E.jsx)(r,{children:tt(t.tokens.cacheWrite)}),(0,E.jsx)(r,{children:tt(t.tokens.cacheRead)}),(0,E.jsx)(r,{children:nt(t.costGBP.opus)}),(0,E.jsx)(r,{children:nt(t.costGBP.sonnet)})]})}function at({show:e,onClose:n,anchorEl:r,sessionId:i,summary:a,loading:o,error:s}){let c=(0,D.useRef)(null);if(c.current=r,!e)return null;let l=!!a&&a.days.length>0;return(0,E.jsxs)(F,{anchorRef:c,onClose:n,className:`usage-popover`,role:`dialog`,ariaLabel:`Session usage and cost`,anchorId:i??void 0,children:[(0,E.jsxs)(`div`,{className:`claude-info-header`,children:[(0,E.jsxs)(`span`,{children:[`Usage & cost`,i?` · ${i.slice(0,8)}`:``]}),l&&(0,E.jsx)(`button`,{className:`usage-download`,onClick:()=>{if(!a)return;let e=new Blob([rt(a)],{type:`text/csv;charset=utf-8`}),t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`usage-${i?i.slice(0,8):`session`}.csv`,document.body.appendChild(n),n.click(),n.remove(),URL.revokeObjectURL(t)},"aria-label":`Download as CSV`,title:`Download as CSV`,children:(0,E.jsx)(t,{size:14})}),(0,E.jsx)(`button`,{className:`claude-info-close`,onClick:n,"aria-label":`Close`,children:(0,E.jsx)(b,{size:14})})]}),(0,E.jsxs)(`div`,{className:`claude-info-section usage-body`,children:[o&&(0,E.jsx)(`div`,{className:`usage-note`,children:`Computing usage…`}),!o&&s&&(0,E.jsx)(`div`,{className:`usage-note usage-error`,children:s}),!o&&!s&&a&&a.days.length===0&&(0,E.jsx)(`div`,{className:`usage-note`,children:`No usage recorded for this session yet.`}),!o&&!s&&a&&a.days.length>0&&(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(`div`,{className:`usage-table-scroll`,children:(0,E.jsxs)(`table`,{className:`usage-table`,children:[(0,E.jsx)(`thead`,{children:(0,E.jsxs)(`tr`,{children:[(0,E.jsx)(`th`,{className:`usage-day`,children:`Day`}),(0,E.jsx)(`th`,{children:`Active`}),(0,E.jsx)(`th`,{children:`Output tok`}),(0,E.jsx)(`th`,{children:`Input tok`}),(0,E.jsx)(`th`,{children:`Cache write`}),(0,E.jsx)(`th`,{children:`Cache read`}),(0,E.jsx)(`th`,{children:`Opus 4.8 (£)`}),(0,E.jsx)(`th`,{children:`Sonnet 4.6 (£)`})]})}),(0,E.jsxs)(`tbody`,{children:[a.days.map(e=>(0,E.jsx)(it,{label:e.date,d:e},e.date)),(0,E.jsx)(it,{label:`TOTAL (${a.days.length} d)`,d:a.totals,bold:!0})]})]})}),(0,E.jsxs)(`div`,{className:`usage-note usage-caveats`,children:[`Prices dated `,a.pricing.opusPriceDate,` · £/$ `,a.pricing.usdPerGbp,` · Sonnet tokenizer factor `,a.pricing.tokenizerFactor,`. Idle human-wait dominates the calendar span; cache-read tokens dominate cost; Sonnet is a tokenizer-adjusted estimate.`]})]})]})]})}var ot=`https://claude.ai/code`,st=200,ct=[500,1e3,1500,2e3,2500,3e3,3e3];function lt(e,t,n){if(e&&n.target)return{kind:`navigate`,url:n.target,sameOrigin:!0};let r=n.slug??n.bridgeSessionId??null;if(e&&r)return{kind:`navigate`,url:`${ot}/${r}`,sameOrigin:!1};let i=n.reason||n.error||`status ${t}`;return{kind:`error`,sessionId:n.sessionId??null,reason:i}}function ut(e){if(!e)return``;let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toLocaleString(void 0,{dateStyle:`medium`,timeStyle:`short`}):``}function dt(e){let{businessName:t,cacheKey:o,onConnectClaude:s,role:c,userName:l,userAvatar:_,onSelectProjects:te,onSelectTasks:b,onCloseMobileDrawer:w,collapsed:ae,onSelectData:T,initialDataSurface:le=!1,onLogout:de,onDisconnect:O,disconnecting:k,claudeConnected:_e=!0,subAccounts:Se,activeAccountId:Ce,switchingAccount:we,onSwitchAccount:M,refreshAccounts:Te,onOpenConversations:Ee}=e,N=C(o),De=(0,D.useCallback)(e=>({key:`reseat`,label:`Reset session ${e.title} (model, mode, effort)`,menuLabel:`Reset`,title:`Reset — move this session onto a chosen model, mode, and effort`,icon:(0,E.jsx)(ve,{size:12}),panel:()=>(0,E.jsx)(Ge,{row:e,adminFetch:N,onError:e=>z({message:e,failed:!0})})}),[N]),Oe=u.productName,P=t||Oe,ke=typeof l==`string`?l:l===null?`name unavailable`:P,Ae=(ke.trim().charAt(0)||`?`).toUpperCase(),[je,Me]=(0,D.useState)(le?`data`:`sessions`),[Ne,Pe]=(0,D.useState)(!1),[F,I]=(0,D.useState)(!1),Ie=!ae&&(Se?.length??0)>1&&!!M,L=Se?.find(e=>e.isHouse)??null,Le=(0,D.useCallback)(()=>{if(L){if(L.accountId===Ce){console.info(`[admin-ui] op=subaccount-switch-house anchor=brand-icon accountId=${L.accountId.slice(0,8)} switched=false reason=already-house`);return}console.info(`[admin-ui] op=subaccount-switch-house anchor=brand-icon accountId=${L.accountId.slice(0,8)} switched=true`),I(!1),M?.(L.accountId,`/`)}},[L,Ce,M]),[R,z]=(0,D.useState)(null),[Re,ze]=(0,D.useState)(null),[Be,Ve]=(0,D.useState)(!1),[B,He]=(0,D.useState)([]),[V]=(0,D.useState)(()=>typeof window>`u`?null:new URLSearchParams(window.location.search).get(`session`)),[H,Ue]=(0,D.useState)(!1),[We,Ke]=(0,D.useState)(null),[qe,Xe]=(0,D.useState)(!1),[Qe,et]=(0,D.useState)(!1),[U,tt]=(0,D.useState)(!1),[nt,rt]=(0,D.useState)(null),[it,ot]=(0,D.useState)(new Set),dt=(0,D.useRef)(new Map),[W,mt]=(0,D.useState)(!1),[G,ht]=(0,D.useState)(new Set),[gt,_t]=(0,D.useState)(!1),[K,vt]=(0,D.useState)(null),[yt,bt]=(0,D.useState)(new Set),[xt,St]=(0,D.useState)(new Set),[Ct,wt]=(0,D.useState)(new Set),[q,J]=(0,D.useState)(null),[Tt,Y]=(0,D.useState)(``),[Et,Dt]=(0,D.useState)(!1),[Ot,kt]=(0,D.useState)(null),[At,jt]=(0,D.useState)(null),[Mt,Nt]=(0,D.useState)(!1),[Pt,Ft]=(0,D.useState)(null),[X,It]=(0,D.useState)(!1),Lt=(0,D.useRef)(0);(0,D.useEffect)(()=>{if(!R)return;let e=setTimeout(()=>z(null),2500);return()=>clearTimeout(e)},[R]);let Rt=V!=null&&B.some(e=>e.sessionId===V);(0,D.useEffect)(()=>{V==null||!H||console.info(`[sidebar-sessions] op=select-highlight session=${V.slice(0,8)} matched=${Rt}`)},[V,Rt,H]);let Z=(0,D.useCallback)(async()=>{if(!o)return null;let e=++Lt.current;Xe(!0),Ke(null);try{let t=await N(`/api/admin/sidebar-sessions`);if(!t.ok)throw Error(`status ${t.status}`);let n=await t.json(),r=n.sessions??[];return e===Lt.current?(He(r),rt(n.accountId??null),Ue(!0),r):(console.info(`[admin-ui] sidebar-sessions-stale-response-dropped token=${e}`),r)}catch(t){let n=t instanceof Error?t.message:String(t);return e===Lt.current&&Ke(`Failed to load sessions: ${n}`),console.error(`[admin-ui] sidebar-sessions fetch failed: ${n}`),null}finally{e===Lt.current&&Xe(!1)}},[o,N]);(0,D.useEffect)(()=>{!o||H||Z()},[o,H,Z]),(0,D.useEffect)(()=>{if(!o)return;let e=null;function t(){console.info(`[admin-ui] sidebar-refresh surface=sessions trigger=poll`),Z()}function n(){e===null&&(e=setInterval(t,ft))}function r(){e!==null&&(clearInterval(e),e=null)}function i(){document.hidden?r():(t(),n())}return document.hidden||n(),document.addEventListener(`visibilitychange`,i),()=>{r(),document.removeEventListener(`visibilitychange`,i)}},[o,Z]);let zt=()=>{console.info(`[admin-ui] sidebar-refresh surface=sessions trigger=manual`),Z()},Bt=()=>{Me(`data`),console.info(`[admin-ui] sidebar-nav surface=data collapsed=${ae}`),T(),w()},Q=typeof window<`u`&&window.location?.pathname||`/`,Vt=je===`data`,Ht=typeof window<`u`&&window.location?.search||``,Ut=new URLSearchParams(Ht),Wt=Ut.has(`label`)&&!Ut.has(`nodeId`),$=e=>{w(),window.location.href=e},Gt=[{key:`dashboard`,label:`Dashboard`,icon:(0,E.jsx)(a,{size:17,strokeWidth:1.75}),active:Q===`/`&&!Vt,onClick:()=>$(`/`)},{key:`chat`,label:`Chat`,icon:(0,E.jsx)(r,{size:17,strokeWidth:1.75}),active:Q.startsWith(`/chat`),onClick:()=>$(`/chat`)},{key:`tasks`,label:`Tasks`,icon:(0,E.jsx)(j,{size:17,strokeWidth:1.75}),active:Q.startsWith(`/tasks`),onClick:()=>{b(),w()}},{key:`calendar`,label:`Calendar`,icon:(0,E.jsx)(d,{size:17,strokeWidth:1.75}),active:Q.startsWith(`/calendar`),onClick:()=>$(`/calendar`)},{key:`routines`,label:`Routines`,icon:(0,E.jsx)(xe,{size:17,strokeWidth:1.75}),active:Q.startsWith(`/routines`),onClick:()=>$(`/routines`)},{key:`skills`,label:`Skills`,icon:(0,E.jsx)(ye,{size:17,strokeWidth:1.75}),active:Q.startsWith(`/skills`),onClick:()=>$(`/skills`)},{key:`data`,label:`Data`,icon:(0,E.jsx)(S,{size:17,strokeWidth:1.75}),active:Vt,onClick:Bt},{key:`container`,label:n().term,icon:(0,E.jsx)(f,{size:17,strokeWidth:1.75}),active:Q.startsWith(`/graph`)&&Wt,onClick:()=>{te(),w()}},{key:`graph`,label:`Graph`,icon:(0,E.jsx)(be,{size:17,strokeWidth:1.75}),active:Q.startsWith(`/graph`)&&!Wt,onClick:()=>$(`/graph`)},{key:`activity`,label:`Activity`,icon:(0,E.jsx)(p,{size:17,strokeWidth:1.75}),active:Q.startsWith(`/activity`),onClick:()=>$(`/activity`)},{key:`browser`,label:`Browser`,icon:(0,E.jsx)(i,{size:17,strokeWidth:1.75}),active:Q.startsWith(`/browser`),onClick:()=>$(`/browser`)}],Kt=(0,D.useCallback)(async e=>{if(yt.has(e.sessionId))return;bt(t=>{let n=new Set(t);return n.add(e.sessionId),n});let t=window.open(``,`_blank`);try{let n=await N(`/api/admin/session-rc-spawn`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({sessionId:e.sessionId,name:e.title||e.sessionId,...e.accountId?{targetAccountId:e.accountId}:{}})}),r=await n.json().catch(()=>({})),i=lt(n.ok,n.status,{...r,sessionId:r.sessionId??e.sessionId});console.info(`[admin-ui] sidebar-session-resume sessionId=${e.sessionId} status=${n.status} outcome=${i.kind} slug=${r.slug??r.bridgeSessionId??`none`}`),i.kind===`navigate`?(w(),t?t.location.href=i.url:window.open(i.url,`_blank`)):(t?.close(),console.error(`[admin-ui] sidebar-session-resume-failed sessionId=${e.sessionId} status=${n.status} reason=${i.reason}`),ze(i))}catch(n){t?.close();let r=n instanceof Error?n.message:String(n);console.error(`[admin-ui] sidebar-session-resume-failed sessionId=${e.sessionId} error=${r}`),ze({sessionId:e.sessionId,reason:r})}finally{bt(t=>{let n=new Set(t);return n.delete(e.sessionId),n})}},[N,w,yt]),qt=(0,D.useCallback)(async e=>{let t=e.slice(0,8);for(let n=1;n<=ct.length;n++){await new Promise(e=>setTimeout(e,ct[n-1]));let r=await Z();if(r&&r.some(t=>t.sessionId===e)){console.info(`[admin-ui] sidebar-new-session-converged sessionId=${t} via=retry attempts=${n}`);return}}console.error(`[admin-ui] sidebar-new-session-converge-timeout sessionId=${t}`)},[Z]),Jt=(0,D.useCallback)(async()=>{if(!X){It(!0);try{let e=await N(`/api/admin/session-rc-spawn`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({})}),t=await e.json().catch(()=>({})),n=lt(e.ok,e.status,t);console.info(`[admin-ui] sidebar-new-session-spawned status=${e.status} outcome=${n.kind} slug=${t.slug??t.bridgeSessionId??`none`}`),n.kind===`navigate`?n.sameOrigin?window.location.assign(n.url):(window.open(n.url,`_blank`),t.sessionId?qt(t.sessionId):console.error(`[admin-ui] sidebar-new-session-converge-skipped reason=no-session-id`)):e.status===503||n.reason===`claude-auth-dead`?(console.info(`[admin-ui] op=llm-action-blocked action=spawn reason=claude-disconnected`),Ve(!0)):(console.error(`[admin-ui] sidebar-new-session-failed status=${e.status} reason=${n.reason}`),ze(n))}catch(e){let t=e instanceof Error?e.message:String(e);console.error(`[admin-ui] sidebar-new-session-failed error=${t}`),ze({sessionId:null,reason:t})}finally{It(!1)}}},[N,X,qt]),Yt=(0,D.useCallback)((e,t)=>{e.stopPropagation(),vt(t)},[]),Xt=(0,D.useCallback)(async(e,t)=>{e.stopPropagation(),kt(t),jt(null),Ft(null),Nt(!0);try{let e=await N(`/api/admin/session-usage?sessionId=${encodeURIComponent(t.sessionId)}`),n=await e.json().catch(()=>({}));e.ok?jt(n):Ft(n.error??`status ${e.status}`)}catch(e){Ft(e instanceof Error?e.message:String(e))}finally{Nt(!1)}},[N]),Zt=(0,D.useCallback)(async(e,t={})=>{let n=t.refresh??!0;if(it.has(e.sessionId))return!1;ot(t=>{let n=new Set(t);return n.add(e.sessionId),n});try{let t=await N(`/api/admin/session-delete`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({sessionId:e.sessionId})});if(!t.ok){let n=await t.json().catch(()=>({}));return console.error(`[admin-ui] sidebar-session-delete-failed sessionId=${e.sessionId} status=${t.status} error=${n.error??`unknown`}`),z({message:`Delete failed: ${n.error??`status ${t.status}`}`,failed:!0}),!1}let r=await t.json();return console.info(`[admin-ui] sidebar-session-delete sessionId=${e.sessionId} live=${e.live} confirmed=true pidKilled=${r.pidKilled??`?`} deleted=${r.deleted??`?`}`),He(t=>t.filter(t=>t.sessionId!==e.sessionId)),n&&Z(),!0}catch(t){let n=t instanceof Error?t.message:String(t);return console.error(`[admin-ui] sidebar-session-delete-failed sessionId=${e.sessionId} error=${n}`),z({message:`Delete failed: ${n}`,failed:!0}),!1}finally{ot(t=>{let n=new Set(t);return n.delete(e.sessionId),n})}},[N,it,Z]),Qt=(0,D.useCallback)(e=>{ht(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),$t=(0,D.useCallback)(()=>{mt(!1),ht(new Set)},[]),en=(0,D.useCallback)(async()=>{let e=[...G].map(e=>B.find(t=>t.sessionId===e)).filter(e=>!!e),t=e.filter(e=>e.live).length;console.info(`[admin-ui] sidebar-bulk-delete op=start count=${e.length} live=${t}`);let n=(await Promise.all(e.map(e=>Zt(e,{refresh:!1})))).filter(Boolean).length;console.info(`[admin-ui] sidebar-bulk-delete op=done requested=${e.length} ok=${n} failed=${e.length-n}`),Z(),$t()},[G,B,Zt,Z,$t]),tn=(0,D.useCallback)(async(e,t)=>{if(e.stopPropagation(),!xt.has(t.sessionId)){St(e=>{let n=new Set(e);return n.add(t.sessionId),n});try{let e=await N(`/api/admin/session-stop`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({sessionId:t.sessionId})});if(!e.ok){let n=await e.json().catch(()=>({}));console.error(`[admin-ui] sidebar-session-stop-failed sessionId=${t.sessionId} status=${e.status} error=${n.error??`unknown`}`),z({message:`Stop failed: ${n.error??`status ${e.status}`}`,failed:!0});return}console.info(`[admin-ui] sidebar-session-stop sessionId=${t.sessionId}`),Z()}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`[admin-ui] sidebar-session-stop-failed sessionId=${t.sessionId} error=${n}`),z({message:`Stop failed: ${n}`,failed:!0})}finally{St(e=>{let n=new Set(e);return n.delete(t.sessionId),n})}}},[N,xt,Z]),nn=(0,D.useCallback)(async(e,t,n)=>{if(e.stopPropagation(),!Ct.has(t.sessionId)){wt(e=>{let n=new Set(e);return n.add(t.sessionId),n});try{let e=await N(`/api/admin/session-archive`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({sessionId:t.sessionId,mode:n})});if(!e.ok){let r=await e.json().catch(()=>({})),i=r.detail??r.error??`status ${e.status}`;console.error(`[admin-ui] sidebar-session-archive-failed sessionId=${t.sessionId} mode=${n} status=${e.status} error=${r.error??`unknown`}`),z({message:`${n===`archive`?`Archive`:`Unarchive`} failed: ${i}`,failed:!0});return}console.info(`[admin-ui] sidebar-session-archive sessionId=${t.sessionId} mode=${n}`),Z()}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`[admin-ui] sidebar-session-archive-failed sessionId=${t.sessionId} mode=${n} error=${r}`),z({message:`${n===`archive`?`Archive`:`Unarchive`} failed: ${r}`,failed:!0})}finally{wt(e=>{let n=new Set(e);return n.delete(t.sessionId),n})}}},[N,Ct,Z]),rn=(0,D.useCallback)(async e=>{let t=Tt.trim();if(!t){z({message:`Title can’t be empty`,failed:!0});return}if(t.length>st){z({message:`Title too long (max ${st})`,failed:!0});return}Dt(!0);try{let n=await N(`/api/admin/session-rename`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({sessionId:e.sessionId,title:t})});if(!n.ok){let t=await n.json().catch(()=>({})),r=t.reason??t.error??`status ${n.status}`;console.error(`[admin-ui] sidebar-session-rename sessionId=${e.sessionId.slice(0,8)} outcome=rejected reason=${r}`),z({message:`Rename failed: ${r}`,failed:!0});return}console.info(`[admin-ui] sidebar-session-rename sessionId=${e.sessionId.slice(0,8)} outcome=ok`),J(null),Y(``),Z()}catch(t){let n=t instanceof Error?t.message:String(t);console.error(`[admin-ui] sidebar-session-rename sessionId=${e.sessionId.slice(0,8)} outcome=rejected reason=${n}`),z({message:`Rename failed: ${n}`,failed:!0})}finally{Dt(!1)}},[N,Tt,Z]);return(0,E.jsxs)(`aside`,{className:`side`,children:[(0,E.jsxs)(`div`,{className:`side-brand`,children:[Ie?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(`button`,{type:`button`,className:`side-brand-icon-btn`,"aria-label":`Switch to house account`,disabled:!L,onClick:Le,children:(0,E.jsx)(`img`,{className:`side-brand-icon`,src:m,alt:``,"aria-hidden":`true`})}),(0,E.jsxs)(`button`,{type:`button`,className:`side-brand-trigger`,"aria-haspopup":`menu`,"aria-expanded":F,"aria-label":`Switch sub-account`,onClick:()=>{let e=!F;I(e),e&&Te?.(),console.info(`[admin-ui] op=subaccount-switcher-toggle anchor=brand-head open=${e} available=true accounts=${Se?.length??0}`)},children:[(0,E.jsxs)(`span`,{className:`side-brand-lockup`,children:[(0,E.jsx)(`span`,{className:`side-brand-business`,children:P}),(0,E.jsx)(`span`,{className:`side-brand-product`,children:u.productName})]}),(0,E.jsx)(A,{size:14,className:`side-brand-caret`,"aria-hidden":`true`})]})]}):(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(`img`,{className:`side-brand-icon`,src:m,alt:``,"aria-hidden":`true`}),(0,E.jsxs)(`span`,{className:`side-brand-lockup`,children:[(0,E.jsx)(`span`,{className:`side-brand-business`,children:P}),(0,E.jsx)(`span`,{className:`side-brand-product`,children:u.productName})]})]}),F&&(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(`div`,{className:`side-brand-scrim`,"aria-hidden":`true`,onClick:()=>I(!1)}),(0,E.jsx)(x,{open:F,accounts:Se??[],activeAccountId:Ce??null,switching:we??!1,onSelect:e=>M?.(e),onClose:()=>I(!1)})]})]}),(0,E.jsx)(`nav`,{className:`side-nav`,children:Gt.map(e=>(0,E.jsxs)(`button`,{type:`button`,className:`admin-row nav-row${e.active?` active`:``}`,"aria-current":e.active?`page`:void 0,onClick:e.onClick,children:[e.icon,(0,E.jsx)(`span`,{className:`label`,children:e.label}),(0,E.jsx)(`span`,{className:`kbd`})]},e.key))}),(()=>{let e=B.filter(e=>Qe?!0:!e.isSubagent).filter(e=>U?!0:!e.archived),t=B.some(e=>e.isSubagent),n=B.some(e=>e.archived);return(0,E.jsx)(`div`,{className:`side-sessions`,children:(0,E.jsxs)(`div`,{className:`side-list`,children:[(0,E.jsxs)(`div`,{className:`group-head`,children:[(0,E.jsx)(`span`,{children:`Sessions`}),(0,E.jsxs)(`span`,{className:`group-head-meta`,children:[(0,E.jsx)(`button`,{type:`button`,className:`group-head-select${W?` active`:``}`,"aria-pressed":W,title:W?`Exit select mode`:`Select multiple sessions to delete`,onClick:()=>{mt(e=>!e),ht(new Set),J(null),Y(``)},children:`Select`}),(0,E.jsx)(`button`,{type:`button`,className:`group-head-refresh`,title:`Refresh sessions`,"aria-label":`Refresh sessions`,onClick:zt,disabled:qe,children:(0,E.jsx)(y,{size:12,className:qe?`spinning`:void 0})}),(0,E.jsx)(`span`,{children:qe?`…`:String(e.length)}),(0,E.jsxs)(`button`,{type:`button`,className:`admin-btn-cta side-sessions-new`,onClick:Jt,disabled:X,"aria-busy":X,"aria-label":X?`Spawning session`:`New session`,title:X?`Spawning session`:`New session`,children:[X?(0,E.jsx)(g,{size:13,className:`spinning`}):(0,E.jsx)(ce,{size:13}),(0,E.jsx)(`span`,{children:X?`Spawning…`:`New session`})]})]})]}),W&&(0,E.jsxs)(`div`,{className:`session-select-bar`,children:[(0,E.jsxs)(`span`,{className:`session-select-count`,children:[G.size,` selected`]}),(0,E.jsxs)(`button`,{type:`button`,className:`session-select-delete`,disabled:G.size===0,onClick:()=>_t(!0),children:[`Delete `,G.size]}),(0,E.jsx)(`button`,{type:`button`,className:`session-select-cancel`,onClick:$t,children:`Cancel`})]}),nt&&(0,E.jsx)(`div`,{className:`side-account-id`,title:`This install's accountId. The first 8 characters match the truncated UUID label on the live Remote Control daemon entry in claude.ai/code.`,children:(0,E.jsx)(`code`,{children:nt})}),(t||n)&&(0,E.jsxs)(`div`,{className:`artefact-filter-chips`,children:[t&&(0,E.jsx)(`button`,{type:`button`,className:`artefact-filter-chip${Qe?` active`:``}`,"aria-pressed":Qe,onClick:()=>et(e=>!e),title:Qe?`Hide subagent sessions`:`Show subagent sessions`,children:`Subagents`}),n&&(0,E.jsx)(`button`,{type:`button`,className:`artefact-filter-chip${U?` active`:``}`,"aria-pressed":U,onClick:()=>tt(e=>!e),title:U?`Hide archived sessions`:`Show archived sessions`,children:`Archived`})]}),We&&(0,E.jsx)(`div`,{className:`conv`,style:{color:`var(--text-tertiary)`,cursor:`default`},children:We}),H&&!We&&e.length===0&&(0,E.jsx)(`div`,{className:`conv`,style:{color:`var(--text-tertiary)`,cursor:`default`},children:`No sessions yet`}),e.map(e=>{let t=ut(e.startedAt),n=yt.has(e.sessionId),r=it.has(e.sessionId),i=xt.has(e.sessionId),a=Ct.has(e.sessionId),o=n||r||i||a,s=()=>{window.location.assign(`/chat?session=${e.sessionId}`)},c=[{key:`open`,label:`Resume session ${e.title} in claude.ai/code`,menuLabel:`Resume in claude.ai/code`,title:`Resume in a fresh local Remote Control PTY`,icon:(0,E.jsx)(re,{size:12}),busy:n,onClick:()=>{Kt(e)}},{key:`message`,label:`Open session ${e.title} in admin webchat`,menuLabel:`Open in webchat`,title:`Open in admin webchat (/chat) — sending resumes this session`,icon:(0,E.jsx)(ge,{size:12}),onClick:()=>{s()}},{key:`usage`,label:`Usage and cost for session ${e.title}`,menuLabel:`Usage & cost`,title:`Per-day active time, tokens, and estimated GBP cost`,icon:(0,E.jsx)(he,{size:12}),onClick:t=>{Xt(t,e)}},...e.live?[{key:`stop`,label:`Stop session ${e.title}`,menuLabel:`Stop`,title:`Stop session process (keeps the conversation, can resume later)`,icon:(0,E.jsx)(se,{size:12}),busy:i,onClick:t=>{tn(t,e)}}]:[],e.archived?{key:`unarchive`,label:`Unarchive session ${e.title}`,menuLabel:`Unarchive`,title:`Unarchive (move back to the active list)`,icon:(0,E.jsx)(fe,{size:12}),busy:a,onClick:t=>{nn(t,e,`unarchive`)}}:{key:`archive`,label:`Archive session ${e.title}`,menuLabel:`Archive`,title:`Archive (hide from the list, keeps the conversation resumable)`,icon:(0,E.jsx)(pe,{size:12}),busy:a,onClick:t=>{nn(t,e,`archive`)}},{key:`rename`,label:`Rename session ${e.title}`,menuLabel:`Rename`,title:`Rename this session`,icon:(0,E.jsx)(h,{size:12}),busy:Et&&q===e.sessionId,onClick:t=>{t.stopPropagation(),J(e.sessionId),Y(e.personName??e.title)}},{key:`delete`,label:`Delete session ${e.title}`,menuLabel:`Delete`,title:`Delete session (stops the process, removes the conversation)`,icon:(0,E.jsx)(ee,{size:12}),danger:!0,busy:r,onClick:t=>{Yt(t,e)}},De({sessionId:e.sessionId,model:e.model??null,title:e.personName??e.title})],l=e.channel===`whatsapp`?` conv-channel-whatsapp`:e.channel===`telegram`?` conv-channel-telegram`:``,u=e.channel===`whatsapp`||e.channel===`telegram`||e.channel===`webchat`,d=ie.includes(e.channel??``)&&e.senderId&&e.titleSource===`prefix`?v({operatorName:e.personName??null,whatsappName:e.whatsappName??null,senderId:e.senderId,title:e.title}):e.personName??e.title;return(0,E.jsxs)(`div`,{ref:t=>{let n=dt.current;t?n.set(e.sessionId,t):n.delete(e.sessionId)},className:`conv conv-with-actions${l}${e.sessionId===V?` active`:``}`,children:[(0,E.jsxs)(`div`,{className:`conv-main-static conv-main-clickable`,role:`button`,tabIndex:0,"aria-label":`Open ${d} in webchat`,onClick:()=>{if(q!==e.sessionId){if(W){Qt(e.sessionId);return}s()}},onKeyDown:t=>{q!==e.sessionId&&(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),W?Qt(e.sessionId):s())},children:[W&&(0,E.jsx)(`span`,{className:`conv-select-check`,onClick:e=>e.stopPropagation(),children:(0,E.jsx)(ue,{checked:G.has(e.sessionId),ariaLabel:`Select ${d}`,onChange:()=>Qt(e.sessionId)})}),(0,E.jsx)(`span`,{className:`conv-live-dot`,"data-live":e.live?`1`:`0`,"data-archived":e.archived?`1`:`0`,"aria-label":e.archived?`archived session`:e.live?`live session`:`ended session`}),(0,E.jsxs)(`span`,{className:`conv-stack`,children:[(0,E.jsxs)(`span`,{className:`conv-name-line`,children:[u&&(0,E.jsx)(oe,{channel:e.channel,size:13}),q===e.sessionId?(0,E.jsx)(`input`,{className:`conv-name conv-name-edit`,autoFocus:!0,onFocus:e=>e.currentTarget.select(),value:Tt,disabled:Et,"aria-label":`New title for session ${e.title}`,onChange:e=>Y(e.target.value),onClick:e=>e.stopPropagation(),onKeyDown:t=>{t.key===`Enter`?(t.preventDefault(),rn(e)):t.key===`Escape`&&(t.preventDefault(),J(null),Y(``))},onBlur:()=>{q===e.sessionId&&!Et&&(J(null),Y(``))}}):(0,E.jsx)(`span`,{className:`conv-name`,title:d,children:d})]}),(0,E.jsxs)(`span`,{className:`conv-timestamp`,children:[(0,E.jsx)(`code`,{className:`conv-session-id`,title:`First 8 characters of this session's id — distinguishes rows with identical auto-titles. The resume/delete buttons act on the full id.`,children:e.sessionId.slice(0,8)}),t&&(0,E.jsxs)(`span`,{children:[` · `,t]})]})]})]}),!W&&(0,E.jsx)(Fe,{actions:c,disabled:o})]},e.sessionId)})]})})})(),(0,E.jsxs)(`div`,{className:`side-foot`,children:[(0,E.jsx)(`div`,{className:`avatar`,children:_?(0,E.jsx)(`img`,{src:_,alt:ke}):Ae}),(0,E.jsxs)(`div`,{className:`who`,children:[(0,E.jsx)(`span`,{className:`name`,children:ke}),(0,E.jsx)(pt,{})]}),(0,E.jsx)(`button`,{type:`button`,className:`side-foot-kebab`,"aria-label":`Account menu`,"aria-haspopup":`menu`,"aria-expanded":Ne,onClick:()=>Pe(e=>!e),children:(0,E.jsx)(me,{size:16})}),Ne&&(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(`div`,{className:`side-foot-menu-scrim`,"aria-hidden":`true`,onClick:()=>Pe(!1)}),(0,E.jsx)(`div`,{className:`side-foot-menu`,role:`menu`,children:(0,E.jsx)(ne,{variant:`admin`,onCloseMenu:()=>Pe(!1),onLogout:de??(()=>{}),onDisconnect:O,disconnecting:k,claudeConnected:_e,onConnectClaude:s,cacheKey:o,onOpenConversations:Ee})})]})]}),R&&(0,E.jsx)(`div`,{className:`copy-toast${R.failed?` copy-toast-failed`:``}`,role:`status`,children:R.message}),(0,E.jsx)(Ze,{error:Re,onClose:()=>ze(null)}),(0,E.jsx)($e,{open:Be,onConnect:()=>{Ve(!1),s?.()},onClose:()=>Ve(!1)}),(0,E.jsx)(Je,{target:K,anchorEl:K?dt.current.get(K.sessionId)??null:null,onCancel:()=>vt(null),onConfirm:()=>{let e=K;vt(null),e&&Zt(e)}},K?.sessionId??`none`),(0,E.jsx)(Ye,{open:gt,count:G.size,liveCount:B.filter(e=>G.has(e.sessionId)&&e.live).length,onConfirm:()=>{_t(!1),en()},onCancel:()=>_t(!1)}),(0,E.jsx)(at,{show:Ot!==null,onClose:()=>{kt(null),jt(null),Ft(null)},anchorEl:Ot?dt.current.get(Ot.sessionId)??null:null,sessionId:Ot?.sessionId??null,summary:At,loading:Mt,error:Pt},Ot?.sessionId??`none`)]})}var W=5e3,ft=3e4;function pt(){let[e,t]=(0,D.useState)(null);if((0,D.useEffect)(()=>{let e=!1,n=null;async function r(){try{let n=await fetch(`/api/admin/system-stats`);if(!n.ok){console.error(`[admin-ui] system-stats-fetch-failed status=${n.status}`);return}let r=await n.json();e||t(r)}catch(e){console.error(`[admin-ui] system-stats-fetch-failed reason=${e instanceof Error?e.message:String(e)}`)}}function i(){n===null&&(r(),n=setInterval(()=>{r()},W))}function a(){n!==null&&(clearInterval(n),n=null)}function o(){document.hidden?a():i()}return document.hidden||i(),document.addEventListener(`visibilitychange`,o),()=>{e=!0,a(),document.removeEventListener(`visibilitychange`,o)}},[]),!e||e.platform===`darwin`)return null;let n=e.cpuPct,r=e.memUsedPct,i=n!==null&&n>=.9,a=n!==null&&n>=.98,o=r!==null&&r>=.9,s=r!==null&&r>=.98,c=i||o,l=a||s,u=e=>e===null?`—`:`${Math.round(e*100)}%`,d=[`system-stats`];return c&&d.push(`system-stats--warn`),l&&d.push(`system-stats--crit`),(0,E.jsxs)(`span`,{className:d.join(` `),role:`status`,"aria-label":`host CPU and RAM`,children:[(0,E.jsxs)(`span`,{className:i?`system-stats__fig system-stats__fig--warn`:`system-stats__fig`,children:[`CPU `,u(n)]}),` · `,(0,E.jsxs)(`span`,{className:o?`system-stats__fig system-stats__fig--warn`:`system-stats__fig`,children:[`RAM `,u(r)]})]})}var mt=`admin-sidebar-collapsed`,G=`admin-sidebar-drawer-open`,ht=1080;function gt(){if(typeof window>`u`)return!1;let e=null;try{e=window.sessionStorage.getItem(mt)}catch{e=null}return e===null?typeof window.matchMedia==`function`?window.matchMedia(`(min-width: 721px) and (max-width: ${ht}px)`).matches:!1:e===`1`}function _t(e){if(!(typeof window>`u`))try{e?window.sessionStorage.setItem(mt,`1`):window.sessionStorage.removeItem(mt)}catch{}}function K(){if(typeof window>`u`)return!1;try{return window.sessionStorage.getItem(G)===`1`}catch{return!1}}function vt(e){if(!(typeof window>`u`))try{e?window.sessionStorage.setItem(G,`1`):window.sessionStorage.removeItem(G)}catch{}}function yt(e){let[t,n]=(0,D.useState)(()=>typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(e).matches);return(0,D.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let t=window.matchMedia(e),r=()=>n(t.matches);return r(),t.addEventListener(`change`,r),()=>t.removeEventListener(`change`,r)},[e]),t}var bt=720;function xt(e,t){return e===`/`?{via:`in-place`}:{via:`navigate`,href:`/?wa=${encodeURIComponent(t.remoteJid??``)}&acct=${encodeURIComponent(t.accountId??``)}`}}function St(e){return e===`/`?{via:`in-place`}:{via:`navigate`,href:`/?data=1`}}function Ct(e,t){if(e!==`/`)return null;let n=new URLSearchParams(t),r=n.get(`wa`),i=n.get(`acct`);return!r||!i?null:{sessionId:``,projectDir:``,title:``,senderId:null,startedAt:``,channel:`whatsapp`,role:`public`,operatorName:null,whatsappName:null,lastMessageAt:null,modelGated:!1,model:null,source:`store`,accountId:i,remoteJid:r}}function wt(e,t){return e===`/`?new URLSearchParams(t).has(`data`):!1}function q(e,t){return t===`operator`&&e===`chat`||e===`dashboard`?`/`:e===`data`?`/data`:e===`graph`?`/graph`:e===`calendar`?`/calendar`:e===`chat`?`/chat`:e===`activity`?`/activity`:`/browser`}function J(e){let{cacheKey:t,businessName:r,variant:i=`admin`,onLogout:a,onDisconnect:o,disconnecting:s,claudeConnected:l,onConnectClaude:u,userName:d,userAvatar:f,role:p,onOpenConversations:m,children:h,footer:g}=e,{subAccounts:_,activeAccountId:ee,switching:v,switchAccount:y,refreshAccounts:ne}=ae(t),[b,x]=(0,D.useState)(!0);(0,D.useEffect)(()=>{if(l!==void 0||i!==`admin`)return;let e=!1,t=async()=>{try{let t=await fetch(`/api/health`);if(!t.ok)return;let n=await t.json();e||x(n.auth_status!==`dead`&&n.auth_status!==`missing`)}catch{}};t();let n=setInterval(t,6e4);return()=>{e=!0,clearInterval(n)}},[l,i]);let S=l??b,re=u??(()=>{window.location.assign(`/?connect=claude`)}),[C,ie]=(0,D.useState)(()=>gt()),[w,oe]=(0,D.useState)(!1),se=(0,D.useRef)(!0);(0,D.useEffect)(()=>{if(se.current){se.current=!1;return}oe(!0);let e=setTimeout(()=>oe(!1),260);return()=>clearTimeout(e)},[C]);let[T,ce]=(0,D.useState)(()=>K()),le=yt(`(max-width: ${bt}px)`),[ue,de]=(0,D.useState)(()=>typeof window>`u`||wt(window.location.pathname,window.location.search)?null:Ct(window.location.pathname,window.location.search)),[O,k]=(0,D.useState)(()=>typeof window>`u`?!1:wt(window.location.pathname,window.location.search)),[fe]=(0,D.useState)(()=>O),pe=(0,D.useCallback)(e=>{_t(e),ie(e)},[]),A=(0,D.useCallback)(e=>{vt(e),ce(e)},[]);(0,D.useEffect)(()=>{if(typeof window>`u`)return;let e=window.location?.pathname??``;console.info(`[admin-ui] shell-mount route=${e} variant=${i} sidebar=${i===`operator`?`none`:`present`} collapsed=${C} drawer=${T}`)},[]),(0,D.useEffect)(()=>{typeof window>`u`||!ue||(console.info(`[admin-ui] wa-hydrate route=/ remoteJid=${ue.remoteJid??``}`),window.history.replaceState(null,``,`/`))},[]),(0,D.useEffect)(()=>{typeof window>`u`||!O||(console.info(`[admin-ui] data-hydrate route=/`),window.history.replaceState(null,``,`/`))},[]);let me=(0,D.useCallback)(e=>{if(k(!1),e===null){de(null);return}let t=typeof window<`u`?window.location.pathname:`/`,n=xt(t,e);console.info(`[admin-ui] wa-open route=${t} via=${n.via} sessionId=${e.sessionId.slice(0,8)}`),n.via===`in-place`?de(e):window.location.href=n.href},[]),he=(0,D.useCallback)(()=>{let e=typeof window<`u`?window.location.pathname:`/`,t=St(e);if(console.info(`[admin-ui] data-open route=${e} via=${t.via}`),t.via===`navigate`){window.location.href=t.href;return}de(null),k(!0)},[]),j=le?T:!C,ge=(0,D.useCallback)(()=>{if(!(typeof window>`u`))if(window.matchMedia(`(max-width: ${bt}px)`).matches){let e=T;console.info(`[admin-ui] header-sidebar-toggle from=${e?`open`:`closed`} mode=drawer`),A(!e)}else{let e=C;console.info(`[admin-ui] header-sidebar-toggle from=${e?`closed`:`open`} mode=collapse`),pe(!e)}},[C,T,pe,A]),_e=(0,D.useCallback)(e=>{let t=q(e,i);console.info(`[admin-ui] header-menu-nav target=${e} dest=${t}`),window.location.href=t},[i]),ve={collapsed:C,mobileDrawerOpen:T,sidebarOpen:j,onToggleSidebar:ge,setMobileDrawerOpen:A,selectedWhatsapp:ue,onClearWhatsapp:()=>de(null),onSelectWhatsappConversation:me,dataOpen:O};return i===`operator`?(0,E.jsxs)(`div`,{className:`admin-shell admin-page admin-shell-root`,children:[v&&(0,E.jsx)(c,{surface:`switch`}),(0,E.jsx)(te,{businessName:r,variant:i,onNavigate:_e,onOpenConversations:m,onToggleSidebar:ge,sidebarOpen:j,onLogout:a,onDisconnect:o,disconnecting:s,cacheKey:t,subAccounts:_,activeAccountId:ee,switchingAccount:v,onSwitchAccount:y,refreshAccounts:ne}),(0,E.jsx)(`div`,{className:`platform platform-operator`,children:typeof h==`function`?h(ve):h}),(0,E.jsx)(N,{variant:`operator`,onOpenConversations:m}),g]}):(0,E.jsxs)(`div`,{className:`admin-shell admin-page admin-shell-root`,children:[v&&(0,E.jsx)(c,{surface:`switch`}),(0,E.jsxs)(`div`,{className:`platform${T?` menu-open`:``}${!le&&C?` sidebar-collapsed`:``}${w?` sidebar-animating`:``}`,"data-artefact":`closed`,children:[(0,E.jsx)(dt,{businessName:r,cacheKey:t,onConnectClaude:re,role:p??null,userName:d,userAvatar:f??null,onSelectProjects:()=>{window.location.href=`/graph?label=${n().label}`},onSelectTasks:()=>{window.location.href=`/tasks`},onCloseMobileDrawer:()=>A(!1),collapsed:C,mobileDrawerOpen:T,onSelectData:he,onCloseData:()=>k(!1),initialDataSurface:fe,onLogout:a,onDisconnect:o,disconnecting:s,claudeConnected:S,subAccounts:_,activeAccountId:ee,switchingAccount:v,onSwitchAccount:y,refreshAccounts:ne,onOpenConversations:m}),!le&&(0,E.jsx)(Ae,{}),(0,E.jsx)(we,{sidebarOpen:j,onToggleSidebar:ge,claudeConnected:S,onConnectClaude:re}),typeof h==`function`?h(ve):h]}),T&&(0,E.jsx)(`div`,{className:`sidebar-backdrop menu-open`,"aria-hidden":`true`,onClick:()=>A(!1)}),(0,E.jsx)(N,{}),g]})}export{le as C,ue as S,me as _,Qe as a,fe as b,Ie as c,xe as d,ye as f,he as g,j as h,$e as i,ze as l,ge as m,yt as n,L as o,ve as p,lt as r,I as s,J as t,R as u,A as v,k as x,pe as y};
@@ -1 +1 @@
1
- import{o as e}from"./chunk-CCr-iYLO.js";import{B as t,G as n,H as r,P as i,T as a,U as o,n as s,p as c}from"./useSubAccountSwitcher-CHwQhkaI.js";import{C as l,S as u,t as d,x as f}from"./AdminShell-BlbUNAPc.js";import{t as p}from"./triangle-alert-CngnWtjD.js";var m=o(),h=e(n(),1),g=t(),_=`—`;function v(e){switch(e){case`waiting`:return`Waiting`;case`never-run`:return`Never run`;case`never-succeeded`:return`Never succeeded`;case`failing`:return`Failing`;case`stalled`:return`Stalled`;case`running`:return`Running`;case`ok`:return`Healthy`}}var y={waiting:`Armed and not due yet. It has no start-up run and its first interval has not elapsed, so it has correctly not fired.`,"never-run":`Its interval has elapsed and it still has not fired once. This is not the same as waiting its turn.`,"never-succeeded":`It has fired, and not one run has finished. The work this loop exists to do has never happened.`,failing:`It worked before and is failing now.`,stalled:`It has not started within three of its own intervals. Something is holding it up.`,running:`A run is in progress right now.`,ok:`The last run finished and the next is due within the interval.`},b=new Set([`never-run`,`never-succeeded`,`failing`,`stalled`]),x=10;function S(e){return e===null||!Number.isFinite(e)?_:`${e.toFixed(1)}%`}function C(e){return e<6e4?`${Math.round(e/1e3)}s`:e<36e5?`${Math.round(e/6e4)}m`:`${Math.round(e/36e5)}h`}function w(e,t){if(e===null)return _;let n=t-e;return n<0?`in ${C(-n)}`:n<6e4?`${Math.round(n/1e3)}s ago`:n<36e5?`${Math.round(n/6e4)}m ago`:`${Math.round(n/36e5)}h ago`}function T(e,t){if(e===null)return _;let n=e-t;return n>=0?`in ${C(n)}`:`overdue by ${C(-n)}`}function E({loops:e,nowMs:t=Date.now()}){let[n,r]=(0,h.useState)(!1);if(!e)return(0,g.jsxs)(`section`,{className:`activity-loops`,children:[(0,g.jsx)(`h2`,{className:`activity-loops-heading`,children:`Scheduled work`}),(0,g.jsx)(`p`,{className:`activity-loops-empty`,children:`Scheduled work could not be read from the server.`})]});let i=e.armed-e.rows.length,a=e.rows.filter(e=>b.has(e.state)),o=e.rows.filter(e=>!b.has(e.state)&&typeof e.cpuPct==`number`&&e.cpuPct>=x),s=n?e.rows:[...a,...o];return(0,g.jsxs)(`section`,{className:`activity-loops`,children:[(0,g.jsx)(`h2`,{className:`activity-loops-heading`,children:`Scheduled work`}),(0,g.jsxs)(`p`,{className:`activity-loops-sub`,children:[e.armed,` `,e.armed===1?`loop`:`loops`,` armed`,a.length>0?` · ${a.length} ${a.length===1?`needs`:`need`} attention`:` · all healthy`,o.length>0&&` · ${o.length} using significant processor`,`. `,(0,g.jsx)(`button`,{type:`button`,className:`activity-loops-toggle`,"aria-expanded":n,onClick:()=>r(e=>!e),children:n?`Show less`:`Show all`})]}),typeof e.processPct==`number`&&(0,g.jsxs)(`p`,{className:`activity-loops-cpu`,children:[`Server process at `,e.processPct.toFixed(1),`% of one core`,typeof e.attributedPct==`number`&&(0,g.jsxs)(g.Fragment,{children:[` · these loops explain `,e.attributedPct.toFixed(1),`%`]}),typeof e.unattributedPct==`number`&&e.unattributedPct>=1&&(0,g.jsxs)(g.Fragment,{children:[` · `,(0,g.jsxs)(`strong`,{children:[e.unattributedPct.toFixed(1),`% is not from these loops`]})]})]}),i>0&&(0,g.jsxs)(`p`,{className:`activity-loops-omission`,role:`status`,children:[i,` armed `,i===1?`loop is`:`loops are`,` missing from this list. The server armed `,e.armed,` but sent `,e.rows.length,`.`]}),s.length===0?null:(0,g.jsx)(`div`,{className:`activity-table-scroll`,children:(0,g.jsxs)(`table`,{className:`activity-table`,children:[(0,g.jsx)(`thead`,{children:(0,g.jsxs)(`tr`,{children:[(0,g.jsx)(`th`,{scope:`col`,className:`activity-th`,children:`Loop`}),(0,g.jsx)(`th`,{scope:`col`,className:`activity-th`,children:`State`}),(0,g.jsx)(`th`,{scope:`col`,className:`activity-th`,children:`Every`}),(0,g.jsx)(`th`,{scope:`col`,className:`activity-th`,children:`Last run`}),(0,g.jsx)(`th`,{scope:`col`,className:`activity-th`,children:`Last OK`}),(0,g.jsx)(`th`,{scope:`col`,className:`activity-th`,children:`Took`}),(0,g.jsx)(`th`,{scope:`col`,className:`activity-th`,children:`CPU`}),(0,g.jsx)(`th`,{scope:`col`,className:`activity-th`,children:`Runs`}),(0,g.jsx)(`th`,{scope:`col`,className:`activity-th`,children:`Produced`}),(0,g.jsx)(`th`,{scope:`col`,className:`activity-th`,children:`Next due`})]})}),(0,g.jsx)(`tbody`,{children:s.map(e=>(0,g.jsxs)(`tr`,{className:b.has(e.state)?`activity-loop-row activity-loop-unhealthy`:`activity-loop-row`,children:[(0,g.jsx)(`td`,{className:`activity-td`,children:e.name}),(0,g.jsx)(`td`,{className:`activity-td`,title:y[e.state],children:(0,g.jsxs)(`span`,{className:`activity-state`,children:[(0,g.jsx)(`span`,{className:e.state===`ok`?`activity-state-dot is-healthy`:b.has(e.state)?`activity-state-dot is-unhealthy`:`activity-state-dot`,"aria-hidden":`true`}),v(e.state)]})}),(0,g.jsx)(`td`,{className:`activity-td activity-num`,children:C(e.intervalMs)}),(0,g.jsx)(`td`,{className:`activity-td activity-num`,children:w(e.lastStartMs,t)}),(0,g.jsx)(`td`,{className:`activity-td activity-num`,children:w(e.lastSuccessMs,t)}),(0,g.jsx)(`td`,{className:`activity-td activity-num`,children:e.lastDurationMs===null?_:`${e.lastDurationMs} ms`}),(0,g.jsx)(`td`,{className:`activity-td activity-num`,title:e.cpuAttributable?e.detached?`Includes the processor time of the separate process this loop starts.`:void 0:`This loop waits on other work while it runs, so the processor time it uses cannot be separated from the rest of the server.`,children:S(e.cpuPct)}),(0,g.jsxs)(`td`,{className:`activity-td activity-num`,children:[e.successCount,`/`,e.runCount]}),(0,g.jsx)(`td`,{className:`activity-td activity-loop-note`,children:(0,g.jsx)(`span`,{className:`activity-loop-note-text`,title:e.lastError??e.lastNote??void 0,children:e.lastError??e.lastNote??_})}),(0,g.jsx)(`td`,{className:`activity-td activity-num`,children:T(e.nextDueMs,t)})]},e.name))})]})}),(0,g.jsxs)(`dl`,{className:`activity-legend`,children:[(0,g.jsxs)(`div`,{className:`activity-legend-item`,children:[(0,g.jsx)(`dt`,{className:`activity-legend-term`,children:`Runs`}),(0,g.jsx)(`dd`,{className:`activity-legend-def`,children:`Finished runs out of attempted runs since the server started. 0 out of a large number means it has tried many times and never once finished.`})]}),(0,g.jsxs)(`div`,{className:`activity-legend-item`,children:[(0,g.jsx)(`dt`,{className:`activity-legend-term`,children:`CPU`}),(0,g.jsx)(`dd`,{className:`activity-legend-def`,children:`Share of one processor core this loop is using, measured between the last two refreshes. It includes any separate process the loop starts, and can pass 100% because those run alongside each other. A dash means it could not be measured: the loop waits on other work while it runs, so its share cannot be separated from the rest of the server.`})]}),(0,g.jsxs)(`div`,{className:`activity-legend-item`,children:[(0,g.jsx)(`dt`,{className:`activity-legend-term`,children:_}),(0,g.jsx)(`dd`,{className:`activity-legend-def`,children:`Not measured. It does not mean zero.`})]})]})]})}var D=`maxy-admin-session-key`;function O(e){switch(e.costUnavailable){case`metering-failed`:return`Cost could not be calculated: ${e.meteringError??`the transcript could not be read`}`;case`model-not-priced`:return`No published price for this model, so cost cannot be estimated.`;case`no-transcript`:return`This session has no transcript yet, so there is nothing to cost.`;default:return}}var k=[{key:`lastMessageAt`,label:`Last activity`,dir:-1},{key:`activeMsInRange`,label:`Active time`,dir:-1},{key:`costGbp`,label:`Cost`,dir:-1},{key:`accountId`,label:`Account name`,dir:1}],A=[{key:`title`,label:`Session`,help:`The conversation name, or its short id when it has none yet.`},{key:`model`,label:`Model`,help:`The model that answered the most recent turn.`},{key:`status`,label:`Status`,help:`What the process is doing right now.`},{key:`activeMsInRange`,label:`Active`,help:`Time this session spent thinking, writing and running tools inside the selected range. This is worked time, not elapsed time.`},{key:`ageMs`,label:`Age`,help:`How long ago this conversation started. Wall-clock, so it counts every hour nobody was working.`},{key:`lastMessageAt`,label:`Last activity`,help:`The clock time of the most recent message, in your timezone. A date appears once it is not today.`},{key:`turnCount`,label:`Turns`,help:`Messages exchanged. A trailing + means the count is a minimum — the conversation is too long to count exactly.`},{key:`rssKb`,label:`RAM`,help:`Memory held by this session and all its helper processes together.`},{key:`cpuPct`,label:`CPU (avg)`,help:`AVERAGE share of one processor core over the last census interval, up to 60 seconds. It is not a reading of this instant, so a session that answered a turn a minute ago still shows a high figure while sitting quiet now. Can exceed 100% because a session runs many processes at once.`},{key:`tokensInRange`,label:`Tokens`,help:`Total tokens billed inside the selected range, added up across every day in it. A cumulative total, not the size of the conversation the model currently reads back.`},{key:`costGbp`,label:`Cost`,help:`Estimated spend inside the selected range, at published prices for this model.`}],j=[`activeMsInRange`,`lastMessageAt`,`cpuPct`,`tokensInRange`],M={label:`Account`,help:`The business this session belongs to. "untagged" means the session records no account.`};function N(e,t){let n=t?.[e];return n&&n.trim()!==``?n:e.slice(0,8)}var P=`—`;function F(e){if(e===null||!Number.isFinite(e)||e<0)return P;let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60);if(n<60)return`${n}m`;let r=Math.floor(n/60);return r<24?`${r}h ${n%60}m`:`${Math.floor(r/24)}d ${r%24}h`}function I(e){return e===null||!Number.isFinite(e)?P:`${(e/1024/1024).toFixed(1)} GB`}function L(e,t){if(!e)return P;let n=Date.parse(e);if(!Number.isFinite(n))return P;let r=new Date(n),i=new Date(t),a=`${String(r.getHours()).padStart(2,`0`)}:${String(r.getMinutes()).padStart(2,`0`)}`;return r.getFullYear()===i.getFullYear()&&r.getMonth()===i.getMonth()&&r.getDate()===i.getDate()?a:`${r.getDate()} ${r.toLocaleString(`en-GB`,{month:`short`})} ${a}`}function R(e){return e===null||!Number.isFinite(e)?P:`${e.toFixed(1)}%`}function z(e){return e===null||!Number.isFinite(e)?P:e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(2)}M`}function B(e){return e===null||!Number.isFinite(e)?P:`£${e.toFixed(2)}`}function V(e){if(e===null||!Number.isFinite(e)||e<0)return P;let t=Math.floor(e/6e4);return`${Math.floor(t/60)}h ${t%60}m`}function H(e,t,n,r){let i=e[n],a=t[n];if(i===null&&a===null)return 0;if(i===null)return 1;if(a===null)return-1;if(n===`lastMessageAt`){let e=Date.parse(String(i)),t=Date.parse(String(a));return!Number.isFinite(e)&&!Number.isFinite(t)?0:Number.isFinite(e)?Number.isFinite(t)?(e-t)*r:-1:1}return typeof i==`number`&&typeof a==`number`?(i-a)*r:String(i).localeCompare(String(a))*r}function U(e){return e.toISOString().slice(0,10)}function W(e){let t=e.getUTCFullYear(),n=e.getUTCMonth();return{from:U(new Date(Date.UTC(t,n,1))),to:U(new Date(Date.UTC(t,n+1,0)))}}function G(e,t){let n=new Date(`${e}T00:00:00.000Z`);return W(new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth()+t,1)))}function ee(e,t){return{from:U(new Date(t-(e-1)*864e5)),to:U(new Date(t))}}function K(e){return new Date(`${e}T00:00:00.000Z`).toLocaleString(`en-GB`,{month:`long`,year:`numeric`,timeZone:`UTC`})}function q(e){if(e===null)return!1;let t=W(new Date(`${e.from}T00:00:00.000Z`));return t.from===e.from&&t.to===e.to}function J(e,t,n){switch(e){case`title`:return t.title??t.sessionId.slice(0,8);case`model`:return t.model??P;case`status`:return t.status??P;case`activeMsInRange`:return V(t.activeMsInRange);case`ageMs`:return F(t.ageMs);case`lastMessageAt`:return L(t.lastMessageAt,n);case`turnCount`:return t.turnCount===null?P:`${t.turnCount}${t.turnCountCapped?`+`:``}`;case`rssKb`:return I(t.rssKb);case`cpuPct`:return R(t.cpuPct);case`tokensInRange`:return z(t.tokensInRange);case`costGbp`:return B(t.costGbp);default:return P}}function Y({adminFetch:e,cacheKey:t}){let[n,r]=(0,h.useState)(null),[o,c]=(0,h.useState)(null),[l,d]=(0,h.useState)(!1),[m,_]=(0,h.useState)(`lastMessageAt`),[v,y]=(0,h.useState)(-1),[b,x]=(0,h.useState)(()=>W(new Date)),[S,C]=(0,h.useState)(!0),[w,T]=(0,h.useState)(!0),[D,I]=(0,h.useState)(!1),L=(0,h.useCallback)(async(e,n)=>{t&&await s(t,e)&&(console.info(`[admin-ui] activity-card-open account=${e.slice(0,8)} session=${n.slice(0,8)}`),window.location.assign(`/chat?session=${encodeURIComponent(n)}`))},[t]),R=(0,h.useRef)(!1),z=(0,h.useRef)(void 0),B=(0,h.useCallback)(async t=>{if(R.current){z.current=t;return}R.current=!0;try{let n=await e(`/api/admin/activity${t?`?from=${t.from}&to=${t.to}`:``}`);if(n.status===403){c(`This view is available to the house account only.`),d(!0);return}if(!n.ok){c(`The session manager did not answer (status ${n.status}).`),d(!0);return}r(await n.json()),c(null)}catch(e){c(e instanceof Error?e.message:String(e))}finally{d(!0),R.current=!1;let e=z.current;z.current=void 0,e!==void 0&&B(e)}},[e]);(0,h.useEffect)(()=>{B(b);let e=setInterval(()=>void B(b),15e3);return()=>clearInterval(e)},[B,b]);let V=(0,h.useMemo)(()=>n?[...n.rows].sort((e,t)=>H(e,t,m,v)):[],[n,m,v]),U=(0,h.useMemo)(()=>V.filter(e=>e.status===`busy`?S:e.status===`idle`?w:!0),[V,S,w]),Y=V.length-U.length;if(!l)return(0,g.jsxs)(`div`,{className:`activity-loading`,children:[(0,g.jsx)(a,{size:18,className:`spin`}),` Loading…`]});if(o)return(0,g.jsx)(`div`,{className:`activity-empty`,children:o});if(!n)return(0,g.jsx)(`div`,{className:`activity-empty`,children:`No response.`});let{accounts:X,census:Z,censusAgeMs:Q}=n,te=Date.now(),ne=X.onDisk!==null&&X.onDisk>X.valid,$=n.range===void 0?b:n.range;return(0,g.jsxs)(`div`,{className:`activity-body`,children:[(0,g.jsxs)(`div`,{className:`activity-head`,children:[(0,g.jsxs)(`span`,{className:`activity-title`,children:[(0,g.jsx)(i,{size:16}),` Live sessions`]}),(0,g.jsxs)(`span`,{className:`activity-meta`,children:[Y>0?`${U.length} of ${V.length} live · ${Y} hidden`:`${V.length} live`,` · `,X.valid,` accounts`,X.untaggedCount>0?` · ${X.untaggedCount} untagged`:``]})]}),(0,g.jsxs)(`div`,{className:`activity-controls`,children:[(0,g.jsxs)(`div`,{className:`activity-control activity-range`,children:[(0,g.jsx)(f,{variant:`secondary`,size:`sm`,"aria-label":`Previous month`,disabled:!q(b),onClick:()=>x(e=>e&&G(e.from,-1)),children:`‹`}),(0,g.jsx)(`span`,{className:`activity-range-label`,children:b===null?`All time`:q(b)?K(b.from):`${b.from} → ${b.to}`}),(0,g.jsx)(f,{variant:`secondary`,size:`sm`,"aria-label":`Next month`,disabled:!q(b),onClick:()=>x(e=>e&&G(e.from,1)),children:`›`})]}),(0,g.jsxs)(`div`,{className:`activity-control activity-presets`,children:[(0,g.jsx)(f,{variant:`secondary`,size:`sm`,"aria-pressed":b!==null&&q(b)&&b.from===W(new Date).from,onClick:()=>x(W(new Date)),children:`This month`}),(0,g.jsx)(f,{variant:`secondary`,size:`sm`,"aria-pressed":b!==null&&!q(b),onClick:()=>x(ee(7,Date.now())),children:`Last 7 days`}),(0,g.jsx)(f,{variant:`secondary`,size:`sm`,"aria-pressed":b===null,onClick:()=>x(null),children:`All time`})]}),(0,g.jsxs)(`div`,{className:`activity-control`,children:[(0,g.jsx)(`label`,{className:`activity-control-label`,htmlFor:`activity-sort`,children:`Sort by`}),(0,g.jsx)(`span`,{className:`activity-select-wrap`,children:(0,g.jsx)(`select`,{id:`activity-sort`,className:`activity-select`,value:m,onChange:e=>{let t=k.find(t=>t.key===e.target.value);t&&(_(t.key),y(t.dir))},children:k.map(e=>(0,g.jsx)(`option`,{value:e.key,children:e.label},e.key))})})]}),(0,g.jsxs)(`div`,{className:`activity-control activity-visibility`,children:[(0,g.jsx)(u,{checked:S,onChange:C,label:`Busy`}),(0,g.jsx)(u,{checked:w,onChange:T,label:`Idle`})]})]}),(0,g.jsxs)(`div`,{className:`activity-range-note`,children:[$===null?`Active time, tokens and cost cover each conversation’s whole history.`:`Active time, tokens and cost cover ${$.from} to ${$.to} (UTC), inclusive.`,n.fullRangeFallback&&(0,g.jsxs)(`strong`,{className:`activity-range-rejected`,children:[` `,`The range was not accepted, so these are all-time figures.`]})]}),(0,g.jsx)(`div`,{className:`activity-census`,children:Z===null?`No census collected yet, so memory and CPU are unavailable.`:`Memory and CPU measured ${F(Q)} ago, averaged over the minute before that · ${Z.cpuNull} of ${Z.live} without a CPU reading`}),ne&&(0,g.jsxs)(`div`,{className:`activity-warning`,children:[(0,g.jsx)(p,{size:14}),` `,X.onDisk,` account folders on disk but only`,` `,X.valid,` are readable. Sessions belonging to the rest cannot be attributed.`]}),V.length===0?(0,g.jsx)(`div`,{className:`activity-empty`,children:`No sessions are running.`}):U.length===0?(0,g.jsxs)(`div`,{className:`activity-empty`,children:[`All `,V.length,` running sessions are hidden by the Busy and Idle filters.`]}):(0,g.jsx)(`div`,{className:`activity-grid`,children:U.map(e=>{let n=e.accountId!==null&&!!t,r=n?()=>void L(e.accountId,e.sessionId):void 0;return(0,g.jsxs)(`article`,{className:`activity-card${n?` activity-card-clickable`:``}`,"data-testid":`activity-card`,"data-session-id":e.sessionId,role:n?`button`:void 0,tabIndex:n?0:void 0,onClick:r,onKeyDown:n?e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),r())}:void 0,children:[(0,g.jsx)(`h3`,{className:`activity-card-heading`,title:e.accountId??void 0,children:e.accountId===null?(0,g.jsx)(`span`,{className:`activity-untagged`,title:`This session records no account, so it cannot be attributed to a business.`,children:`untagged`}):N(e.accountId,X.names)}),(0,g.jsx)(`dl`,{className:`activity-card-rows`,children:A.map(t=>(0,g.jsxs)(`div`,{className:`activity-card-row`,children:[(0,g.jsx)(`dt`,{className:`activity-card-label`,"data-testid":`activity-card-label`,title:t.help,children:t.label}),(0,g.jsx)(`dd`,{className:`activity-card-value`,title:t.key===`costGbp`?O(e):void 0,children:J(t.key,e,te)})]},t.key))})]},e.sessionId)})}),V.length>0&&(0,g.jsxs)(`div`,{className:`activity-glossary`,children:[(0,g.jsxs)(`dl`,{className:`activity-legend`,children:[D&&(0,g.jsxs)(`div`,{className:`activity-legend-item`,children:[(0,g.jsx)(`dt`,{className:`activity-legend-term`,"data-testid":`activity-glossary-term`,children:M.label}),(0,g.jsx)(`dd`,{className:`activity-legend-def`,children:M.help})]},`heading`),(D?A:A.filter(e=>j.includes(e.key))).map(e=>(0,g.jsxs)(`div`,{className:`activity-legend-item`,children:[(0,g.jsx)(`dt`,{className:`activity-legend-term`,"data-testid":`activity-glossary-term`,children:e.label}),(0,g.jsx)(`dd`,{className:`activity-legend-def`,children:e.help})]},e.key)),(0,g.jsxs)(`div`,{className:`activity-legend-item`,children:[(0,g.jsx)(`dt`,{className:`activity-legend-term`,children:P}),(0,g.jsxs)(`dd`,{className:`activity-legend-def`,children:[`Not measured. It does not mean zero — a measured zero is written as a figure, so `,(0,g.jsx)(`em`,{children:`0h 0m`}),` and `,(0,g.jsx)(`em`,{children:`£0.00`}),` are real readings. Hover a dashed value for the reason where one exists.`]})]})]}),(0,g.jsx)(f,{variant:`secondary`,size:`sm`,className:`activity-glossary-toggle`,onClick:()=>I(e=>!e),children:D?`Show fewer`:`Explain every figure`})]}),(0,g.jsx)(E,{loops:n?.loops})]})}function X({cacheKey:e}){let{adminFetch:t}=r({initialCacheKey:e,surface:`activity`});return(0,g.jsx)(Y,{adminFetch:t,cacheKey:e})}function Z(){let[e,t]=(0,h.useState)(null),[n,r]=(0,h.useState)(!1),[i,o]=(0,h.useState)(void 0),[s,u]=(0,h.useState)(null),[f,p]=(0,h.useState)(null),[m,_]=(0,h.useState)(null),[v,y]=(0,h.useState)(null);(0,h.useEffect)(()=>{let e=!1,n=null;try{n=sessionStorage.getItem(D)}catch{}if(!n){t(null),r(!0);return}return fetch(`/api/admin/session?session_key=${encodeURIComponent(n)}`).then(async i=>{if(!e){if(i.status===401){try{sessionStorage.removeItem(D)}catch{}window.location.href=`/`;return}if(i.ok)try{let e=await i.json();typeof e.businessName==`string`&&o(e.businessName),e.sessionId!==void 0&&u(e.sessionId??null),p(e.role??null),_(e.userName===void 0?null:e.userName),y(e.avatar??null)}catch{}t(n),r(!0)}}).catch(()=>{e||(t(n),r(!0))}),()=>{e=!0}},[]);let b=(0,h.useCallback)(()=>{try{sessionStorage.removeItem(D)}catch{}window.location.href=`/`},[]),[x,S]=(0,h.useState)(!1),C=(0,h.useCallback)(async()=>{S(!0);try{let e=await l();if(e){try{sessionStorage.removeItem(D)}catch{}window.location.href=`/`}return e}finally{S(!1)}},[]);return n?e?(0,g.jsx)(c,{cacheKey:e,surface:`activity`,onSessionExpired:({code:e,path:t})=>{console.warn(`[admin-auth] outcome=session-expired-redirect code=${e} path=${t} surface=activity`);try{sessionStorage.removeItem(D)}catch{}window.location.href=`/`},children:(0,g.jsx)(d,{cacheKey:e,businessName:i,sessionId:s,onLogout:b,onDisconnect:C,disconnecting:x,userName:m,userAvatar:v,role:f,children:(0,g.jsx)(X,{cacheKey:e})})}):(0,g.jsx)(`div`,{className:`activity-page`,children:(0,g.jsxs)(`div`,{className:`activity-empty`,children:[(0,g.jsx)(`p`,{children:`You are not signed in.`}),(0,g.jsxs)(`p`,{children:[`Open the `,(0,g.jsx)(`a`,{href:`/`,className:`activity-link`,children:`main admin page`}),` and log in, then return here.`]})]})}):(0,g.jsx)(`div`,{className:`activity-page`,children:(0,g.jsxs)(`div`,{className:`activity-loading`,children:[(0,g.jsx)(a,{size:18,className:`spin`}),` Loading…`]})})}(0,m.createRoot)(document.getElementById(`root`)).render((0,g.jsx)(Z,{}));
1
+ import{o as e}from"./chunk-CCr-iYLO.js";import{K as t,P as n,T as r,U as i,V as a,W as o,n as s,p as c}from"./useSubAccountSwitcher-iQGqNJhI.js";import{C as l,S as u,t as d,x as f}from"./AdminShell-Gq8DU_ig.js";import{t as p}from"./triangle-alert-k8ulav-N.js";var m=o(),h=e(t(),1),g=a(),_=`—`;function v(e){switch(e){case`waiting`:return`Waiting`;case`never-run`:return`Never run`;case`never-succeeded`:return`Never succeeded`;case`failing`:return`Failing`;case`stalled`:return`Stalled`;case`running`:return`Running`;case`ok`:return`Healthy`}}var y={waiting:`Armed and not due yet. It has no start-up run and its first interval has not elapsed, so it has correctly not fired.`,"never-run":`Its interval has elapsed and it still has not fired once. This is not the same as waiting its turn.`,"never-succeeded":`It has fired, and not one run has finished. The work this loop exists to do has never happened.`,failing:`It worked before and is failing now.`,stalled:`It has not started within three of its own intervals. Something is holding it up.`,running:`A run is in progress right now.`,ok:`The last run finished and the next is due within the interval.`},b=new Set([`never-run`,`never-succeeded`,`failing`,`stalled`]),x=10;function S(e){return e===null||!Number.isFinite(e)?_:`${e.toFixed(1)}%`}function C(e){return e<6e4?`${Math.round(e/1e3)}s`:e<36e5?`${Math.round(e/6e4)}m`:`${Math.round(e/36e5)}h`}function w(e,t){if(e===null)return _;let n=t-e;return n<0?`in ${C(-n)}`:n<6e4?`${Math.round(n/1e3)}s ago`:n<36e5?`${Math.round(n/6e4)}m ago`:`${Math.round(n/36e5)}h ago`}function T(e,t){if(e===null)return _;let n=e-t;return n>=0?`in ${C(n)}`:`overdue by ${C(-n)}`}function E({loops:e,nowMs:t=Date.now()}){let[n,r]=(0,h.useState)(!1);if(!e)return(0,g.jsxs)(`section`,{className:`activity-loops`,children:[(0,g.jsx)(`h2`,{className:`activity-loops-heading`,children:`Scheduled work`}),(0,g.jsx)(`p`,{className:`activity-loops-empty`,children:`Scheduled work could not be read from the server.`})]});let i=e.armed-e.rows.length,a=e.rows.filter(e=>b.has(e.state)),o=e.rows.filter(e=>!b.has(e.state)&&typeof e.cpuPct==`number`&&e.cpuPct>=x),s=n?e.rows:[...a,...o];return(0,g.jsxs)(`section`,{className:`activity-loops`,children:[(0,g.jsx)(`h2`,{className:`activity-loops-heading`,children:`Scheduled work`}),(0,g.jsxs)(`p`,{className:`activity-loops-sub`,children:[e.armed,` `,e.armed===1?`loop`:`loops`,` armed`,a.length>0?` · ${a.length} ${a.length===1?`needs`:`need`} attention`:` · all healthy`,o.length>0&&` · ${o.length} using significant processor`,`. `,(0,g.jsx)(`button`,{type:`button`,className:`activity-loops-toggle`,"aria-expanded":n,onClick:()=>r(e=>!e),children:n?`Show less`:`Show all`})]}),typeof e.processPct==`number`&&(0,g.jsxs)(`p`,{className:`activity-loops-cpu`,children:[`Server process at `,e.processPct.toFixed(1),`% of one core`,typeof e.attributedPct==`number`&&(0,g.jsxs)(g.Fragment,{children:[` · these loops explain `,e.attributedPct.toFixed(1),`%`]}),typeof e.unattributedPct==`number`&&e.unattributedPct>=1&&(0,g.jsxs)(g.Fragment,{children:[` · `,(0,g.jsxs)(`strong`,{children:[e.unattributedPct.toFixed(1),`% is not from these loops`]})]})]}),i>0&&(0,g.jsxs)(`p`,{className:`activity-loops-omission`,role:`status`,children:[i,` armed `,i===1?`loop is`:`loops are`,` missing from this list. The server armed `,e.armed,` but sent `,e.rows.length,`.`]}),s.length===0?null:(0,g.jsx)(`div`,{className:`activity-table-scroll`,children:(0,g.jsxs)(`table`,{className:`activity-table`,children:[(0,g.jsx)(`thead`,{children:(0,g.jsxs)(`tr`,{children:[(0,g.jsx)(`th`,{scope:`col`,className:`activity-th`,children:`Loop`}),(0,g.jsx)(`th`,{scope:`col`,className:`activity-th`,children:`State`}),(0,g.jsx)(`th`,{scope:`col`,className:`activity-th`,children:`Every`}),(0,g.jsx)(`th`,{scope:`col`,className:`activity-th`,children:`Last run`}),(0,g.jsx)(`th`,{scope:`col`,className:`activity-th`,children:`Last OK`}),(0,g.jsx)(`th`,{scope:`col`,className:`activity-th`,children:`Took`}),(0,g.jsx)(`th`,{scope:`col`,className:`activity-th`,children:`CPU`}),(0,g.jsx)(`th`,{scope:`col`,className:`activity-th`,children:`Runs`}),(0,g.jsx)(`th`,{scope:`col`,className:`activity-th`,children:`Produced`}),(0,g.jsx)(`th`,{scope:`col`,className:`activity-th`,children:`Next due`})]})}),(0,g.jsx)(`tbody`,{children:s.map(e=>(0,g.jsxs)(`tr`,{className:b.has(e.state)?`activity-loop-row activity-loop-unhealthy`:`activity-loop-row`,children:[(0,g.jsx)(`td`,{className:`activity-td`,children:e.name}),(0,g.jsx)(`td`,{className:`activity-td`,title:y[e.state],children:(0,g.jsxs)(`span`,{className:`activity-state`,children:[(0,g.jsx)(`span`,{className:e.state===`ok`?`activity-state-dot is-healthy`:b.has(e.state)?`activity-state-dot is-unhealthy`:`activity-state-dot`,"aria-hidden":`true`}),v(e.state)]})}),(0,g.jsx)(`td`,{className:`activity-td activity-num`,children:C(e.intervalMs)}),(0,g.jsx)(`td`,{className:`activity-td activity-num`,children:w(e.lastStartMs,t)}),(0,g.jsx)(`td`,{className:`activity-td activity-num`,children:w(e.lastSuccessMs,t)}),(0,g.jsx)(`td`,{className:`activity-td activity-num`,children:e.lastDurationMs===null?_:`${e.lastDurationMs} ms`}),(0,g.jsx)(`td`,{className:`activity-td activity-num`,title:e.cpuAttributable?e.detached?`Includes the processor time of the separate process this loop starts.`:void 0:`This loop waits on other work while it runs, so the processor time it uses cannot be separated from the rest of the server.`,children:S(e.cpuPct)}),(0,g.jsxs)(`td`,{className:`activity-td activity-num`,children:[e.successCount,`/`,e.runCount]}),(0,g.jsx)(`td`,{className:`activity-td activity-loop-note`,children:(0,g.jsx)(`span`,{className:`activity-loop-note-text`,title:e.lastError??e.lastNote??void 0,children:e.lastError??e.lastNote??_})}),(0,g.jsx)(`td`,{className:`activity-td activity-num`,children:T(e.nextDueMs,t)})]},e.name))})]})}),(0,g.jsxs)(`dl`,{className:`activity-legend`,children:[(0,g.jsxs)(`div`,{className:`activity-legend-item`,children:[(0,g.jsx)(`dt`,{className:`activity-legend-term`,children:`Runs`}),(0,g.jsx)(`dd`,{className:`activity-legend-def`,children:`Finished runs out of attempted runs since the server started. 0 out of a large number means it has tried many times and never once finished.`})]}),(0,g.jsxs)(`div`,{className:`activity-legend-item`,children:[(0,g.jsx)(`dt`,{className:`activity-legend-term`,children:`CPU`}),(0,g.jsx)(`dd`,{className:`activity-legend-def`,children:`Share of one processor core this loop is using, measured between the last two refreshes. It includes any separate process the loop starts, and can pass 100% because those run alongside each other. A dash means it could not be measured: the loop waits on other work while it runs, so its share cannot be separated from the rest of the server.`})]}),(0,g.jsxs)(`div`,{className:`activity-legend-item`,children:[(0,g.jsx)(`dt`,{className:`activity-legend-term`,children:_}),(0,g.jsx)(`dd`,{className:`activity-legend-def`,children:`Not measured. It does not mean zero.`})]})]})]})}var D=`maxy-admin-session-key`;function O(e){switch(e.costUnavailable){case`metering-failed`:return`Cost could not be calculated: ${e.meteringError??`the transcript could not be read`}`;case`model-not-priced`:return`No published price for this model, so cost cannot be estimated.`;case`no-transcript`:return`This session has no transcript yet, so there is nothing to cost.`;default:return}}var k=[{key:`lastMessageAt`,label:`Last activity`,dir:-1},{key:`activeMsInRange`,label:`Active time`,dir:-1},{key:`costGbp`,label:`Cost`,dir:-1},{key:`accountId`,label:`Account name`,dir:1}],A=[{key:`title`,label:`Session`,help:`The conversation name, or its short id when it has none yet.`},{key:`model`,label:`Model`,help:`The model that answered the most recent turn.`},{key:`status`,label:`Status`,help:`What the process is doing right now.`},{key:`activeMsInRange`,label:`Active`,help:`Time this session spent thinking, writing and running tools inside the selected range. This is worked time, not elapsed time.`},{key:`ageMs`,label:`Age`,help:`How long ago this conversation started. Wall-clock, so it counts every hour nobody was working.`},{key:`lastMessageAt`,label:`Last activity`,help:`The clock time of the most recent message, in your timezone. A date appears once it is not today.`},{key:`turnCount`,label:`Turns`,help:`Messages exchanged. A trailing + means the count is a minimum — the conversation is too long to count exactly.`},{key:`rssKb`,label:`RAM`,help:`Memory held by this session and all its helper processes together.`},{key:`cpuPct`,label:`CPU (avg)`,help:`AVERAGE share of one processor core over the last census interval, up to 60 seconds. It is not a reading of this instant, so a session that answered a turn a minute ago still shows a high figure while sitting quiet now. Can exceed 100% because a session runs many processes at once.`},{key:`tokensInRange`,label:`Tokens`,help:`Total tokens billed inside the selected range, added up across every day in it. A cumulative total, not the size of the conversation the model currently reads back.`},{key:`costGbp`,label:`Cost`,help:`Estimated spend inside the selected range, at published prices for this model.`}],j=[`activeMsInRange`,`lastMessageAt`,`cpuPct`,`tokensInRange`],M={label:`Account`,help:`The business this session belongs to. "untagged" means the session records no account.`};function N(e,t){let n=t?.[e];return n&&n.trim()!==``?n:e.slice(0,8)}var P=`—`;function F(e){if(e===null||!Number.isFinite(e)||e<0)return P;let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60);if(n<60)return`${n}m`;let r=Math.floor(n/60);return r<24?`${r}h ${n%60}m`:`${Math.floor(r/24)}d ${r%24}h`}function I(e){return e===null||!Number.isFinite(e)?P:`${(e/1024/1024).toFixed(1)} GB`}function L(e,t){if(!e)return P;let n=Date.parse(e);if(!Number.isFinite(n))return P;let r=new Date(n),i=new Date(t),a=`${String(r.getHours()).padStart(2,`0`)}:${String(r.getMinutes()).padStart(2,`0`)}`;return r.getFullYear()===i.getFullYear()&&r.getMonth()===i.getMonth()&&r.getDate()===i.getDate()?a:`${r.getDate()} ${r.toLocaleString(`en-GB`,{month:`short`})} ${a}`}function R(e){return e===null||!Number.isFinite(e)?P:`${e.toFixed(1)}%`}function z(e){return e===null||!Number.isFinite(e)?P:e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(2)}M`}function B(e){return e===null||!Number.isFinite(e)?P:`£${e.toFixed(2)}`}function V(e){if(e===null||!Number.isFinite(e)||e<0)return P;let t=Math.floor(e/6e4);return`${Math.floor(t/60)}h ${t%60}m`}function H(e,t,n,r){let i=e[n],a=t[n];if(i===null&&a===null)return 0;if(i===null)return 1;if(a===null)return-1;if(n===`lastMessageAt`){let e=Date.parse(String(i)),t=Date.parse(String(a));return!Number.isFinite(e)&&!Number.isFinite(t)?0:Number.isFinite(e)?Number.isFinite(t)?(e-t)*r:-1:1}return typeof i==`number`&&typeof a==`number`?(i-a)*r:String(i).localeCompare(String(a))*r}function U(e){return e.toISOString().slice(0,10)}function W(e){let t=e.getUTCFullYear(),n=e.getUTCMonth();return{from:U(new Date(Date.UTC(t,n,1))),to:U(new Date(Date.UTC(t,n+1,0)))}}function G(e,t){let n=new Date(`${e}T00:00:00.000Z`);return W(new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth()+t,1)))}function ee(e,t){return{from:U(new Date(t-(e-1)*864e5)),to:U(new Date(t))}}function K(e){return new Date(`${e}T00:00:00.000Z`).toLocaleString(`en-GB`,{month:`long`,year:`numeric`,timeZone:`UTC`})}function q(e){if(e===null)return!1;let t=W(new Date(`${e.from}T00:00:00.000Z`));return t.from===e.from&&t.to===e.to}function J(e,t,n){switch(e){case`title`:return t.title??t.sessionId.slice(0,8);case`model`:return t.model??P;case`status`:return t.status??P;case`activeMsInRange`:return V(t.activeMsInRange);case`ageMs`:return F(t.ageMs);case`lastMessageAt`:return L(t.lastMessageAt,n);case`turnCount`:return t.turnCount===null?P:`${t.turnCount}${t.turnCountCapped?`+`:``}`;case`rssKb`:return I(t.rssKb);case`cpuPct`:return R(t.cpuPct);case`tokensInRange`:return z(t.tokensInRange);case`costGbp`:return B(t.costGbp);default:return P}}function Y({adminFetch:e,cacheKey:t}){let[i,a]=(0,h.useState)(null),[o,c]=(0,h.useState)(null),[l,d]=(0,h.useState)(!1),[m,_]=(0,h.useState)(`lastMessageAt`),[v,y]=(0,h.useState)(-1),[b,x]=(0,h.useState)(()=>W(new Date)),[S,C]=(0,h.useState)(!0),[w,T]=(0,h.useState)(!0),[D,I]=(0,h.useState)(!1),L=(0,h.useCallback)(async(e,n)=>{t&&await s(t,e)&&(console.info(`[admin-ui] activity-card-open account=${e.slice(0,8)} session=${n.slice(0,8)}`),window.location.assign(`/chat?session=${encodeURIComponent(n)}`))},[t]),R=(0,h.useRef)(!1),z=(0,h.useRef)(void 0),B=(0,h.useCallback)(async t=>{if(R.current){z.current=t;return}R.current=!0;try{let n=await e(`/api/admin/activity${t?`?from=${t.from}&to=${t.to}`:``}`);if(n.status===403){c(`This view is available to the house account only.`),d(!0);return}if(!n.ok){c(`The session manager did not answer (status ${n.status}).`),d(!0);return}a(await n.json()),c(null)}catch(e){c(e instanceof Error?e.message:String(e))}finally{d(!0),R.current=!1;let e=z.current;z.current=void 0,e!==void 0&&B(e)}},[e]);(0,h.useEffect)(()=>{B(b);let e=setInterval(()=>void B(b),15e3);return()=>clearInterval(e)},[B,b]);let V=(0,h.useMemo)(()=>i?[...i.rows].sort((e,t)=>H(e,t,m,v)):[],[i,m,v]),U=(0,h.useMemo)(()=>V.filter(e=>e.status===`busy`?S:e.status===`idle`?w:!0),[V,S,w]),Y=V.length-U.length;if(!l)return(0,g.jsxs)(`div`,{className:`activity-loading`,children:[(0,g.jsx)(r,{size:18,className:`spin`}),` Loading…`]});if(o)return(0,g.jsx)(`div`,{className:`activity-empty`,children:o});if(!i)return(0,g.jsx)(`div`,{className:`activity-empty`,children:`No response.`});let{accounts:X,census:Z,censusAgeMs:Q}=i,te=Date.now(),ne=X.onDisk!==null&&X.onDisk>X.valid,$=i.range===void 0?b:i.range;return(0,g.jsxs)(`div`,{className:`activity-body`,children:[(0,g.jsxs)(`div`,{className:`activity-head`,children:[(0,g.jsxs)(`span`,{className:`activity-title`,children:[(0,g.jsx)(n,{size:16}),` Live sessions`]}),(0,g.jsxs)(`span`,{className:`activity-meta`,children:[Y>0?`${U.length} of ${V.length} live · ${Y} hidden`:`${V.length} live`,` · `,X.valid,` accounts`,X.untaggedCount>0?` · ${X.untaggedCount} untagged`:``]})]}),(0,g.jsxs)(`div`,{className:`activity-controls`,children:[(0,g.jsxs)(`div`,{className:`activity-control activity-range`,children:[(0,g.jsx)(f,{variant:`secondary`,size:`sm`,"aria-label":`Previous month`,disabled:!q(b),onClick:()=>x(e=>e&&G(e.from,-1)),children:`‹`}),(0,g.jsx)(`span`,{className:`activity-range-label`,children:b===null?`All time`:q(b)?K(b.from):`${b.from} → ${b.to}`}),(0,g.jsx)(f,{variant:`secondary`,size:`sm`,"aria-label":`Next month`,disabled:!q(b),onClick:()=>x(e=>e&&G(e.from,1)),children:`›`})]}),(0,g.jsxs)(`div`,{className:`activity-control activity-presets`,children:[(0,g.jsx)(f,{variant:`secondary`,size:`sm`,"aria-pressed":b!==null&&q(b)&&b.from===W(new Date).from,onClick:()=>x(W(new Date)),children:`This month`}),(0,g.jsx)(f,{variant:`secondary`,size:`sm`,"aria-pressed":b!==null&&!q(b),onClick:()=>x(ee(7,Date.now())),children:`Last 7 days`}),(0,g.jsx)(f,{variant:`secondary`,size:`sm`,"aria-pressed":b===null,onClick:()=>x(null),children:`All time`})]}),(0,g.jsxs)(`div`,{className:`activity-control`,children:[(0,g.jsx)(`label`,{className:`activity-control-label`,htmlFor:`activity-sort`,children:`Sort by`}),(0,g.jsx)(`span`,{className:`activity-select-wrap`,children:(0,g.jsx)(`select`,{id:`activity-sort`,className:`activity-select`,value:m,onChange:e=>{let t=k.find(t=>t.key===e.target.value);t&&(_(t.key),y(t.dir))},children:k.map(e=>(0,g.jsx)(`option`,{value:e.key,children:e.label},e.key))})})]}),(0,g.jsxs)(`div`,{className:`activity-control activity-visibility`,children:[(0,g.jsx)(u,{checked:S,onChange:C,label:`Busy`}),(0,g.jsx)(u,{checked:w,onChange:T,label:`Idle`})]})]}),(0,g.jsxs)(`div`,{className:`activity-range-note`,children:[$===null?`Active time, tokens and cost cover each conversation’s whole history.`:`Active time, tokens and cost cover ${$.from} to ${$.to} (UTC), inclusive.`,i.fullRangeFallback&&(0,g.jsxs)(`strong`,{className:`activity-range-rejected`,children:[` `,`The range was not accepted, so these are all-time figures.`]})]}),(0,g.jsx)(`div`,{className:`activity-census`,children:Z===null?`No census collected yet, so memory and CPU are unavailable.`:`Memory and CPU measured ${F(Q)} ago, averaged over the minute before that · ${Z.cpuNull} of ${Z.live} without a CPU reading`}),ne&&(0,g.jsxs)(`div`,{className:`activity-warning`,children:[(0,g.jsx)(p,{size:14}),` `,X.onDisk,` account folders on disk but only`,` `,X.valid,` are readable. Sessions belonging to the rest cannot be attributed.`]}),V.length===0?(0,g.jsx)(`div`,{className:`activity-empty`,children:`No sessions are running.`}):U.length===0?(0,g.jsxs)(`div`,{className:`activity-empty`,children:[`All `,V.length,` running sessions are hidden by the Busy and Idle filters.`]}):(0,g.jsx)(`div`,{className:`activity-grid`,children:U.map(e=>{let n=e.accountId!==null&&!!t,r=n?()=>void L(e.accountId,e.sessionId):void 0;return(0,g.jsxs)(`article`,{className:`activity-card${n?` activity-card-clickable`:``}`,"data-testid":`activity-card`,"data-session-id":e.sessionId,role:n?`button`:void 0,tabIndex:n?0:void 0,onClick:r,onKeyDown:n?e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),r())}:void 0,children:[(0,g.jsx)(`h3`,{className:`activity-card-heading`,title:e.accountId??void 0,children:e.accountId===null?(0,g.jsx)(`span`,{className:`activity-untagged`,title:`This session records no account, so it cannot be attributed to a business.`,children:`untagged`}):N(e.accountId,X.names)}),(0,g.jsx)(`dl`,{className:`activity-card-rows`,children:A.map(t=>(0,g.jsxs)(`div`,{className:`activity-card-row`,children:[(0,g.jsx)(`dt`,{className:`activity-card-label`,"data-testid":`activity-card-label`,title:t.help,children:t.label}),(0,g.jsx)(`dd`,{className:`activity-card-value`,title:t.key===`costGbp`?O(e):void 0,children:J(t.key,e,te)})]},t.key))})]},e.sessionId)})}),V.length>0&&(0,g.jsxs)(`div`,{className:`activity-glossary`,children:[(0,g.jsxs)(`dl`,{className:`activity-legend`,children:[D&&(0,g.jsxs)(`div`,{className:`activity-legend-item`,children:[(0,g.jsx)(`dt`,{className:`activity-legend-term`,"data-testid":`activity-glossary-term`,children:M.label}),(0,g.jsx)(`dd`,{className:`activity-legend-def`,children:M.help})]},`heading`),(D?A:A.filter(e=>j.includes(e.key))).map(e=>(0,g.jsxs)(`div`,{className:`activity-legend-item`,children:[(0,g.jsx)(`dt`,{className:`activity-legend-term`,"data-testid":`activity-glossary-term`,children:e.label}),(0,g.jsx)(`dd`,{className:`activity-legend-def`,children:e.help})]},e.key)),(0,g.jsxs)(`div`,{className:`activity-legend-item`,children:[(0,g.jsx)(`dt`,{className:`activity-legend-term`,children:P}),(0,g.jsxs)(`dd`,{className:`activity-legend-def`,children:[`Not measured. It does not mean zero — a measured zero is written as a figure, so `,(0,g.jsx)(`em`,{children:`0h 0m`}),` and `,(0,g.jsx)(`em`,{children:`£0.00`}),` are real readings. Hover a dashed value for the reason where one exists.`]})]})]}),(0,g.jsx)(f,{variant:`secondary`,size:`sm`,className:`activity-glossary-toggle`,onClick:()=>I(e=>!e),children:D?`Show fewer`:`Explain every figure`})]}),(0,g.jsx)(E,{loops:i?.loops})]})}function X({cacheKey:e}){let{adminFetch:t}=i({initialCacheKey:e,surface:`activity`});return(0,g.jsx)(Y,{adminFetch:t,cacheKey:e})}function Z(){let[e,t]=(0,h.useState)(null),[n,i]=(0,h.useState)(!1),[a,o]=(0,h.useState)(void 0),[s,u]=(0,h.useState)(null),[f,p]=(0,h.useState)(null),[m,_]=(0,h.useState)(null),[v,y]=(0,h.useState)(null);(0,h.useEffect)(()=>{let e=!1,n=null;try{n=sessionStorage.getItem(D)}catch{}if(!n){t(null),i(!0);return}return fetch(`/api/admin/session?session_key=${encodeURIComponent(n)}`).then(async r=>{if(!e){if(r.status===401){try{sessionStorage.removeItem(D)}catch{}window.location.href=`/`;return}if(r.ok)try{let e=await r.json();typeof e.businessName==`string`&&o(e.businessName),e.sessionId!==void 0&&u(e.sessionId??null),p(e.role??null),_(e.userName===void 0?null:e.userName),y(e.avatar??null)}catch{}t(n),i(!0)}}).catch(()=>{e||(t(n),i(!0))}),()=>{e=!0}},[]);let b=(0,h.useCallback)(()=>{try{sessionStorage.removeItem(D)}catch{}window.location.href=`/`},[]),[x,S]=(0,h.useState)(!1),C=(0,h.useCallback)(async()=>{S(!0);try{let e=await l();if(e){try{sessionStorage.removeItem(D)}catch{}window.location.href=`/`}return e}finally{S(!1)}},[]);return n?e?(0,g.jsx)(c,{cacheKey:e,surface:`activity`,onSessionExpired:({code:e,path:t})=>{console.warn(`[admin-auth] outcome=session-expired-redirect code=${e} path=${t} surface=activity`);try{sessionStorage.removeItem(D)}catch{}window.location.href=`/`},children:(0,g.jsx)(d,{cacheKey:e,businessName:a,sessionId:s,onLogout:b,onDisconnect:C,disconnecting:x,userName:m,userAvatar:v,role:f,children:(0,g.jsx)(X,{cacheKey:e})})}):(0,g.jsx)(`div`,{className:`activity-page`,children:(0,g.jsxs)(`div`,{className:`activity-empty`,children:[(0,g.jsx)(`p`,{children:`You are not signed in.`}),(0,g.jsxs)(`p`,{children:[`Open the `,(0,g.jsx)(`a`,{href:`/`,className:`activity-link`,children:`main admin page`}),` and log in, then return here.`]})]})}):(0,g.jsx)(`div`,{className:`activity-page`,children:(0,g.jsxs)(`div`,{className:`activity-loading`,children:[(0,g.jsx)(r,{size:18,className:`spin`}),` Loading…`]})})}(0,m.createRoot)(document.getElementById(`root`)).render((0,g.jsx)(Z,{}));