pi-mega-compact 0.20.76 → 0.20.78

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 (75) hide show
  1. package/dist/config/vector-cortex-vc9b.js +4 -3
  2. package/dist/extensions/dashboard-server/api-contracts/endpoints/registry-ext.js +1 -1
  3. package/dist/extensions/dashboard-server/routes-rag-settings-vector-cortex.js +1 -1
  4. package/dist/extensions/dashboard-server/routes-setup-cortex-actions.js +6 -5
  5. package/dist/extensions/dashboard-server/setup-cortex-actions-vc2.js +334 -0
  6. package/dist/extensions/dashboard-server/setup-cortex-actions.js +18 -69
  7. package/dist/src/config/vector-cortex-vc9b.js +4 -3
  8. package/extensions/dashboard-client/dist/assets/{AdminTab-B8JqsA41.js → AdminTab-BsA8-_bX.js} +2 -2
  9. package/extensions/dashboard-client/dist/assets/{AdminTab-B8JqsA41.js.map → AdminTab-BsA8-_bX.js.map} +1 -1
  10. package/extensions/dashboard-client/dist/assets/{AreaChart-CeaexvWO.js → AreaChart-BRHEfWhc.js} +2 -2
  11. package/extensions/dashboard-client/dist/assets/{AreaChart-CeaexvWO.js.map → AreaChart-BRHEfWhc.js.map} +1 -1
  12. package/extensions/dashboard-client/dist/assets/{BarChart-Bhyviy7_.js → BarChart-C-M0LaFc.js} +2 -2
  13. package/extensions/dashboard-client/dist/assets/{BarChart-Bhyviy7_.js.map → BarChart-C-M0LaFc.js.map} +1 -1
  14. package/extensions/dashboard-client/dist/assets/{CacheTab-C6bFdEHq.js → CacheTab-Cj3n59U3.js} +2 -2
  15. package/extensions/dashboard-client/dist/assets/{CacheTab-C6bFdEHq.js.map → CacheTab-Cj3n59U3.js.map} +1 -1
  16. package/extensions/dashboard-client/dist/assets/{ConfigTab-CbsdI5yj.js → ConfigTab-C016XTNC.js} +2 -2
  17. package/extensions/dashboard-client/dist/assets/{ConfigTab-CbsdI5yj.js.map → ConfigTab-C016XTNC.js.map} +1 -1
  18. package/extensions/dashboard-client/dist/assets/{EventsTab-kvB5Znx2.js → EventsTab-DE29fuqe.js} +2 -2
  19. package/extensions/dashboard-client/dist/assets/{EventsTab-kvB5Znx2.js.map → EventsTab-DE29fuqe.js.map} +1 -1
  20. package/extensions/dashboard-client/dist/assets/{HealthTab-DqEUk5LW.js → HealthTab-D4eVI8ar.js} +2 -2
  21. package/extensions/dashboard-client/dist/assets/{HealthTab-DqEUk5LW.js.map → HealthTab-D4eVI8ar.js.map} +1 -1
  22. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-CS5HqDkY.js → MaintenanceTab-4fJ7M4S4.js} +2 -2
  23. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-CS5HqDkY.js.map → MaintenanceTab-4fJ7M4S4.js.map} +1 -1
  24. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-Oq-iqvUq.js → MemoryMapTab-CDbcK9e4.js} +2 -2
  25. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-Oq-iqvUq.js.map → MemoryMapTab-CDbcK9e4.js.map} +1 -1
  26. package/extensions/dashboard-client/dist/assets/{MetricsCards-36RVmtPj.js → MetricsCards-VUEcgGzo.js} +2 -2
  27. package/extensions/dashboard-client/dist/assets/{MetricsCards-36RVmtPj.js.map → MetricsCards-VUEcgGzo.js.map} +1 -1
  28. package/extensions/dashboard-client/dist/assets/MetricsTab-CKqJ0Zl-.js +2 -0
  29. package/extensions/dashboard-client/dist/assets/{MetricsTab-Clkcniuo.js.map → MetricsTab-CKqJ0Zl-.js.map} +1 -1
  30. package/extensions/dashboard-client/dist/assets/{OverviewTab-Cl2Zx7r1.js → OverviewTab-9Kxo79mi.js} +2 -2
  31. package/extensions/dashboard-client/dist/assets/{OverviewTab-Cl2Zx7r1.js.map → OverviewTab-9Kxo79mi.js.map} +1 -1
  32. package/extensions/dashboard-client/dist/assets/{ReposTab-DUoDgjk-.js → ReposTab-C4iveqrP.js} +2 -2
  33. package/extensions/dashboard-client/dist/assets/{ReposTab-DUoDgjk-.js.map → ReposTab-C4iveqrP.js.map} +1 -1
  34. package/extensions/dashboard-client/dist/assets/{SessionsTab-hEQ_OAfB.js → SessionsTab-DSEwkMQm.js} +2 -2
  35. package/extensions/dashboard-client/dist/assets/{SessionsTab-hEQ_OAfB.js.map → SessionsTab-DSEwkMQm.js.map} +1 -1
  36. package/extensions/dashboard-client/dist/assets/{SetupTab-Bqibg0cD.js → SetupTab-CCyWgy4O.js} +2 -2
  37. package/extensions/dashboard-client/dist/assets/{SetupTab-Bqibg0cD.js.map → SetupTab-CCyWgy4O.js.map} +1 -1
  38. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-9QMQUc7L.js → TimeSavedCard-CyD8e_e_.js} +2 -2
  39. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-9QMQUc7L.js.map → TimeSavedCard-CyD8e_e_.js.map} +1 -1
  40. package/extensions/dashboard-client/dist/assets/{TurnMemoryView-DAfqhJqd.js → TurnMemoryView-5tLbWkRv.js} +2 -2
  41. package/extensions/dashboard-client/dist/assets/{TurnMemoryView-DAfqhJqd.js.map → TurnMemoryView-5tLbWkRv.js.map} +1 -1
  42. package/extensions/dashboard-client/dist/assets/TurnsTab-C7pm92Hg.js +2 -0
  43. package/extensions/dashboard-client/dist/assets/{TurnsTab-C-uZNH2F.js.map → TurnsTab-C7pm92Hg.js.map} +1 -1
  44. package/extensions/dashboard-client/dist/assets/{VcStatusBadge-DyOagOVb.js → VcStatusBadge-ObhcIyfN.js} +2 -2
  45. package/extensions/dashboard-client/dist/assets/{VcStatusBadge-DyOagOVb.js.map → VcStatusBadge-ObhcIyfN.js.map} +1 -1
  46. package/extensions/dashboard-client/dist/assets/{VectorCortexTab-BxsbSUGv.js → VectorCortexTab-BtHZb7o7.js} +2 -2
  47. package/extensions/dashboard-client/dist/assets/{VectorCortexTab-BxsbSUGv.js.map → VectorCortexTab-BtHZb7o7.js.map} +1 -1
  48. package/extensions/dashboard-client/dist/assets/{WikiTab-CjefloQb.js → WikiTab-lQ4l3QIK.js} +2 -2
  49. package/extensions/dashboard-client/dist/assets/{WikiTab-CjefloQb.js.map → WikiTab-lQ4l3QIK.js.map} +1 -1
  50. package/extensions/dashboard-client/dist/assets/{button-D-9nb4Bw.js → button-DhQQAJGm.js} +2 -2
  51. package/extensions/dashboard-client/dist/assets/{button-D-9nb4Bw.js.map → button-DhQQAJGm.js.map} +1 -1
  52. package/extensions/dashboard-client/dist/assets/{card-Dvl16_R5.js → card-Cfhz9X31.js} +2 -2
  53. package/extensions/dashboard-client/dist/assets/{card-Dvl16_R5.js.map → card-Cfhz9X31.js.map} +1 -1
  54. package/extensions/dashboard-client/dist/assets/{client-extra-BShDrG99.js → client-extra-CKNOGEz_.js} +2 -2
  55. package/extensions/dashboard-client/dist/assets/{client-extra-BShDrG99.js.map → client-extra-CKNOGEz_.js.map} +1 -1
  56. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-Q_V4fqVi.js → generateCategoricalChart-JKjK9_cB.js} +2 -2
  57. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-Q_V4fqVi.js.map → generateCategoricalChart-JKjK9_cB.js.map} +1 -1
  58. package/extensions/dashboard-client/dist/assets/{index-CL6Af_JZ.js → index-iuxgtzEW.js} +4 -4
  59. package/extensions/dashboard-client/dist/assets/{index-CL6Af_JZ.js.map → index-iuxgtzEW.js.map} +1 -1
  60. package/extensions/dashboard-client/dist/assets/{switch-0MNUTR9I.js → switch-7EHEQMSP.js} +2 -2
  61. package/extensions/dashboard-client/dist/assets/{switch-0MNUTR9I.js.map → switch-7EHEQMSP.js.map} +1 -1
  62. package/extensions/dashboard-client/dist/assets/{toggle-DHbWo-CW.js → toggle-z1lWY4UM.js} +2 -2
  63. package/extensions/dashboard-client/dist/assets/{toggle-DHbWo-CW.js.map → toggle-z1lWY4UM.js.map} +1 -1
  64. package/extensions/dashboard-client/dist/assets/{useSSE-DcBpzKtI.js → useSSE-sctOZuRM.js} +2 -2
  65. package/extensions/dashboard-client/dist/assets/{useSSE-DcBpzKtI.js.map → useSSE-sctOZuRM.js.map} +1 -1
  66. package/extensions/dashboard-client/dist/index.html +1 -1
  67. package/extensions/dashboard-server/api-contracts/endpoints/registry-ext.ts +1 -1
  68. package/extensions/dashboard-server/routes-rag-settings-vector-cortex.ts +1 -1
  69. package/extensions/dashboard-server/routes-setup-cortex-actions.ts +6 -5
  70. package/extensions/dashboard-server/setup-cortex-actions-vc2.ts +400 -0
  71. package/extensions/dashboard-server/setup-cortex-actions.ts +18 -71
  72. package/package.json +1 -1
  73. package/src/config/vector-cortex-vc9b.ts +4 -3
  74. package/extensions/dashboard-client/dist/assets/MetricsTab-Clkcniuo.js +0 -2
  75. package/extensions/dashboard-client/dist/assets/TurnsTab-C-uZNH2F.js +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"SessionsTab-hEQ_OAfB.js","sources":["../../src/components/SessionsMemoryChart.tsx","../../src/components/ActiveSessionsTable.tsx","../../src/tabs/SessionsTab.tsx"],"sourcesContent":["/**\n * dashboard-client/src/components/SessionsMemoryChart.tsx — Stacked memory graph (S39).\n *\n * Recharts stacked `<Area>` per session + total `<Line>` + `<Tooltip>` +\n * `<Legend>` + `<ResponsiveContainer>`. Data comes from `/api/sessions/timeseries`\n * which returns `SessionSeries[]` (per-session data points + stable hex color)\n * and a `totals[]` array (sum across all sessions per timestamp).\n *\n * PREVENT-PI-004: recharts is bundled into this localhost-served static\n * dashboard bundle; it makes no runtime network calls. Chart data arrives via\n * same-origin fetch to the dashboard server (loopback, ports 9320–9329).\n */\n\nimport type React from \"react\";\nimport { useMemo } from \"react\";\nimport {\n\tResponsiveContainer,\n\tAreaChart,\n\tArea,\n\tLine,\n\tXAxis,\n\tYAxis,\n\tCartesianGrid,\n\tTooltip,\n\tLegend,\n} from \"recharts\";\nimport type { SessionSeries } from \"@contracts\";\nimport { Card, CardContent } from \"../components/ui/card\";\n\nexport interface SessionsMemoryChartProps {\n\t/** Per-session series with stable colors (from /api/sessions/timeseries). */\n\tseries: SessionSeries[];\n\t/** Totals (sum across all sessions) per timestamp. */\n\ttotals: ReadonlyArray<{ ts: number; tokens: number }>;\n}\n\n/** A row in the pivoted data table passed to recharts `<AreaChart>`. */\ninterface PivotedRow {\n\t/** Unix timestamp (ms). */\n\tts: number;\n\t/** Total tokens across all sessions at this timestamp. */\n\ttotal: number;\n\t/** Per-session token count keyed by sessionId. */\n\t[sessionId: string]: number;\n}\n\n/**\n * Pivot the per-session series + totals into recharts' expected flat shape:\n * one row per unique timestamp, with each session's token count as a column\n * keyed by sessionId. Missing values for a session at a given timestamp are\n * filled with zero so the stack renders continuously.\n */\nfunction pivot(\n\tseries: SessionSeries[],\n\ttotals: ReadonlyArray<{ ts: number; tokens: number }>,\n): PivotedRow[] {\n\tconst map = new Map<number, PivotedRow>();\n\tconst sessionIds = series.map((s) => s.sessionId);\n\n\tfor (const s of series) {\n\t\tfor (const pt of s.data) {\n\t\t\tlet row = map.get(pt.ts);\n\t\t\tif (!row) {\n\t\t\t\trow = { ts: pt.ts, total: 0 } as PivotedRow;\n\t\t\t\tfor (const sid of sessionIds) row[sid] = 0;\n\t\t\t\tmap.set(pt.ts, row);\n\t\t\t}\n\t\t\trow[s.sessionId] = pt.tokens;\n\t\t}\n\t}\n\tfor (const t of totals) {\n\t\tlet row = map.get(t.ts);\n\t\tif (!row) {\n\t\t\trow = { ts: t.ts, total: 0 } as PivotedRow;\n\t\t\tfor (const sid of sessionIds) row[sid] = 0;\n\t\t\tmap.set(t.ts, row);\n\t\t}\n\t\trow.total = t.tokens;\n\t}\n\n\treturn [...map.values()].sort((a, b) => a.ts - b.ts);\n}\n\nfunction fmtTs(ts: number): string {\n\treturn new Date(ts).toLocaleTimeString([], {\n\t\thour: \"2-digit\",\n\t\tminute: \"2-digit\",\n\t\tsecond: \"2-digit\",\n\t});\n}\n\nfunction fmtTokens(value: number | string): string {\n\tconst n = Number(value);\n\treturn Number.isFinite(n) ? n.toLocaleString() : String(value);\n}\n\n/** Sanitize an arbitrary sessionId for use in an SVG gradient id. */\nfunction gradId(sessionId: string): string {\n\tconst safe = sessionId.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n\treturn `grad-${safe}`;\n}\n\nexport function SessionsMemoryChart({\n\tseries,\n\ttotals,\n}: SessionsMemoryChartProps): React.ReactElement {\n\tconst data = useMemo(\n\t\t() => pivot(series, totals),\n\t\t[series, totals],\n\t);\n\n\tif (series.length === 0) {\n\t\treturn (\n\t\t\t<Card>\n\t\t\t\t<CardContent>No token samples in this window yet.</CardContent>\n\t\t\t</Card>\n\t\t);\n\t}\n\n\treturn (\n\t\t<Card>\n\t\t\t<CardContent>\n\t\t\t<ResponsiveContainer width=\"100%\" height={360}>\n\t\t\t\t<AreaChart\n\t\t\t\t\tdata={data}\n\t\t\t\t\tmargin={{ top: 8, right: 16, left: 0, bottom: 0 }}\n\t\t\t\t>\n\t\t\t\t\t<defs>\n\t\t\t\t\t\t{series.map((s) => (\n\t\t\t\t\t\t\t<linearGradient\n\t\t\t\t\t\t\t\tkey={`${s.sessionId}-grad`}\n\t\t\t\t\t\t\t\tid={gradId(s.sessionId)}\n\t\t\t\t\t\t\t\tx1=\"0\"\n\t\t\t\t\t\t\t\ty1=\"0\"\n\t\t\t\t\t\t\t\tx2=\"0\"\n\t\t\t\t\t\t\t\ty2=\"1\"\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t<stop offset=\"5%\" stopColor={s.color} stopOpacity={0.7} />\n\t\t\t\t\t\t\t\t<stop offset=\"95%\" stopColor={s.color} stopOpacity={0.25} />\n\t\t\t\t\t\t\t</linearGradient>\n\t\t\t\t\t\t))}\n\t\t\t\t\t</defs>\n\t\t\t\t\t<CartesianGrid strokeDasharray=\"3 3\" stroke=\"#30363d\" />\n\t\t\t\t\t<XAxis\n\t\t\t\t\t\tdataKey=\"ts\"\n\t\t\t\t\t\ttype=\"number\"\n\t\t\t\t\t\tdomain={[\"dataMin\", \"dataMax\"]}\n\t\t\t\t\t\ttickFormatter={(ts: number) => fmtTs(ts)}\n\t\t\t\t\t\tstroke=\"#8b949e\"\n\t\t\t\t\t\ttick={{ fontSize: 11 }}\n\t\t\t\t\t\tscale=\"time\"\n\t\t\t\t\t/>\n\t\t\t\t\t<YAxis\n\t\t\t\t\t\tstroke=\"#8b949e\"\n\t\t\t\t\t\ttick={{ fontSize: 11 }}\n\t\t\t\t\t\twidth={56}\n\t\t\t\t\t\ttickFormatter={(v: number) => fmtTokens(v)}\n\t\t\t\t\t/>\n\t\t\t\t\t<Tooltip\n\t\t\t\t\t\tlabelFormatter={(ts: number) => fmtTs(ts)}\n\t\t\t\t\t\tformatter={(value) =>\n\t\t\t\t\t\t\t[fmtTokens(value as number), \"tokens\"] as [string, string]\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontentStyle={{\n\t\t\t\t\t\t\tbackground: \"#161b22\",\n\t\t\t\t\t\t\tborder: \"1px solid #30363d\",\n\t\t\t\t\t\t\tborderRadius: \"6px\",\n\t\t\t\t\t\t\tcolor: \"#e6edf3\",\n\t\t\t\t\t\t}}\n\t\t\t\t\t\tlabelStyle={{ color: \"#8b949e\", fontSize: 12 }}\n\t\t\t\t\t/>\n\t\t\t\t\t<Legend wrapperStyle={{ fontSize: 12 }} />\n\t\t\t\t\t{series.map((s) => (\n\t\t\t\t\t\t<Area\n\t\t\t\t\t\t\tkey={s.sessionId}\n\t\t\t\t\t\t\ttype=\"monotone\"\n\t\t\t\t\t\t\tdataKey={s.sessionId}\n\t\t\t\t\t\t\tname={s.label}\n\t\t\t\t\t\t\tstackId=\"1\"\n\t\t\t\t\t\t\tstroke={s.color}\n\t\t\t\t\t\t\tfill={`url(#${gradId(s.sessionId)})`}\n\t\t\t\t\t\t\tfillOpacity={1}\n\t\t\t\t\t\t\tisAnimationActive={false}\n\t\t\t\t\t\t\tdot={false}\n\t\t\t\t\t\t/>\n\t\t\t\t\t))}\n\t\t\t\t\t<Line\n\t\t\t\t\t\ttype=\"monotone\"\n\t\t\t\t\t\tdataKey=\"total\"\n\t\t\t\t\t\tname=\"Total\"\n\t\t\t\t\t\tstroke=\"#e6edf3\"\n\t\t\t\t\t\tstrokeWidth={1.5}\n\t\t\t\t\t\tstrokeDasharray=\"4 2\"\n\t\t\t\t\t\tdot={false}\n\t\t\t\t\t\tisAnimationActive={false}\n\t\t\t\t\t/>\n\t\t\t\t</AreaChart>\n\t\t\t</ResponsiveContainer>\n\t\t\t</CardContent>\n\t\t</Card>\n\t);\n}\n","/**\n * dashboard-client/src/components/ActiveSessionsTable.tsx — Active sessions table (S39).\n *\n * Per-session rows: PID, Repo, Model, Context %, Tokens/Window,\n * Heartbeat age, State dir, Sparkline.\n *\n * Data from /api/sessions (active sessions list) and /api/sessions/timeseries\n * (per-session data points used to render inline sparklines).\n */\n\nimport type React from \"react\";\nimport type { ActiveSession, SessionSeries } from \"@contracts\";\nimport { Card, CardContent } from \"../components/ui/card\";\n\nexport interface ActiveSessionsTableProps {\n\t/** Active sessions, sorted by lastSeen descending (from /api/sessions). */\n\tsessions: ActiveSession[];\n\t/** Per-session timeseries used to render the inline sparkline column. */\n\tseries: SessionSeries[];\n}\n\nconst HEADERS = [\n\t\"PID\",\n\t\"Repo\",\n\t\"Model\",\n\t\"Context %\",\n\t\"Tokens / Window\",\n\t\"Last Heartbeat\",\n\t\"State Dir\",\n\t\"Trend\",\n] as const;\n\n/** Format a duration in milliseconds → human-readable age string. */\nfunction fmtAge(ms: number): string {\n\tconst s = Math.max(0, Math.round(ms / 1000));\n\tif (s < 60) return `${s}s ago`;\n\tconst m = Math.floor(s / 60);\n\tif (m < 60) return `${m}m ${s % 60}s ago`;\n\tconst h = Math.floor(m / 60);\n\treturn `${h}h ${m % 60}m ago`;\n}\n\nfunction fmtTokens(n: number | null): string {\n\tif (n == null) return \"\\u2014\";\n\tif (n >= 100_000) return `${(n / 1000).toFixed(0)}k`;\n\tif (n >= 1000) return `${(n / 1000).toFixed(1)}k`;\n\treturn n.toLocaleString();\n}\n\nfunction pctClass(pct: number | null): string {\n\tif (pct == null) return \"sessions-pct-ok\";\n\tif (pct >= 85) return \"sessions-pct-err\";\n\tif (pct >= 60) return \"sessions-pct-warn\";\n\treturn \"sessions-pct-ok\";\n}\n\nfunction fmtPct(pct: number | null): string {\n\tif (pct == null) return \"\\u2014\";\n\treturn `${Math.round(pct)}%`;\n}\n\nfunction fmtWindow(tokens: number | null, window: number): string {\n\tif (tokens == null) return \"\\u2014\";\n\treturn `${fmtTokens(tokens)} / ${fmtTokens(window)}`;\n}\n\ninterface SparklineProps {\n\t/** Token counts over time (oldest → newest). */\n\tpoints: number[];\n\t/** Stable hex color for the stroke. */\n\tcolor: string;\n}\n\nfunction Sparkline({ points, color }: SparklineProps): React.ReactElement {\n\tif (points.length < 2) {\n\t\treturn <span className=\"sessions-sparkline-empty\">{\"\\u2014\"}</span>;\n\t}\n\tconst min = Math.min(...points);\n\tconst max = Math.max(...points);\n\tconst range = max - min || 1;\n\tconst w = 64;\n\tconst h = 18;\n\tconst stepX = w / (points.length - 1);\n\tconst segments = points.map((p, i) => {\n\t\tconst x = i * stepX;\n\t\tconst y = h - ((p - min) / range) * h;\n\t\treturn `${i === 0 ? \"M\" : \"L\"} ${x.toFixed(1)} ${y.toFixed(1)}`;\n\t});\n\treturn (\n\t\t<svg\n\t\t\tclassName=\"sessions-sparkline\"\n\t\t\twidth={w}\n\t\t\theight={h}\n\t\t\tviewBox={`0 0 ${w} ${h}`}\n\t\t\trole=\"img\"\n\t\t\taria-label=\"token trend\"\n\t\t>\n\t\t\t<path\n\t\t\t\td={segments.join(\" \")}\n\t\t\t\tfill=\"none\"\n\t\t\t\tstroke={color}\n\t\t\t\tstrokeWidth=\"1.5\"\n\t\t\t\tstrokeLinejoin=\"round\"\n\t\t\t\tstrokeLinecap=\"round\"\n\t\t\t/>\n\t\t</svg>\n\t);\n}\n\n/** Map sessionId → series for the sparkline column lookup. */\nfunction indexSeries(\n\tseries: SessionSeries[],\n): Map<string, SessionSeries> {\n\tconst m = new Map<string, SessionSeries>();\n\tfor (const s of series) m.set(s.sessionId, s);\n\treturn m;\n}\n\nexport function ActiveSessionsTable({\n\tsessions,\n\tseries,\n}: ActiveSessionsTableProps): React.ReactElement {\n\tconst seriesById = indexSeries(series);\n\tconst now = Date.now();\n\n\treturn (\n\t\t<Card>\n\t\t\t<CardContent>\n\t\t\t<div className=\"overflow-x-auto\">\n\t\t\t\t<table className=\"w-full border-collapse text-sm\">\n\t\t\t\t\t<thead>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t{HEADERS.map((h, i) => (\n\t\t\t\t\t\t\t\t<th\n\t\t\t\t\t\t\t\t\tkey={h}\n\t\t\t\t\t\t\t\t\tclassName={`border-b border-border px-3 py-2 text-left font-medium text-muted-foreground${\n\t\t\t\t\t\t\t\t\t\ti >= 3 && i !== 6 ? \" text-right\" : \"\"\n\t\t\t\t\t\t\t\t\t}`}\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t{h}\n\t\t\t\t\t\t\t\t</th>\n\t\t\t\t\t\t\t))}\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</thead>\n\t\t\t\t\t<tbody>\n\t\t\t\t\t\t{sessions.length === 0 && (\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<td colSpan={HEADERS.length} className=\"px-3 py-4 text-muted-foreground\">\n\t\t\t\t\t\t\t\t\tNo active sessions.\n\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t)}\n\t\t\t\t\t\t{sessions.map((s) => {\n\t\t\t\t\t\t\tconst srs = seriesById.get(s.sessionId);\n\t\t\t\t\t\t\tconst sparkPts =\n\t\t\t\t\t\t\t\tsrs?.data.map((d) => d.tokens) ?? [];\n\t\t\t\t\t\t\tconst color = srs?.color ?? \"#58a6ff\";\n\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t<tr\n\t\t\t\t\t\t\t\t\tkey={`${s.pid}:${s.sessionId}`}\n\t\t\t\t\t\t\t\t\tclassName=\"border-b border-border/50 hover:bg-bg-elevated/40\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t<td className=\"px-3 py-2 text-right font-mono\">{s.pid}</td>\n\t\t\t\t\t\t\t\t\t<td className=\"px-3 py-2\" title={s.repoRoot ?? undefined}>\n\t\t\t\t\t\t\t\t\t\t{s.displayName || s.repoRoot || \"\\u2014\"}\n\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t\t<td className=\"px-3 py-2\">{s.model ?? \"\\u2014\"}</td>\n\t\t\t\t\t\t\t\t\t<td className=\"px-3 py-2 text-right\">\n\t\t\t\t\t\t\t\t\t\t<span className={`sessions-pct-pill ${pctClass(s.percent)}`}>\n\t\t\t\t\t\t\t\t\t\t\t{fmtPct(s.percent)}\n\t\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t\t<td className=\"px-3 py-2 text-right\">\n\t\t\t\t\t\t\t\t\t\t{fmtWindow(s.tokens, s.ctxWindow)}\n\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t\t<td className=\"px-3 py-2 text-right\">{fmtAge(now - s.lastSeen)}</td>\n\t\t\t\t\t\t\t\t\t<td\n\t\t\t\t\t\t\t\t\t\ttitle={s.stateDir ?? undefined}\n\t\t\t\t\t\t\t\t\t\tclassName=\"px-3 py-2 font-mono text-muted-foreground\"\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t{s.stateDir\n\t\t\t\t\t\t\t\t\t\t\t? s.stateDir.split(\"/\").pop() || s.stateDir\n\t\t\t\t\t\t\t\t\t\t\t: \"\\u2014\"}\n\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t\t<td className=\"px-3 py-2\">\n\t\t\t\t\t\t\t\t\t\t<Sparkline points={sparkPts} color={color} />\n\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t})}\n\t\t\t\t\t</tbody>\n\t\t\t\t</table>\n\t\t\t</div>\n\t\t\t</CardContent>\n\t\t</Card>\n\t);\n}\n","/**\n * dashboard-client/src/tabs/SessionsTab.tsx — Sessions tab (S39, DASH-0b).\n *\n * DASH-0b: the Sessions surface absorbs the existent TurnsTab as a drill-down.\n * A `SessionsViews` toggle (\"Active Sessions\" / \"Turn Memory\") switches between\n * the existent sessions summary/chart/table body and the turns view (rendered by\n * `SessionsTab/TurnMemoryView.tsx` — the turns body moved VERBATIM from the\n * standalone TurnsTab.tsx, which is left untouched this sprint for flag-off\n * parity).\n *\n * Flag: `MEGACOMPACT_DASH_0B` default ON. The dashboard client is a browser\n * bundle with NO `process` global, so the positive sprint flag cannot be read\n * server-side-style (`process.env`) inside the client. Instead the flag is read\n * from the server-authoritative `/api/rag-settings` state: the server resolves\n * `process.env[\"MEGACOMPACT_DASH_0B\"] ?? default` into the `SettingState.value`\n * boolean. When the flag is OFF (settings confirmed value=false), this surface\n * renders ONLY the existent sessions body — no toggle, no TurnMemoryView branch\n * (byte-identical predecessor). The standalone TurnsTab.tsx top-level surface is\n * untouched and remains reachable for flag-off parity.\n *\n * Data sources: fetchSessions() + fetchSessionTimeseries(minutes). Both poll\n * every 2s for near-real-time updates. useSSE() listens for session_sample\n * events emitted by appendTokenSample (Step 5) so the chart refetches\n * instantly between polls when a new token sample is appended to events.log.\n *\n * Empty state: shows \"No active sessions.\" when the /api/sessions response\n * returns an empty array (e.g. no pi processes are running yet).\n */\n\nimport type React from \"react\";\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { useApi } from \"../hooks/useApi\";\nimport { useSSE } from \"../hooks/useSSE\";\nimport { fetchSessions, fetchSessionTimeseries, fetchSettings } from \"../api/client\";\nimport type {\n\tSseEvent,\n\tSseSessionSample,\n\tSessionsResponse,\n\tSessionTimeseriesResponse,\n\tSettingsResponse,\n} from \"@contracts\";\nimport { SessionsMemoryChart } from \"../components/SessionsMemoryChart\";\nimport { ActiveSessionsTable } from \"../components/ActiveSessionsTable\";\nimport { Toggle } from \"../components/ui/toggle\";\nimport { Card, CardContent } from \"../components/ui/card\";\nimport { TurnMemoryView } from \"./SessionsTab/TurnMemoryView\";\n\n/**\n * Shape of the {@link SseSessionSample} SSE event appended to events.log by\n * `appendTokenSample` (src/store/sqlite/global-index.ts). The contract now\n * defines this variant as part of the {@link SseEvent} union (Step 5); the\n * local alias keeps the surface terser in this file.\n */\ntype SessionSampleEvent = SseSessionSample;\n\n/** Type guard: narrows an SSE event to a session_sample event. */\nfunction isSessionSample(\n\te: SseEvent,\n): e is SessionSampleEvent {\n\treturn e.type === \"session_sample\";\n}\n\nconst DASH_0B_KEY = \"MEGACOMPACT_DASH_0B\";\n\n/** Resolve the DASH-0b consolidation flag from the server settings state.\n * Absent/not-yet-loaded => false (flag-off posture), so flag-off users never\n * see a toggle flash; the toggle appears only once settings confirm it is ON. */\nfunction dash0bEnabled(settings: SettingsResponse | null): boolean {\n\tif (!settings) return false;\n\tfor (const cat of settings.categories) {\n\t\tfor (const s of cat.settings) {\n\t\t\tif (s.key === DASH_0B_KEY && s.type === \"boolean\") return s.value === true;\n\t\t}\n\t}\n\treturn false;\n}\n\nconst WINDOWS: ReadonlyArray<{ value: number; label: string }> = [\n\t{ value: 5, label: \"5m\" },\n\t{ value: 15, label: \"15m\" },\n\t{ value: 30, label: \"30m\" },\n\t{ value: 60, label: \"60m\" },\n] as const;\n\ninterface SummaryTilesProps {\n\tsessions: SessionsResponse;\n}\n\nfunction SummaryTiles({ sessions }: SummaryTilesProps): React.ReactElement {\n\tconst active = sessions.sessions.length;\n\tconst combinedTokens = sessions.sessions.reduce(\n\t\t(sum, s) => sum + (s.tokens ?? 0),\n\t\t0,\n\t);\n\tconst maxWindow = sessions.sessions.reduce(\n\t\t(max, s) => Math.max(max, s.ctxWindow),\n\t\t0,\n\t);\n\tconst combinedPct = maxWindow > 0 ? (combinedTokens / maxWindow) * 100 : 0;\n\treturn (\n\t\t<div className=\"grid grid-cols-2 gap-4 md:grid-cols-4\">\n\t\t\t<Card>\n\t\t\t\t<CardContent>\n\t\t\t\t\t<span className=\"text-xs text-muted-foreground\">Active sessions</span>\n\t\t\t\t\t<div className=\"text-xl font-semibold\">{active}</div>\n\t\t\t\t</CardContent>\n\t\t\t</Card>\n\t\t\t<Card>\n\t\t\t\t<CardContent>\n\t\t\t\t\t<span className=\"text-xs text-muted-foreground\">Combined tokens</span>\n\t\t\t\t\t<div className=\"text-xl font-semibold\">\n\t\t\t\t\t\t{combinedTokens >= 100_000\n\t\t\t\t\t\t\t? `${(combinedTokens / 1000).toFixed(0)}k`\n\t\t\t\t\t\t\t: combinedTokens.toLocaleString()}\n\t\t\t\t\t</div>\n\t\t\t\t</CardContent>\n\t\t\t</Card>\n\t\t\t<Card>\n\t\t\t\t<CardContent>\n\t\t\t\t\t<span className=\"text-xs text-muted-foreground\">\n\t\t\t\t\t\tCombined % of max window\n\t\t\t\t\t</span>\n\t\t\t\t\t<div className=\"text-xl font-semibold\">{Math.round(combinedPct)}%</div>\n\t\t\t\t</CardContent>\n\t\t\t</Card>\n\t\t\t<Card>\n\t\t\t\t<CardContent>\n\t\t\t\t\t<span className=\"text-xs text-muted-foreground\">Pruned (stale)</span>\n\t\t\t\t\t<div className=\"text-xl font-semibold\">{sessions.pruned}</div>\n\t\t\t\t</CardContent>\n\t\t\t</Card>\n\t\t</div>\n\t);\n}\n\ntype SessionsView = \"active\" | \"turns\";\n\nexport default function SessionsTab(): React.ReactElement {\n\tconst [minutes, setMinutes] = useState(30);\n\tconst [view, setView] = useState<SessionsView>(\"active\");\n\n\tconst {\n\t\tdata: settingsData,\n\t} = useApi<SettingsResponse>(\n\t\tuseCallback(() => fetchSettings(), []),\n\t\t{ pollInterval: 0, maxRetries: 0 },\n\t);\n\tconst dash0bOn = dash0bEnabled(settingsData);\n\n\tconst {\n\t\tdata: sessionsData,\n\t\terror: sessionsErr,\n\t\trefetch: refetchSessions,\n\t} = useApi<SessionsResponse>(\n\t\tuseCallback(() => fetchSessions(), []),\n\t\t{ pollInterval: 2_000 },\n\t);\n\n\tconst {\n\t\tdata: timeseriesData,\n\t\terror: timeseriesErr,\n\t\trefetch: refetchTimeseries,\n\t} = useApi<SessionTimeseriesResponse>(\n\t\tuseCallback(() => fetchSessionTimeseries(minutes), [minutes]),\n\t\t{ pollInterval: 2_000 },\n\t);\n\n\tconst { events } = useSSE();\n\n\t// Filter SSE events for session_sample pushes (Step 5) and trigger an\n\t// immediate refetch when a new sample arrives, so the chart updates\n\t// between the 2s polls. The events array grows as new samples arrive; the\n\t// length-based dependency means the effect re-runs when a new sample event\n\t// lands (not on every poll). We debounce via a microtask guard.\n\tconst sampleEvents = useMemo(\n\t\t() => events.filter(isSessionSample),\n\t\t[events],\n\t);\n\n\tconst lastSampleTs = useMemo(() => {\n\t\tif (sampleEvents.length === 0) return null;\n\t\treturn sampleEvents[sampleEvents.length - 1].ts;\n\t}, [sampleEvents]);\n\n\tuseEffect(() => {\n\t\tif (lastSampleTs == null) return;\n\t\trefetchSessions();\n\t\trefetchTimeseries();\n\t}, [lastSampleTs, refetchSessions, refetchTimeseries]);\n\n\tif (dash0bOn && view === \"turns\") {\n\t\treturn <TurnMemoryView />;\n\t}\n\n\tif (sessionsErr && !sessionsData) {\n\t\treturn (\n\t\t\t<div className=\"tab-stub\">\n\t\t\t\tError loading sessions: {sessionsErr.message}\n\t\t\t</div>\n\t\t);\n\t}\n\tif (timeseriesErr && !timeseriesData) {\n\t\treturn (\n\t\t\t<div className=\"tab-stub\">\n\t\t\t\tError loading timeseries: {timeseriesErr.message}\n\t\t\t</div>\n\t\t);\n\t}\n\tif (!sessionsData) {\n\t\treturn <div className=\"tab-stub\">Loading sessions…</div>;\n\t}\n\n\tconst sessions = sessionsData.sessions;\n\tconst series = timeseriesData?.series ?? [];\n\tconst totals = timeseriesData?.totals ?? [];\n\tconst windowLabel =\n\t\tWINDOWS.find((w) => w.value === minutes)?.label ?? `${minutes}m`;\n\n\treturn (\n\t\t<div className=\"flex flex-col gap-4\">\n\t\t\t<div className=\"flex items-center justify-between\">\n\t\t\t\t<h2 className=\"font-heading text-lg font-semibold\">\n\t\t\t\t\tSession Memory Graph\n\t\t\t\t</h2>\n\t\t\t\t<div className=\"flex gap-2\">\n\t\t\t\t\t{WINDOWS.map((w) => (\n\t\t\t\t\t\t<Toggle\n\t\t\t\t\t\t\tkey={w.value}\n\t\t\t\t\t\t\tpressed={minutes === w.value}\n\t\t\t\t\t\t\tonClick={() => setMinutes(w.value)}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{w.label}\n\t\t\t\t\t\t</Toggle>\n\t\t\t\t\t))}\n\t\t\t\t</div>\n\t\t\t</div>\n\n\t\t\t{dash0bOn && (\n\t\t\t\t<div\n\t\t\t\t\tclassName=\"flex items-center gap-2\"\n\t\t\t\t\trole=\"tablist\"\n\t\t\t\t\taria-label=\"Sessions views\"\n\t\t\t\t>\n\t\t\t\t\t<Toggle\n\t\t\t\t\t\tpressed={view === \"active\"}\n\t\t\t\t\t\tonClick={() => setView(\"active\")}\n\t\t\t\t\t>\n\t\t\t\t\t\tActive Sessions\n\t\t\t\t\t</Toggle>\n\t\t\t\t\t<Toggle\n\t\t\t\t\t\tpressed={view === \"turns\"}\n\t\t\t\t\t\tonClick={() => setView(\"turns\")}\n\t\t\t\t\t>\n\t\t\t\t\t\tTurn Memory\n\t\t\t\t\t</Toggle>\n\t\t\t\t</div>\n\t\t\t)}\n\n\t\t\t{sessions.length === 0 ? (\n\t\t\t\t<div className=\"text-sm text-muted-foreground\">No active sessions.</div>\n\t\t\t) : (\n\t\t\t\t<>\n\t\t\t\t\t<SummaryTiles sessions={sessionsData} />\n\t\t\t\t\t<SessionsMemoryChart series={series} totals={totals} />\n\t\t\t\t\t<h2 className=\"font-heading text-lg font-semibold\">\n\t\t\t\t\t\tActive Sessions\n\t\t\t\t\t</h2>\n\t\t\t\t\t<ActiveSessionsTable sessions={sessions} series={series} />\n\t\t\t\t\t<div className=\"text-xs text-muted-foreground\">\n\t\t\t\t\t\t{series.length} series · {totals.length} timestamps ·{\" \"}\n\t\t\t\t\t\t{windowLabel} window · updated{\" \"}\n\t\t\t\t\t\t{timeseriesData?.updatedAt ?? sessionsData.updatedAt}\n\t\t\t\t\t</div>\n\t\t\t\t</>\n\t\t\t)}\n\t\t</div>\n\t);\n}\n"],"names":["pivot","series","totals","map","sessionIds","s","pt","row","sid","a","b","fmtTs","ts","fmtTokens","value","n","gradId","sessionId","SessionsMemoryChart","data","useMemo","jsx","Card","CardContent","ResponsiveContainer","jsxs","AreaChart","CartesianGrid","XAxis","YAxis","v","Tooltip","Legend","Area","Line","HEADERS","fmtAge","ms","m","pctClass","pct","fmtPct","fmtWindow","tokens","window","Sparkline","points","color","min","range","w","h","stepX","segments","p","i","x","y","indexSeries","ActiveSessionsTable","sessions","seriesById","now","srs","sparkPts","d","isSessionSample","e","DASH_0B_KEY","dash0bEnabled","settings","cat","WINDOWS","SummaryTiles","active","combinedTokens","sum","maxWindow","max","combinedPct","SessionsTab","minutes","setMinutes","useState","view","setView","settingsData","useApi","useCallback","fetchSettings","dash0bOn","sessionsData","sessionsErr","refetchSessions","fetchSessions","timeseriesData","timeseriesErr","refetchTimeseries","fetchSessionTimeseries","events","useSSE","sampleEvents","lastSampleTs","useEffect","TurnMemoryView","windowLabel","Toggle","Fragment"],"mappings":"4aAoDA,SAASA,EACRC,EACAC,EACe,CACf,MAAMC,MAAU,IACVC,EAAaH,EAAO,IAAKI,GAAMA,EAAE,SAAS,EAEhD,UAAWA,KAAKJ,EACf,UAAWK,KAAMD,EAAE,KAAM,CACxB,IAAIE,EAAMJ,EAAI,IAAIG,EAAG,EAAE,EACvB,GAAI,CAACC,EAAK,CACTA,EAAM,CAAE,GAAID,EAAG,GAAI,MAAO,CAAA,EAC1B,UAAWE,KAAOJ,EAAYG,EAAIC,CAAG,EAAI,EACzCL,EAAI,IAAIG,EAAG,GAAIC,CAAG,CACnB,CACAA,EAAIF,EAA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KtB,GACb7B,EAAAA,IAACqF,EAAA,CAEA,QAASzB,IAAY/B,EAAE,MACvB,QAAS,IAAMgC,EAAWhC,EAAE,KAAK,EAEhC,SAAAA,EAAE,KAAA,EAJEA,EAAE,KAAA,CAMR,CAAA,CACF,CAAA,EACD,EAECwC,GACAjE,EAAAA,KAAC,MAAA,CACA,UAAU,0BACV,KAAK,UACL,aAAW,iBAEX,SAAA,CAAAJ,EAAAA,IAACqF,EAAA,CACA,QAAStB,IAAS,SAClB,QAAS,IAAMC,EAAQ,QAAQ,EAC/B,SAAA,iBAAA,CAAA,EAGDhE,EAAAA,IAACqF,EAAA,CACA,QAAStB,IAAS,QAClB,QAAS,IAAMC,EAAQ,OAAO,EAC9B,SAAA,aAAA,CAAA,CAED,CAAA,CAAA,EAIDzB,EAAS,SAAW,EACpBvC,EAAAA,IAAC,OAAI,UAAU,gCAAgC,SAAA,qBAAA,CAAmB,EAElEI,EAAAA,KAAAkF,EAAAA,SAAA,CACC,SAAA,CAAAtF,EAAAA,IAACoD,GAAA,CAAa,SAAUkB,CAAA,CAAc,EACtCtE,EAAAA,IAACH,EAAA,CAAoB,OAAAjB,EAAgB,OAAAC,CAAA,CAAgB,EACrDmB,EAAAA,IAAC,KAAA,CAAG,UAAU,qCAAqC,SAAA,kBAEnD,EACAA,EAAAA,IAACsC,GAAA,CAAoB,SAAAC,EAAoB,OAAA3D,CAAA,CAAgB,EACzDwB,EAAAA,KAAC,MAAA,CAAI,UAAU,gCACb,SAAA,CAAAxB,EAAO,OAAO,aAAWC,EAAO,OAAO,gBAAc,IACrDuG,EAAY,oBAAkB,IAC9BV,GAAgB,WAAaJ,EAAa,SAAA,CAAA,CAC5C,CAAA,CAAA,CACD,CAAA,EAEF,CAEF"}
1
+ {"version":3,"file":"SessionsTab-DSEwkMQm.js","sources":["../../src/components/SessionsMemoryChart.tsx","../../src/components/ActiveSessionsTable.tsx","../../src/tabs/SessionsTab.tsx"],"sourcesContent":["/**\n * dashboard-client/src/components/SessionsMemoryChart.tsx — Stacked memory graph (S39).\n *\n * Recharts stacked `<Area>` per session + total `<Line>` + `<Tooltip>` +\n * `<Legend>` + `<ResponsiveContainer>`. Data comes from `/api/sessions/timeseries`\n * which returns `SessionSeries[]` (per-session data points + stable hex color)\n * and a `totals[]` array (sum across all sessions per timestamp).\n *\n * PREVENT-PI-004: recharts is bundled into this localhost-served static\n * dashboard bundle; it makes no runtime network calls. Chart data arrives via\n * same-origin fetch to the dashboard server (loopback, ports 9320–9329).\n */\n\nimport type React from \"react\";\nimport { useMemo } from \"react\";\nimport {\n\tResponsiveContainer,\n\tAreaChart,\n\tArea,\n\tLine,\n\tXAxis,\n\tYAxis,\n\tCartesianGrid,\n\tTooltip,\n\tLegend,\n} from \"recharts\";\nimport type { SessionSeries } from \"@contracts\";\nimport { Card, CardContent } from \"../components/ui/card\";\n\nexport interface SessionsMemoryChartProps {\n\t/** Per-session series with stable colors (from /api/sessions/timeseries). */\n\tseries: SessionSeries[];\n\t/** Totals (sum across all sessions) per timestamp. */\n\ttotals: ReadonlyArray<{ ts: number; tokens: number }>;\n}\n\n/** A row in the pivoted data table passed to recharts `<AreaChart>`. */\ninterface PivotedRow {\n\t/** Unix timestamp (ms). */\n\tts: number;\n\t/** Total tokens across all sessions at this timestamp. */\n\ttotal: number;\n\t/** Per-session token count keyed by sessionId. */\n\t[sessionId: string]: number;\n}\n\n/**\n * Pivot the per-session series + totals into recharts' expected flat shape:\n * one row per unique timestamp, with each session's token count as a column\n * keyed by sessionId. Missing values for a session at a given timestamp are\n * filled with zero so the stack renders continuously.\n */\nfunction pivot(\n\tseries: SessionSeries[],\n\ttotals: ReadonlyArray<{ ts: number; tokens: number }>,\n): PivotedRow[] {\n\tconst map = new Map<number, PivotedRow>();\n\tconst sessionIds = series.map((s) => s.sessionId);\n\n\tfor (const s of series) {\n\t\tfor (const pt of s.data) {\n\t\t\tlet row = map.get(pt.ts);\n\t\t\tif (!row) {\n\t\t\t\trow = { ts: pt.ts, total: 0 } as PivotedRow;\n\t\t\t\tfor (const sid of sessionIds) row[sid] = 0;\n\t\t\t\tmap.set(pt.ts, row);\n\t\t\t}\n\t\t\trow[s.sessionId] = pt.tokens;\n\t\t}\n\t}\n\tfor (const t of totals) {\n\t\tlet row = map.get(t.ts);\n\t\tif (!row) {\n\t\t\trow = { ts: t.ts, total: 0 } as PivotedRow;\n\t\t\tfor (const sid of sessionIds) row[sid] = 0;\n\t\t\tmap.set(t.ts, row);\n\t\t}\n\t\trow.total = t.tokens;\n\t}\n\n\treturn [...map.values()].sort((a, b) => a.ts - b.ts);\n}\n\nfunction fmtTs(ts: number): string {\n\treturn new Date(ts).toLocaleTimeString([], {\n\t\thour: \"2-digit\",\n\t\tminute: \"2-digit\",\n\t\tsecond: \"2-digit\",\n\t});\n}\n\nfunction fmtTokens(value: number | string): string {\n\tconst n = Number(value);\n\treturn Number.isFinite(n) ? n.toLocaleString() : String(value);\n}\n\n/** Sanitize an arbitrary sessionId for use in an SVG gradient id. */\nfunction gradId(sessionId: string): string {\n\tconst safe = sessionId.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n\treturn `grad-${safe}`;\n}\n\nexport function SessionsMemoryChart({\n\tseries,\n\ttotals,\n}: SessionsMemoryChartProps): React.ReactElement {\n\tconst data = useMemo(\n\t\t() => pivot(series, totals),\n\t\t[series, totals],\n\t);\n\n\tif (series.length === 0) {\n\t\treturn (\n\t\t\t<Card>\n\t\t\t\t<CardContent>No token samples in this window yet.</CardContent>\n\t\t\t</Card>\n\t\t);\n\t}\n\n\treturn (\n\t\t<Card>\n\t\t\t<CardContent>\n\t\t\t<ResponsiveContainer width=\"100%\" height={360}>\n\t\t\t\t<AreaChart\n\t\t\t\t\tdata={data}\n\t\t\t\t\tmargin={{ top: 8, right: 16, left: 0, bottom: 0 }}\n\t\t\t\t>\n\t\t\t\t\t<defs>\n\t\t\t\t\t\t{series.map((s) => (\n\t\t\t\t\t\t\t<linearGradient\n\t\t\t\t\t\t\t\tkey={`${s.sessionId}-grad`}\n\t\t\t\t\t\t\t\tid={gradId(s.sessionId)}\n\t\t\t\t\t\t\t\tx1=\"0\"\n\t\t\t\t\t\t\t\ty1=\"0\"\n\t\t\t\t\t\t\t\tx2=\"0\"\n\t\t\t\t\t\t\t\ty2=\"1\"\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t<stop offset=\"5%\" stopColor={s.color} stopOpacity={0.7} />\n\t\t\t\t\t\t\t\t<stop offset=\"95%\" stopColor={s.color} stopOpacity={0.25} />\n\t\t\t\t\t\t\t</linearGradient>\n\t\t\t\t\t\t))}\n\t\t\t\t\t</defs>\n\t\t\t\t\t<CartesianGrid strokeDasharray=\"3 3\" stroke=\"#30363d\" />\n\t\t\t\t\t<XAxis\n\t\t\t\t\t\tdataKey=\"ts\"\n\t\t\t\t\t\ttype=\"number\"\n\t\t\t\t\t\tdomain={[\"dataMin\", \"dataMax\"]}\n\t\t\t\t\t\ttickFormatter={(ts: number) => fmtTs(ts)}\n\t\t\t\t\t\tstroke=\"#8b949e\"\n\t\t\t\t\t\ttick={{ fontSize: 11 }}\n\t\t\t\t\t\tscale=\"time\"\n\t\t\t\t\t/>\n\t\t\t\t\t<YAxis\n\t\t\t\t\t\tstroke=\"#8b949e\"\n\t\t\t\t\t\ttick={{ fontSize: 11 }}\n\t\t\t\t\t\twidth={56}\n\t\t\t\t\t\ttickFormatter={(v: number) => fmtTokens(v)}\n\t\t\t\t\t/>\n\t\t\t\t\t<Tooltip\n\t\t\t\t\t\tlabelFormatter={(ts: number) => fmtTs(ts)}\n\t\t\t\t\t\tformatter={(value) =>\n\t\t\t\t\t\t\t[fmtTokens(value as number), \"tokens\"] as [string, string]\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontentStyle={{\n\t\t\t\t\t\t\tbackground: \"#161b22\",\n\t\t\t\t\t\t\tborder: \"1px solid #30363d\",\n\t\t\t\t\t\t\tborderRadius: \"6px\",\n\t\t\t\t\t\t\tcolor: \"#e6edf3\",\n\t\t\t\t\t\t}}\n\t\t\t\t\t\tlabelStyle={{ color: \"#8b949e\", fontSize: 12 }}\n\t\t\t\t\t/>\n\t\t\t\t\t<Legend wrapperStyle={{ fontSize: 12 }} />\n\t\t\t\t\t{series.map((s) => (\n\t\t\t\t\t\t<Area\n\t\t\t\t\t\t\tkey={s.sessionId}\n\t\t\t\t\t\t\ttype=\"monotone\"\n\t\t\t\t\t\t\tdataKey={s.sessionId}\n\t\t\t\t\t\t\tname={s.label}\n\t\t\t\t\t\t\tstackId=\"1\"\n\t\t\t\t\t\t\tstroke={s.color}\n\t\t\t\t\t\t\tfill={`url(#${gradId(s.sessionId)})`}\n\t\t\t\t\t\t\tfillOpacity={1}\n\t\t\t\t\t\t\tisAnimationActive={false}\n\t\t\t\t\t\t\tdot={false}\n\t\t\t\t\t\t/>\n\t\t\t\t\t))}\n\t\t\t\t\t<Line\n\t\t\t\t\t\ttype=\"monotone\"\n\t\t\t\t\t\tdataKey=\"total\"\n\t\t\t\t\t\tname=\"Total\"\n\t\t\t\t\t\tstroke=\"#e6edf3\"\n\t\t\t\t\t\tstrokeWidth={1.5}\n\t\t\t\t\t\tstrokeDasharray=\"4 2\"\n\t\t\t\t\t\tdot={false}\n\t\t\t\t\t\tisAnimationActive={false}\n\t\t\t\t\t/>\n\t\t\t\t</AreaChart>\n\t\t\t</ResponsiveContainer>\n\t\t\t</CardContent>\n\t\t</Card>\n\t);\n}\n","/**\n * dashboard-client/src/components/ActiveSessionsTable.tsx — Active sessions table (S39).\n *\n * Per-session rows: PID, Repo, Model, Context %, Tokens/Window,\n * Heartbeat age, State dir, Sparkline.\n *\n * Data from /api/sessions (active sessions list) and /api/sessions/timeseries\n * (per-session data points used to render inline sparklines).\n */\n\nimport type React from \"react\";\nimport type { ActiveSession, SessionSeries } from \"@contracts\";\nimport { Card, CardContent } from \"../components/ui/card\";\n\nexport interface ActiveSessionsTableProps {\n\t/** Active sessions, sorted by lastSeen descending (from /api/sessions). */\n\tsessions: ActiveSession[];\n\t/** Per-session timeseries used to render the inline sparkline column. */\n\tseries: SessionSeries[];\n}\n\nconst HEADERS = [\n\t\"PID\",\n\t\"Repo\",\n\t\"Model\",\n\t\"Context %\",\n\t\"Tokens / Window\",\n\t\"Last Heartbeat\",\n\t\"State Dir\",\n\t\"Trend\",\n] as const;\n\n/** Format a duration in milliseconds → human-readable age string. */\nfunction fmtAge(ms: number): string {\n\tconst s = Math.max(0, Math.round(ms / 1000));\n\tif (s < 60) return `${s}s ago`;\n\tconst m = Math.floor(s / 60);\n\tif (m < 60) return `${m}m ${s % 60}s ago`;\n\tconst h = Math.floor(m / 60);\n\treturn `${h}h ${m % 60}m ago`;\n}\n\nfunction fmtTokens(n: number | null): string {\n\tif (n == null) return \"\\u2014\";\n\tif (n >= 100_000) return `${(n / 1000).toFixed(0)}k`;\n\tif (n >= 1000) return `${(n / 1000).toFixed(1)}k`;\n\treturn n.toLocaleString();\n}\n\nfunction pctClass(pct: number | null): string {\n\tif (pct == null) return \"sessions-pct-ok\";\n\tif (pct >= 85) return \"sessions-pct-err\";\n\tif (pct >= 60) return \"sessions-pct-warn\";\n\treturn \"sessions-pct-ok\";\n}\n\nfunction fmtPct(pct: number | null): string {\n\tif (pct == null) return \"\\u2014\";\n\treturn `${Math.round(pct)}%`;\n}\n\nfunction fmtWindow(tokens: number | null, window: number): string {\n\tif (tokens == null) return \"\\u2014\";\n\treturn `${fmtTokens(tokens)} / ${fmtTokens(window)}`;\n}\n\ninterface SparklineProps {\n\t/** Token counts over time (oldest → newest). */\n\tpoints: number[];\n\t/** Stable hex color for the stroke. */\n\tcolor: string;\n}\n\nfunction Sparkline({ points, color }: SparklineProps): React.ReactElement {\n\tif (points.length < 2) {\n\t\treturn <span className=\"sessions-sparkline-empty\">{\"\\u2014\"}</span>;\n\t}\n\tconst min = Math.min(...points);\n\tconst max = Math.max(...points);\n\tconst range = max - min || 1;\n\tconst w = 64;\n\tconst h = 18;\n\tconst stepX = w / (points.length - 1);\n\tconst segments = points.map((p, i) => {\n\t\tconst x = i * stepX;\n\t\tconst y = h - ((p - min) / range) * h;\n\t\treturn `${i === 0 ? \"M\" : \"L\"} ${x.toFixed(1)} ${y.toFixed(1)}`;\n\t});\n\treturn (\n\t\t<svg\n\t\t\tclassName=\"sessions-sparkline\"\n\t\t\twidth={w}\n\t\t\theight={h}\n\t\t\tviewBox={`0 0 ${w} ${h}`}\n\t\t\trole=\"img\"\n\t\t\taria-label=\"token trend\"\n\t\t>\n\t\t\t<path\n\t\t\t\td={segments.join(\" \")}\n\t\t\t\tfill=\"none\"\n\t\t\t\tstroke={color}\n\t\t\t\tstrokeWidth=\"1.5\"\n\t\t\t\tstrokeLinejoin=\"round\"\n\t\t\t\tstrokeLinecap=\"round\"\n\t\t\t/>\n\t\t</svg>\n\t);\n}\n\n/** Map sessionId → series for the sparkline column lookup. */\nfunction indexSeries(\n\tseries: SessionSeries[],\n): Map<string, SessionSeries> {\n\tconst m = new Map<string, SessionSeries>();\n\tfor (const s of series) m.set(s.sessionId, s);\n\treturn m;\n}\n\nexport function ActiveSessionsTable({\n\tsessions,\n\tseries,\n}: ActiveSessionsTableProps): React.ReactElement {\n\tconst seriesById = indexSeries(series);\n\tconst now = Date.now();\n\n\treturn (\n\t\t<Card>\n\t\t\t<CardContent>\n\t\t\t<div className=\"overflow-x-auto\">\n\t\t\t\t<table className=\"w-full border-collapse text-sm\">\n\t\t\t\t\t<thead>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t{HEADERS.map((h, i) => (\n\t\t\t\t\t\t\t\t<th\n\t\t\t\t\t\t\t\t\tkey={h}\n\t\t\t\t\t\t\t\t\tclassName={`border-b border-border px-3 py-2 text-left font-medium text-muted-foreground${\n\t\t\t\t\t\t\t\t\t\ti >= 3 && i !== 6 ? \" text-right\" : \"\"\n\t\t\t\t\t\t\t\t\t}`}\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t{h}\n\t\t\t\t\t\t\t\t</th>\n\t\t\t\t\t\t\t))}\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</thead>\n\t\t\t\t\t<tbody>\n\t\t\t\t\t\t{sessions.length === 0 && (\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<td colSpan={HEADERS.length} className=\"px-3 py-4 text-muted-foreground\">\n\t\t\t\t\t\t\t\t\tNo active sessions.\n\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t)}\n\t\t\t\t\t\t{sessions.map((s) => {\n\t\t\t\t\t\t\tconst srs = seriesById.get(s.sessionId);\n\t\t\t\t\t\t\tconst sparkPts =\n\t\t\t\t\t\t\t\tsrs?.data.map((d) => d.tokens) ?? [];\n\t\t\t\t\t\t\tconst color = srs?.color ?? \"#58a6ff\";\n\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t<tr\n\t\t\t\t\t\t\t\t\tkey={`${s.pid}:${s.sessionId}`}\n\t\t\t\t\t\t\t\t\tclassName=\"border-b border-border/50 hover:bg-bg-elevated/40\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t<td className=\"px-3 py-2 text-right font-mono\">{s.pid}</td>\n\t\t\t\t\t\t\t\t\t<td className=\"px-3 py-2\" title={s.repoRoot ?? undefined}>\n\t\t\t\t\t\t\t\t\t\t{s.displayName || s.repoRoot || \"\\u2014\"}\n\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t\t<td className=\"px-3 py-2\">{s.model ?? \"\\u2014\"}</td>\n\t\t\t\t\t\t\t\t\t<td className=\"px-3 py-2 text-right\">\n\t\t\t\t\t\t\t\t\t\t<span className={`sessions-pct-pill ${pctClass(s.percent)}`}>\n\t\t\t\t\t\t\t\t\t\t\t{fmtPct(s.percent)}\n\t\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t\t<td className=\"px-3 py-2 text-right\">\n\t\t\t\t\t\t\t\t\t\t{fmtWindow(s.tokens, s.ctxWindow)}\n\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t\t<td className=\"px-3 py-2 text-right\">{fmtAge(now - s.lastSeen)}</td>\n\t\t\t\t\t\t\t\t\t<td\n\t\t\t\t\t\t\t\t\t\ttitle={s.stateDir ?? undefined}\n\t\t\t\t\t\t\t\t\t\tclassName=\"px-3 py-2 font-mono text-muted-foreground\"\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t{s.stateDir\n\t\t\t\t\t\t\t\t\t\t\t? s.stateDir.split(\"/\").pop() || s.stateDir\n\t\t\t\t\t\t\t\t\t\t\t: \"\\u2014\"}\n\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t\t<td className=\"px-3 py-2\">\n\t\t\t\t\t\t\t\t\t\t<Sparkline points={sparkPts} color={color} />\n\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t})}\n\t\t\t\t\t</tbody>\n\t\t\t\t</table>\n\t\t\t</div>\n\t\t\t</CardContent>\n\t\t</Card>\n\t);\n}\n","/**\n * dashboard-client/src/tabs/SessionsTab.tsx — Sessions tab (S39, DASH-0b).\n *\n * DASH-0b: the Sessions surface absorbs the existent TurnsTab as a drill-down.\n * A `SessionsViews` toggle (\"Active Sessions\" / \"Turn Memory\") switches between\n * the existent sessions summary/chart/table body and the turns view (rendered by\n * `SessionsTab/TurnMemoryView.tsx` — the turns body moved VERBATIM from the\n * standalone TurnsTab.tsx, which is left untouched this sprint for flag-off\n * parity).\n *\n * Flag: `MEGACOMPACT_DASH_0B` default ON. The dashboard client is a browser\n * bundle with NO `process` global, so the positive sprint flag cannot be read\n * server-side-style (`process.env`) inside the client. Instead the flag is read\n * from the server-authoritative `/api/rag-settings` state: the server resolves\n * `process.env[\"MEGACOMPACT_DASH_0B\"] ?? default` into the `SettingState.value`\n * boolean. When the flag is OFF (settings confirmed value=false), this surface\n * renders ONLY the existent sessions body — no toggle, no TurnMemoryView branch\n * (byte-identical predecessor). The standalone TurnsTab.tsx top-level surface is\n * untouched and remains reachable for flag-off parity.\n *\n * Data sources: fetchSessions() + fetchSessionTimeseries(minutes). Both poll\n * every 2s for near-real-time updates. useSSE() listens for session_sample\n * events emitted by appendTokenSample (Step 5) so the chart refetches\n * instantly between polls when a new token sample is appended to events.log.\n *\n * Empty state: shows \"No active sessions.\" when the /api/sessions response\n * returns an empty array (e.g. no pi processes are running yet).\n */\n\nimport type React from \"react\";\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { useApi } from \"../hooks/useApi\";\nimport { useSSE } from \"../hooks/useSSE\";\nimport { fetchSessions, fetchSessionTimeseries, fetchSettings } from \"../api/client\";\nimport type {\n\tSseEvent,\n\tSseSessionSample,\n\tSessionsResponse,\n\tSessionTimeseriesResponse,\n\tSettingsResponse,\n} from \"@contracts\";\nimport { SessionsMemoryChart } from \"../components/SessionsMemoryChart\";\nimport { ActiveSessionsTable } from \"../components/ActiveSessionsTable\";\nimport { Toggle } from \"../components/ui/toggle\";\nimport { Card, CardContent } from \"../components/ui/card\";\nimport { TurnMemoryView } from \"./SessionsTab/TurnMemoryView\";\n\n/**\n * Shape of the {@link SseSessionSample} SSE event appended to events.log by\n * `appendTokenSample` (src/store/sqlite/global-index.ts). The contract now\n * defines this variant as part of the {@link SseEvent} union (Step 5); the\n * local alias keeps the surface terser in this file.\n */\ntype SessionSampleEvent = SseSessionSample;\n\n/** Type guard: narrows an SSE event to a session_sample event. */\nfunction isSessionSample(\n\te: SseEvent,\n): e is SessionSampleEvent {\n\treturn e.type === \"session_sample\";\n}\n\nconst DASH_0B_KEY = \"MEGACOMPACT_DASH_0B\";\n\n/** Resolve the DASH-0b consolidation flag from the server settings state.\n * Absent/not-yet-loaded => false (flag-off posture), so flag-off users never\n * see a toggle flash; the toggle appears only once settings confirm it is ON. */\nfunction dash0bEnabled(settings: SettingsResponse | null): boolean {\n\tif (!settings) return false;\n\tfor (const cat of settings.categories) {\n\t\tfor (const s of cat.settings) {\n\t\t\tif (s.key === DASH_0B_KEY && s.type === \"boolean\") return s.value === true;\n\t\t}\n\t}\n\treturn false;\n}\n\nconst WINDOWS: ReadonlyArray<{ value: number; label: string }> = [\n\t{ value: 5, label: \"5m\" },\n\t{ value: 15, label: \"15m\" },\n\t{ value: 30, label: \"30m\" },\n\t{ value: 60, label: \"60m\" },\n] as const;\n\ninterface SummaryTilesProps {\n\tsessions: SessionsResponse;\n}\n\nfunction SummaryTiles({ sessions }: SummaryTilesProps): React.ReactElement {\n\tconst active = sessions.sessions.length;\n\tconst combinedTokens = sessions.sessions.reduce(\n\t\t(sum, s) => sum + (s.tokens ?? 0),\n\t\t0,\n\t);\n\tconst maxWindow = sessions.sessions.reduce(\n\t\t(max, s) => Math.max(max, s.ctxWindow),\n\t\t0,\n\t);\n\tconst combinedPct = maxWindow > 0 ? (combinedTokens / maxWindow) * 100 : 0;\n\treturn (\n\t\t<div className=\"grid grid-cols-2 gap-4 md:grid-cols-4\">\n\t\t\t<Card>\n\t\t\t\t<CardContent>\n\t\t\t\t\t<span className=\"text-xs text-muted-foreground\">Active sessions</span>\n\t\t\t\t\t<div className=\"text-xl font-semibold\">{active}</div>\n\t\t\t\t</CardContent>\n\t\t\t</Card>\n\t\t\t<Card>\n\t\t\t\t<CardContent>\n\t\t\t\t\t<span className=\"text-xs text-muted-foreground\">Combined tokens</span>\n\t\t\t\t\t<div className=\"text-xl font-semibold\">\n\t\t\t\t\t\t{combinedTokens >= 100_000\n\t\t\t\t\t\t\t? `${(combinedTokens / 1000).toFixed(0)}k`\n\t\t\t\t\t\t\t: combinedTokens.toLocaleString()}\n\t\t\t\t\t</div>\n\t\t\t\t</CardContent>\n\t\t\t</Card>\n\t\t\t<Card>\n\t\t\t\t<CardContent>\n\t\t\t\t\t<span className=\"text-xs text-muted-foreground\">\n\t\t\t\t\t\tCombined % of max window\n\t\t\t\t\t</span>\n\t\t\t\t\t<div className=\"text-xl font-semibold\">{Math.round(combinedPct)}%</div>\n\t\t\t\t</CardContent>\n\t\t\t</Card>\n\t\t\t<Card>\n\t\t\t\t<CardContent>\n\t\t\t\t\t<span className=\"text-xs text-muted-foreground\">Pruned (stale)</span>\n\t\t\t\t\t<div className=\"text-xl font-semibold\">{sessions.pruned}</div>\n\t\t\t\t</CardContent>\n\t\t\t</Card>\n\t\t</div>\n\t);\n}\n\ntype SessionsView = \"active\" | \"turns\";\n\nexport default function SessionsTab(): React.ReactElement {\n\tconst [minutes, setMinutes] = useState(30);\n\tconst [view, setView] = useState<SessionsView>(\"active\");\n\n\tconst {\n\t\tdata: settingsData,\n\t} = useApi<SettingsResponse>(\n\t\tuseCallback(() => fetchSettings(), []),\n\t\t{ pollInterval: 0, maxRetries: 0 },\n\t);\n\tconst dash0bOn = dash0bEnabled(settingsData);\n\n\tconst {\n\t\tdata: sessionsData,\n\t\terror: sessionsErr,\n\t\trefetch: refetchSessions,\n\t} = useApi<SessionsResponse>(\n\t\tuseCallback(() => fetchSessions(), []),\n\t\t{ pollInterval: 2_000 },\n\t);\n\n\tconst {\n\t\tdata: timeseriesData,\n\t\terror: timeseriesErr,\n\t\trefetch: refetchTimeseries,\n\t} = useApi<SessionTimeseriesResponse>(\n\t\tuseCallback(() => fetchSessionTimeseries(minutes), [minutes]),\n\t\t{ pollInterval: 2_000 },\n\t);\n\n\tconst { events } = useSSE();\n\n\t// Filter SSE events for session_sample pushes (Step 5) and trigger an\n\t// immediate refetch when a new sample arrives, so the chart updates\n\t// between the 2s polls. The events array grows as new samples arrive; the\n\t// length-based dependency means the effect re-runs when a new sample event\n\t// lands (not on every poll). We debounce via a microtask guard.\n\tconst sampleEvents = useMemo(\n\t\t() => events.filter(isSessionSample),\n\t\t[events],\n\t);\n\n\tconst lastSampleTs = useMemo(() => {\n\t\tif (sampleEvents.length === 0) return null;\n\t\treturn sampleEvents[sampleEvents.length - 1].ts;\n\t}, [sampleEvents]);\n\n\tuseEffect(() => {\n\t\tif (lastSampleTs == null) return;\n\t\trefetchSessions();\n\t\trefetchTimeseries();\n\t}, [lastSampleTs, refetchSessions, refetchTimeseries]);\n\n\tif (dash0bOn && view === \"turns\") {\n\t\treturn <TurnMemoryView />;\n\t}\n\n\tif (sessionsErr && !sessionsData) {\n\t\treturn (\n\t\t\t<div className=\"tab-stub\">\n\t\t\t\tError loading sessions: {sessionsErr.message}\n\t\t\t</div>\n\t\t);\n\t}\n\tif (timeseriesErr && !timeseriesData) {\n\t\treturn (\n\t\t\t<div className=\"tab-stub\">\n\t\t\t\tError loading timeseries: {timeseriesErr.message}\n\t\t\t</div>\n\t\t);\n\t}\n\tif (!sessionsData) {\n\t\treturn <div className=\"tab-stub\">Loading sessions…</div>;\n\t}\n\n\tconst sessions = sessionsData.sessions;\n\tconst series = timeseriesData?.series ?? [];\n\tconst totals = timeseriesData?.totals ?? [];\n\tconst windowLabel =\n\t\tWINDOWS.find((w) => w.value === minutes)?.label ?? `${minutes}m`;\n\n\treturn (\n\t\t<div className=\"flex flex-col gap-4\">\n\t\t\t<div className=\"flex items-center justify-between\">\n\t\t\t\t<h2 className=\"font-heading text-lg font-semibold\">\n\t\t\t\t\tSession Memory Graph\n\t\t\t\t</h2>\n\t\t\t\t<div className=\"flex gap-2\">\n\t\t\t\t\t{WINDOWS.map((w) => (\n\t\t\t\t\t\t<Toggle\n\t\t\t\t\t\t\tkey={w.value}\n\t\t\t\t\t\t\tpressed={minutes === w.value}\n\t\t\t\t\t\t\tonClick={() => setMinutes(w.value)}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{w.label}\n\t\t\t\t\t\t</Toggle>\n\t\t\t\t\t))}\n\t\t\t\t</div>\n\t\t\t</div>\n\n\t\t\t{dash0bOn && (\n\t\t\t\t<div\n\t\t\t\t\tclassName=\"flex items-center gap-2\"\n\t\t\t\t\trole=\"tablist\"\n\t\t\t\t\taria-label=\"Sessions views\"\n\t\t\t\t>\n\t\t\t\t\t<Toggle\n\t\t\t\t\t\tpressed={view === \"active\"}\n\t\t\t\t\t\tonClick={() => setView(\"active\")}\n\t\t\t\t\t>\n\t\t\t\t\t\tActive Sessions\n\t\t\t\t\t</Toggle>\n\t\t\t\t\t<Toggle\n\t\t\t\t\t\tpressed={view === \"turns\"}\n\t\t\t\t\t\tonClick={() => setView(\"turns\")}\n\t\t\t\t\t>\n\t\t\t\t\t\tTurn Memory\n\t\t\t\t\t</Toggle>\n\t\t\t\t</div>\n\t\t\t)}\n\n\t\t\t{sessions.length === 0 ? (\n\t\t\t\t<div className=\"text-sm text-muted-foreground\">No active sessions.</div>\n\t\t\t) : (\n\t\t\t\t<>\n\t\t\t\t\t<SummaryTiles sessions={sessionsData} />\n\t\t\t\t\t<SessionsMemoryChart series={series} totals={totals} />\n\t\t\t\t\t<h2 className=\"font-heading text-lg font-semibold\">\n\t\t\t\t\t\tActive Sessions\n\t\t\t\t\t</h2>\n\t\t\t\t\t<ActiveSessionsTable sessions={sessions} series={series} />\n\t\t\t\t\t<div className=\"text-xs text-muted-foreground\">\n\t\t\t\t\t\t{series.length} series · {totals.length} timestamps ·{\" \"}\n\t\t\t\t\t\t{windowLabel} window · updated{\" \"}\n\t\t\t\t\t\t{timeseriesData?.updatedAt ?? sessionsData.updatedAt}\n\t\t\t\t\t</div>\n\t\t\t\t</>\n\t\t\t)}\n\t\t</div>\n\t);\n}\n"],"names":["pivot","series","totals","map","sessionIds","s","pt","row","sid","a","b","fmtTs","ts","fmtTokens","value","n","gradId","sessionId","SessionsMemoryChart","data","useMemo","jsx","Card","CardContent","ResponsiveContainer","jsxs","AreaChart","CartesianGrid","XAxis","YAxis","v","Tooltip","Legend","Area","Line","HEADERS","fmtAge","ms","m","pctClass","pct","fmtPct","fmtWindow","tokens","window","Sparkline","points","color","min","range","w","h","stepX","segments","p","i","x","y","indexSeries","ActiveSessionsTable","sessions","seriesById","now","srs","sparkPts","d","isSessionSample","e","DASH_0B_KEY","dash0bEnabled","settings","cat","WINDOWS","SummaryTiles","active","combinedTokens","sum","maxWindow","max","combinedPct","SessionsTab","minutes","setMinutes","useState","view","setView","settingsData","useApi","useCallback","fetchSettings","dash0bOn","sessionsData","sessionsErr","refetchSessions","fetchSessions","timeseriesData","timeseriesErr","refetchTimeseries","fetchSessionTimeseries","events","useSSE","sampleEvents","lastSampleTs","useEffect","TurnMemoryView","windowLabel","Toggle","Fragment"],"mappings":"4aAoDA,SAASA,EACRC,EACAC,EACe,CACf,MAAMC,MAAU,IACVC,EAAaH,EAAO,IAAKI,GAAMA,EAAE,SAAS,EAEhD,UAAWA,KAAKJ,EACf,UAAWK,KAAMD,EAAE,KAAM,CACxB,IAAIE,EAAMJ,EAAI,IAAIG,EAAG,EAAE,EACvB,GAAI,CAACC,EAAK,CACTA,EAAM,CAAE,GAAID,EAAG,GAAI,MAAO,CAAA,EAC1B,UAAWE,KAAOJ,EAAYG,EAAIC,CAAG,EAAI,EACzCL,EAAI,IAAIG,EAAG,GAAIC,CAAG,CACnB,CACAA,EAAIF,EAAE,SAAS,EAAIC,EAAG,MACvB,CAED,UAAW,KAAKJ,EAAQ,CACvB,IAAIK,EAAMJ,EAAI,IAAI,EAAE,EAAE,EACtB,GAAI,CAACI,EAAK,CACTA,EAAM,CAAE,GAAI,EAAE,GAAI,MAAO,CAAA,EACzB,UAAWC,KAAOJ,EAAYG,EAAIC,CAAG,EAAI,EACzCL,EAAI,IAAI,EAAE,GAAII,CAAG,CAClB,CACAA,EAAI,MAAQ,EAAE,MACf,CAEA,MAAO,CAAC,GAAGJ,EAAI,OAAA,CAAQ,EAAE,KAAK,CAACM,EAAGC,IAAMD,EAAE,GAAKC,EAAE,EAAE,CACpD,CAEA,SAASC,EAAMC,EAAoB,CAClC,OAAO,IAAI,KAAKA,CAAE,EAAE,mBAAmB,CAAA,EAAI,CAC1C,KAAM,UACN,OAAQ,UACR,OAAQ,SAAA,CACR,CACF,CAEA,SAASC,EAAUC,EAAgC,CAClD,MAAMC,EAAI,OAAOD,CAAK,EACtB,OAAO,OAAO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AAtF,EAAAA,IAACoD,GAAA,CAAa,SAAUkB,CAAA,CAAc,EACtCtE,EAAAA,IAACH,EAAA,CAAoB,OAAAjB,EAAgB,OAAAC,CAAA,CAAgB,EACrDmB,EAAAA,IAAC,KAAA,CAAG,UAAU,qCAAqC,SAAA,kBAEnD,EACAA,EAAAA,IAACsC,GAAA,CAAoB,SAAAC,EAAoB,OAAA3D,CAAA,CAAgB,EACzDwB,EAAAA,KAAC,MAAA,CAAI,UAAU,gCACb,SAAA,CAAAxB,EAAO,OAAO,aAAWC,EAAO,OAAO,gBAAc,IACrDuG,EAAY,oBAAkB,IAC9BV,GAAgB,WAAaJ,EAAa,SAAA,CAAA,CAC5C,CAAA,CAAA,CACD,CAAA,EAEF,CAEF"}
@@ -1,3 +1,3 @@
1
- import{r as s,j as e,o as L,p as Z,q as ae,s as le,C as oe,t as ie,e as ee,v as de,w as D,x as F,y as ce,u as K,z as te,A as se}from"./index-CL6Af_JZ.js";import{C as ue}from"./ConfigTab-CbsdI5yj.js";import{S as me}from"./switch-0MNUTR9I.js";import{b as he,p as pe,d as fe}from"./client-extra-BShDrG99.js";import{V as xe}from"./VcStatusBadge-DyOagOVb.js";import{T as ge}from"./toggle-DHbWo-CW.js";function be(t){try{return new Date(t*1e3).toLocaleString()}catch{return"—"}}function ne({achievements:t}){const r=s.useRef(0),[n,l]=s.useState(null),a=t.reduce((o,c)=>Math.max(o,c.unlocked_at??0),0),i=r.current;s.useEffect(()=>{a>r.current&&(r.current=a)},[a]),s.useEffect(()=>{if(i>0&&a>i){const o=t.filter(c=>c.unlocked_at!=null&&(c.unlocked_at??0)>i);if(o.length>0){const c=o.map(h=>`${h.icon??""} ${h.title}`.trim()).join(", ")+" unlocked!";l(c);const f=setTimeout(()=>l(null),4e3);return()=>clearTimeout(f)}}},[t,a,i]);const u=t.filter(o=>!(o.hidden===1&&o.unlocked_at==null));return e.jsxs("div",{className:"ach-section",children:[n!=null&&e.jsx("div",{className:"ach-toast show",children:n}),e.jsxs("div",{className:"ach-tiles",children:[u.length===0&&e.jsx("span",{className:"repo-none",children:"no achievements yet"}),u.map(o=>{if(o.unlocked_at!=null){const c=i>0&&(o.unlocked_at??0)>i;return e.jsxs("div",{className:`ach-tile unlocked${c?" just-unlocked":""}`,children:[o.icon??""," ",o.title,e.jsxs("span",{className:"ach-detail",children:["unlocked ",be(o.unlocked_at)]})]},o.id)}return e.jsxs("div",{className:"ach-tile locked",children:["??? ",o.title]},o.id)})]})]})}function _(t){return(Math.round(t*10)/10).toString()+"%"}function V(t){return t!=null?new Date(t).toLocaleString():"—"}function q(t){return t&&typeof t=="object"?t:{}}function ye(t){return t.split("/").pop()||t}function $({title:t,rows:r,badge:n,renderValue:l}){return e.jsxs("div",{className:"lb-card",children:[e.jsxs("h3",{children:[t,n]}),r.length===0?e.jsx("div",{className:"lb-empty",children:"—"}):e.jsx("table",{children:e.jsx("tbody",{children:r.map((a,i)=>e.jsxs("tr",{children:[e.jsx("td",{title:a.repo_root,children:ye(a.repo_root)}),e.jsx("td",{className:"num",children:l(a)})]},`${a.repo_root}-${i}`))})})]})}function je(){const[t,r]=s.useState({}),[n,l]=s.useState(0),[a,i]=s.useState([]),[u,o]=s.useState(!1),[c,f]=s.useState(!0),[h,b]=s.useState(null),g=s.useRef(0),S=s.useCallback(async()=>{try{const[y,x,B,z,U,H]=await Promise.all([L({metric:"cache",limit:25}),L({metric:"dedupe",limit:25}),L({metric:"turns",limit:25}),L({metric:"mega_cache",limit:25}),L({metric:"repos",limit:1}),Z()]),P=z.find(I=>I.ts>g.current&&I.value>100);g.current>0&&P&&(b(`oopsie! cache went to ${Math.round(P.value)}% — MEGA CACHE 🥧`),setTimeout(()=>b(null),4e3)),z.length>0&&(g.current=Math.max(...z.map(I=>I.ts))),r({cache:y,dedupe:x,turns:B,mega_cache:z}),l(U[0]?.value??0),i(H)}catch{}finally{f(!1)}},[]);s.useEffect(()=>{let y=!0;const x=async()=>{y&&await S()};x();const B=setInterval(()=>void x(),15e3);return()=>{y=!1,clearInterval(B)}},[S]),s.useEffect(()=>{let y=!0;const x=async()=>{try{const z=await ae();y&&(o(!!z.game_mode_on),z.theme&&(document.documentElement.dataset.theme=z.theme))}catch{}};x();const B=setInterval(()=>void x(),15e3);return()=>{y=!1,clearInterval(B)}},[]);const C=t.mega_cache??[];let w=null,T=null;for(const y of C){(w==null||y.value>w)&&(w=y.value);const x=q(y.meta),B=x.firstSeenTs??x.firstSeen??y.ts;(T==null||B<T)&&(T=B)}const j=w!=null&&w>100,m=t.turns??[],v=m.reduce((y,x)=>Math.max(y,x.value),0),k=Math.floor(Math.log2(v+1))+1,N=(t.cache?.length??0)>0||(t.dedupe?.length??0)>0||m.length>0||C.length>0||n>0;return e.jsxs("div",{className:`game-tab${u?" game-mode-on":""}`,children:[h!=null&&e.jsx("div",{className:"mega-cache-toast show",children:h}),j&&e.jsxs("div",{className:"mega-cache-banner",children:["🥧"," MEGA CACHE! peak ",_(w)," — first reached ",V(T)]}),j&&e.jsxs("div",{className:"achievement-tile unlocked",children:["🏆"," Opie's Wild Ride",e.jsxs("span",{className:"ach-detail",children:["best ",_(w)," · first ",V(T)]})]}),e.jsx("h2",{children:"High Scores"}),!N&&!c&&e.jsx("div",{className:"game-empty",children:"No scores yet — run a session with game mode on."}),N&&e.jsxs("div",{className:"game-leaderboards",children:[e.jsx($,{title:"Cache %",rows:t.cache??[],renderValue:y=>_(y.value)}),e.jsx($,{title:"Dedupe (collapsed)",rows:t.dedupe??[],renderValue:y=>y.value.toLocaleString()}),e.jsx($,{title:"Turns",rows:m,badge:m.length>0?e.jsxs("span",{className:"lvl-badge",children:["LVL ",k]}):void 0,renderValue:y=>y.value.toLocaleString()}),e.jsx($,{title:"MEGA CACHE trophies",rows:C,renderValue:y=>e.jsxs(e.Fragment,{children:[_(y.value),e.jsx("span",{className:"lb-meta",children:V(q(y.meta).firstSeenTs??q(y.meta).firstSeen??y.ts)})]})})]}),n>0&&e.jsx("div",{className:"repos-badge-line",children:e.jsxs("span",{className:"repos-badge",children:[n," repos"]})}),e.jsx("h3",{children:"Achievements"}),e.jsx(ne,{achievements:a})]})}function ve(){const[t,r]=s.useState([]),[n,l]=s.useState(!0),[a,i]=s.useState(null),u=s.useCallback(async()=>{try{const o=await Z();r(o),i(null)}catch(o){i(o instanceof Error?o:new Error(String(o)))}finally{l(!1)}},[]);return s.useEffect(()=>{let o=!0;const c=async()=>{o&&await u()};c();const f=setInterval(()=>void c(),15e3);return()=>{o=!1,clearInterval(f)}},[u]),n&&t.length===0?e.jsx("div",{className:"tab-stub",children:"Loading achievements…"}):a&&t.length===0?e.jsxs("div",{className:"tab-stub",children:["Error: ",a.message]}):e.jsxs("div",{className:"achievements-tab",children:[e.jsx("h2",{children:"Achievements"}),e.jsx(ne,{achievements:t})]})}const A={section:{background:"#1a1a2e",borderRadius:"8px",padding:"1rem",marginBottom:"1rem",border:"1px solid #2a2a4e"},sectionTitle:{fontSize:"1.1rem",fontWeight:700,marginTop:0,marginBottom:"0.75rem",color:"#e0e0e0",borderBottom:"1px solid #333",paddingBottom:"0.5rem"},label:{fontWeight:600,color:"#a0a0c0",marginRight:"0.5rem"},value:{color:"#e0e0e0"},row:{marginBottom:"0.4rem",fontSize:"0.9rem"}};function Se(){const[t,r]=s.useState(null),[n,l]=s.useState(null),a=s.useCallback(()=>{le().then(r).catch(f=>l(f instanceof Error?f.message:String(f)))},[]);s.useEffect(()=>{a()},[a]),s.useEffect(()=>{const f=setInterval(a,3e4);return()=>clearInterval(f)},[a]);const i=t?.status==="ok",u=t?.status==="ok"?"Working":t?.status==="unreachable"?"Unreachable":"Error",o=i?"#4caf50":"#f44336",c=i?"✓":"✗";return e.jsxs("div",{style:A.section,children:[e.jsx("h3",{style:A.sectionTitle,children:"Embedder Health"}),n&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error: ",n]}),!t&&!n&&e.jsx("p",{style:{color:"#888",fontSize:"0.85rem"},children:"Probing embedder..."}),t&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:A.row,children:[e.jsxs("span",{style:{...A.label,color:`${o}`},children:[c," ",u,":"]}),e.jsxs("span",{style:A.value,children:[t.dim," dims"]}),t.latencyMs!==void 0&&e.jsxs("span",{style:{color:"#a0a0c0",marginLeft:"0.5rem"},children:["(",t.latencyMs.toFixed(1)," ms)"]})]}),e.jsxs("div",{style:A.row,children:[e.jsx("span",{style:A.label,children:"Endpoint:"}),e.jsx("span",{style:A.value,children:t.url??e.jsx("span",{style:{color:"#888"},children:"built-in (no URL)"})})]}),t.error&&e.jsx("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:t.error})]})]})}function we({title:t,children:r}){const[n,l]=s.useState(!0),a=`settings-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`;return e.jsxs("section",{className:"overflow-hidden rounded-xl border border-border bg-bg-elevated/40",children:[e.jsxs("button",{type:"button",onClick:()=>l(i=>!i),className:"flex w-full items-center justify-between rounded-t-xl bg-bg-elevated/60 px-4 py-3 text-left text-sm font-semibold text-foreground transition-colors hover:bg-bg-elevated","aria-expanded":n,"aria-controls":a,children:[e.jsx("span",{children:t}),e.jsx(oe,{className:ie("h-4 w-4 text-muted-foreground transition-transform",n&&"rotate-180"),"aria-hidden":"true"})]}),n&&e.jsx("div",{id:a,className:"divide-y divide-border px-4 py-1",children:r})]})}const ke="rounded-md border border-border bg-bg-elevated/50 px-2 py-1 text-sm outline-none transition-colors focus:border-primary disabled:cursor-not-allowed disabled:opacity-50";function Ce(){return e.jsx("span",{className:"ml-2 inline-flex items-center rounded-md border border-warning/40 bg-warning/15 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-warning",title:"Requires an LLM embedder (Ollama/HTTP) to be effective",children:"LLM"})}function Ee({setting:t,id:r,llmActive:n,saving:l,onUpdate:a}){const[i,u]=s.useState(null),o=t.requiresLlm&&!n,c=s.useRef(null);s.useEffect(()=>()=>{c.current&&clearTimeout(c.current)},[]);const f=s.useCallback(g=>{a(t.key,g).then(S=>u(S)).catch(S=>u(S instanceof Error?S.message:String(S)))},[a,t.key]),h=s.useCallback(g=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>f(g),500)},[f]),b=l||o;return e.jsxs("div",{className:"py-2.5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center text-sm font-semibold text-foreground",children:[e.jsx("label",{htmlFor:`${r}-input`,className:"cursor-pointer",children:t.label}),t.requiresLlm&&!n&&e.jsx(Ce,{})]}),e.jsx("div",{className:"mt-0.5 text-xs text-muted-foreground",children:t.description})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-2",children:t.type==="boolean"?e.jsx(me,{id:`${r}-input`,checked:!!t.value,disabled:b||o,onCheckedChange:g=>f(String(g)),"aria-label":t.label}):e.jsxs(e.Fragment,{children:[e.jsx("input",{id:`${r}-input`,type:t.type==="number"?"number":"text",defaultValue:String(t.value??""),min:t.min,max:t.max,disabled:b,onChange:g=>h(g.target.value),className:`${ke} ${t.type==="number"?"w-24":"w-56"}`}),t.unit&&e.jsx("span",{className:"text-xs text-muted-foreground",children:t.unit})]})})]}),i&&e.jsxs("p",{className:"mt-1 text-xs text-danger",children:["Error: ",i]})]})}function Re(){const[t,r]=s.useState(null),[n,l]=s.useState(null),[a,i]=s.useState(!1),[u,o]=s.useState(null),c=s.useCallback(()=>{ee().then(r).catch(h=>l(h instanceof Error?h.message:String(h)))},[]);s.useEffect(()=>{c()},[c]);const f=s.useCallback(async(h,b)=>{i(!0);try{const g=await de({key:h,value:b});return o(g.restartRequired?"Saved — restart pi to apply changes.":"Saved."),c(),null}catch(g){return g instanceof Error?g.message:String(g)}finally{i(!1)}},[c]);return e.jsxs("div",{className:"flex flex-col gap-3",children:[n&&e.jsxs("p",{className:"text-sm text-danger",children:["Error: ",n]}),!t&&!n&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading settings..."}),t?.categories.map(h=>e.jsx(we,{title:h.name,children:h.settings.map(b=>e.jsx(Ee,{setting:b,id:`${h.name.replace(/[^a-z0-9]+/gi,"-")}-${b.key}`,llmActive:t.llmActive,saving:a,onUpdate:f},b.key))},h.name)),u&&e.jsx("div",{className:"mt-1 rounded-md border border-warning/40 bg-warning/10 p-2 text-xs text-warning",role:"status",children:u})]})}const p={container:{padding:"1rem",maxWidth:"720px",margin:"0 auto",fontFamily:"system-ui, sans-serif",color:"#e0e0e0"},section:{background:"#1a1a2e",borderRadius:"8px",padding:"1rem",marginBottom:"1rem",border:"1px solid #2a2a4e"},sectionTitle:{fontSize:"1.1rem",fontWeight:700,marginTop:0,marginBottom:"0.75rem",color:"#e0e0e0",borderBottom:"1px solid #333",paddingBottom:"0.5rem"},label:{fontWeight:600,color:"#a0a0c0",marginRight:"0.5rem"},value:{color:"#e0e0e0"},row:{marginBottom:"0.4rem",fontSize:"0.9rem"},warning:{background:"#3a2a00",border:"1px solid #665500",borderRadius:"8px",padding:"0.75rem",marginTop:"0.5rem",color:"#ffcc00",fontSize:"0.85rem"},badge:{display:"inline-block",padding:"0.15rem 0.5rem",borderRadius:"4px",fontSize:"0.8rem",fontWeight:600,marginLeft:"0.5rem"},detectRow:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.5rem 0",borderBottom:"1px solid #2a2a4e"},button:{background:"#3a5a9f",color:"#fff",border:"none",borderRadius:"6px",padding:"0.5rem 1rem",cursor:"pointer",fontSize:"0.9rem",fontWeight:600}},Te="Saved; takes effect on next session start";function Ne({customUrl:t,setCustomUrl:r,applyEmbedder:n,configuring:l,inputEnabled:a,apiKeySet:i,embeddingDim:u,embeddingHeadersSet:o,allowRemoteEmbedder:c,configureResult:f,configureError:h}){const[b,g]=s.useState(""),[S,C]=s.useState(""),[w,T]=s.useState(!1),[j,m]=s.useState(""),[v,k]=s.useState(!1),[N,y]=s.useState(!1);return a&&!w&&typeof u=="string"&&(C(u),T(!0)),a&&!N&&typeof c=="boolean"&&(k(c),y(!0)),e.jsxs("div",{style:p.section,children:[e.jsx("h3",{style:p.sectionTitle,children:"Custom Endpoint (remote / third-party)"}),e.jsxs("p",{style:{fontSize:"0.85rem",color:"#a0a0c0",marginTop:0},children:["Point at any OpenAI-compatible embeddings API or hosted endpoint. This opts in to a non-loopback connection (sets"," ",e.jsx("code",{children:"MEGACOMPACT_ALLOW_REMOTE_EMBEDDER=1"}),") — your prompts' embedding requests will be sent to the URL you enter. Default is loopback-only."]}),e.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap",alignItems:"center"},children:[e.jsx("input",{type:"url",placeholder:"https://api.example.com/v1/embeddings",value:t,onChange:x=>r(x.target.value),style:{flex:"1 1 300px",background:"#12122a",color:"#e0e0e0",border:"1px solid #2a2a4e",borderRadius:"6px",padding:"0.4rem 0.6rem",fontSize:"0.85rem",fontFamily:"monospace"}}),a&&e.jsx("input",{type:"password",autoComplete:"new-password","aria-label":"API key (optional Bearer)",placeholder:"API key (optional Bearer)",value:b,onChange:x=>g(x.target.value),style:{flex:"1 1 300px",background:"#12122a",color:"#e0e0e0",border:"1px solid #2a2a4e",borderRadius:"6px",padding:"0.4rem 0.6rem",fontSize:"0.85rem",fontFamily:"monospace"}}),a&&i&&e.jsx("span",{style:{fontSize:"0.75rem",color:"#81c784",border:"1px solid #2a4e2a",borderRadius:"4px",padding:"0.15rem 0.45rem"},children:"API key saved"}),a&&o&&e.jsx("span",{style:{fontSize:"0.75rem",color:"#81c784",border:"1px solid #2a4e2a",borderRadius:"4px",padding:"0.15rem 0.45rem"},children:"Headers saved"}),e.jsx("button",{style:{...p.button,opacity:t?1:.4},onClick:()=>n("custom",t,b,S,j,v),disabled:!t||l!==null,children:l==="custom"?"Writing...":"Use Custom URL"})]}),a&&e.jsxs("div",{style:{marginTop:"0.75rem"},children:[e.jsxs("div",{style:{marginBottom:"0.5rem"},children:[e.jsx("label",{style:{...p.label,display:"block",marginBottom:"0.25rem"},children:"Embedding dim (optional)"}),e.jsx("input",{type:"number",min:1,placeholder:"e.g. 384",value:S,onChange:x=>C(x.target.value),style:{width:"200px",background:"#12122a",color:"#e0e0e0",border:"1px solid #2a2a4e",borderRadius:"6px",padding:"0.4rem 0.6rem",fontSize:"0.85rem",fontFamily:"monospace"}})]}),e.jsxs("div",{style:{marginBottom:"0.5rem"},children:[e.jsx("label",{style:{...p.label,display:"block",marginBottom:"0.25rem"},children:"Embedding headers (JSON, write-only — never re-displayed)"}),e.jsx("textarea",{placeholder:'{"Authorization": "Bearer ..."}',value:j,onChange:x=>m(x.target.value),"aria-label":"Embedding headers JSON (write-only — never re-displayed)",rows:2,style:{width:"100%",background:"#12122a",color:"#e0e0e0",border:"1px solid #2a2a4e",borderRadius:"6px",padding:"0.4rem 0.6rem",fontSize:"0.85rem",fontFamily:"monospace",resize:"vertical"}})]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.85rem"},children:[e.jsx("input",{type:"checkbox",checked:v,onChange:x=>k(x.target.checked),"aria-label":"Allow remote embedder (skips loopback-only check)"}),"Allow remote embedder (skips loopback-only check)"]})]}),h!==null&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem",marginTop:"0.5rem"},children:["Configure error: ",h]}),f!==null&&f.embedder==="custom"&&e.jsx("div",{style:p.warning,children:Te}),e.jsxs("div",{style:p.warning,children:[e.jsx("strong",{children:"Heads up:"})," a remote endpoint receives the text you embed (it does NOT receive your full conversation — only the strings passed to",e.jsx("code",{children:" embed()"})," for recall/dedup). Verify the endpoint's privacy policy before use."]})]})}function J(t){switch(t){case"trigram":return"TrigramEmbedder (heuristic, default)";case"http":return"HTTP Embedder (BYO localhost)";case"minilm":return"MiniLM (experimental)";default:return"Unknown"}}function Be(t){return t?.currentEmbedder!=="trigram"?null:e.jsxs("div",{style:p.warning,children:[e.jsx("strong",{children:"Note:"})," TrigramEmbedder is a heuristic-strength default embedder. It works without any setup but recall quality may be lower than a dedicated embedding backend. If you notice poor recall results, consider installing Ollama and running the"," ",e.jsx("code",{children:"/megasetup"})," command, or set"," ",e.jsx("code",{children:"MEGACOMPACT_EMBEDDING_URL"})," to point at your own localhost embedding server."]})}function G(t){const r=t?"#1a5a1a":"#3a1a1a",n=t?"#4caf50":"#f44336";return e.jsx("span",{style:{...p.badge,background:r,color:n},children:t?"Detected":"Not found"})}function Me({status:t,statusError:r}){return e.jsxs("div",{style:p.section,children:[e.jsx("h3",{style:p.sectionTitle,children:"Current Embedder Configuration"}),r&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error: ",r]}),t&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:p.row,children:[e.jsx("span",{style:p.label,children:"Active Embedder:"}),e.jsx("span",{style:p.value,children:J(t.currentEmbedder)})]}),"configuredEmbedder"in t&&t.configuredEmbedder!==t.currentEmbedder&&e.jsxs("div",{style:p.warning,children:[e.jsx("strong",{children:"Configured but not active:"})," ",J(t.configuredEmbedder)," is configured in .mega-compact.env but not yet loaded."," ",e.jsx("strong",{children:"Restart pi"})," to activate it.",t.configuredUrl&&e.jsxs(e.Fragment,{children:[" (",t.configuredUrl,")"]})]}),"restartRequired"in t&&t.restartRequired&&e.jsxs("div",{style:{...p.row,color:"#ff9800"},children:[e.jsx("span",{style:p.label,children:"Status:"}),e.jsx("span",{style:p.value,children:"Restart required to activate the configured embedder"})]}),e.jsxs("div",{style:p.row,children:[e.jsx("span",{style:p.label,children:"Embedding URL:"}),e.jsx("span",{style:p.value,children:t.embeddingUrl??e.jsx("span",{style:{color:"#888"},children:"not set"})})]}),e.jsxs("div",{style:p.row,children:[e.jsx("span",{style:p.label,children:"Embed Cache:"}),e.jsx("span",{style:p.value,children:t.embedCache??e.jsx("span",{style:{color:"#888"},children:"not set"})})]}),e.jsxs("div",{style:p.row,children:[e.jsx("span",{style:p.label,children:"MiniLM:"}),e.jsx("span",{style:p.value,children:t.minilm?"enabled":"disabled"})]}),Be(t)]}),!t&&!r&&e.jsx("p",{style:{color:"#888",fontSize:"0.85rem"},children:"Loading configuration..."})]})}function ze(){const[t,r]=s.useState(null),[n,l]=s.useState(null),[a,i]=s.useState(null),[u,o]=s.useState(null),[c,f]=s.useState(!1),[h,b]=s.useState(null),[g,S]=s.useState(null),[C,w]=s.useState(null),[T,j]=s.useState(""),[m,v]=s.useState(!1),k=s.useCallback(()=>{D().then(r).catch(x=>i(x instanceof Error?x.message:String(x)))},[]),N=s.useCallback((x,B,z,U,H,P)=>{b(x),w(null),S(null);const I="embeddingHeadersSet"in(t??{});F({embedder:x,url:B,embeddingEndpointUrl:B,embeddingApiKey:z,...I?{embeddingDim:U,embeddingHeaders:H,allowRemoteEmbedder:P}:{}}).then(O=>{S(O),b(null),k()}).catch(O=>{w(O instanceof Error?O.message:String(O)),b(null)})},[k,t]),y=s.useCallback(()=>{f(!0),o(null),ce().then(x=>{l(x),f(!1)}).catch(x=>{o(x instanceof Error?x.message:String(x)),f(!1)})},[]);return s.useEffect(()=>{k()},[k]),s.useEffect(()=>{m||t&&typeof t.embeddingEndpointUrl=="string"&&t.embeddingEndpointUrl.length>0&&(j(t.embeddingEndpointUrl),v(!0))},[t,m]),s.useEffect(()=>{const x=setInterval(k,5e3);return()=>clearInterval(x)},[k]),s.useEffect(()=>{y();const x=setInterval(y,5e3);return()=>clearInterval(x)},[y]),e.jsxs("div",{style:p.container,children:[e.jsx("h2",{style:{fontSize:"1.3rem",marginTop:0,marginBottom:"1rem"},children:"Embedder Setup"}),e.jsx(Se,{}),e.jsx(Me,{status:t,statusError:a}),e.jsxs("div",{style:p.section,children:[e.jsx("h3",{style:p.sectionTitle,children:"Local Embedder Detection"}),e.jsx("p",{style:{fontSize:"0.85rem",color:"#a0a0c0",marginTop:0},children:"Detect which local embedding backends are available on this machine. No software is installed — detection only."}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:p.detectRow,children:[e.jsx("span",{children:e.jsx("strong",{children:"Ollama"})}),n.ollama!==null?e.jsxs("span",{children:[G(n.ollama.installed),n.ollama.installed&&e.jsx("span",{style:{fontSize:"0.8rem",color:"#a0a0c0",marginLeft:"0.5rem"},children:n.ollama.running?`server running, ${n.ollama.models.length} model(s)`:"server not running"})]}):e.jsx("span",{style:{color:"#888",fontSize:"0.85rem"},children:"not checked"})]}),e.jsxs("div",{style:p.detectRow,children:[e.jsx("span",{children:e.jsx("strong",{children:"llama.cpp"})}),n.llamaCpp!==null?e.jsxs("span",{children:[G(n.llamaCpp.installed),n.llamaCpp.installed&&n.llamaCpp.detail&&e.jsx("span",{style:{fontSize:"0.8rem",color:"#a0a0c0",marginLeft:"0.5rem"},children:n.llamaCpp.detail})]}):e.jsx("span",{style:{color:"#888",fontSize:"0.85rem"},children:"not checked"})]}),e.jsxs("div",{style:p.detectRow,children:[e.jsx("span",{children:e.jsx("strong",{children:"ONNX Runtime"})}),n.onnx!==null?e.jsxs("span",{children:[G(n.onnx.installed),n.onnx.installed&&n.onnx.detail&&e.jsx("span",{style:{fontSize:"0.8rem",color:"#a0a0c0",marginLeft:"0.5rem"},children:n.onnx.detail})]}):e.jsx("span",{style:{color:"#888",fontSize:"0.85rem"},children:"not checked"})]}),n.error&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.8rem",marginTop:"0.5rem"},children:["Detection error: ",n.error]})]}),u&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error: ",u]}),e.jsxs("div",{style:{marginTop:"1rem"},children:[e.jsx("button",{style:p.button,onClick:y,disabled:c,children:c?"Detecting...":"Run Detection"}),e.jsxs("span",{style:{fontSize:"0.8rem",color:"#888",marginLeft:"0.75rem"},children:["Or run ",e.jsx("code",{children:"/megasetup"})," in the chat for an interactive wizard."]})]}),n&&e.jsxs("div",{style:{marginTop:"1rem",paddingTop:"0.75rem",borderTop:"1px solid #2a2a4e"},children:[e.jsx("div",{style:{fontSize:"0.9rem",fontWeight:600,marginBottom:"0.5rem"},children:"Configure"}),e.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:[e.jsx("button",{style:{...p.button,opacity:n.ollama?.installed?1:.4},onClick:()=>N("ollama"),disabled:!n.ollama?.installed||h!==null,children:h==="ollama"?"Writing...":"Use Ollama"}),e.jsx("button",{style:{...p.button,opacity:n.llamaCpp?.installed?1:.4},onClick:()=>N("llama"),disabled:!n.llamaCpp?.installed||h!==null,children:h==="llama"?"Writing...":"Use llama.cpp"}),e.jsx("button",{style:{...p.button,opacity:n.onnx?.installed?1:.4},onClick:()=>N("onnx"),disabled:!n.onnx?.installed||h!==null,children:h==="onnx"?"Writing...":"Use ONNX"}),e.jsx("button",{style:{...p.button,background:"#444"},onClick:()=>N("trigram"),disabled:h!==null,children:h==="trigram"?"Writing...":"Use Trigram (default)"})]}),g&&g.embedder!=="custom"&&e.jsx("div",{style:p.warning,children:g.alreadyActive?"Already active — no restart needed.":`Configured ${g.embedder}. Restart pi to activate (config written to ${g.envPath}).`}),C&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem",marginTop:"0.5rem"},children:["Configure error: ",C]})]})]}),e.jsx(Ne,{customUrl:T,setCustomUrl:j,applyEmbedder:N,configuring:h,inputEnabled:t!==null&&"embeddingApiKeySet"in t,apiKeySet:t?.embeddingApiKeySet===!0,embeddingDim:t?.embeddingDim,embeddingHeadersSet:t?.embeddingHeadersSet===!0,allowRemoteEmbedder:t?.allowRemoteEmbedder,configureResult:g,configureError:C}),e.jsxs("div",{style:p.section,children:[e.jsx("h3",{style:p.sectionTitle,children:"How to Upgrade"}),e.jsxs("ul",{style:{fontSize:"0.85rem",lineHeight:1.6,paddingLeft:"1.25rem"},children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Ollama:"})," Install from"," ",e.jsx("a",{href:"https://ollama.com",style:{color:"#6a9fff"},target:"_blank",rel:"noopener noreferrer",children:"ollama.com"}),", then ",e.jsx("code",{children:"ollama pull nomic-embed-text"})," and restart pi. Set ",e.jsx("code",{children:"MEGACOMPACT_EMBEDDING_URL=http://localhost:11434/api/embeddings"}),"."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"llama.cpp:"})," Build or install llama.cpp, run"," ",e.jsx("code",{children:"llama-server"})," with an embedding model, and set the URL accordingly."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"ONNX Runtime:"})," Run a local text-embeddings server (e.g. TEI) and click ",e.jsx("strong",{children:"Use ONNX"})," above. Default URL: ",e.jsx("code",{children:"http://localhost:8081/v1/embeddings"}),"."]})]})]}),e.jsxs("div",{style:p.section,children:[e.jsx("h3",{style:p.sectionTitle,children:"Settings"}),e.jsx(Re,{})]})]})}function W(t){return t>=1e6?`${(t/1e6).toFixed(2)}M`:t>=1e3?`${Math.round(t/1e3)}K`:String(t)}function Ae(t,r,n){if(t<=0)return"—";const a=(r>0?r:Math.ceil(t*.1))+Math.ceil(t*(n/100)),i=t-a;return i<=0?"0 (at risk)":`${W(i)} tokens`}function Y({label:t,value:r,min:n,max:l,step:a=1,onChange:i,warning:u}){return e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"font-medium text-fg-muted",children:t}),e.jsxs("span",{className:`font-mono ${u?"text-warning":"text-fg"}`,title:u,children:[r,"%"]})]}),e.jsx("input",{type:"range",min:n,max:l,step:a,value:r,onChange:o=>i(Number(o.target.value)),className:"threshold-slider w-full"}),u&&e.jsxs("p",{className:"text-[10px] text-warning",children:["⚠ ",u]})]})}function Ie({model:t,defaults:r,safetyRange:n,fireRange:l,onSave:a,onReset:i,saving:u}){const[o,c]=s.useState(t.threshold.safetyMarginPct),[f,h]=s.useState(t.threshold.firePointPct),[b,g]=s.useState(!1),[S,C]=s.useState(null);s.useEffect(()=>{c(t.threshold.safetyMarginPct),h(t.threshold.firePointPct),g(!1)},[t.threshold.safetyMarginPct,t.threshold.firePointPct]);const w=o<5?'Low safety margin — risks "conversation too long" errors when a single turn injects a large tool output between gate fires.':void 0,T=f>85?"High fire point — compaction may trigger close to the window cap; a single large turn can overshoot before the gate fires.":void 0,j=s.useCallback(async()=>{C(null);try{await a(t.modelId,o,f),g(!1)}catch(m){C(m instanceof Error?m.message:String(m))}},[t.modelId,o,f,a]);return e.jsxs("div",{className:"rounded-md border border-border bg-bg-elevated/30 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-semibold text-fg",children:t.modelName??t.modelId}),t.threshold.isOverride&&e.jsx("span",{className:"rounded border border-primary/40 bg-primary/15 px-1.5 py-0.5 text-[10px] font-semibold uppercase text-primary",title:"This model has a custom override (not the default)",children:"Override"})]}),e.jsxs("div",{className:"text-[11px] text-fg-muted",children:[t.provider," · ",W(t.contextWindow)," window ·"," ",W(t.maxTokens)," output"]})]}),e.jsxs("div",{className:"text-right text-[11px] text-fg-muted",children:[e.jsxs("div",{children:["Usable tail:"," ",e.jsx("span",{className:"font-mono text-fg",children:Ae(t.contextWindow,t.maxTokens,o)})]}),e.jsxs("div",{children:["Compaction fires at:"," ",e.jsx("span",{className:"font-mono text-fg",children:W(Math.ceil(t.contextWindow*(f/100)))})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsx(Y,{label:"Safety margin",value:o,min:n[0],max:n[1],onChange:m=>{c(m),g(!0)},warning:w}),e.jsx(Y,{label:"Fire point",value:f,min:l[0],max:l[1],onChange:m=>{h(m),g(!0)},warning:T})]}),e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsx("button",{type:"button",onClick:j,disabled:!b||u,className:"rounded-md bg-primary px-2.5 py-1 text-xs font-semibold text-primary-fg disabled:cursor-not-allowed disabled:opacity-50",children:b?"Save override":"Saved"}),t.threshold.isOverride&&e.jsxs("button",{type:"button",onClick:()=>i(t.modelId),disabled:u,className:"rounded-md border border-border px-2.5 py-1 text-xs text-fg-muted disabled:cursor-not-allowed disabled:opacity-50",children:["Reset to default (",r.safetyMarginPct,"% /"," ",r.firePointPct,"%)"]}),S&&e.jsx("span",{className:"text-[11px] text-error",children:S})]})]})}function Oe(){const[t,r]=s.useState(null),[n,l]=s.useState(!0),[a,i]=s.useState(null),[u,o]=s.useState(!1),c=s.useCallback(async()=>{try{i(null),r(await he())}catch(b){i(b instanceof Error?b.message:String(b))}finally{l(!1)}},[]);s.useEffect(()=>{c()},[c]);const f=s.useCallback(async(b,g,S)=>{o(!0);try{await pe({modelId:b,safetyMarginPct:g,firePointPct:S}),await c()}finally{o(!1)}},[c]),h=s.useCallback(async b=>{o(!0);try{await fe(b),await c()}finally{o(!1)}},[c]);return n?e.jsx("div",{className:"p-4 text-sm text-fg-muted",children:"Loading thresholds…"}):a?e.jsxs("div",{className:"p-4 text-sm text-error",children:["Error: ",a]}):t?e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"rounded-md border border-border bg-bg-elevated/20 p-3",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Per-Model Compaction Thresholds"}),e.jsxs("p",{className:"mt-1 text-[11px] text-fg-muted",children:["Tune when compaction fires + how much safety margin to reserve,",e.jsx("strong",{children:" per model"}),". Different providers' models range from 8K to 1M+ context — one global % is wrong. Defaults:"," ",e.jsxs("span",{className:"font-mono",children:[t.defaults.safetyMarginPct,"% safety"]})," ","/"," ",e.jsxs("span",{className:"font-mono",children:[t.defaults.firePointPct,"% fire"]}),". Values outside the safe band show warnings."]})]}),t.models.length===0?e.jsx("div",{className:"rounded-md border border-border p-4 text-sm text-fg-muted",children:"No models captured yet. Start a pi session in any repo to populate model snapshots, then return here to tune per-model thresholds."}):e.jsx("div",{className:"flex flex-col gap-3",children:t.models.map(b=>e.jsx(Ie,{model:b,defaults:t.defaults,safetyRange:t.defaults.safetyMarginRange,fireRange:t.defaults.firePointRange,onSave:f,onReset:h,saving:u},b.modelId))})]}):e.jsx("div",{className:"p-4 text-sm text-fg-muted",children:"No data."})}async function Le(){const t=await fetch("/api/setup-cortex-status");if(!t.ok)throw new Error(`setup-cortex status: ${t.status}`);return t.json()}async function De(t){const r=await fetch("/api/setup-cortex-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(r.ok)return{ok:!0,result:await r.json()};let n;try{n=await r.json()}catch{n={error:"disabled"}}return{ok:!1,status:r.status,error:n}}async function Pe(t){const r=await fetch(`/api/setup-cortex-action-log?name=${encodeURIComponent(t)}`);if(!r.ok)throw new Error(`setup-cortex action-log: ${r.status}`);return r.json()}function _e(t){return t===null?!0:t.enabled&&t.status!=="off"}function re(){const[t,r]=s.useState({loading:!0,error:null,data:null}),n=s.useCallback(()=>{r(l=>({...l,loading:!0})),Le().then(l=>r(a=>({...a,data:l,loading:!1,error:null}))).catch(l=>r(a=>({...a,loading:!1,error:l instanceof Error?l.message:String(l)})))},[]);return s.useEffect(()=>{n();const l=setInterval(n,5e3);return()=>clearInterval(l)},[n]),[t,n]}const d={container:{padding:"1rem",maxWidth:"720px",margin:"0 auto",fontFamily:"system-ui, sans-serif",color:"#e0e0e0"},section:{background:"#1a1a2e",borderRadius:"8px",padding:"1rem",marginBottom:"1rem",border:"1px solid #2a2a4e"},sectionTitle:{fontSize:"1.1rem",fontWeight:700,marginTop:0,marginBottom:"0.75rem",color:"#e0e0e0",borderBottom:"1px solid #333",paddingBottom:"0.5rem"},label:{fontWeight:600,color:"#a0a0c0",marginRight:"0.5rem"},value:{color:"#e0e0e0"},row:{marginBottom:"0.4rem",fontSize:"0.9rem"},warning:{background:"#3a2a00",border:"1px solid #665500",borderRadius:"8px",padding:"0.75rem",marginTop:"0.5rem",color:"#ffcc00",fontSize:"0.85rem"},blocked:{background:"#3a1a1a",border:"1px solid #662222",borderRadius:"8px",padding:"0.75rem",marginTop:"0.5rem",color:"#ff6666",fontSize:"0.85rem"},badge:{display:"inline-block",padding:"0.15rem 0.5rem",borderRadius:"4px",fontSize:"0.8rem",fontWeight:600,marginLeft:"0.5rem"},button:{background:"#3a5a9f",color:"#fff",border:"none",borderRadius:"6px",padding:"0.5rem 1rem",cursor:"pointer",fontSize:"0.9rem",fontWeight:600},buttonDanger:{background:"#6a2a2a",color:"#ffb3b3",border:"1px solid #662222",borderRadius:"6px",padding:"0.5rem 1rem",cursor:"pointer",fontSize:"0.9rem",fontWeight:600},blockerRow:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.6rem",borderRadius:"6px",marginBottom:"0.35rem",fontSize:"0.85rem"},blockerRowHighlighted:{background:"#3a1a1a",border:"1px solid #662222"},mono:{fontFamily:"ui-monospace, monospace",fontSize:"0.8rem"}};function $e(t){switch(t){case"A":return"A — qualified learned encoder asset";case"B":return"B — demoted (heuristic/trigram)";case"C":return"C — absent (asset not verified)";default:return"—"}}function We(t){const r=t==="qualified"?"#1a5a1a":t==="demoted"?"#3a3a1a":"#3a1a1a",n=t==="qualified"?"#4caf50":t==="demoted"?"#ffcc00":"#f44336";return e.jsx("span",{style:{...d.badge,background:r,color:n},children:t??"unknown"})}function Fe({data:t,error:r}){return e.jsxs("div",{style:d.section,children:[e.jsxs("h3",{style:d.sectionTitle,children:[e.jsx("span",{style:{marginRight:"0.5rem"},children:"Cortex Encoder"}),e.jsx(xe,{status:t?.status})]}),r&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error: ",r]}),!t&&!r&&e.jsx("p",{style:{color:"#888",fontSize:"0.85rem"},children:"Loading cortex status..."}),!t?.enabled&&e.jsx("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:"Cortex status disabled (VC9A off)."}),e.jsxs("div",{style:d.row,children:[e.jsx("span",{style:d.label,children:"Mode:"}),e.jsx("span",{style:d.value,children:$e(t?.encoderHealth.mode)})]}),e.jsxs("div",{style:d.row,children:[e.jsx("span",{style:d.label,children:"Asset digest prefix:"}),e.jsx("span",{style:{...d.value,...d.mono},children:t?.assetDigestPrefix??e.jsx("span",{style:{color:"#888"},children:"not available"})})]}),e.jsxs("div",{style:d.row,children:[e.jsx("span",{style:d.label,children:"Qualification:"}),We(t?.qualification.verdict)]}),(t?.qualification.thresholdFailures.length??0)>0&&e.jsxs("div",{style:d.warning,children:[e.jsx("strong",{children:"Threshold failure(s):"})," ",t?.qualification.thresholdFailures.join(", ")]}),t?.status==="awaiting_data"&&e.jsx("p",{style:{color:"#a0a0c0",fontSize:"0.85rem"},children:"Awaiting encoder data. Qualification will appear once an asset is present."}),t?.status==="deferred"&&e.jsx("p",{style:{color:"#a0a0c0",fontSize:"0.85rem"},children:"Encoder status deferred."})]})}function Ue(t){switch(t){case"blocker":return"#f44336";case"high":return"#ff9800";default:return"#a0a0c0"}}function He({blockers:t,highlight:r,darwinX64:n}){const l=r??[];return e.jsxs("div",{style:d.section,children:[e.jsxs("h3",{style:d.sectionTitle,children:["Open Hard-Gate Blockers",e.jsx("span",{style:{...d.badge,background:"#3a1a1a",color:"#f44336"},children:t.length})]}),t.length===0&&e.jsx("p",{style:{color:"#4caf50",fontSize:"0.85rem"},children:"No open hard-gate blockers."}),n?.demoted===!0&&e.jsxs("div",{style:d.blockerRow,"data-darwin-x64-demoted":"true",children:[e.jsx("span",{style:{...d.mono,fontWeight:700},children:"HG-4"}),e.jsx("span",{style:{flex:1,color:"#e0e0e0"},children:n.reason||"darwin-x64: demoted to WASM (reason unavailable)"}),e.jsx("span",{style:{color:"#ff9800"},children:"high"}),e.jsx("span",{style:{color:"#4caf50",fontStyle:"italic"},children:"diagnosed"})]}),t.map(a=>{const i=l.includes(a.id);return e.jsxs("div",{style:{...d.blockerRow,...i?d.blockerRowHighlighted:{}},children:[e.jsx("span",{style:{...d.mono,fontWeight:700},children:a.id}),e.jsx("span",{style:{flex:1,color:"#e0e0e0"},children:a.title}),e.jsx("span",{style:{color:Ue(a.severity)},children:a.severity}),e.jsx("span",{style:{color:"#a0a0c0",fontStyle:"italic"},children:i?"gates this action":a.status})]},a.id)}),l.length>0&&e.jsxs("div",{style:d.blocked,children:[e.jsx("strong",{children:"Blocked:"})," the requested action is gated by the highlighted open hard-gate item(s). It was not run."]})]})}const Ve=[{key:"fetch-model",label:"Fetch Model",desc:"Fetch the qualified encoder model asset",dangerous:!0,confirm:"Fetch the encoder model asset onto this host? (Gated by any open hard gate.)"},{key:"bench",label:"Bench Encoder",desc:"Benchmark the encoder runtime on this host",dangerous:!0,confirm:"Run an encoder benchmark on this host? (Gated by any open hard gate.)"},{key:"verify-asset",label:"Verify Asset",desc:"Re-verify the committed encoder asset",dangerous:!1,confirm:"Re-verify the committed encoder asset?"},{key:"install-native-ort",label:"Install Native ORT",desc:"Lazy-download + install the native onnxruntime binding",dangerous:!0,confirm:"Download + install the native onnxruntime binding on this host? (npm-mediated, sha256-verified; then re-qualified.)"}];function qe({data:t,onBlocked:r,onAction:n}){const[l,a]=s.useState(null),[i,u]=s.useState(null),[o,c]=s.useState(null),[f,h]=s.useState(!1),[b,g]=s.useState(null),S=s.useCallback(()=>{D().then(j=>{g(j),h(!1)}).catch(()=>{})},[]);s.useEffect(()=>{S();const j=setInterval(S,5e3);return()=>clearInterval(j)},[S]);const C=(b?.nativeOrtInstalledVersion??null)!==null,w=s.useCallback(async j=>{a(j.key),c(null),u(null),h(!1),r([]);try{const m=await De({action:j.key,confirm:!0});if(m.ok){const v=m.result;let k=null,N=null;try{const y=await Pe(v.logName);k=y.tail,N=y.complete}catch{}u({action:v.action,logName:v.logName,tail:k,complete:N,message:v.ok?`${v.action} completed (spawned: ${v.spawned})`:`${v.action} did not complete cleanly`,retest:v.nativeOrtRetestResult!=null?{verdict:v.nativeOrtRetestResult.verdict,p95Ms:v.nativeOrtRetestResult.p95Ms,rssMiB:v.nativeOrtRetestResult.rssMiB,backend:v.nativeOrtBackendEffective??null}:null}),n()}else m.error.error==="action_blocked_by_open_item"?(r(m.error.blockers),c("The action is blocked by an open hard-gate item and was not run.")):m.error.error==="confirmation_required"?c("The server rejected the action: explicit confirmation is required."):m.status===404?(h(!0),c("Setup Cortex actions are disabled (off).")):c(`Action failed (${m.status}).`)}catch(m){c(m instanceof Error?m.message:String(m))}finally{a(null)}},[r,n]),T=j=>{window.confirm(j.confirm)&&w(j)};return e.jsxs("div",{style:d.section,children:[e.jsx("h3",{style:d.sectionTitle,children:"Cortex Actions"}),Ve.filter(j=>j.key!=="install-native-ort"||!C).map(j=>{const m=l===j.key;return e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"0.5rem",padding:"0.5rem 0",borderBottom:"1px solid #2a2a4e"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontWeight:600},children:j.label}),e.jsx("div",{style:{fontSize:"0.8rem",color:"#a0a0c0"},children:j.desc})]}),e.jsx("button",{style:j.dangerous?d.buttonDanger:d.button,disabled:l!==null,onClick:()=>T(j),children:m?"Running…":"Run"})]},j.key)}),f&&e.jsx("div",{style:d.blocked,children:"Setup Cortex actions are disabled. Enable MEGACOMPACT_VC9B to run them."}),o&&!f&&e.jsx("p",{style:{color:"#f44336",fontSize:"0.85rem",marginTop:"0.5rem"},children:o}),i&&e.jsxs("div",{style:d.warning,"data-testid":"cortex-action-result",children:[e.jsxs("strong",{children:["Result (",i.action,"):"]})," ",i.message,i.logName&&e.jsxs("span",{style:{...d.mono,marginLeft:"0.5rem"},children:["log: ",i.logName]}),i.retest!==null&&e.jsxs("div",{style:{marginTop:"0.5rem",fontSize:"0.85rem",display:"flex",flexWrap:"wrap",gap:"0.75rem"},children:[e.jsxs("span",{style:d.label,children:["Re-qualified:"," ",e.jsx("span",{style:{color:"#4caf50",fontWeight:600},children:i.retest.verdict})]}),e.jsxs("span",{style:d.label,children:["p95: ",i.retest.p95Ms.toFixed(1)," ms"]}),e.jsxs("span",{style:d.label,children:["RSS: ",i.retest.rssMiB.toFixed(1)," MiB"]}),i.retest.backend!==null&&e.jsxs("span",{style:d.label,children:["backend: ",i.retest.backend]})]}),i.tail!==null&&e.jsxs("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:"0.75rem",maxHeight:"12rem",overflow:"auto",marginTop:"0.5rem"},children:[i.tail,i.complete===!1&&`
1
+ import{r as s,j as e,o as L,p as Z,q as ae,s as le,C as oe,t as ie,e as ee,v as de,w as D,x as F,y as ce,u as K,z as te,A as se}from"./index-iuxgtzEW.js";import{C as ue}from"./ConfigTab-C016XTNC.js";import{S as me}from"./switch-7EHEQMSP.js";import{b as he,p as pe,d as fe}from"./client-extra-CKNOGEz_.js";import{V as xe}from"./VcStatusBadge-ObhcIyfN.js";import{T as ge}from"./toggle-z1lWY4UM.js";function be(t){try{return new Date(t*1e3).toLocaleString()}catch{return"—"}}function ne({achievements:t}){const r=s.useRef(0),[n,l]=s.useState(null),a=t.reduce((o,c)=>Math.max(o,c.unlocked_at??0),0),i=r.current;s.useEffect(()=>{a>r.current&&(r.current=a)},[a]),s.useEffect(()=>{if(i>0&&a>i){const o=t.filter(c=>c.unlocked_at!=null&&(c.unlocked_at??0)>i);if(o.length>0){const c=o.map(h=>`${h.icon??""} ${h.title}`.trim()).join(", ")+" unlocked!";l(c);const f=setTimeout(()=>l(null),4e3);return()=>clearTimeout(f)}}},[t,a,i]);const u=t.filter(o=>!(o.hidden===1&&o.unlocked_at==null));return e.jsxs("div",{className:"ach-section",children:[n!=null&&e.jsx("div",{className:"ach-toast show",children:n}),e.jsxs("div",{className:"ach-tiles",children:[u.length===0&&e.jsx("span",{className:"repo-none",children:"no achievements yet"}),u.map(o=>{if(o.unlocked_at!=null){const c=i>0&&(o.unlocked_at??0)>i;return e.jsxs("div",{className:`ach-tile unlocked${c?" just-unlocked":""}`,children:[o.icon??""," ",o.title,e.jsxs("span",{className:"ach-detail",children:["unlocked ",be(o.unlocked_at)]})]},o.id)}return e.jsxs("div",{className:"ach-tile locked",children:["??? ",o.title]},o.id)})]})]})}function _(t){return(Math.round(t*10)/10).toString()+"%"}function V(t){return t!=null?new Date(t).toLocaleString():"—"}function q(t){return t&&typeof t=="object"?t:{}}function ye(t){return t.split("/").pop()||t}function $({title:t,rows:r,badge:n,renderValue:l}){return e.jsxs("div",{className:"lb-card",children:[e.jsxs("h3",{children:[t,n]}),r.length===0?e.jsx("div",{className:"lb-empty",children:"—"}):e.jsx("table",{children:e.jsx("tbody",{children:r.map((a,i)=>e.jsxs("tr",{children:[e.jsx("td",{title:a.repo_root,children:ye(a.repo_root)}),e.jsx("td",{className:"num",children:l(a)})]},`${a.repo_root}-${i}`))})})]})}function je(){const[t,r]=s.useState({}),[n,l]=s.useState(0),[a,i]=s.useState([]),[u,o]=s.useState(!1),[c,f]=s.useState(!0),[h,b]=s.useState(null),g=s.useRef(0),S=s.useCallback(async()=>{try{const[y,x,B,z,U,H]=await Promise.all([L({metric:"cache",limit:25}),L({metric:"dedupe",limit:25}),L({metric:"turns",limit:25}),L({metric:"mega_cache",limit:25}),L({metric:"repos",limit:1}),Z()]),P=z.find(I=>I.ts>g.current&&I.value>100);g.current>0&&P&&(b(`oopsie! cache went to ${Math.round(P.value)}% — MEGA CACHE 🥧`),setTimeout(()=>b(null),4e3)),z.length>0&&(g.current=Math.max(...z.map(I=>I.ts))),r({cache:y,dedupe:x,turns:B,mega_cache:z}),l(U[0]?.value??0),i(H)}catch{}finally{f(!1)}},[]);s.useEffect(()=>{let y=!0;const x=async()=>{y&&await S()};x();const B=setInterval(()=>void x(),15e3);return()=>{y=!1,clearInterval(B)}},[S]),s.useEffect(()=>{let y=!0;const x=async()=>{try{const z=await ae();y&&(o(!!z.game_mode_on),z.theme&&(document.documentElement.dataset.theme=z.theme))}catch{}};x();const B=setInterval(()=>void x(),15e3);return()=>{y=!1,clearInterval(B)}},[]);const C=t.mega_cache??[];let w=null,T=null;for(const y of C){(w==null||y.value>w)&&(w=y.value);const x=q(y.meta),B=x.firstSeenTs??x.firstSeen??y.ts;(T==null||B<T)&&(T=B)}const j=w!=null&&w>100,m=t.turns??[],v=m.reduce((y,x)=>Math.max(y,x.value),0),k=Math.floor(Math.log2(v+1))+1,N=(t.cache?.length??0)>0||(t.dedupe?.length??0)>0||m.length>0||C.length>0||n>0;return e.jsxs("div",{className:`game-tab${u?" game-mode-on":""}`,children:[h!=null&&e.jsx("div",{className:"mega-cache-toast show",children:h}),j&&e.jsxs("div",{className:"mega-cache-banner",children:["🥧"," MEGA CACHE! peak ",_(w)," — first reached ",V(T)]}),j&&e.jsxs("div",{className:"achievement-tile unlocked",children:["🏆"," Opie's Wild Ride",e.jsxs("span",{className:"ach-detail",children:["best ",_(w)," · first ",V(T)]})]}),e.jsx("h2",{children:"High Scores"}),!N&&!c&&e.jsx("div",{className:"game-empty",children:"No scores yet — run a session with game mode on."}),N&&e.jsxs("div",{className:"game-leaderboards",children:[e.jsx($,{title:"Cache %",rows:t.cache??[],renderValue:y=>_(y.value)}),e.jsx($,{title:"Dedupe (collapsed)",rows:t.dedupe??[],renderValue:y=>y.value.toLocaleString()}),e.jsx($,{title:"Turns",rows:m,badge:m.length>0?e.jsxs("span",{className:"lvl-badge",children:["LVL ",k]}):void 0,renderValue:y=>y.value.toLocaleString()}),e.jsx($,{title:"MEGA CACHE trophies",rows:C,renderValue:y=>e.jsxs(e.Fragment,{children:[_(y.value),e.jsx("span",{className:"lb-meta",children:V(q(y.meta).firstSeenTs??q(y.meta).firstSeen??y.ts)})]})})]}),n>0&&e.jsx("div",{className:"repos-badge-line",children:e.jsxs("span",{className:"repos-badge",children:[n," repos"]})}),e.jsx("h3",{children:"Achievements"}),e.jsx(ne,{achievements:a})]})}function ve(){const[t,r]=s.useState([]),[n,l]=s.useState(!0),[a,i]=s.useState(null),u=s.useCallback(async()=>{try{const o=await Z();r(o),i(null)}catch(o){i(o instanceof Error?o:new Error(String(o)))}finally{l(!1)}},[]);return s.useEffect(()=>{let o=!0;const c=async()=>{o&&await u()};c();const f=setInterval(()=>void c(),15e3);return()=>{o=!1,clearInterval(f)}},[u]),n&&t.length===0?e.jsx("div",{className:"tab-stub",children:"Loading achievements…"}):a&&t.length===0?e.jsxs("div",{className:"tab-stub",children:["Error: ",a.message]}):e.jsxs("div",{className:"achievements-tab",children:[e.jsx("h2",{children:"Achievements"}),e.jsx(ne,{achievements:t})]})}const A={section:{background:"#1a1a2e",borderRadius:"8px",padding:"1rem",marginBottom:"1rem",border:"1px solid #2a2a4e"},sectionTitle:{fontSize:"1.1rem",fontWeight:700,marginTop:0,marginBottom:"0.75rem",color:"#e0e0e0",borderBottom:"1px solid #333",paddingBottom:"0.5rem"},label:{fontWeight:600,color:"#a0a0c0",marginRight:"0.5rem"},value:{color:"#e0e0e0"},row:{marginBottom:"0.4rem",fontSize:"0.9rem"}};function Se(){const[t,r]=s.useState(null),[n,l]=s.useState(null),a=s.useCallback(()=>{le().then(r).catch(f=>l(f instanceof Error?f.message:String(f)))},[]);s.useEffect(()=>{a()},[a]),s.useEffect(()=>{const f=setInterval(a,3e4);return()=>clearInterval(f)},[a]);const i=t?.status==="ok",u=t?.status==="ok"?"Working":t?.status==="unreachable"?"Unreachable":"Error",o=i?"#4caf50":"#f44336",c=i?"✓":"✗";return e.jsxs("div",{style:A.section,children:[e.jsx("h3",{style:A.sectionTitle,children:"Embedder Health"}),n&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error: ",n]}),!t&&!n&&e.jsx("p",{style:{color:"#888",fontSize:"0.85rem"},children:"Probing embedder..."}),t&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:A.row,children:[e.jsxs("span",{style:{...A.label,color:`${o}`},children:[c," ",u,":"]}),e.jsxs("span",{style:A.value,children:[t.dim," dims"]}),t.latencyMs!==void 0&&e.jsxs("span",{style:{color:"#a0a0c0",marginLeft:"0.5rem"},children:["(",t.latencyMs.toFixed(1)," ms)"]})]}),e.jsxs("div",{style:A.row,children:[e.jsx("span",{style:A.label,children:"Endpoint:"}),e.jsx("span",{style:A.value,children:t.url??e.jsx("span",{style:{color:"#888"},children:"built-in (no URL)"})})]}),t.error&&e.jsx("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:t.error})]})]})}function we({title:t,children:r}){const[n,l]=s.useState(!0),a=`settings-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`;return e.jsxs("section",{className:"overflow-hidden rounded-xl border border-border bg-bg-elevated/40",children:[e.jsxs("button",{type:"button",onClick:()=>l(i=>!i),className:"flex w-full items-center justify-between rounded-t-xl bg-bg-elevated/60 px-4 py-3 text-left text-sm font-semibold text-foreground transition-colors hover:bg-bg-elevated","aria-expanded":n,"aria-controls":a,children:[e.jsx("span",{children:t}),e.jsx(oe,{className:ie("h-4 w-4 text-muted-foreground transition-transform",n&&"rotate-180"),"aria-hidden":"true"})]}),n&&e.jsx("div",{id:a,className:"divide-y divide-border px-4 py-1",children:r})]})}const ke="rounded-md border border-border bg-bg-elevated/50 px-2 py-1 text-sm outline-none transition-colors focus:border-primary disabled:cursor-not-allowed disabled:opacity-50";function Ce(){return e.jsx("span",{className:"ml-2 inline-flex items-center rounded-md border border-warning/40 bg-warning/15 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-warning",title:"Requires an LLM embedder (Ollama/HTTP) to be effective",children:"LLM"})}function Ee({setting:t,id:r,llmActive:n,saving:l,onUpdate:a}){const[i,u]=s.useState(null),o=t.requiresLlm&&!n,c=s.useRef(null);s.useEffect(()=>()=>{c.current&&clearTimeout(c.current)},[]);const f=s.useCallback(g=>{a(t.key,g).then(S=>u(S)).catch(S=>u(S instanceof Error?S.message:String(S)))},[a,t.key]),h=s.useCallback(g=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>f(g),500)},[f]),b=l||o;return e.jsxs("div",{className:"py-2.5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center text-sm font-semibold text-foreground",children:[e.jsx("label",{htmlFor:`${r}-input`,className:"cursor-pointer",children:t.label}),t.requiresLlm&&!n&&e.jsx(Ce,{})]}),e.jsx("div",{className:"mt-0.5 text-xs text-muted-foreground",children:t.description})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-2",children:t.type==="boolean"?e.jsx(me,{id:`${r}-input`,checked:!!t.value,disabled:b||o,onCheckedChange:g=>f(String(g)),"aria-label":t.label}):e.jsxs(e.Fragment,{children:[e.jsx("input",{id:`${r}-input`,type:t.type==="number"?"number":"text",defaultValue:String(t.value??""),min:t.min,max:t.max,disabled:b,onChange:g=>h(g.target.value),className:`${ke} ${t.type==="number"?"w-24":"w-56"}`}),t.unit&&e.jsx("span",{className:"text-xs text-muted-foreground",children:t.unit})]})})]}),i&&e.jsxs("p",{className:"mt-1 text-xs text-danger",children:["Error: ",i]})]})}function Re(){const[t,r]=s.useState(null),[n,l]=s.useState(null),[a,i]=s.useState(!1),[u,o]=s.useState(null),c=s.useCallback(()=>{ee().then(r).catch(h=>l(h instanceof Error?h.message:String(h)))},[]);s.useEffect(()=>{c()},[c]);const f=s.useCallback(async(h,b)=>{i(!0);try{const g=await de({key:h,value:b});return o(g.restartRequired?"Saved — restart pi to apply changes.":"Saved."),c(),null}catch(g){return g instanceof Error?g.message:String(g)}finally{i(!1)}},[c]);return e.jsxs("div",{className:"flex flex-col gap-3",children:[n&&e.jsxs("p",{className:"text-sm text-danger",children:["Error: ",n]}),!t&&!n&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading settings..."}),t?.categories.map(h=>e.jsx(we,{title:h.name,children:h.settings.map(b=>e.jsx(Ee,{setting:b,id:`${h.name.replace(/[^a-z0-9]+/gi,"-")}-${b.key}`,llmActive:t.llmActive,saving:a,onUpdate:f},b.key))},h.name)),u&&e.jsx("div",{className:"mt-1 rounded-md border border-warning/40 bg-warning/10 p-2 text-xs text-warning",role:"status",children:u})]})}const p={container:{padding:"1rem",maxWidth:"720px",margin:"0 auto",fontFamily:"system-ui, sans-serif",color:"#e0e0e0"},section:{background:"#1a1a2e",borderRadius:"8px",padding:"1rem",marginBottom:"1rem",border:"1px solid #2a2a4e"},sectionTitle:{fontSize:"1.1rem",fontWeight:700,marginTop:0,marginBottom:"0.75rem",color:"#e0e0e0",borderBottom:"1px solid #333",paddingBottom:"0.5rem"},label:{fontWeight:600,color:"#a0a0c0",marginRight:"0.5rem"},value:{color:"#e0e0e0"},row:{marginBottom:"0.4rem",fontSize:"0.9rem"},warning:{background:"#3a2a00",border:"1px solid #665500",borderRadius:"8px",padding:"0.75rem",marginTop:"0.5rem",color:"#ffcc00",fontSize:"0.85rem"},badge:{display:"inline-block",padding:"0.15rem 0.5rem",borderRadius:"4px",fontSize:"0.8rem",fontWeight:600,marginLeft:"0.5rem"},detectRow:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.5rem 0",borderBottom:"1px solid #2a2a4e"},button:{background:"#3a5a9f",color:"#fff",border:"none",borderRadius:"6px",padding:"0.5rem 1rem",cursor:"pointer",fontSize:"0.9rem",fontWeight:600}},Te="Saved; takes effect on next session start";function Ne({customUrl:t,setCustomUrl:r,applyEmbedder:n,configuring:l,inputEnabled:a,apiKeySet:i,embeddingDim:u,embeddingHeadersSet:o,allowRemoteEmbedder:c,configureResult:f,configureError:h}){const[b,g]=s.useState(""),[S,C]=s.useState(""),[w,T]=s.useState(!1),[j,m]=s.useState(""),[v,k]=s.useState(!1),[N,y]=s.useState(!1);return a&&!w&&typeof u=="string"&&(C(u),T(!0)),a&&!N&&typeof c=="boolean"&&(k(c),y(!0)),e.jsxs("div",{style:p.section,children:[e.jsx("h3",{style:p.sectionTitle,children:"Custom Endpoint (remote / third-party)"}),e.jsxs("p",{style:{fontSize:"0.85rem",color:"#a0a0c0",marginTop:0},children:["Point at any OpenAI-compatible embeddings API or hosted endpoint. This opts in to a non-loopback connection (sets"," ",e.jsx("code",{children:"MEGACOMPACT_ALLOW_REMOTE_EMBEDDER=1"}),") — your prompts' embedding requests will be sent to the URL you enter. Default is loopback-only."]}),e.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap",alignItems:"center"},children:[e.jsx("input",{type:"url",placeholder:"https://api.example.com/v1/embeddings",value:t,onChange:x=>r(x.target.value),style:{flex:"1 1 300px",background:"#12122a",color:"#e0e0e0",border:"1px solid #2a2a4e",borderRadius:"6px",padding:"0.4rem 0.6rem",fontSize:"0.85rem",fontFamily:"monospace"}}),a&&e.jsx("input",{type:"password",autoComplete:"new-password","aria-label":"API key (optional Bearer)",placeholder:"API key (optional Bearer)",value:b,onChange:x=>g(x.target.value),style:{flex:"1 1 300px",background:"#12122a",color:"#e0e0e0",border:"1px solid #2a2a4e",borderRadius:"6px",padding:"0.4rem 0.6rem",fontSize:"0.85rem",fontFamily:"monospace"}}),a&&i&&e.jsx("span",{style:{fontSize:"0.75rem",color:"#81c784",border:"1px solid #2a4e2a",borderRadius:"4px",padding:"0.15rem 0.45rem"},children:"API key saved"}),a&&o&&e.jsx("span",{style:{fontSize:"0.75rem",color:"#81c784",border:"1px solid #2a4e2a",borderRadius:"4px",padding:"0.15rem 0.45rem"},children:"Headers saved"}),e.jsx("button",{style:{...p.button,opacity:t?1:.4},onClick:()=>n("custom",t,b,S,j,v),disabled:!t||l!==null,children:l==="custom"?"Writing...":"Use Custom URL"})]}),a&&e.jsxs("div",{style:{marginTop:"0.75rem"},children:[e.jsxs("div",{style:{marginBottom:"0.5rem"},children:[e.jsx("label",{style:{...p.label,display:"block",marginBottom:"0.25rem"},children:"Embedding dim (optional)"}),e.jsx("input",{type:"number",min:1,placeholder:"e.g. 384",value:S,onChange:x=>C(x.target.value),style:{width:"200px",background:"#12122a",color:"#e0e0e0",border:"1px solid #2a2a4e",borderRadius:"6px",padding:"0.4rem 0.6rem",fontSize:"0.85rem",fontFamily:"monospace"}})]}),e.jsxs("div",{style:{marginBottom:"0.5rem"},children:[e.jsx("label",{style:{...p.label,display:"block",marginBottom:"0.25rem"},children:"Embedding headers (JSON, write-only — never re-displayed)"}),e.jsx("textarea",{placeholder:'{"Authorization": "Bearer ..."}',value:j,onChange:x=>m(x.target.value),"aria-label":"Embedding headers JSON (write-only — never re-displayed)",rows:2,style:{width:"100%",background:"#12122a",color:"#e0e0e0",border:"1px solid #2a2a4e",borderRadius:"6px",padding:"0.4rem 0.6rem",fontSize:"0.85rem",fontFamily:"monospace",resize:"vertical"}})]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.85rem"},children:[e.jsx("input",{type:"checkbox",checked:v,onChange:x=>k(x.target.checked),"aria-label":"Allow remote embedder (skips loopback-only check)"}),"Allow remote embedder (skips loopback-only check)"]})]}),h!==null&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem",marginTop:"0.5rem"},children:["Configure error: ",h]}),f!==null&&f.embedder==="custom"&&e.jsx("div",{style:p.warning,children:Te}),e.jsxs("div",{style:p.warning,children:[e.jsx("strong",{children:"Heads up:"})," a remote endpoint receives the text you embed (it does NOT receive your full conversation — only the strings passed to",e.jsx("code",{children:" embed()"})," for recall/dedup). Verify the endpoint's privacy policy before use."]})]})}function J(t){switch(t){case"trigram":return"TrigramEmbedder (heuristic, default)";case"http":return"HTTP Embedder (BYO localhost)";case"minilm":return"MiniLM (experimental)";default:return"Unknown"}}function Be(t){return t?.currentEmbedder!=="trigram"?null:e.jsxs("div",{style:p.warning,children:[e.jsx("strong",{children:"Note:"})," TrigramEmbedder is a heuristic-strength default embedder. It works without any setup but recall quality may be lower than a dedicated embedding backend. If you notice poor recall results, consider installing Ollama and running the"," ",e.jsx("code",{children:"/megasetup"})," command, or set"," ",e.jsx("code",{children:"MEGACOMPACT_EMBEDDING_URL"})," to point at your own localhost embedding server."]})}function G(t){const r=t?"#1a5a1a":"#3a1a1a",n=t?"#4caf50":"#f44336";return e.jsx("span",{style:{...p.badge,background:r,color:n},children:t?"Detected":"Not found"})}function Me({status:t,statusError:r}){return e.jsxs("div",{style:p.section,children:[e.jsx("h3",{style:p.sectionTitle,children:"Current Embedder Configuration"}),r&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error: ",r]}),t&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:p.row,children:[e.jsx("span",{style:p.label,children:"Active Embedder:"}),e.jsx("span",{style:p.value,children:J(t.currentEmbedder)})]}),"configuredEmbedder"in t&&t.configuredEmbedder!==t.currentEmbedder&&e.jsxs("div",{style:p.warning,children:[e.jsx("strong",{children:"Configured but not active:"})," ",J(t.configuredEmbedder)," is configured in .mega-compact.env but not yet loaded."," ",e.jsx("strong",{children:"Restart pi"})," to activate it.",t.configuredUrl&&e.jsxs(e.Fragment,{children:[" (",t.configuredUrl,")"]})]}),"restartRequired"in t&&t.restartRequired&&e.jsxs("div",{style:{...p.row,color:"#ff9800"},children:[e.jsx("span",{style:p.label,children:"Status:"}),e.jsx("span",{style:p.value,children:"Restart required to activate the configured embedder"})]}),e.jsxs("div",{style:p.row,children:[e.jsx("span",{style:p.label,children:"Embedding URL:"}),e.jsx("span",{style:p.value,children:t.embeddingUrl??e.jsx("span",{style:{color:"#888"},children:"not set"})})]}),e.jsxs("div",{style:p.row,children:[e.jsx("span",{style:p.label,children:"Embed Cache:"}),e.jsx("span",{style:p.value,children:t.embedCache??e.jsx("span",{style:{color:"#888"},children:"not set"})})]}),e.jsxs("div",{style:p.row,children:[e.jsx("span",{style:p.label,children:"MiniLM:"}),e.jsx("span",{style:p.value,children:t.minilm?"enabled":"disabled"})]}),Be(t)]}),!t&&!r&&e.jsx("p",{style:{color:"#888",fontSize:"0.85rem"},children:"Loading configuration..."})]})}function ze(){const[t,r]=s.useState(null),[n,l]=s.useState(null),[a,i]=s.useState(null),[u,o]=s.useState(null),[c,f]=s.useState(!1),[h,b]=s.useState(null),[g,S]=s.useState(null),[C,w]=s.useState(null),[T,j]=s.useState(""),[m,v]=s.useState(!1),k=s.useCallback(()=>{D().then(r).catch(x=>i(x instanceof Error?x.message:String(x)))},[]),N=s.useCallback((x,B,z,U,H,P)=>{b(x),w(null),S(null);const I="embeddingHeadersSet"in(t??{});F({embedder:x,url:B,embeddingEndpointUrl:B,embeddingApiKey:z,...I?{embeddingDim:U,embeddingHeaders:H,allowRemoteEmbedder:P}:{}}).then(O=>{S(O),b(null),k()}).catch(O=>{w(O instanceof Error?O.message:String(O)),b(null)})},[k,t]),y=s.useCallback(()=>{f(!0),o(null),ce().then(x=>{l(x),f(!1)}).catch(x=>{o(x instanceof Error?x.message:String(x)),f(!1)})},[]);return s.useEffect(()=>{k()},[k]),s.useEffect(()=>{m||t&&typeof t.embeddingEndpointUrl=="string"&&t.embeddingEndpointUrl.length>0&&(j(t.embeddingEndpointUrl),v(!0))},[t,m]),s.useEffect(()=>{const x=setInterval(k,5e3);return()=>clearInterval(x)},[k]),s.useEffect(()=>{y();const x=setInterval(y,5e3);return()=>clearInterval(x)},[y]),e.jsxs("div",{style:p.container,children:[e.jsx("h2",{style:{fontSize:"1.3rem",marginTop:0,marginBottom:"1rem"},children:"Embedder Setup"}),e.jsx(Se,{}),e.jsx(Me,{status:t,statusError:a}),e.jsxs("div",{style:p.section,children:[e.jsx("h3",{style:p.sectionTitle,children:"Local Embedder Detection"}),e.jsx("p",{style:{fontSize:"0.85rem",color:"#a0a0c0",marginTop:0},children:"Detect which local embedding backends are available on this machine. No software is installed — detection only."}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:p.detectRow,children:[e.jsx("span",{children:e.jsx("strong",{children:"Ollama"})}),n.ollama!==null?e.jsxs("span",{children:[G(n.ollama.installed),n.ollama.installed&&e.jsx("span",{style:{fontSize:"0.8rem",color:"#a0a0c0",marginLeft:"0.5rem"},children:n.ollama.running?`server running, ${n.ollama.models.length} model(s)`:"server not running"})]}):e.jsx("span",{style:{color:"#888",fontSize:"0.85rem"},children:"not checked"})]}),e.jsxs("div",{style:p.detectRow,children:[e.jsx("span",{children:e.jsx("strong",{children:"llama.cpp"})}),n.llamaCpp!==null?e.jsxs("span",{children:[G(n.llamaCpp.installed),n.llamaCpp.installed&&n.llamaCpp.detail&&e.jsx("span",{style:{fontSize:"0.8rem",color:"#a0a0c0",marginLeft:"0.5rem"},children:n.llamaCpp.detail})]}):e.jsx("span",{style:{color:"#888",fontSize:"0.85rem"},children:"not checked"})]}),e.jsxs("div",{style:p.detectRow,children:[e.jsx("span",{children:e.jsx("strong",{children:"ONNX Runtime"})}),n.onnx!==null?e.jsxs("span",{children:[G(n.onnx.installed),n.onnx.installed&&n.onnx.detail&&e.jsx("span",{style:{fontSize:"0.8rem",color:"#a0a0c0",marginLeft:"0.5rem"},children:n.onnx.detail})]}):e.jsx("span",{style:{color:"#888",fontSize:"0.85rem"},children:"not checked"})]}),n.error&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.8rem",marginTop:"0.5rem"},children:["Detection error: ",n.error]})]}),u&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error: ",u]}),e.jsxs("div",{style:{marginTop:"1rem"},children:[e.jsx("button",{style:p.button,onClick:y,disabled:c,children:c?"Detecting...":"Run Detection"}),e.jsxs("span",{style:{fontSize:"0.8rem",color:"#888",marginLeft:"0.75rem"},children:["Or run ",e.jsx("code",{children:"/megasetup"})," in the chat for an interactive wizard."]})]}),n&&e.jsxs("div",{style:{marginTop:"1rem",paddingTop:"0.75rem",borderTop:"1px solid #2a2a4e"},children:[e.jsx("div",{style:{fontSize:"0.9rem",fontWeight:600,marginBottom:"0.5rem"},children:"Configure"}),e.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:[e.jsx("button",{style:{...p.button,opacity:n.ollama?.installed?1:.4},onClick:()=>N("ollama"),disabled:!n.ollama?.installed||h!==null,children:h==="ollama"?"Writing...":"Use Ollama"}),e.jsx("button",{style:{...p.button,opacity:n.llamaCpp?.installed?1:.4},onClick:()=>N("llama"),disabled:!n.llamaCpp?.installed||h!==null,children:h==="llama"?"Writing...":"Use llama.cpp"}),e.jsx("button",{style:{...p.button,opacity:n.onnx?.installed?1:.4},onClick:()=>N("onnx"),disabled:!n.onnx?.installed||h!==null,children:h==="onnx"?"Writing...":"Use ONNX"}),e.jsx("button",{style:{...p.button,background:"#444"},onClick:()=>N("trigram"),disabled:h!==null,children:h==="trigram"?"Writing...":"Use Trigram (default)"})]}),g&&g.embedder!=="custom"&&e.jsx("div",{style:p.warning,children:g.alreadyActive?"Already active — no restart needed.":`Configured ${g.embedder}. Restart pi to activate (config written to ${g.envPath}).`}),C&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem",marginTop:"0.5rem"},children:["Configure error: ",C]})]})]}),e.jsx(Ne,{customUrl:T,setCustomUrl:j,applyEmbedder:N,configuring:h,inputEnabled:t!==null&&"embeddingApiKeySet"in t,apiKeySet:t?.embeddingApiKeySet===!0,embeddingDim:t?.embeddingDim,embeddingHeadersSet:t?.embeddingHeadersSet===!0,allowRemoteEmbedder:t?.allowRemoteEmbedder,configureResult:g,configureError:C}),e.jsxs("div",{style:p.section,children:[e.jsx("h3",{style:p.sectionTitle,children:"How to Upgrade"}),e.jsxs("ul",{style:{fontSize:"0.85rem",lineHeight:1.6,paddingLeft:"1.25rem"},children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Ollama:"})," Install from"," ",e.jsx("a",{href:"https://ollama.com",style:{color:"#6a9fff"},target:"_blank",rel:"noopener noreferrer",children:"ollama.com"}),", then ",e.jsx("code",{children:"ollama pull nomic-embed-text"})," and restart pi. Set ",e.jsx("code",{children:"MEGACOMPACT_EMBEDDING_URL=http://localhost:11434/api/embeddings"}),"."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"llama.cpp:"})," Build or install llama.cpp, run"," ",e.jsx("code",{children:"llama-server"})," with an embedding model, and set the URL accordingly."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"ONNX Runtime:"})," Run a local text-embeddings server (e.g. TEI) and click ",e.jsx("strong",{children:"Use ONNX"})," above. Default URL: ",e.jsx("code",{children:"http://localhost:8081/v1/embeddings"}),"."]})]})]}),e.jsxs("div",{style:p.section,children:[e.jsx("h3",{style:p.sectionTitle,children:"Settings"}),e.jsx(Re,{})]})]})}function W(t){return t>=1e6?`${(t/1e6).toFixed(2)}M`:t>=1e3?`${Math.round(t/1e3)}K`:String(t)}function Ae(t,r,n){if(t<=0)return"—";const a=(r>0?r:Math.ceil(t*.1))+Math.ceil(t*(n/100)),i=t-a;return i<=0?"0 (at risk)":`${W(i)} tokens`}function Y({label:t,value:r,min:n,max:l,step:a=1,onChange:i,warning:u}){return e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"font-medium text-fg-muted",children:t}),e.jsxs("span",{className:`font-mono ${u?"text-warning":"text-fg"}`,title:u,children:[r,"%"]})]}),e.jsx("input",{type:"range",min:n,max:l,step:a,value:r,onChange:o=>i(Number(o.target.value)),className:"threshold-slider w-full"}),u&&e.jsxs("p",{className:"text-[10px] text-warning",children:["⚠ ",u]})]})}function Ie({model:t,defaults:r,safetyRange:n,fireRange:l,onSave:a,onReset:i,saving:u}){const[o,c]=s.useState(t.threshold.safetyMarginPct),[f,h]=s.useState(t.threshold.firePointPct),[b,g]=s.useState(!1),[S,C]=s.useState(null);s.useEffect(()=>{c(t.threshold.safetyMarginPct),h(t.threshold.firePointPct),g(!1)},[t.threshold.safetyMarginPct,t.threshold.firePointPct]);const w=o<5?'Low safety margin — risks "conversation too long" errors when a single turn injects a large tool output between gate fires.':void 0,T=f>85?"High fire point — compaction may trigger close to the window cap; a single large turn can overshoot before the gate fires.":void 0,j=s.useCallback(async()=>{C(null);try{await a(t.modelId,o,f),g(!1)}catch(m){C(m instanceof Error?m.message:String(m))}},[t.modelId,o,f,a]);return e.jsxs("div",{className:"rounded-md border border-border bg-bg-elevated/30 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-semibold text-fg",children:t.modelName??t.modelId}),t.threshold.isOverride&&e.jsx("span",{className:"rounded border border-primary/40 bg-primary/15 px-1.5 py-0.5 text-[10px] font-semibold uppercase text-primary",title:"This model has a custom override (not the default)",children:"Override"})]}),e.jsxs("div",{className:"text-[11px] text-fg-muted",children:[t.provider," · ",W(t.contextWindow)," window ·"," ",W(t.maxTokens)," output"]})]}),e.jsxs("div",{className:"text-right text-[11px] text-fg-muted",children:[e.jsxs("div",{children:["Usable tail:"," ",e.jsx("span",{className:"font-mono text-fg",children:Ae(t.contextWindow,t.maxTokens,o)})]}),e.jsxs("div",{children:["Compaction fires at:"," ",e.jsx("span",{className:"font-mono text-fg",children:W(Math.ceil(t.contextWindow*(f/100)))})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsx(Y,{label:"Safety margin",value:o,min:n[0],max:n[1],onChange:m=>{c(m),g(!0)},warning:w}),e.jsx(Y,{label:"Fire point",value:f,min:l[0],max:l[1],onChange:m=>{h(m),g(!0)},warning:T})]}),e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsx("button",{type:"button",onClick:j,disabled:!b||u,className:"rounded-md bg-primary px-2.5 py-1 text-xs font-semibold text-primary-fg disabled:cursor-not-allowed disabled:opacity-50",children:b?"Save override":"Saved"}),t.threshold.isOverride&&e.jsxs("button",{type:"button",onClick:()=>i(t.modelId),disabled:u,className:"rounded-md border border-border px-2.5 py-1 text-xs text-fg-muted disabled:cursor-not-allowed disabled:opacity-50",children:["Reset to default (",r.safetyMarginPct,"% /"," ",r.firePointPct,"%)"]}),S&&e.jsx("span",{className:"text-[11px] text-error",children:S})]})]})}function Oe(){const[t,r]=s.useState(null),[n,l]=s.useState(!0),[a,i]=s.useState(null),[u,o]=s.useState(!1),c=s.useCallback(async()=>{try{i(null),r(await he())}catch(b){i(b instanceof Error?b.message:String(b))}finally{l(!1)}},[]);s.useEffect(()=>{c()},[c]);const f=s.useCallback(async(b,g,S)=>{o(!0);try{await pe({modelId:b,safetyMarginPct:g,firePointPct:S}),await c()}finally{o(!1)}},[c]),h=s.useCallback(async b=>{o(!0);try{await fe(b),await c()}finally{o(!1)}},[c]);return n?e.jsx("div",{className:"p-4 text-sm text-fg-muted",children:"Loading thresholds…"}):a?e.jsxs("div",{className:"p-4 text-sm text-error",children:["Error: ",a]}):t?e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"rounded-md border border-border bg-bg-elevated/20 p-3",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Per-Model Compaction Thresholds"}),e.jsxs("p",{className:"mt-1 text-[11px] text-fg-muted",children:["Tune when compaction fires + how much safety margin to reserve,",e.jsx("strong",{children:" per model"}),". Different providers' models range from 8K to 1M+ context — one global % is wrong. Defaults:"," ",e.jsxs("span",{className:"font-mono",children:[t.defaults.safetyMarginPct,"% safety"]})," ","/"," ",e.jsxs("span",{className:"font-mono",children:[t.defaults.firePointPct,"% fire"]}),". Values outside the safe band show warnings."]})]}),t.models.length===0?e.jsx("div",{className:"rounded-md border border-border p-4 text-sm text-fg-muted",children:"No models captured yet. Start a pi session in any repo to populate model snapshots, then return here to tune per-model thresholds."}):e.jsx("div",{className:"flex flex-col gap-3",children:t.models.map(b=>e.jsx(Ie,{model:b,defaults:t.defaults,safetyRange:t.defaults.safetyMarginRange,fireRange:t.defaults.firePointRange,onSave:f,onReset:h,saving:u},b.modelId))})]}):e.jsx("div",{className:"p-4 text-sm text-fg-muted",children:"No data."})}async function Le(){const t=await fetch("/api/setup-cortex-status");if(!t.ok)throw new Error(`setup-cortex status: ${t.status}`);return t.json()}async function De(t){const r=await fetch("/api/setup-cortex-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(r.ok)return{ok:!0,result:await r.json()};let n;try{n=await r.json()}catch{n={error:"disabled"}}return{ok:!1,status:r.status,error:n}}async function Pe(t){const r=await fetch(`/api/setup-cortex-action-log?name=${encodeURIComponent(t)}`);if(!r.ok)throw new Error(`setup-cortex action-log: ${r.status}`);return r.json()}function _e(t){return t===null?!0:t.enabled&&t.status!=="off"}function re(){const[t,r]=s.useState({loading:!0,error:null,data:null}),n=s.useCallback(()=>{r(l=>({...l,loading:!0})),Le().then(l=>r(a=>({...a,data:l,loading:!1,error:null}))).catch(l=>r(a=>({...a,loading:!1,error:l instanceof Error?l.message:String(l)})))},[]);return s.useEffect(()=>{n();const l=setInterval(n,5e3);return()=>clearInterval(l)},[n]),[t,n]}const d={container:{padding:"1rem",maxWidth:"720px",margin:"0 auto",fontFamily:"system-ui, sans-serif",color:"#e0e0e0"},section:{background:"#1a1a2e",borderRadius:"8px",padding:"1rem",marginBottom:"1rem",border:"1px solid #2a2a4e"},sectionTitle:{fontSize:"1.1rem",fontWeight:700,marginTop:0,marginBottom:"0.75rem",color:"#e0e0e0",borderBottom:"1px solid #333",paddingBottom:"0.5rem"},label:{fontWeight:600,color:"#a0a0c0",marginRight:"0.5rem"},value:{color:"#e0e0e0"},row:{marginBottom:"0.4rem",fontSize:"0.9rem"},warning:{background:"#3a2a00",border:"1px solid #665500",borderRadius:"8px",padding:"0.75rem",marginTop:"0.5rem",color:"#ffcc00",fontSize:"0.85rem"},blocked:{background:"#3a1a1a",border:"1px solid #662222",borderRadius:"8px",padding:"0.75rem",marginTop:"0.5rem",color:"#ff6666",fontSize:"0.85rem"},badge:{display:"inline-block",padding:"0.15rem 0.5rem",borderRadius:"4px",fontSize:"0.8rem",fontWeight:600,marginLeft:"0.5rem"},button:{background:"#3a5a9f",color:"#fff",border:"none",borderRadius:"6px",padding:"0.5rem 1rem",cursor:"pointer",fontSize:"0.9rem",fontWeight:600},buttonDanger:{background:"#6a2a2a",color:"#ffb3b3",border:"1px solid #662222",borderRadius:"6px",padding:"0.5rem 1rem",cursor:"pointer",fontSize:"0.9rem",fontWeight:600},blockerRow:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.6rem",borderRadius:"6px",marginBottom:"0.35rem",fontSize:"0.85rem"},blockerRowHighlighted:{background:"#3a1a1a",border:"1px solid #662222"},mono:{fontFamily:"ui-monospace, monospace",fontSize:"0.8rem"}};function $e(t){switch(t){case"A":return"A — qualified learned encoder asset";case"B":return"B — demoted (heuristic/trigram)";case"C":return"C — absent (asset not verified)";default:return"—"}}function We(t){const r=t==="qualified"?"#1a5a1a":t==="demoted"?"#3a3a1a":"#3a1a1a",n=t==="qualified"?"#4caf50":t==="demoted"?"#ffcc00":"#f44336";return e.jsx("span",{style:{...d.badge,background:r,color:n},children:t??"unknown"})}function Fe({data:t,error:r}){return e.jsxs("div",{style:d.section,children:[e.jsxs("h3",{style:d.sectionTitle,children:[e.jsx("span",{style:{marginRight:"0.5rem"},children:"Cortex Encoder"}),e.jsx(xe,{status:t?.status})]}),r&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error: ",r]}),!t&&!r&&e.jsx("p",{style:{color:"#888",fontSize:"0.85rem"},children:"Loading cortex status..."}),!t?.enabled&&e.jsx("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:"Cortex status disabled (VC9A off)."}),e.jsxs("div",{style:d.row,children:[e.jsx("span",{style:d.label,children:"Mode:"}),e.jsx("span",{style:d.value,children:$e(t?.encoderHealth.mode)})]}),e.jsxs("div",{style:d.row,children:[e.jsx("span",{style:d.label,children:"Asset digest prefix:"}),e.jsx("span",{style:{...d.value,...d.mono},children:t?.assetDigestPrefix??e.jsx("span",{style:{color:"#888"},children:"not available"})})]}),e.jsxs("div",{style:d.row,children:[e.jsx("span",{style:d.label,children:"Qualification:"}),We(t?.qualification.verdict)]}),(t?.qualification.thresholdFailures.length??0)>0&&e.jsxs("div",{style:d.warning,children:[e.jsx("strong",{children:"Threshold failure(s):"})," ",t?.qualification.thresholdFailures.join(", ")]}),t?.status==="awaiting_data"&&e.jsx("p",{style:{color:"#a0a0c0",fontSize:"0.85rem"},children:"Awaiting encoder data. Qualification will appear once an asset is present."}),t?.status==="deferred"&&e.jsx("p",{style:{color:"#a0a0c0",fontSize:"0.85rem"},children:"Encoder status deferred."})]})}function Ue(t){switch(t){case"blocker":return"#f44336";case"high":return"#ff9800";default:return"#a0a0c0"}}function He({blockers:t,highlight:r,darwinX64:n}){const l=r??[];return e.jsxs("div",{style:d.section,children:[e.jsxs("h3",{style:d.sectionTitle,children:["Open Hard-Gate Blockers",e.jsx("span",{style:{...d.badge,background:"#3a1a1a",color:"#f44336"},children:t.length})]}),t.length===0&&e.jsx("p",{style:{color:"#4caf50",fontSize:"0.85rem"},children:"No open hard-gate blockers."}),n?.demoted===!0&&e.jsxs("div",{style:d.blockerRow,"data-darwin-x64-demoted":"true",children:[e.jsx("span",{style:{...d.mono,fontWeight:700},children:"HG-4"}),e.jsx("span",{style:{flex:1,color:"#e0e0e0"},children:n.reason||"darwin-x64: demoted to WASM (reason unavailable)"}),e.jsx("span",{style:{color:"#ff9800"},children:"high"}),e.jsx("span",{style:{color:"#4caf50",fontStyle:"italic"},children:"diagnosed"})]}),t.map(a=>{const i=l.includes(a.id);return e.jsxs("div",{style:{...d.blockerRow,...i?d.blockerRowHighlighted:{}},children:[e.jsx("span",{style:{...d.mono,fontWeight:700},children:a.id}),e.jsx("span",{style:{flex:1,color:"#e0e0e0"},children:a.title}),e.jsx("span",{style:{color:Ue(a.severity)},children:a.severity}),e.jsx("span",{style:{color:"#a0a0c0",fontStyle:"italic"},children:i?"gates this action":a.status})]},a.id)}),l.length>0&&e.jsxs("div",{style:d.blocked,children:[e.jsx("strong",{children:"Blocked:"})," the requested action is gated by the highlighted open hard-gate item(s). It was not run."]})]})}const Ve=[{key:"fetch-model",label:"Fetch Model",desc:"Fetch the qualified encoder model asset",dangerous:!0,confirm:"Fetch the encoder model asset onto this host? (Gated by any open hard gate.)"},{key:"bench",label:"Bench Encoder",desc:"Benchmark the encoder runtime on this host",dangerous:!0,confirm:"Run an encoder benchmark on this host? (Gated by any open hard gate.)"},{key:"verify-asset",label:"Verify Asset",desc:"Re-verify the committed encoder asset",dangerous:!1,confirm:"Re-verify the committed encoder asset?"},{key:"install-native-ort",label:"Install Native ORT",desc:"Lazy-download + install the native onnxruntime binding",dangerous:!0,confirm:"Download + install the native onnxruntime binding on this host? (npm-mediated, sha256-verified; then re-qualified.)"}];function qe({data:t,onBlocked:r,onAction:n}){const[l,a]=s.useState(null),[i,u]=s.useState(null),[o,c]=s.useState(null),[f,h]=s.useState(!1),[b,g]=s.useState(null),S=s.useCallback(()=>{D().then(j=>{g(j),h(!1)}).catch(()=>{})},[]);s.useEffect(()=>{S();const j=setInterval(S,5e3);return()=>clearInterval(j)},[S]);const C=(b?.nativeOrtInstalledVersion??null)!==null,w=s.useCallback(async j=>{a(j.key),c(null),u(null),h(!1),r([]);try{const m=await De({action:j.key,confirm:!0});if(m.ok){const v=m.result;let k=null,N=null;try{const y=await Pe(v.logName);k=y.tail,N=y.complete}catch{}u({action:v.action,logName:v.logName,tail:k,complete:N,message:v.ok?`${v.action} completed (spawned: ${v.spawned})`:`${v.action} did not complete cleanly`,retest:v.nativeOrtRetestResult!=null?{verdict:v.nativeOrtRetestResult.verdict,p95Ms:v.nativeOrtRetestResult.p95Ms,rssMiB:v.nativeOrtRetestResult.rssMiB,backend:v.nativeOrtBackendEffective??null}:null}),n()}else m.error.error==="action_blocked_by_open_item"?(r(m.error.blockers),c("The action is blocked by an open hard-gate item and was not run.")):m.error.error==="confirmation_required"?c("The server rejected the action: explicit confirmation is required."):m.status===404?(h(!0),c("Setup Cortex actions are disabled (off).")):c(`Action failed (${m.status}).`)}catch(m){c(m instanceof Error?m.message:String(m))}finally{a(null)}},[r,n]),T=j=>{window.confirm(j.confirm)&&w(j)};return e.jsxs("div",{style:d.section,children:[e.jsx("h3",{style:d.sectionTitle,children:"Cortex Actions"}),Ve.filter(j=>j.key!=="install-native-ort"||!C).map(j=>{const m=l===j.key;return e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"0.5rem",padding:"0.5rem 0",borderBottom:"1px solid #2a2a4e"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontWeight:600},children:j.label}),e.jsx("div",{style:{fontSize:"0.8rem",color:"#a0a0c0"},children:j.desc})]}),e.jsx("button",{style:j.dangerous?d.buttonDanger:d.button,disabled:l!==null,onClick:()=>T(j),children:m?"Running…":"Run"})]},j.key)}),f&&e.jsx("div",{style:d.blocked,children:"Setup Cortex actions are disabled. Enable MEGACOMPACT_VC9B to run them."}),o&&!f&&e.jsx("p",{style:{color:"#f44336",fontSize:"0.85rem",marginTop:"0.5rem"},children:o}),i&&e.jsxs("div",{style:d.warning,"data-testid":"cortex-action-result",children:[e.jsxs("strong",{children:["Result (",i.action,"):"]})," ",i.message,i.logName&&e.jsxs("span",{style:{...d.mono,marginLeft:"0.5rem"},children:["log: ",i.logName]}),i.retest!==null&&e.jsxs("div",{style:{marginTop:"0.5rem",fontSize:"0.85rem",display:"flex",flexWrap:"wrap",gap:"0.75rem"},children:[e.jsxs("span",{style:d.label,children:["Re-qualified:"," ",e.jsx("span",{style:{color:"#4caf50",fontWeight:600},children:i.retest.verdict})]}),e.jsxs("span",{style:d.label,children:["p95: ",i.retest.p95Ms.toFixed(1)," ms"]}),e.jsxs("span",{style:d.label,children:["RSS: ",i.retest.rssMiB.toFixed(1)," MiB"]}),i.retest.backend!==null&&e.jsxs("span",{style:d.label,children:["backend: ",i.retest.backend]})]}),i.tail!==null&&e.jsxs("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:"0.75rem",maxHeight:"12rem",overflow:"auto",marginTop:"0.5rem"},children:[i.tail,i.complete===!1&&`
2
2
  … (truncated)`]})]}),!t?.enabled&&!f&&e.jsx("p",{style:{color:"#a0a0c0",fontSize:"0.8rem",marginTop:"0.5rem"},children:"Cortex status unavailable — actions may not be schedulable."})]})}const M={section:{background:"#1a1a2e",borderRadius:"8px",padding:"1rem",marginBottom:"1rem",border:"1px solid #2a2a4e"},sectionTitle:{fontSize:"1.1rem",fontWeight:700,marginTop:0,marginBottom:"0.25rem",color:"#e0e0e0"},subtitle:{fontSize:"0.85rem",color:"#a0a0c0",marginTop:0,marginBottom:"0.75rem"},row:{marginBottom:"0.4rem",fontSize:"0.9rem"},label:{fontWeight:600,color:"#a0a0c0",marginRight:"0.5rem"},value:{color:"#e0e0e0"},warning:{background:"#3a2a00",border:"1px solid #665500",borderRadius:"8px",padding:"0.75rem",marginTop:"0.5rem",color:"#ffcc00",fontSize:"0.85rem"},toggleRow:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.75rem",fontSize:"0.9rem"}},X=8192;function Ge(){const[t,r]=s.useState(null),[n,l]=s.useState(null),[a,i]=s.useState(!1),[u,o]=s.useState(""),[c,f]=s.useState(!1),h=s.useCallback(()=>{D().then(r).catch(m=>l(m instanceof Error?m.message:String(m)))},[]);s.useEffect(()=>{h()},[h]),s.useEffect(()=>{const m=setInterval(h,5e3);return()=>clearInterval(m)},[h]);const b=t!==null&&"encoderNativeOptIn"in t,g=t?.nativeOrtBudgetEffectiveMib;s.useEffect(()=>{if(!c&&t&&"nativeOrtBudgetEffectiveMib"in t){const m=t.nativeOrtBudgetMib??t.nativeOrtBudgetEffectiveMib??"";typeof m=="string"&&o(m),f(!0)}},[c,t]);const S=s.useCallback(m=>{i(!0),l(null),F({encoderNativeOptIn:m}).then(()=>{i(!1),h()}).catch(v=>{l(v instanceof Error?v.message:String(v)),i(!1)})},[h]),C=s.useCallback(()=>{const m=u.trim();if(!/^\d+$/.test(m)){l("Install budget must be a positive integer (MiB)");return}const v=Number(m);if(!Number.isSafeInteger(v)||v<1||v>X){l(`Install budget must be between 1 and ${X} MiB`);return}i(!0),l(null),F({nativeOrtBudgetMib:m}).then(()=>{i(!1),h()}).catch(k=>{l(k instanceof Error?k.message:String(k)),i(!1)})},[u,t,h]);if(!b)return e.jsx(e.Fragment,{});const w=t?.encoderBackend??"wasm",T=t?.encoderDemotionReason??null,j=t!==null&&"nativeOrtBudgetEffectiveMib"in t;return e.jsxs("div",{style:M.section,children:[e.jsx("h3",{style:M.sectionTitle,children:"Encoder Runtime"}),e.jsx("p",{style:M.subtitle,children:"ONNX backend selection"}),e.jsxs("div",{style:M.toggleRow,children:[e.jsx("input",{type:"checkbox",checked:t?.encoderNativeOptIn===!0,onChange:m=>S(m.target.checked),disabled:a,"aria-label":"Native ONNX runtime (onnxruntime-node)"}),e.jsx("label",{children:"Native ONNX runtime (onnxruntime-node)"}),a&&e.jsx("span",{style:{fontSize:"0.8rem",color:"#a0a0c0"},children:"saving..."})]}),e.jsxs("div",{style:M.row,children:[e.jsx("span",{style:M.label,children:"Effective backend (selected):"}),e.jsx("span",{style:M.value,children:w})]}),j&&e.jsxs("div",{style:M.row,children:[e.jsx("label",{htmlFor:"enc2-budget-input",style:{...M.label,marginRight:"0.5rem"},children:"Native install budget (MiB):"}),e.jsx("input",{id:"enc2-budget-input",type:"number",min:1,max:X,step:1,value:u,onChange:m=>o(m.target.value),disabled:a,style:{width:"6rem"},"aria-label":"Native onnxruntime install budget in MiB"}),e.jsx("button",{type:"button",onClick:C,disabled:a||u.trim().length===0,style:{marginLeft:"0.5rem"},children:"Save"}),g!==void 0&&e.jsxs("span",{style:{...M.value,marginLeft:"0.5rem"},children:["(effective: ",g," MiB)"]})]}),T!==null&&e.jsxs("div",{style:M.warning,children:[e.jsx("strong",{children:"Demoted:"})," ",T]}),n&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error: ",n]})]})}function Xe(){const[t,r]=s.useState(!1),n=s.useCallback(async l=>{try{await navigator.clipboard.writeText(l),r(!0),window.setTimeout(()=>r(!1),1500)}catch{r(!1)}},[]);return[t,n]}function Ke(){const[t,r]=s.useState(null),[n,l]=Xe(),a=s.useCallback(()=>{D().then(r).catch(()=>{})},[]);s.useEffect(()=>{a();const o=setInterval(a,5e3);return()=>clearInterval(o)},[a]);const i=t?.nativeOrtInstallGuide??null,u=t?.nativeOrtInstalledVersion??null;return i?e.jsxs("div",{style:d.section,children:[e.jsx("h3",{style:d.sectionTitle,children:"Encoder Runtime Install"}),e.jsxs("p",{style:{...d.label,fontSize:"0.85rem",marginBottom:"0.75rem"},children:["Platform: ",i.platform]}),u!==null&&e.jsxs("div",{style:d.row,children:[e.jsx("span",{style:d.label,children:"Detected:"}),e.jsx("span",{style:d.value,children:u})]}),i.commands.map((o,c)=>e.jsxs("div",{style:d.row,children:[e.jsxs("span",{style:d.label,children:["Step ",c+1,":"]}),e.jsx("code",{style:{...d.mono,display:"inline-block",marginTop:"0.15rem"},children:o}),e.jsx("button",{type:"button",onClick:()=>{l(o)},style:{marginLeft:"0.5rem",fontSize:"0.8rem"},children:"Copy"})]},`${c}-${o}`)),e.jsxs("p",{style:{...d.row,fontSize:"0.85rem"},children:[e.jsx("span",{style:d.label,children:"Script:"})," ",e.jsx("code",{style:d.mono,children:i.scriptPath})]}),n&&e.jsx("p",{style:{color:"#4caf50",fontSize:"0.8rem",margin:"0.25rem 0 0"},children:"Copied to clipboard"})]}):e.jsx(e.Fragment,{})}const Je={qualified:{...d.badge,background:"#1f3a2a",color:"#4caf50"},degraded:{...d.badge,background:"#3a2f00",color:"#ff9800"},failed:{...d.badge,background:"#3a1a1a",color:"#ff5252"}};function Ye(){const[t,r]=s.useState(null),[n,l]=s.useState(!1),a=s.useCallback(()=>{D().then(r).catch(()=>{})},[]);s.useEffect(()=>{a();const f=setInterval(a,5e3);return()=>clearInterval(f)},[a]);const i=s.useCallback(()=>{l(!0),F({embedder:"trigram",nativeOrtRetest:!0}).then(()=>a()).finally(()=>l(!1))},[a]),u=t?.nativeOrtInstalledVersion??null,o=t?.nativeOrtRetestResult??null,c=t?.nativeOrtBackendEffective??null;return u===null||o===null?e.jsx(e.Fragment,{}):e.jsxs("div",{style:d.section,children:[e.jsx("h3",{style:d.sectionTitle,children:"Encoder Runtime Retest"}),e.jsxs("div",{style:d.row,children:[e.jsx("span",{style:d.label,children:"Platform:"}),e.jsx("span",{style:d.value,children:o.platform})]}),e.jsxs("div",{style:d.row,children:[e.jsx("span",{style:d.label,children:"Version:"}),e.jsx("span",{style:d.value,children:o.version})]}),e.jsxs("div",{style:d.row,children:[e.jsx("span",{style:d.label,children:"Verdict:"}),e.jsx("span",{style:Je[o.verdict],children:o.verdict})]}),e.jsxs("div",{style:d.row,children:[e.jsx("span",{style:d.label,children:"p95 latency:"}),e.jsxs("span",{style:d.value,children:[o.p95Ms," ms"]})]}),e.jsxs("div",{style:d.row,children:[e.jsx("span",{style:d.label,children:"RSS:"}),e.jsxs("span",{style:d.value,children:[o.rssMiB," MiB"]})]}),e.jsxs("div",{style:d.row,children:[e.jsx("span",{style:d.label,children:"Tested:"}),e.jsx("span",{style:d.value,children:new Date(o.testedAt).toISOString()})]}),c!==null&&e.jsxs("div",{style:d.row,children:[e.jsx("span",{style:d.label,children:"Effective backend (measured):"}),e.jsx("span",{style:d.value,children:c})]}),c!==null&&t?.encoderBackend!=null&&c!==t.encoderBackend&&e.jsxs("p",{style:{fontSize:"0.8rem",color:"#a0a0c0",marginTop:"0.25rem"},children:["Measured backend differs from the selected backend above: the retest benchmarked the native binding and found it over the p95/RSS gates, so the runtime is demoted to ",e.jsx("strong",{children:c})," despite the binding being installed."]}),e.jsx("button",{type:"button",onClick:i,disabled:n,children:n?"Retesting…":"Retest now"})]})}const E={section:{background:"#1a1a2e",borderRadius:"8px",padding:"1rem",marginBottom:"1rem",border:"1px solid #2a2a4e"},sectionTitle:{fontSize:"1.1rem",fontWeight:700,marginTop:0,marginBottom:"0.25rem",color:"#e0e0e0"},subtitle:{fontSize:"0.85rem",color:"#a0a0c0",marginTop:0,marginBottom:"0.75rem"},row:{marginBottom:"0.4rem",fontSize:"0.9rem"},label:{fontWeight:600,color:"#a0a0c0",marginRight:"0.5rem"},value:{color:"#e0e0e0"},disabled:{background:"#1a1a2e",border:"1px solid #2a2a4e",borderRadius:"8px",padding:"1rem",marginBottom:"1rem",color:"#a0a0c0",fontSize:"0.85rem"}},Qe=()=>{const{data:t,error:r,loading:n}=K(s.useMemo(()=>()=>te("/api/cosine-fp-report").catch(l=>{if(l instanceof se&&l.status===404)return null;throw l}),[]),{pollInterval:5e3});return t===null&&!r&&!n?e.jsx("div",{style:E.disabled,children:"Cosine FP synthetic bench: disabled (MEGACOMPACT_COSINE_FP_BENCH=0)."}):e.jsxs("div",{style:E.section,children:[e.jsx("h3",{style:E.sectionTitle,children:"Cosine FP threshold"}),e.jsx("p",{style:E.subtitle,children:"Last synthetic bench threshold recommendation"}),r!==null?e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error loading report: ",r.message]}):t===null?e.jsx("div",{style:E.value,children:"Loading…"}):e.jsxs("div",{children:[e.jsxs("div",{style:E.row,children:[e.jsx("span",{style:E.label,children:"Recommended default:"}),e.jsxs("span",{style:E.value,children:[t.recommendedDefault??"—"," (shipped"," ",t.shippedDefault,")"]})]}),e.jsxs("div",{style:E.row,children:[e.jsx("span",{style:E.label,children:"Overrides:"}),e.jsxs("span",{style:E.value,children:["CODE ",t.overrides?.code??"—"," · PROSE"," ",t.overrides?.prose??"—"," · MIXED"," ",t.overrides?.mixed??"—"]})]}),e.jsxs("div",{style:E.row,children:[e.jsx("span",{style:E.label,children:"Grid:"}),e.jsx("span",{style:E.value,children:t.grid?`${t.grid.lo} → ${t.grid.hi} (${t.grid.points} points)`:"—"})]}),e.jsxs("div",{style:E.row,children:[e.jsx("span",{style:E.label,children:"Report digest:"}),e.jsx("span",{style:E.value,title:t.digest??void 0,children:t.digest?t.digest.slice(0,16)+"…":"—"})]})]})]})},R={section:{background:"#1a1a2e",borderRadius:"8px",padding:"1rem",marginBottom:"1rem",border:"1px solid #2a2a4e"},sectionTitle:{fontSize:"1.1rem",fontWeight:700,marginTop:0,marginBottom:"0.25rem",color:"#e0e0e0"},subtitle:{fontSize:"0.85rem",color:"#a0a0c0",marginTop:0,marginBottom:"0.75rem"},row:{marginBottom:"0.4rem",fontSize:"0.9rem"},label:{fontWeight:600,color:"#a0a0c0",marginRight:"0.5rem"},value:{color:"#e0e0e0"},disabled:{background:"#1a1a2e",border:"1px solid #2a2a4e",borderRadius:"8px",padding:"1rem",marginBottom:"1rem",color:"#a0a0c0",fontSize:"0.85rem"}},Ze=()=>{const{data:t,error:r,loading:n}=K(s.useMemo(()=>()=>te("/api/repo-corpus").catch(l=>{if(l instanceof se&&l.status===404)return null;throw l}),[]),{pollInterval:5e3});return t===null&&!r&&!n?e.jsx("div",{style:R.disabled,children:"Cross-repo corpus: disabled (MEGACOMPACT_REPO_CORPUS=0)."}):e.jsxs("div",{style:R.section,children:[e.jsx("h3",{style:R.sectionTitle,children:"Cross-Repo Corpus"}),e.jsx("p",{style:R.subtitle,children:"Pseudonymous consent status across donated repos"}),r!==null?e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error loading corpus: ",r.message]}):t===null?e.jsx("div",{style:R.value,children:"Loading…"}):e.jsxs("div",{children:[e.jsxs("div",{style:R.row,children:[e.jsx("span",{style:R.label,children:"Status:"}),e.jsx("span",{style:R.value,children:t.status})]}),e.jsxs("div",{style:R.row,children:[e.jsx("span",{style:R.label,children:"Total events:"}),e.jsx("span",{style:R.value,children:t.totalEvents})]}),e.jsxs("div",{style:R.row,children:[e.jsx("span",{style:R.label,children:"Overlap pairs:"}),e.jsx("span",{style:R.value,children:t.corpus?t.corpus.overlaps.length:0})]}),e.jsx("div",{style:{marginTop:"0.5rem"},children:(t.perRepo??[]).map(l=>e.jsxs("div",{style:R.row,children:[e.jsxs("span",{style:R.label,children:[l.repoPseudonym.slice(0,8),":"]}),e.jsxs("span",{style:R.value,children:[l.sessions," sessions ·"," ",l.consentedCrossRepo?l.revokedAt?`revoked ${l.revokedAt}`:"consented":"not consented"]})]},l.repoPseudonym))})]})]})};function et(){const[t,r]=re(),[n,l]=s.useState([]),a=s.useCallback(u=>{l(u)},[]),i=s.useCallback(()=>{r()},[r]);return e.jsxs("div",{style:d.container,children:[e.jsx("h2",{style:{fontSize:"1.3rem",marginTop:0,marginBottom:"1rem"},children:"Setup Cortex"}),e.jsx("p",{style:{fontSize:"0.85rem",color:"#a0a0c0",marginTop:0},children:"Vector-cortex encoder gate: mode, qualification, open hard-gate blockers, and the confirmation-gated fetch/bench/verify actions."}),e.jsx(Fe,{data:t.data,error:t.error}),e.jsx(Ge,{}),e.jsx(Ke,{}),e.jsx(Ye,{}),e.jsx(Qe,{}),e.jsx(Ze,{}),e.jsx(He,{blockers:t.data?.blockers??[],highlight:n,darwinX64:t.data?.darwinX64}),e.jsx(qe,{data:t.data,onBlocked:a,onAction:i})]})}const tt="MEGACOMPACT_DASH_0C";function st(t){if(!t)return!1;for(const r of t.categories)for(const n of r.settings)if(n.key===tt&&n.type==="boolean")return n.value===!0;return!1}const Q=[{id:"embedder",label:"Embedder"},{id:"thresholds",label:"Thresholds"},{id:"config",label:"Config"},{id:"game",label:"Game Mode"},{id:"achievements",label:"Achievements"}],nt={id:"cortex",label:"Cortex"};function ct(){const[t,r]=s.useState("embedder"),[n]=re(),{data:l}=K(s.useCallback(()=>ee(),[]),{pollInterval:0,maxRetries:0}),a=st(l),i=s.useMemo(()=>{const u=a?Q.filter(o=>o.id!=="config"):[...Q];return _e(n.data)&&u.push(nt),u},[n.data,a]);return e.jsxs("div",{className:"mx-auto flex max-w-3xl flex-col gap-4 p-4",children:[e.jsx("nav",{className:"flex gap-2 border-b border-border pb-2","aria-label":"Setup sections",children:i.map(u=>e.jsx(ge,{pressed:t===u.id,onClick:()=>r(u.id),children:u.label},u.id))}),t==="embedder"&&e.jsx(ze,{}),t==="thresholds"&&e.jsx(Oe,{}),t==="config"&&!a&&e.jsx(ue,{}),t==="game"&&e.jsx(je,{}),t==="achievements"&&e.jsx(ve,{}),t==="cortex"&&e.jsx(et,{})]})}export{ct as default};
3
- //# sourceMappingURL=SetupTab-Bqibg0cD.js.map
3
+ //# sourceMappingURL=SetupTab-CCyWgy4O.js.map