pi-mega-compact 0.20.32 → 0.20.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/config/vector-cortex-pcc.js +30 -0
- package/dist/config/vector-cortex.js +2 -2
- package/dist/config.js +1 -1
- package/dist/extensions/dashboard-server/api-contracts/endpoints/registry-ext.js +7 -0
- package/dist/extensions/dashboard-server/api-contracts/prefix-stability.js +8 -0
- package/dist/extensions/dashboard-server/route-dispatch.js +3 -1
- package/dist/extensions/dashboard-server/routes-prefix-stability.js +132 -0
- package/dist/extensions/dashboard-server/routes-rag-settings-vector-cortex.js +1 -0
- package/dist/extensions/dashboard-server/routes.js +1 -0
- package/dist/extensions/mega-events/context-handler/tailResult.js +5 -1
- package/dist/src/config/vector-cortex-pcc.js +30 -0
- package/dist/src/config/vector-cortex.js +2 -2
- package/dist/src/config.js +1 -1
- package/extensions/dashboard-client/dist/assets/{AreaChart-EL8l2Fcj.js → AreaChart-DjXp8u2Y.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{AreaChart-EL8l2Fcj.js.map → AreaChart-DjXp8u2Y.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{BarChart-TrwfSh0w.js → BarChart-BZbus-dR.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{BarChart-TrwfSh0w.js.map → BarChart-BZbus-dR.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/CacheTab-DQ2CjxVW.js +2 -0
- package/extensions/dashboard-client/dist/assets/CacheTab-DQ2CjxVW.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{EventsTab-CNrT-b7t.js → EventsTab-DUpnOV1p.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{EventsTab-CNrT-b7t.js.map → EventsTab-DUpnOV1p.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{HealthTab-CkBCFPk6.js → HealthTab-Bul_xjcn.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{HealthTab-CkBCFPk6.js.map → HealthTab-Bul_xjcn.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{MaintenanceTab-CcbKszwx.js → MaintenanceTab-DLUjdKd3.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{MaintenanceTab-CcbKszwx.js.map → MaintenanceTab-DLUjdKd3.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{MemoryMapTab-B2LvwScj.js → MemoryMapTab-BFy0hb6F.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{MemoryMapTab-B2LvwScj.js.map → MemoryMapTab-BFy0hb6F.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{MetricsTab-Dv_xZtOG.js → MetricsTab-BpYuUkq3.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{MetricsTab-Dv_xZtOG.js.map → MetricsTab-BpYuUkq3.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{OverviewTab-D7xwhpOl.js → OverviewTab-z7yuT-uq.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{OverviewTab-D7xwhpOl.js.map → OverviewTab-z7yuT-uq.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{ReposTab-BfhiPXdA.js → ReposTab-ClORoDy_.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{ReposTab-BfhiPXdA.js.map → ReposTab-ClORoDy_.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{SessionsTab-tQM0TQLp.js → SessionsTab-CUpehIt9.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{SessionsTab-tQM0TQLp.js.map → SessionsTab-CUpehIt9.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/SetupTab-Cii80Fdz.js +3 -0
- package/extensions/dashboard-client/dist/assets/{SetupTab-G-MkdQiR.js.map → SetupTab-Cii80Fdz.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{TimeSavedCard-CYltysD3.js → TimeSavedCard-BV2iCSdV.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{TimeSavedCard-CYltysD3.js.map → TimeSavedCard-BV2iCSdV.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{TurnsTab-1Y_Lpxx-.js → TurnsTab-1T86rHnD.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{TurnsTab-1Y_Lpxx-.js.map → TurnsTab-1T86rHnD.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{VcStatusBadge-BNHVeTG7.js → VcStatusBadge-DKPleja8.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{VcStatusBadge-BNHVeTG7.js.map → VcStatusBadge-DKPleja8.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{VectorCortexTab-goacPxL1.js → VectorCortexTab-BRzvd_pU.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{VectorCortexTab-goacPxL1.js.map → VectorCortexTab-BRzvd_pU.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{WikiTab-DTOemYtE.js → WikiTab-DKTILa1M.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{WikiTab-DTOemYtE.js.map → WikiTab-DKTILa1M.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{button-B_4j_PVR.js → button-5fSU8BZj.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{button-B_4j_PVR.js.map → button-5fSU8BZj.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{card-Ce58rSXG.js → card-BFUnpXE_.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{card-Ce58rSXG.js.map → card-BFUnpXE_.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/client-extra-BZbw21wu.js +2 -0
- package/extensions/dashboard-client/dist/assets/client-extra-BZbw21wu.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-DtNoJ6fZ.js → generateCategoricalChart-xCzi6pWn.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-DtNoJ6fZ.js.map → generateCategoricalChart-xCzi6pWn.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{index-eoCm0uxj.js → index-DqjmZ88m.js} +21 -21
- package/extensions/dashboard-client/dist/assets/index-DqjmZ88m.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{switch-B9kM0N7R.js → switch-CeZUPf_e.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{switch-B9kM0N7R.js.map → switch-CeZUPf_e.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{toggle-BwoHYpMa.js → toggle-MQQwdkwD.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{toggle-BwoHYpMa.js.map → toggle-MQQwdkwD.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{useSSE-DohG5AGv.js → useSSE-BetS7QHN.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{useSSE-DohG5AGv.js.map → useSSE-BetS7QHN.js.map} +1 -1
- package/extensions/dashboard-client/dist/index.html +1 -1
- package/extensions/dashboard-client/src/api/client-extra.ts +53 -0
- package/extensions/dashboard-client/src/api/client-http.ts +81 -0
- package/extensions/dashboard-client/src/api/client.ts +11 -100
- package/extensions/dashboard-client/src/components/PrefixStabilityCard.tsx +98 -0
- package/extensions/dashboard-client/src/tabs/CacheTab.tsx +27 -0
- package/extensions/dashboard-server/api-contracts/endpoints/registry-ext.ts +15 -0
- package/extensions/dashboard-server/api-contracts/index.ts +6 -0
- package/extensions/dashboard-server/api-contracts/prefix-stability.ts +40 -0
- package/extensions/dashboard-server/route-dispatch.ts +2 -0
- package/extensions/dashboard-server/routes-prefix-stability.ts +142 -0
- package/extensions/dashboard-server/routes-rag-settings-vector-cortex.ts +6 -0
- package/extensions/dashboard-server/routes.ts +1 -0
- package/extensions/mega-events/context-handler/tailResult.ts +5 -1
- package/package.json +1 -1
- package/src/config/vector-cortex-pcc.ts +32 -0
- package/src/config/vector-cortex.ts +2 -2
- package/src/config.ts +1 -0
- package/extensions/dashboard-client/dist/assets/CacheTab-C3KWDFDm.js +0 -2
- package/extensions/dashboard-client/dist/assets/CacheTab-C3KWDFDm.js.map +0 -1
- package/extensions/dashboard-client/dist/assets/SetupTab-G-MkdQiR.js +0 -3
- package/extensions/dashboard-client/dist/assets/index-eoCm0uxj.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"CacheTab-C3KWDFDm.js","sources":["../../src/components/ProviderCacheCard.tsx","../../src/components/StripeDistributionCard.tsx","../../src/components/CacheHitRateTrendCard.tsx","../../src/tabs/CacheTab.tsx"],"sourcesContent":["/**\n * dashboard-client/src/components/ProviderCacheCard.tsx — Provider prompt cache stats card.\n *\n * Displays lifetime provider prompt cache hit-rate aggregates + estimated\n * dollar savings from the /api/provider-cache endpoint.\n * Reuses the `ov-stat-row` / `StatRow` pattern from CacheHitsCard.tsx.\n *\n * B.2 spec: Cache Hit Rate with color classes, humanized token counts,\n * priced $ rows with green/red net, model name, locale date + relative time.\n */\n\nimport type React from \"react\";\nimport {\n\tfmtTokens,\n\tfmtDollars,\n\tfmtDate,\n\tfmtRelativeTime,\n} from \"../utils/format\";\nimport { lookupModelInputRate } from \"@pricing\";\nimport { Card, CardContent, CardHeader, CardTitle } from \"../components/ui/card\";\n\n// ---------------------------------------------------------------------------\n// Per-model breakdown type (mirrors the API contract).\n// ---------------------------------------------------------------------------\n\nexport interface ByModelEntry {\n\tmodel: string;\n\thitPct: number;\n\ttotalCacheRead: number;\n\ttotalCacheWrite: number;\n\tsampleCount: number;\n}\n\n// ---------------------------------------------------------------------------\n// Flattened props — destructured from ProviderCacheResponse in CacheTab.\n// ---------------------------------------------------------------------------\n\nexport interface ProviderCacheCardProps {\n\t/** Cache hit rate percentage (0–100). */\n\thitPct: number;\n\t/** Number of turns with cache_hit_pct samples. */\n\tturnCount: number;\n\t/** Total cache-read tokens across all sampled turns. */\n\ttotalCacheRead: number;\n\t/** Total cache-write tokens across all sampled turns. */\n\ttotalCacheWrite: number;\n\t/** Total input tokens across all sampled turns. */\n\ttotalInput: number;\n\t/** $ saved from cache reads (null when unpriced). */\n\tcacheReadSaved: number | null;\n\t/** $ spent on cache writes (null when unpriced). */\n\tcacheWriteCost: number | null;\n\t/** netSaved = cacheReadSaved - cacheWriteCost (null when unpriced). */\n\tnetSaved: number | null;\n\t/** Model display name (modelName || modelId, or null). */\n\tmodelLabel: string | null;\n\t/** ISO timestamp of first recorded turn. */\n\tfirstTurnAt: string | null;\n\t/** ISO timestamp of latest recorded turn. */\n\tlatestTurnAt: string | null;\n\t/** Per-model breakdown (F4). */\n\tbyModel: ByModelEntry[];\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Hit-rate color: green ≥80, yellow ≥50, red <50. */\nfunction hitPctClass(pct: number): string {\n\tif (pct >= 80) return \"ov-stat-value-green\";\n\tif (pct >= 50) return \"ov-stat-value-yellow\";\n\treturn \"ov-stat-value-red\";\n}\n\n/** Net-saved color: green positive, red negative. */\nfunction netClass(v: number | null): string {\n\tif (v == null) return \"\";\n\treturn v >= 0 ? \"ov-stat-value-green\" : \"ov-stat-value-red\";\n}\n\nfunction StatRow({\n\tlabel,\n\tvalue,\n\tclassName,\n\ttitle,\n}: {\n\tlabel: string;\n\tvalue: string;\n\tclassName?: string;\n\ttitle?: string;\n}): React.ReactElement {\n\treturn (\n\t\t<div className=\"flex items-baseline justify-between border-b border-border py-1 text-sm\">\n\t\t\t<span className=\"text-xs text-muted-foreground\" title={title}>\n\t\t\t\t{label}\n\t\t\t</span>\n\t\t\t<span className={`font-semibold${className ? ` ${className}` : \"\"}`}>\n\t\t\t\t{value}\n\t\t\t</span>\n\t\t</div>\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// Card\n// ---------------------------------------------------------------------------\n\nexport function ProviderCacheCard(\n\tprops: ProviderCacheCardProps,\n): React.ReactElement {\n\treturn (\n\t\t<Card className=\"electric-hover\">\n\t\t\t<CardHeader>\n\t\t\t\t<CardTitle>Provider Prompt Cache</CardTitle>\n\t\t\t</CardHeader>\n\t\t\t<CardContent>\n\t\t\t{/* --- Hit Rate + Turns --- */}\n\t\t\t<StatRow\n\t\t\t\tlabel=\"Cache Hit Rate\"\n\t\t\t\tvalue={`${props.hitPct.toFixed(1)}%`}\n\t\t\t\tclassName={hitPctClass(props.hitPct)}\n\t\t\t/>\n\t\t\t<StatRow label=\"Turns Recorded\" value={String(props.turnCount)} />\n\n\t\t\t{/* --- Token counts --- */}\n\t\t\t<StatRow\n\t\t\t\tlabel=\"Cache Read Tokens\"\n\t\t\t\tvalue={fmtTokens(props.totalCacheRead)}\n\t\t\t/>\n\t\t\t<StatRow\n\t\t\t\tlabel=\"Cache Write Tokens\"\n\t\t\t\tvalue={fmtTokens(props.totalCacheWrite)}\n\t\t\t/>\n\t\t\t<StatRow label=\"Input Tokens\" value={fmtTokens(props.totalInput)} />\n\n\t\t\t{/* --- Dollar rows (null when unpriced) --- */}\n\t\t\t<StatRow\n\t\t\t\tlabel=\"$ Saved (reads)\"\n\t\t\t\tvalue={fmtDollars(props.cacheReadSaved)}\n\t\t\t/>\n\t\t\t<StatRow\n\t\t\t\tlabel=\"Write Investment\"\n\t\t\t\tvalue={fmtDollars(props.cacheWriteCost)}\n\t\t\t/>\n\t\t\t<StatRow\n\t\t\t\tlabel=\"Net Saved\"\n\t\t\t\tvalue={fmtDollars(props.netSaved)}\n\t\t\t\tclassName={netClass(props.netSaved)}\n\t\t\t/>\n\n\t\t\t{/* --- Model + timestamps --- */}\n\t\t\t<StatRow label=\"Model\" value={props.modelLabel ?? \"\\u2014\"} />\n\t\t\t<StatRow label=\"Tracked Since\" value={fmtDate(props.firstTurnAt)} />\n\t\t\t<StatRow\n\t\t\t\tlabel=\"Last Updated\"\n\t\t\t\tvalue={fmtRelativeTime(props.latestTurnAt)}\n\t\t\t/>\n\n\t\t\t{/* --- Per-model breakdown (F4) --- */}\n\t\t\t{props.byModel.length > 0 && (\n\t\t\t\t<>\n\t\t\t\t\t<div className=\"mt-2 text-xs font-semibold text-muted-foreground\">\n\t\t\t\t\t\tPer Model\n\t\t\t\t\t</div>\n\t\t\t\t\t{props.byModel.map((m) => {\n\t\t\t\t\t\tconst rate = lookupModelInputRate(m.model);\n\t\t\t\t\t\tconst cr =\n\t\t\t\t\t\t\trate != null ? (m.totalCacheRead / 1_000_000) * rate : null;\n\t\t\t\t\t\tconst cw =\n\t\t\t\t\t\t\trate != null ? (m.totalCacheWrite / 1_000_000) * rate : null;\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t<div key={m.model} className=\"mt-2\">\n\t\t\t\t\t\t\t\t<StatRow label=\"Model\" value={m.model} />\n\t\t\t\t\t\t\t\t<StatRow\n\t\t\t\t\t\t\t\t\tlabel=\"Hit Rate\"\n\t\t\t\t\t\t\t\t\tvalue={`${m.hitPct.toFixed(1)}%`}\n\t\t\t\t\t\t\t\t\tclassName={hitPctClass(m.hitPct)}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t<StatRow\n\t\t\t\t\t\t\t\t\tlabel=\"Cache Read\"\n\t\t\t\t\t\t\t\t\tvalue={fmtTokens(m.totalCacheRead)}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t<StatRow\n\t\t\t\t\t\t\t\t\tlabel=\"Cache Write\"\n\t\t\t\t\t\t\t\t\tvalue={fmtTokens(m.totalCacheWrite)}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t<StatRow label=\"Samples\" value={String(m.sampleCount)} />\n\t\t\t\t\t\t\t\t<StatRow\n\t\t\t\t\t\t\t\t\tlabel=\"$ Saved (reads)\"\n\t\t\t\t\t\t\t\t\tvalue={cr != null ? fmtDollars(cr) : \"\\u2014\"}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t<StatRow\n\t\t\t\t\t\t\t\t\tlabel=\"Write Investment\"\n\t\t\t\t\t\t\t\t\tvalue={cw != null ? fmtDollars(cw) : \"\\u2014\"}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t);\n\t\t\t\t\t})}\n\t\t\t\t</>\n\t\t\t)}\n\t\t\t</CardContent>\n\t\t</Card>\n\t);\n}\n","/**\n * dashboard-client/src/components/StripeDistributionCard.tsx — Cache stripe\n * distribution visualization (A3, PLAN_V2 Phase 4).\n *\n * Renders a horizontal bar chart of stripe buckets (0–4) with stability\n * indicators, plus a health-score summary box.\n *\n * Uses only CSS-based bar rendering — no external charting dependencies.\n */\n\nimport type React from \"react\";\nimport type { CacheStripesResponse } from \"@contracts\";\nimport { fmtPctFromFraction } from \"../utils/format\";\n\nconst STRIPE_COLORS = [\n\t\"ov-bar-green\", // 0 permanent\n\t\"ov-bar-blue\", // 1 epoch\n\t\"ov-bar-teal\", // 2 topic\n\t\"ov-bar-yellow\", // 3 thread\n\t\"ov-bar-gray\", // 4 volatile\n];\n\nconst STRIPE_LABELS = [\n\t\"Permanent\",\n\t\"Epoch\",\n\t\"Topic\",\n\t\"Thread\",\n\t\"Volatile\",\n];\n\nconst HEALTH_LABEL_COLOR: Record<string, string> = {\n\tgood: \"ov-text-green\",\n\tfair: \"ov-text-yellow\",\n\tdegraded: \"ov-text-orange\",\n\tpoor: \"ov-text-red\",\n};\n\nexport interface StripeDistributionCardProps {\n\tdata: CacheStripesResponse;\n}\n\nexport function StripeDistributionCard({\n\tdata,\n}: StripeDistributionCardProps): React.ReactElement {\n\tconst maxCount = Math.max(...data.buckets.map((b) => b.count), 1);\n\tconst healthColor = HEALTH_LABEL_COLOR[data.health.label] ?? \"ov-text-gray\";\n\n\treturn (\n\t\t<div className=\"ov-card\">\n\t\t\t<h3 className=\"ov-card-title\">Cache Stripe Distribution</h3>\n\n\t\t\t{/* Health score summary */}\n\t\t\t<div className=\"ov-stripe-health-summary\">\n\t\t\t\t<span className={`ov-stripe-health-badge ${healthColor}`}>\n\t\t\t\t\t{data.health.label}\n\t\t\t\t</span>\n\t\t\t\t<span className=\"ov-stripe-health-score\">\n\t\t\t\t\t{fmtPctFromFraction(data.health.score)}\n\t\t\t\t</span>\n\t\t\t\t<span className=\"ov-stripe-churn\">\n\t\t\t\t\tChurn: {fmtPctFromFraction(data.health.churnRate)}\n\t\t\t\t</span>\n\t\t\t\t<span className=\"ov-stripe-total\">\n\t\t\t\t\t{data.totalChunks} total chunks\n\t\t\t\t</span>\n\t\t\t</div>\n\n\t\t\t{/* Bar chart — one row per stripe */}\n\t\t\t<div className=\"ov-stripe-bars\">\n\t\t\t\t{data.buckets.map((bucket) => {\n\t\t\t\t\tconst pct =\n\t\t\t\t\t\tmaxCount > 0\n\t\t\t\t\t\t\t? Math.max(0, Math.min(100, (bucket.count / maxCount) * 100))\n\t\t\t\t\t\t\t: 0;\n\t\t\t\t\tconst colorClass =\n\t\t\t\t\t\tSTRIPE_COLORS[bucket.stripe] ?? \"ov-bar-gray\";\n\t\t\t\t\tconst label =\n\t\t\t\t\t\tbucket.label || (STRIPE_LABELS[bucket.stripe] ?? `Stripe ${bucket.stripe}`);\n\t\t\t\t\treturn (\n\t\t\t\t\t\t<div key={bucket.stripe} className=\"ov-stripe-row\">\n\t\t\t\t\t\t\t<span className=\"ov-stripe-label\" title={label}>\n\t\t\t\t\t\t\t\t{label}\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t<div className=\"ov-bar-track\">\n\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\tclassName={`ov-bar-fill ${colorClass}`}\n\t\t\t\t\t\t\t\t\tstyle={{ width: `${pct}%` }}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<span className=\"ov-stripe-count\">{bucket.count}</span>\n\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\tclassName=\"ov-stripe-stability\"\n\t\t\t\t\t\t\t\ttitle={`min ${fmtPctFromFraction(bucket.minStability)} / max ${fmtPctFromFraction(bucket.maxStability)}`}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{fmtPctFromFraction(bucket.avgStability)}\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t);\n\t\t\t\t})}\n\t\t\t</div>\n\n\t\t\t{/* Epoch info */}\n\t\t\t<div className=\"ov-stripe-footer\">\n\t\t\t\tEpoch: {data.epochId ?? \"—\"}\n\t\t\t\t·\n\t\t\t\tDominant tier: {fmtPctFromFraction(data.health.dominantTier)}\n\t\t\t</div>\n\t\t</div>\n\t);\n}\n","/**\n * dashboard-client/src/components/CacheHitRateTrendCard.tsx -- Cache hit-rate\n * time-series trend chart (A3, PLAN_V2 Phase 4).\n *\n * Renders a sparkline view of cache hit rate from the /api/perf endpoint using\n * real cache_hit_pct samples with timestamps. Each bar represents one sample.\n * Shows the latest, average, and sample count.\n *\n * Uses .ov-sparkline / .ov-sparkline-bar CSS classes from cache.css.\n * No external charting dependencies.\n */\n\nimport type React from \"react\";\nimport type { PerfResponse, CacheHitSample } from \"@contracts\";\nimport { Card, CardContent, CardHeader, CardTitle } from \"../components/ui/card\";\n\nexport interface CacheHitRateTrendCardProps {\n\tperf: PerfResponse;\n}\n\nfunction fmtPct(n: number): string {\n\treturn `${n.toFixed(1)}%`;\n}\n\n/**\n * Map a percentage (0–100) to a CSS color class:\n * >= 80: green (healthy)\n * >= 60: teal (fair)\n * >= 40: yellow (degraded)\n * >= 20: orange (poor)\n * < 20: red (critical)\n */\nfunction pctColorClass(pct: number): string {\n\tif (pct >= 80) return \"ov-bar-green\";\n\tif (pct >= 60) return \"ov-bar-teal\";\n\tif (pct >= 40) return \"ov-bar-yellow\";\n\tif (pct >= 20) return \"ov-bar-orange\";\n\treturn \"ov-bar-red\";\n}\n\nexport const CacheHitRateTrendCard: React.FC<CacheHitRateTrendCardProps> = ({\n\tperf,\n}) => {\n\tconst { cache_hit_pct: c } = perf;\n\tconst samples: CacheHitSample[] =\n\t\tc.samples && c.samples.length > 0 ? c.samples : [];\n\n\treturn (\n\t\t<Card className=\"electric-hover\">\n\t\t\t<CardHeader>\n\t\t\t\t<CardTitle>Cache Hit-Rate Trend</CardTitle>\n\t\t\t</CardHeader>\n\t\t\t<CardContent>\n\t\t\t{/* Metric summary */}\n\t\t\t<div className=\"mb-3 flex gap-4 text-sm text-muted-foreground\">\n\t\t\t\t<div>\n\t\t\t\t\tAvg: <strong className=\"text-foreground\">{fmtPct(c.avg)}</strong>\n\t\t\t\t</div>\n\t\t\t\t<div>\n\t\t\t\t\tLatest: <strong className=\"text-foreground\">{fmtPct(c.latest)}</strong>\n\t\t\t\t</div>\n\t\t\t\t<div>\n\t\t\t\t\tSamples: <strong className=\"text-foreground\">{c.n}</strong>\n\t\t\t\t</div>\n\t\t\t</div>\n\n\t\t\t{/* Sparkline bars from real samples */}\n\t\t\t{samples.length > 0 ? (\n\t\t\t\t<>\n\t\t\t\t\t<div\n\t\t\t\t\t\tclassName=\"ov-sparkline\"\n\t\t\t\t\t\trole=\"img\"\n\t\t\t\t\t\taria-label={`Cache hit rate trend: ${c.n} samples, average ${fmtPct(c.avg)}, latest ${fmtPct(c.latest)}`}\n\t\t\t\t\t>\n\t\t\t\t\t\t{samples.map((s, i) => {\n\t\t\t\t\t\t\tconst barH = Math.max(2, Math.round(s.pct * 0.6));\n\t\t\t\t\t\t\tconst colorClass = pctColorClass(s.pct);\n\t\t\t\t\t\t\tconst isLatest = i === samples.length - 1;\n\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\tkey={i}\n\t\t\t\t\t\t\t\t\tclassName={`ov-sparkline-bar ${colorClass}${isLatest ? \" ov-bar-latest\" : \"\"}`}\n\t\t\t\t\t\t\t\t\tstyle={{ height: `${barH}px` }}\n\t\t\t\t\t\t\t\t\ttitle={`${fmtPct(s.pct)} at ${new Date(s.ts).toLocaleTimeString()}`}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t})}\n\t\t\t\t\t</div>\n\t\t\t\t\t<div className=\"mt-1 text-xs text-muted-foreground\">\n\t\t\t\t\t\t{samples.length} sample{samples.length !== 1 ? \"s\" : \"\"} over{\" \"}\n\t\t\t\t\t\t{samples.length > 1\n\t\t\t\t\t\t\t? `${Math.round(\n\t\t\t\t\t\t\t\t\t(samples[samples.length - 1].ts - samples[0].ts) / 1000,\n\t\t\t\t\t\t\t\t)}s`\n\t\t\t\t\t\t\t: \"latest turn\"}\n\t\t\t\t\t</div>\n\t\t\t\t</>\n\t\t\t) : (\n\t\t\t\t<div className=\"text-sm text-muted-foreground\">No cache-hit samples yet</div>\n\t\t\t)}\n\t\t\t</CardContent>\n\t\t</Card>\n\t);\n};\n","/**\n * dashboard-client/src/tabs/CacheTab.tsx -- Cache tab (B.3 + A3).\n *\n * Sections:\n * 1. Provider Prompt Cache -> ProviderCacheCard (/api/provider-cache)\n * 2. Cache Stripe Distribution -> StripeDistributionCard (/api/cache-stripes)\n * 3. Cache Hit-Rate Trend -> CacheHitRateTrendCard (/api/perf)\n * 4. Mega-Compact Dedup Cache -> CacheHitsCard + TimeSavedCard (/api/snapshot)\n *\n * Each section fetches independently; failures in one do not affect others.\n * 5s polling on provider cache and activity snapshot; 15s on stripes + trend.\n */\n\nimport { useState, useCallback } from \"react\";\nimport type {\n\tSnapshotResponse,\n\tProviderCacheResponse,\n\tCacheStripesResponse,\n\tPerfResponse,\n} from \"@contracts\";\nimport { useApi } from \"../hooks/useApi\";\nimport {\n\tfetchSnapshot,\n\tfetchProviderCache,\n\tfetchCacheStripes,\n\tfetchPerf,\n} from \"../api/client\";\nimport { CacheHitsCard } from \"../components/CacheHitsCard\";\nimport { TimeSavedCard } from \"../components/TimeSavedCard\";\nimport { ProviderCacheCard } from \"../components/ProviderCacheCard\";\nimport { StripeDistributionCard } from \"../components/StripeDistributionCard\";\nimport { CacheHitRateTrendCard } from \"../components/CacheHitRateTrendCard\";\nimport { Button } from \"../components/ui/button\";\nimport { Card, CardContent, CardHeader, CardTitle } from \"../components/ui/card\";\n\nexport default function CacheTab(): React.ReactElement {\n\tconst [infoExpanded, setInfoExpanded] = useState(false);\n\t/* --- Provider prompt cache (5s poll) --- */\n\tconst {\n\t\tdata: providerCache,\n\t\tloading: pcLoading,\n\t\terror: pcError,\n\t} = useApi<ProviderCacheResponse>(\n\t\tuseCallback(() => fetchProviderCache(), []),\n\t\t{ pollInterval: 5000 },\n\t);\n\n\t/* --- Cache stripe distribution (15s poll) --- */\n\tconst {\n\t\tdata: stripes,\n\t\tloading: stripesLoading,\n\t\terror: stripesError,\n\t} = useApi<CacheStripesResponse>(\n\t\tuseCallback(() => fetchCacheStripes(), []),\n\t\t{ pollInterval: 15000 },\n\t);\n\n\t/* --- Cache hit-rate trend from perf samples (15s poll) --- */\n\tconst {\n\t\tdata: perf,\n\t\tloading: perfLoading,\n\t\terror: perfError,\n\t} = useApi<PerfResponse>(\n\t\tuseCallback(() => fetchPerf({ minutes: 30 }), []),\n\t\t{ pollInterval: 15000 },\n\t);\n\n\t/* --- Dedup cache snapshot (5s poll) --- */\n\tconst {\n\t\tdata: snapshot,\n\t\tloading: snapLoading,\n\t\terror: snapError,\n\t} = useApi<SnapshotResponse>(\n\t\tuseCallback(() => fetchSnapshot(), []),\n\t\t{ pollInterval: 5000 },\n\t);\n\n\treturn (\n\t\t<div className=\"flex flex-col gap-4\">\n\t\t\t<div>\n\t\t\t\t<Button\n\t\t\t\t\ttype=\"button\"\n\t\t\t\t\tvariant=\"outline\"\n\t\t\t\t\tonClick={() => setInfoExpanded(!infoExpanded)}\n\t\t\t\t>\n\t\t\t\t\t{infoExpanded ? \"Hide Guidance\" : \"Show Cache-Friendly Prompt Ordering Guidance\"}\n\t\t\t\t</Button>\n\t\t\t\t{infoExpanded && (\n\t\t\t\t\t<Card className=\"mt-3\">\n\t\t\t\t\t\t<CardHeader>\n\t\t\t\t\t\t\t<CardTitle>Cache-Friendly Prompt Ordering</CardTitle>\n\t\t\t\t\t\t</CardHeader>\n\t\t\t\t\t\t<CardContent>\n\t\t\t\t\t\t\t<ul className=\"list-disc space-y-1 pl-5\">\n\t\t\t\t\t\t\t\t<li>Keep system prompts and stable context at the top of your conversation — the provider caches the leading prefix.</li>\n\t\t\t\t\t\t\t\t<li>Tool results and volatile content are automatically moved to the tail by message separation (<code>MEGACOMPACT_MESSAGE_SEPARATION</code>) so they don't invalidate the cache prefix.</li>\n\t\t\t\t\t\t\t\t<li>Cache striping (<code>MEGACOMPACT_CACHE_STRIPING</code>) further orders stable context by a stability score so the most durable chunks lead.</li>\n\t\t\t\t\t\t\t\t<li>Avoid inserting new instructions mid-conversation — prepend them instead.</li>\n\t\t\t\t\t\t\t</ul>\n\t\t\t\t\t\t\t{snapshot && (\n\t\t\t\t\t\t\t\t<div className=\"mt-2 text-sm\">\n\t\t\t\t\t\t\t\t\t<strong>Status:</strong>{\" \"}\n\t\t\t\t\t\t\t\t\t{snapshot.config.auto ? \"Auto-compaction Enabled\" : \"Auto-compaction Disabled\"} |{\" \"}\n\t\t\t\t\t\t\t\t\tfast-gate {snapshot.config.fastGatePct}% / threshold{\" \"}\n\t\t\t\t\t\t\t\t\t{snapshot.config.thresholdTokens.toLocaleString()} tokens\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t</CardContent>\n\t\t\t\t\t</Card>\n\t\t\t\t)}\n\t\t\t</div>\n\t\t\t{/* ==============================================================\n\t\t\t Section 1 -- Provider Prompt Cache\n\t\t\t ============================================================== */}\n\t\t\t<h2 className=\"font-heading text-lg font-semibold\">Provider Prompt Cache</h2>\n\t\t\t{pcLoading ? (\n\t\t\t\t<p className=\"tab-stub\">Loading...</p>\n\t\t\t) : pcError ? (\n\t\t\t\t<p className=\"tab-stub\">\n\t\t\t\t\tProvider cache unavailable: {pcError.message}\n\t\t\t\t</p>\n\t\t\t) : providerCache ? (\n\t\t\t\t<ProviderCacheCard\n\t\t\t\t\thitPct={providerCache.cache.avgHitPct}\n\t\t\t\t\tturnCount={providerCache.cache.turnCount}\n\t\t\t\t\ttotalCacheRead={providerCache.cache.totalCacheRead}\n\t\t\t\t\ttotalCacheWrite={providerCache.cache.totalCacheWrite}\n\t\t\t\t\ttotalInput={providerCache.cache.totalInput}\n\t\t\t\t\tcacheReadSaved={providerCache.savings?.cacheReadSaved ?? null}\n\t\t\t\t\tcacheWriteCost={providerCache.savings?.cacheWriteCost ?? null}\n\t\t\t\t\tnetSaved={providerCache.savings?.netSaved ?? null}\n\t\t\t\t\tmodelLabel={providerCache.savings?.model ?? null}\n\t\t\t\t\tfirstTurnAt={providerCache.cache.firstTurnAt}\n\t\t\t\t\tlatestTurnAt={providerCache.cache.latestTurnAt}\n\t\t\t\t\tbyModel={providerCache.cache.byModel ?? []}\n\t\t\t\t/>\n\t\t\t) : null}\n\n\t\t\t{/* ==============================================================\n\t\t\t Section 2 -- Cache Stripe Distribution\n\t\t\t ============================================================== */}\n\t\t\t<h2 className=\"font-heading text-lg font-semibold\">Cache Stripe Distribution</h2>\n\t\t\t{stripesLoading ? (\n\t\t\t\t<p className=\"tab-stub\">Loading...</p>\n\t\t\t) : stripesError ? (\n\t\t\t\t<p className=\"tab-stub\">\n\t\t\t\t\tCache stripe data unavailable: {stripesError.message}\n\t\t\t\t</p>\n\t\t\t) : stripes ? (\n\t\t\t\t<StripeDistributionCard data={stripes} />\n\t\t\t) : null}\n\n\t\t\t{/* ==============================================================\n\t\t\t Section 3 -- Cache Hit-Rate Trend\n\t\t\t ============================================================== */}\n\t\t\t<h2 className=\"font-heading text-lg font-semibold\">Cache Hit-Rate Trend</h2>\n\t\t\t{perfLoading ? (\n\t\t\t\t<p className=\"tab-stub\">Loading...</p>\n\t\t\t) : perfError ? (\n\t\t\t\t<p className=\"tab-stub\">\n\t\t\t\t\tHit-rate trend unavailable: {perfError.message}\n\t\t\t\t</p>\n\t\t\t) : perf ? (\n\t\t\t\t<CacheHitRateTrendCard perf={perf} />\n\t\t\t) : null}\n\n\t\t\t{/* ==============================================================\n\t\t\t Section 4 -- Mega-Compact Dedup Cache\n\t\t\t ============================================================== */}\n\t\t\t<h2 className=\"font-heading text-lg font-semibold\">Mega-Compact Dedup Cache</h2>\n\t\t\t{snapLoading ? (\n\t\t\t\t<p className=\"tab-stub\">Loading...</p>\n\t\t\t) : snapError ? (\n\t\t\t\t<p className=\"tab-stub\">Snapshot unavailable: {snapError.message}</p>\n\t\t\t) : (\n\t\t\t\tsnapshot &&\n\t\t\t\t(() => {\n\t\t\t\t\tconst { cacheHits, compacts, timeSaved } = snapshot;\n\t\t\t\t\treturn (\n\t\t\t\t\t\t<div className=\"grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3\">\n\t\t\t\t\t\t\t<CacheHitsCard\n\t\t\t\t\t\t\t\tcacheHitsSession={cacheHits.session}\n\t\t\t\t\t\t\t\tcacheHitsTotal={cacheHits.total}\n\t\t\t\t\t\t\t\ttokensSavedSession={cacheHits.sessionTokensSaved}\n\t\t\t\t\t\t\t\ttokensSavedTotal={cacheHits.totalTokensSaved}\n\t\t\t\t\t\t\t\tcompactionsSession={compacts.session}\n\t\t\t\t\t\t\t\tcompactionsTotal={compacts.total}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t<TimeSavedCard\n\t\t\t\t\t\t\t\tcompactSessionSec={timeSaved.compact.sessionSec}\n\t\t\t\t\t\t\t\tcompactTotalSec={timeSaved.compact.totalSec}\n\t\t\t\t\t\t\t\tcacheHitSessionSec={timeSaved.cacheHit.sessionSec}\n\t\t\t\t\t\t\t\tcacheHitTotalSec={timeSaved.cacheHit.totalSec}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t);\n\t\t\t\t})()\n\t\t\t)}\n\t\t</div>\n\t);\n}\n"],"names":["hitPctClass","pct","netClass","v","StatRow","label","value","className","title","jsxs","jsx","ProviderCacheCard","props","Card","CardHeader","CardTitle","CardContent","fmtTokens","fmtDollars","fmtDate","fmtRelativeTime","Fragment","m","rate","lookupModelInputRate","cr","cw","STRIPE_COLORS","STRIPE_LABELS","HEALTH_LABEL_COLOR","StripeDistributionCard","data","maxCount","b","healthColor","fmtPctFromFraction","bucket","colorClass","fmtPct","n","pctColorClass","CacheHitRateTrendCard","perf","c","samples","s","i","barH","isLatest","CacheTab","infoExpanded","setInfoExpanded","useState","providerCache","pcLoading","pcError","useApi","useCallback","fetchProviderCache","stripes","stripesLoading","stripesError","fetchCacheStripes","perfLoading","perfError","fetchPerf","snapshot","snapLoading","snapError","fetchSnapshot","Button","cacheHits","compacts","timeSaved","CacheHitsCard","TimeSavedCard"],"mappings":"6VAqEA,SAASA,EAAYC,EAAqB,CACzC,OAAIA,GAAO,GAAW,sBAClBA,GAAO,GAAW,uBACf,mBACR,CAGA,SAASC,EAASC,EAA0B,CAC3C,OAAIA,GAAK,KAAa,GACfA,GAAK,EAAI,sBAAwB,mBACzC,CAEA,SAASC,EAAQ,CAChB,MAAAC,EACA,MAAAC,EACA,UAAAC,EACA,MAAAC,CACD,EAKuB,CACtB,OACCC,EAAAA,KAAC,MAAA,CAAI,UAAU,0EACd,SAAA,CAAAC,EAAAA,IAAC,OAAA,CAAK,UAAU,gCAAgC,MAAAF,EAC9C,SAAAH,EACF,EACAK,EAAAA,IAAC,OAAA,CAAK,UAAW,gBAAgBH,EAAY,IAAIA,CAAS,GAAK,EAAE,GAC/D,SAAAD,CAAA,CACF,CAAA,EACD,CAEF,CAMO,SAASK,EACfC,EACqB,CACrB,OACCH,EAAAA,KAACI,EAAA,CAAK,UAAU,iBACf,SAAA,CAAAH,MAACI,EAAA,CACA,SAAAJ,EAAAA,IAACK,EAAA,CAAU,SAAA,uBAAA,CAAqB,EACjC,SACCC,EAAA,CAED,SAAA,CAAAN,EAAAA,IAACN,EAAA,CACA,MAAM,iBACN,MAAO,GAAGQ,EAAM,OAAO,QAAQ,CAAC,CAAC,IACjC,UAAWZ,EAAYY,EAAM,MAAM,CAAA,CAAA,EAEpCF,MAACN,GAAQ,MAAM,iBAAiB,MAAO,OAAOQ,EAAM,SAAS,EAAG,EAGhEF,EAAAA,IAACN,EAAA,CACA,MAAM,oBACN,MAAOa,EAAUL,EAAM,cAAc,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AAA,CAAU,EAC/B0D,EACH3D,EAAAA,KAAC,IAAA,CAAE,UAAU,WAAW,SAAA,CAAA,yBAAuB2D,EAAU,OAAA,EAAQ,EAEjEF,IACC,IAAM,CACN,KAAM,CAAE,UAAAK,EAAW,SAAAC,EAAU,UAAAC,CAAA,EAAcP,EAC3C,OACCzD,EAAAA,KAAC,MAAA,CAAI,UAAU,uDACd,SAAA,CAAAC,EAAAA,IAACgE,EAAA,CACA,iBAAkBH,EAAU,QAC5B,eAAgBA,EAAU,MAC1B,mBAAoBA,EAAU,mBAC9B,iBAAkBA,EAAU,iBAC5B,mBAAoBC,EAAS,QAC7B,iBAAkBA,EAAS,KAAA,CAAA,EAE5B9D,EAAAA,IAACiE,EAAA,CACA,kBAAmBF,EAAU,QAAQ,WACrC,gBAAiBA,EAAU,QAAQ,SACnC,mBAAoBA,EAAU,SAAS,WACvC,iBAAkBA,EAAU,SAAS,QAAA,CAAA,CACtC,EACD,CAEF,GAAA,CAAG,EAEL,CAEF"}
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{r as n,j as e,h as A,i as F,k as G,p as K,l as Q,m as J,C as Y,n as Z,o as ee,q as te,s as se,t as ne,v as re,w as ae,x as le,y as oe}from"./index-eoCm0uxj.js";import{S as ie}from"./switch-B9kM0N7R.js";import{V as ce}from"./VcStatusBadge-BNHVeTG7.js";import{T as de}from"./toggle-BwoHYpMa.js";function me(t){try{return new Date(t*1e3).toLocaleString()}catch{return"—"}}function H({achievements:t}){const r=n.useRef(0),[s,l]=n.useState(null),a=t.reduce((o,d)=>Math.max(o,d.unlocked_at??0),0),c=r.current;n.useEffect(()=>{a>r.current&&(r.current=a)},[a]),n.useEffect(()=>{if(c>0&&a>c){const o=t.filter(d=>d.unlocked_at!=null&&(d.unlocked_at??0)>c);if(o.length>0){const d=o.map(m=>`${m.icon??""} ${m.title}`.trim()).join(", ")+" unlocked!";l(d);const g=setTimeout(()=>l(null),4e3);return()=>clearTimeout(g)}}},[t,a,c]);const f=t.filter(o=>!(o.hidden===1&&o.unlocked_at==null));return e.jsxs("div",{className:"ach-section",children:[s!=null&&e.jsx("div",{className:"ach-toast show",children:s}),e.jsxs("div",{className:"ach-tiles",children:[f.length===0&&e.jsx("span",{className:"repo-none",children:"no achievements yet"}),f.map(o=>{if(o.unlocked_at!=null){const d=c>0&&(o.unlocked_at??0)>c;return e.jsxs("div",{className:`ach-tile unlocked${d?" just-unlocked":""}`,children:[o.icon??""," ",o.title,e.jsxs("span",{className:"ach-detail",children:["unlocked ",me(o.unlocked_at)]})]},o.id)}return e.jsxs("div",{className:"ach-tile locked",children:["??? ",o.title]},o.id)})]})]})}function I(t){return(Math.round(t*10)/10).toString()+"%"}function O(t){return t!=null?new Date(t).toLocaleString():"—"}function D(t){return t&&typeof t=="object"?t:{}}function ue(t){return t.split("/").pop()||t}function P({title:t,rows:r,badge:s,renderValue:l}){return e.jsxs("div",{className:"lb-card",children:[e.jsxs("h3",{children:[t,s]}),r.length===0?e.jsx("div",{className:"lb-empty",children:"—"}):e.jsx("table",{children:e.jsx("tbody",{children:r.map((a,c)=>e.jsxs("tr",{children:[e.jsx("td",{title:a.repo_root,children:ue(a.repo_root)}),e.jsx("td",{className:"num",children:l(a)})]},`${a.repo_root}-${c}`))})})]})}function he(){const[t,r]=n.useState({}),[s,l]=n.useState(0),[a,c]=n.useState([]),[f,o]=n.useState(!1),[d,g]=n.useState(!0),[m,x]=n.useState(null),i=n.useRef(0),u=n.useCallback(async()=>{try{const[y,w,p,k,T,X]=await Promise.all([A({metric:"cache",limit:25}),A({metric:"dedupe",limit:25}),A({metric:"turns",limit:25}),A({metric:"mega_cache",limit:25}),A({metric:"repos",limit:1}),F()]),W=k.find(B=>B.ts>i.current&&B.value>100);i.current>0&&W&&(x(`oopsie! cache went to ${Math.round(W.value)}% — MEGA CACHE 🥧`),setTimeout(()=>x(null),4e3)),k.length>0&&(i.current=Math.max(...k.map(B=>B.ts))),r({cache:y,dedupe:w,turns:p,mega_cache:k}),l(T[0]?.value??0),c(X)}catch{}finally{g(!1)}},[]);n.useEffect(()=>{let y=!0;const w=async()=>{y&&await u()};w();const p=setInterval(()=>void w(),15e3);return()=>{y=!1,clearInterval(p)}},[u]),n.useEffect(()=>{let y=!0;const w=async()=>{try{const k=await G();y&&(o(!!k.game_mode_on),k.theme&&(document.documentElement.dataset.theme=k.theme))}catch{}};w();const p=setInterval(()=>void w(),15e3);return()=>{y=!1,clearInterval(p)}},[]);const j=t.mega_cache??[];let v=null,N=null;for(const y of j){(v==null||y.value>v)&&(v=y.value);const w=D(y.meta),p=w.firstSeenTs??w.firstSeen??y.ts;(N==null||p<N)&&(N=p)}const C=v!=null&&v>100,S=t.turns??[],M=S.reduce((y,w)=>Math.max(y,w.value),0),L=Math.floor(Math.log2(M+1))+1,z=(t.cache?.length??0)>0||(t.dedupe?.length??0)>0||S.length>0||j.length>0||s>0;return e.jsxs("div",{className:`game-tab${f?" game-mode-on":""}`,children:[m!=null&&e.jsx("div",{className:"mega-cache-toast show",children:m}),C&&e.jsxs("div",{className:"mega-cache-banner",children:["🥧"," MEGA CACHE! peak ",I(v)," — first reached ",O(N)]}),C&&e.jsxs("div",{className:"achievement-tile unlocked",children:["🏆"," Opie's Wild Ride",e.jsxs("span",{className:"ach-detail",children:["best ",I(v)," · first ",O(N)]})]}),e.jsx("h2",{children:"High Scores"}),!z&&!d&&e.jsx("div",{className:"game-empty",children:"No scores yet — run a session with game mode on."}),z&&e.jsxs("div",{className:"game-leaderboards",children:[e.jsx(P,{title:"Cache %",rows:t.cache??[],renderValue:y=>I(y.value)}),e.jsx(P,{title:"Dedupe (collapsed)",rows:t.dedupe??[],renderValue:y=>y.value.toLocaleString()}),e.jsx(P,{title:"Turns",rows:S,badge:S.length>0?e.jsxs("span",{className:"lvl-badge",children:["LVL ",L]}):void 0,renderValue:y=>y.value.toLocaleString()}),e.jsx(P,{title:"MEGA CACHE trophies",rows:j,renderValue:y=>e.jsxs(e.Fragment,{children:[I(y.value),e.jsx("span",{className:"lb-meta",children:O(D(y.meta).firstSeenTs??D(y.meta).firstSeen??y.ts)})]})})]}),s>0&&e.jsx("div",{className:"repos-badge-line",children:e.jsxs("span",{className:"repos-badge",children:[s," repos"]})}),e.jsx("h3",{children:"Achievements"}),e.jsx(H,{achievements:a})]})}function fe(){const[t,r]=n.useState([]),[s,l]=n.useState(!0),[a,c]=n.useState(null),f=n.useCallback(async()=>{try{const o=await F();r(o),c(null)}catch(o){c(o instanceof Error?o:new Error(String(o)))}finally{l(!1)}},[]);return n.useEffect(()=>{let o=!0;const d=async()=>{o&&await f()};d();const g=setInterval(()=>void d(),15e3);return()=>{o=!1,clearInterval(g)}},[f]),s&&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(H,{achievements:t})]})}const q=[{id:"transparent",label:"Transparent (accents only)",css:{bg:null,fg:"#c9d1d9",accent:"#3fb950",mega:"#f0883e"},ansi:{bg:null,fg:"39",accent:"32",mega:"33"}},{id:"retro",label:"Retro 8-bit green",css:{bg:"#003300",fg:"#33ff33",accent:"#00ff41",mega:"#39ff14"},ansi:{bg:"40",fg:"92",accent:"92",mega:"1;92"}},{id:"orange-bold",label:"Orange bold",css:{bg:"#1a0f00",fg:"#ff8c00",accent:"#ff6b00",mega:"#ff4500"},ansi:{bg:"48;5;52",fg:"38;5;208",accent:"38;5;208",mega:"1;38;5;202"}},{id:"cyan-neon",label:"Cyan neon",css:{bg:"#001a1a",fg:"#00ffff",accent:"#22d3ee",mega:"#7df9ff"},ansi:{bg:"48;5;23",fg:"38;5;51",accent:"38;5;51",mega:"1;38;5;51"}},{id:"amber-mono",label:"Amber phosphor",css:{bg:"#1a1200",fg:"#ffb000",accent:"#ff8c00",mega:"#ff5500"},ansi:{bg:"48;5;58",fg:"38;5;214",accent:"38;5;214",mega:"1;38;5;208"}},{id:"grayscale",label:"Grayscale minimal",css:{bg:"#161616",fg:"#b0b0b0",accent:"#8b949e",mega:"#e6edf3"},ansi:{bg:"48;5;235",fg:"38;5;249",accent:"38;5;249",mega:"1;38;5;255"}}],$=q.map(t=>t.id),E={gameMode:"Turn game mode on/off (themes the widget + dashboard)",theme:"Visual theme (applies instantly)",tuiMode:"TUI widget display density",tier:"Live pressure band — climbs low→mega as context fills the window.",preset:"The env-resolved base compaction preset (low/medium/high/ultra/mega) that set the token threshold.",pressure:"Live pressure = currentTokens / threshold — % of the model context window (threshold fires at the tier's % of window).",threshold:"Compaction threshold = tierPct × model context window — mega-compact trims BELOW pi's native ~80% auto-compact for any model size.",fastGate:"Fast-gate arming floor — the live trim arms once context passes this % of the window."};function ge(t,r,s){let l=t.toLocaleString();return r!=null&&s>0&&(l+=` (${Math.round(r*100)}% of ${s.toLocaleString()})`),l}function xe(t){return`${Math.round((t||0)*100)}%`}function pe(){const[t,r]=n.useState(null),[s,l]=n.useState(null),[a,c]=n.useState(!1);n.useEffect(()=>{let i=!0;const u=async()=>{try{const v=await Q();i&&r(v)}catch{}};u();const j=setInterval(()=>void u(),5e3);return()=>{i=!1,clearInterval(j)}},[]),n.useEffect(()=>{let i=!0;const u=async()=>{try{const v=await G();i&&(l(v),v.theme&&(document.documentElement.dataset.theme=v.theme))}catch{}};u();const j=setInterval(()=>void u(),5e3);return()=>{i=!1,clearInterval(j)}},[]);const f=n.useCallback(async i=>{c(!0);try{const u=await K(i);l(u),u.theme&&(document.documentElement.dataset.theme=u.theme)}catch{}c(!1)},[]),o=s?.game_mode_on??!1,d=s?.theme??"transparent",g=s?.tui_display_mode??"full",m=t?.config,x=t?.context.contextWindow??0;return e.jsxs("div",{className:"config-tab",children:[e.jsxs("section",{className:"config-settings",children:[e.jsx("h3",{children:"Settings"}),e.jsx("div",{className:"settings-row",children:e.jsxs("label",{title:E.gameMode,children:[e.jsx("input",{type:"checkbox",checked:o,onChange:i=>f({game_mode_on:i.currentTarget.checked}),disabled:a}),"Game Mode"]})}),e.jsx("div",{className:"settings-row",children:e.jsxs("label",{title:E.theme,children:["Theme",e.jsx("select",{value:d,onChange:i=>f({theme:i.currentTarget.value}),disabled:a,children:q.map(i=>e.jsx("option",{value:i.id,children:i.label},i.id))}),e.jsx("button",{type:"button",disabled:a,className:"theme-cycle-btn",title:"Cycle to the next theme (P3)",onClick:()=>{const i=$.indexOf(d),u=$[(i<0?0:i+1)%$.length];u&&f({theme:u})},children:"Next theme →"})]})}),e.jsx("div",{className:"settings-row",children:e.jsxs("label",{title:E.tuiMode,children:["TUI Mode",e.jsxs("select",{value:g,onChange:i=>f({tui_display_mode:i.currentTarget.value}),disabled:a,children:[e.jsx("option",{value:"full",children:"Full"}),e.jsx("option",{value:"minimal",children:"Minimal"})]})," ",e.jsx("span",{className:"tui-mode-hint",children:"(affects the in-app TUI widget; not shown here)"})]})})]}),e.jsxs("section",{className:"config-display",children:[e.jsx("h3",{children:"Configuration"}),e.jsxs("div",{className:"config-grid",children:[e.jsxs("div",{className:"config-item",children:[e.jsx("span",{className:"config-label",title:E.tier,children:"Tier"}),e.jsx("span",{className:"config-value",children:t?`${t.tier} (live)`:"—"})]}),e.jsxs("div",{className:"config-item",children:[e.jsx("span",{className:"config-label",title:E.preset,children:"Preset"}),e.jsx("span",{className:"config-value",children:t?.presetTier??"—"})]}),e.jsxs("div",{className:"config-item",children:[e.jsx("span",{className:"config-label",title:E.pressure,children:"Pressure"}),e.jsx("span",{className:"config-value",children:t?xe(t.pressure):"—"})]}),e.jsxs("div",{className:"config-item",children:[e.jsx("span",{className:"config-label",title:E.threshold,children:"Threshold"}),e.jsx("span",{className:"config-value",children:m?ge(m.thresholdTokens,m.tierPct,x):"—"})]}),e.jsxs("div",{className:"config-item",children:[e.jsx("span",{className:"config-label",title:E.fastGate,children:"Fast Gate"}),e.jsx("span",{className:"config-value",children:m?`${m.fastGatePct}%`:"—"})]}),e.jsxs("div",{className:"config-item",children:[e.jsx("span",{className:"config-label",children:"Auto"}),e.jsx("span",{className:"config-value",children:m?m.auto?"enabled":"disabled":"—"})]}),e.jsxs("div",{className:"config-item",children:[e.jsx("span",{className:"config-label",children:"Anchor"}),e.jsx("span",{className:"config-value",children:m?.anchorUserMessages??"—"})]})]})]})]})}const R={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 be(){const[t,r]=n.useState(null),[s,l]=n.useState(null),a=n.useCallback(()=>{J().then(r).catch(g=>l(g instanceof Error?g.message:String(g)))},[]);n.useEffect(()=>{a()},[a]),n.useEffect(()=>{const g=setInterval(a,3e4);return()=>clearInterval(g)},[a]);const c=t?.status==="ok",f=t?.status==="ok"?"Working":t?.status==="unreachable"?"Unreachable":"Error",o=c?"#4caf50":"#f44336",d=c?"✓":"✗";return e.jsxs("div",{style:R.section,children:[e.jsx("h3",{style:R.sectionTitle,children:"Embedder Health"}),s&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error: ",s]}),!t&&!s&&e.jsx("p",{style:{color:"#888",fontSize:"0.85rem"},children:"Probing embedder..."}),t&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:R.row,children:[e.jsxs("span",{style:{...R.label,color:`${o}`},children:[d," ",f,":"]}),e.jsxs("span",{style:R.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:R.row,children:[e.jsx("span",{style:R.label,children:"Endpoint:"}),e.jsx("span",{style:R.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 je({title:t,children:r}){const[s,l]=n.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(c=>!c),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":s,"aria-controls":a,children:[e.jsx("span",{children:t}),e.jsx(Y,{className:Z("h-4 w-4 text-muted-foreground transition-transform",s&&"rotate-180"),"aria-hidden":"true"})]}),s&&e.jsx("div",{id:a,className:"divide-y divide-border px-4 py-1",children:r})]})}const ye="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 ve(){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 Se({setting:t,id:r,llmActive:s,saving:l,onUpdate:a}){const[c,f]=n.useState(null),o=t.requiresLlm&&!s,d=n.useRef(null);n.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]);const g=n.useCallback(i=>{a(t.key,i).then(u=>f(u)).catch(u=>f(u instanceof Error?u.message:String(u)))},[a,t.key]),m=n.useCallback(i=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>g(i),500)},[g]),x=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&&!s&&e.jsx(ve,{})]}),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(ie,{id:`${r}-input`,checked:!!t.value,disabled:x||o,onCheckedChange:i=>g(String(i)),"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:x,onChange:i=>m(i.target.value),className:`${ye} ${t.type==="number"?"w-24":"w-56"}`}),t.unit&&e.jsx("span",{className:"text-xs text-muted-foreground",children:t.unit})]})})]}),c&&e.jsxs("p",{className:"mt-1 text-xs text-danger",children:["Error: ",c]})]})}function we(){const[t,r]=n.useState(null),[s,l]=n.useState(null),[a,c]=n.useState(!1),[f,o]=n.useState(null),d=n.useCallback(()=>{ee().then(r).catch(m=>l(m instanceof Error?m.message:String(m)))},[]);n.useEffect(()=>{d()},[d]);const g=n.useCallback(async(m,x)=>{c(!0);try{const i=await te({key:m,value:x});return o(i.restartRequired?"Saved — restart pi to apply changes.":"Saved."),d(),null}catch(i){return i instanceof Error?i.message:String(i)}finally{c(!1)}},[d]);return e.jsxs("div",{className:"flex flex-col gap-3",children:[s&&e.jsxs("p",{className:"text-sm text-danger",children:["Error: ",s]}),!t&&!s&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading settings..."}),t?.categories.map(m=>e.jsx(je,{title:m.name,children:m.settings.map(x=>e.jsx(Se,{setting:x,id:`${m.name.replace(/[^a-z0-9]+/gi,"-")}-${x.key}`,llmActive:t.llmActive,saving:a,onUpdate:g},x.key))},m.name)),f&&e.jsx("div",{className:"mt-1 rounded-md border border-warning/40 bg-warning/10 p-2 text-xs text-warning",role:"status",children:f})]})}const h={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}};function Ne({customUrl:t,setCustomUrl:r,applyEmbedder:s,configuring:l}){return e.jsxs("div",{style:h.section,children:[e.jsx("h3",{style:h.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:a=>r(a.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"}}),e.jsx("button",{style:{...h.button,opacity:t?1:.4},onClick:()=>s("custom",t),disabled:!t||l!==null,children:l==="custom"?"Writing...":"Use Custom URL"})]}),e.jsxs("div",{style:h.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 ke(){const[t,r]=n.useState(null),[s,l]=n.useState(null),[a,c]=n.useState(null),[f,o]=n.useState(null),[d,g]=n.useState(!1),[m,x]=n.useState(null),[i,u]=n.useState(null),[j,v]=n.useState(null),[N,C]=n.useState(""),S=n.useCallback(()=>{se().then(r).catch(p=>c(p instanceof Error?p.message:String(p)))},[]),M=n.useCallback((p,k)=>{x(p),v(null),u(null),ne({embedder:p,url:k}).then(T=>{u(T),x(null),S()}).catch(T=>{v(T instanceof Error?T.message:String(T)),x(null)})},[S]),L=n.useCallback(()=>{g(!0),o(null),re().then(p=>{l(p),g(!1)}).catch(p=>{o(p instanceof Error?p.message:String(p)),g(!1)})},[]);n.useEffect(()=>{S()},[S]),n.useEffect(()=>{const p=setInterval(S,5e3);return()=>clearInterval(p)},[S]),n.useEffect(()=>{L();const p=setInterval(L,5e3);return()=>clearInterval(p)},[L]);const z=p=>{switch(p){case"trigram":return"TrigramEmbedder (heuristic, default)";case"http":return"HTTP Embedder (BYO localhost)";case"minilm":return"MiniLM (experimental)";default:return"Unknown"}},y=t?.currentEmbedder==="trigram"&&e.jsxs("div",{style:h.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."]}),w=p=>{const k=p?"#1a5a1a":"#3a1a1a",T=p?"#4caf50":"#f44336";return e.jsx("span",{style:{...h.badge,background:k,color:T},children:p?"Detected":"Not found"})};return e.jsxs("div",{style:h.container,children:[e.jsx("h2",{style:{fontSize:"1.3rem",marginTop:0,marginBottom:"1rem"},children:"Embedder Setup"}),e.jsx(be,{}),e.jsxs("div",{style:h.section,children:[e.jsx("h3",{style:h.sectionTitle,children:"Current Embedder Configuration"}),a&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error: ",a]}),t&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:h.row,children:[e.jsx("span",{style:h.label,children:"Active Embedder:"}),e.jsx("span",{style:h.value,children:z(t.currentEmbedder)})]}),"configuredEmbedder"in t&&t.configuredEmbedder!==t.currentEmbedder&&e.jsxs("div",{style:h.warning,children:[e.jsx("strong",{children:"Configured but not active:"})," ",z(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:{...h.row,color:"#ff9800"},children:[e.jsx("span",{style:h.label,children:"Status:"}),e.jsx("span",{style:h.value,children:"Restart required to activate the configured embedder"})]}),e.jsxs("div",{style:h.row,children:[e.jsx("span",{style:h.label,children:"Embedding URL:"}),e.jsx("span",{style:h.value,children:t.embeddingUrl??e.jsx("span",{style:{color:"#888"},children:"not set"})})]}),e.jsxs("div",{style:h.row,children:[e.jsx("span",{style:h.label,children:"Embed Cache:"}),e.jsx("span",{style:h.value,children:t.embedCache??e.jsx("span",{style:{color:"#888"},children:"not set"})})]}),e.jsxs("div",{style:h.row,children:[e.jsx("span",{style:h.label,children:"MiniLM:"}),e.jsx("span",{style:h.value,children:t.minilm?"enabled":"disabled"})]}),y]}),!t&&!a&&e.jsx("p",{style:{color:"#888",fontSize:"0.85rem"},children:"Loading configuration..."})]}),e.jsxs("div",{style:h.section,children:[e.jsx("h3",{style:h.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."}),s&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:h.detectRow,children:[e.jsx("span",{children:e.jsx("strong",{children:"Ollama"})}),s.ollama!==null?e.jsxs("span",{children:[w(s.ollama.installed),s.ollama.installed&&e.jsx("span",{style:{fontSize:"0.8rem",color:"#a0a0c0",marginLeft:"0.5rem"},children:s.ollama.running?`server running, ${s.ollama.models.length} model(s)`:"server not running"})]}):e.jsx("span",{style:{color:"#888",fontSize:"0.85rem"},children:"not checked"})]}),e.jsxs("div",{style:h.detectRow,children:[e.jsx("span",{children:e.jsx("strong",{children:"llama.cpp"})}),s.llamaCpp!==null?e.jsxs("span",{children:[w(s.llamaCpp.installed),s.llamaCpp.installed&&s.llamaCpp.detail&&e.jsx("span",{style:{fontSize:"0.8rem",color:"#a0a0c0",marginLeft:"0.5rem"},children:s.llamaCpp.detail})]}):e.jsx("span",{style:{color:"#888",fontSize:"0.85rem"},children:"not checked"})]}),e.jsxs("div",{style:h.detectRow,children:[e.jsx("span",{children:e.jsx("strong",{children:"ONNX Runtime"})}),s.onnx!==null?e.jsxs("span",{children:[w(s.onnx.installed),s.onnx.installed&&s.onnx.detail&&e.jsx("span",{style:{fontSize:"0.8rem",color:"#a0a0c0",marginLeft:"0.5rem"},children:s.onnx.detail})]}):e.jsx("span",{style:{color:"#888",fontSize:"0.85rem"},children:"not checked"})]}),s.error&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.8rem",marginTop:"0.5rem"},children:["Detection error: ",s.error]})]}),f&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error: ",f]}),e.jsxs("div",{style:{marginTop:"1rem"},children:[e.jsx("button",{style:h.button,onClick:L,disabled:d,children:d?"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."]})]}),s&&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:{...h.button,opacity:s.ollama?.installed?1:.4},onClick:()=>M("ollama"),disabled:!s.ollama?.installed||m!==null,children:m==="ollama"?"Writing...":"Use Ollama"}),e.jsx("button",{style:{...h.button,opacity:s.llamaCpp?.installed?1:.4},onClick:()=>M("llama"),disabled:!s.llamaCpp?.installed||m!==null,children:m==="llama"?"Writing...":"Use llama.cpp"}),e.jsx("button",{style:{...h.button,opacity:s.onnx?.installed?1:.4},onClick:()=>M("onnx"),disabled:!s.onnx?.installed||m!==null,children:m==="onnx"?"Writing...":"Use ONNX"}),e.jsx("button",{style:{...h.button,background:"#444"},onClick:()=>M("trigram"),disabled:m!==null,children:m==="trigram"?"Writing...":"Use Trigram (default)"})]}),i&&e.jsx("div",{style:h.warning,children:i.alreadyActive?"Already active — no restart needed.":`Configured ${i.embedder}. Restart pi to activate (config written to ${i.envPath}).`}),j&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem",marginTop:"0.5rem"},children:["Configure error: ",j]})]})]}),e.jsx(Ne,{customUrl:N,setCustomUrl:C,applyEmbedder:M,configuring:m}),e.jsxs("div",{style:h.section,children:[e.jsx("h3",{style:h.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:h.section,children:[e.jsx("h3",{style:h.sectionTitle,children:"Settings"}),e.jsx(we,{})]})]})}function _(t){return t>=1e6?`${(t/1e6).toFixed(2)}M`:t>=1e3?`${Math.round(t/1e3)}K`:String(t)}function Ce(t,r,s){if(t<=0)return"—";const a=(r>0?r:Math.ceil(t*.1))+Math.ceil(t*(s/100)),c=t-a;return c<=0?"0 (at risk)":`${_(c)} tokens`}function U({label:t,value:r,min:s,max:l,step:a=1,onChange:c,warning:f}){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 ${f?"text-warning":"text-fg"}`,title:f,children:[r,"%"]})]}),e.jsx("input",{type:"range",min:s,max:l,step:a,value:r,onChange:o=>c(Number(o.target.value)),className:"threshold-slider w-full"}),f&&e.jsxs("p",{className:"text-[10px] text-warning",children:["⚠ ",f]})]})}function Te({model:t,defaults:r,safetyRange:s,fireRange:l,onSave:a,onReset:c,saving:f}){const[o,d]=n.useState(t.threshold.safetyMarginPct),[g,m]=n.useState(t.threshold.firePointPct),[x,i]=n.useState(!1),[u,j]=n.useState(null);n.useEffect(()=>{d(t.threshold.safetyMarginPct),m(t.threshold.firePointPct),i(!1)},[t.threshold.safetyMarginPct,t.threshold.firePointPct]);const v=o<5?'Low safety margin — risks "conversation too long" errors when a single turn injects a large tool output between gate fires.':void 0,N=g>85?"High fire point — compaction may trigger close to the window cap; a single large turn can overshoot before the gate fires.":void 0,C=n.useCallback(async()=>{j(null);try{await a(t.modelId,o,g),i(!1)}catch(S){j(S instanceof Error?S.message:String(S))}},[t.modelId,o,g,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," · ",_(t.contextWindow)," window ·"," ",_(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:Ce(t.contextWindow,t.maxTokens,o)})]}),e.jsxs("div",{children:["Compaction fires at:"," ",e.jsx("span",{className:"font-mono text-fg",children:_(Math.ceil(t.contextWindow*(g/100)))})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsx(U,{label:"Safety margin",value:o,min:s[0],max:s[1],onChange:S=>{d(S),i(!0)},warning:v}),e.jsx(U,{label:"Fire point",value:g,min:l[0],max:l[1],onChange:S=>{m(S),i(!0)},warning:N})]}),e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsx("button",{type:"button",onClick:C,disabled:!x||f,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:x?"Save override":"Saved"}),t.threshold.isOverride&&e.jsxs("button",{type:"button",onClick:()=>c(t.modelId),disabled:f,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,"%)"]}),u&&e.jsx("span",{className:"text-[11px] text-error",children:u})]})]})}function Ee(){const[t,r]=n.useState(null),[s,l]=n.useState(!0),[a,c]=n.useState(null),[f,o]=n.useState(!1),d=n.useCallback(async()=>{try{c(null),r(await ae())}catch(x){c(x instanceof Error?x.message:String(x))}finally{l(!1)}},[]);n.useEffect(()=>{d()},[d]);const g=n.useCallback(async(x,i,u)=>{o(!0);try{await le({modelId:x,safetyMarginPct:i,firePointPct:u}),await d()}finally{o(!1)}},[d]),m=n.useCallback(async x=>{o(!0);try{await oe(x),await d()}finally{o(!1)}},[d]);return s?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(x=>e.jsx(Te,{model:x,defaults:t.defaults,safetyRange:t.defaults.safetyMarginRange,fireRange:t.defaults.firePointRange,onSave:g,onReset:m,saving:f},x.modelId))})]}):e.jsx("div",{className:"p-4 text-sm text-fg-muted",children:"No data."})}async function Re(){const t=await fetch("/api/setup-cortex-status");if(!t.ok)throw new Error(`setup-cortex status: ${t.status}`);return t.json()}async function Me(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 s;try{s=await r.json()}catch{s={error:"disabled"}}return{ok:!1,status:r.status,error:s}}async function Le(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 ze(t){return t===null?!0:t.enabled&&t.status!=="off"}function V(){const[t,r]=n.useState({loading:!0,error:null,data:null}),s=n.useCallback(()=>{r(l=>({...l,loading:!0})),Re().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 n.useEffect(()=>{s();const l=setInterval(s,5e3);return()=>clearInterval(l)},[s]),[t,s]}const b={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 Ae(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 Be(t){const r=t==="qualified"?"#1a5a1a":t==="demoted"?"#3a3a1a":"#3a1a1a",s=t==="qualified"?"#4caf50":t==="demoted"?"#ffcc00":"#f44336";return e.jsx("span",{style:{...b.badge,background:r,color:s},children:t??"unknown"})}function Ie({data:t,error:r}){return e.jsxs("div",{style:b.section,children:[e.jsxs("h3",{style:b.sectionTitle,children:[e.jsx("span",{style:{marginRight:"0.5rem"},children:"Cortex Encoder"}),e.jsx(ce,{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:b.row,children:[e.jsx("span",{style:b.label,children:"Mode:"}),e.jsx("span",{style:b.value,children:Ae(t?.encoderHealth.mode)})]}),e.jsxs("div",{style:b.row,children:[e.jsx("span",{style:b.label,children:"Asset digest prefix:"}),e.jsx("span",{style:{...b.value,...b.mono},children:t?.assetDigestPrefix??e.jsx("span",{style:{color:"#888"},children:"not available"})})]}),e.jsxs("div",{style:b.row,children:[e.jsx("span",{style:b.label,children:"Qualification:"}),Be(t?.qualification.verdict)]}),(t?.qualification.thresholdFailures.length??0)>0&&e.jsxs("div",{style:b.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 Pe(t){switch(t){case"blocker":return"#f44336";case"high":return"#ff9800";default:return"#a0a0c0"}}function _e({blockers:t,highlight:r}){const s=r??[];return e.jsxs("div",{style:b.section,children:[e.jsxs("h3",{style:b.sectionTitle,children:["Open Hard-Gate Blockers",e.jsx("span",{style:{...b.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."}),t.map(l=>{const a=s.includes(l.id);return e.jsxs("div",{style:{...b.blockerRow,...a?b.blockerRowHighlighted:{}},children:[e.jsx("span",{style:{...b.mono,fontWeight:700},children:l.id}),e.jsx("span",{style:{flex:1,color:"#e0e0e0"},children:l.title}),e.jsx("span",{style:{color:Pe(l.severity)},children:l.severity}),e.jsx("span",{style:{color:"#a0a0c0",fontStyle:"italic"},children:a?"gates this action":l.status})]},l.id)}),s.length>0&&e.jsxs("div",{style:b.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 Oe=[{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?"}];function De({data:t,onBlocked:r,onAction:s}){const[l,a]=n.useState(null),[c,f]=n.useState(null),[o,d]=n.useState(null),[g,m]=n.useState(!1),x=n.useCallback(async u=>{a(u.key),d(null),f(null),m(!1),r([]);try{const j=await Me({action:u.key,confirm:!0});if(j.ok){const v=j.result;let N=null,C=null;try{const S=await Le(v.logName);N=S.tail,C=S.complete}catch{}f({action:v.action,logName:v.logName,tail:N,complete:C,message:v.ok?`${v.action} completed (spawned: ${v.spawned})`:`${v.action} did not complete cleanly`}),s()}else j.error.error==="action_blocked_by_open_item"?(r(j.error.blockers),d("The action is blocked by an open hard-gate item and was not run.")):j.error.error==="confirmation_required"?d("The server rejected the action: explicit confirmation is required."):(m(!0),d(j.status===404?"Setup Cortex actions are disabled (off).":`Action failed (${j.status}).`))}catch(j){d(j instanceof Error?j.message:String(j))}finally{a(null)}},[r,s]),i=u=>{window.confirm(u.confirm)&&x(u)};return e.jsxs("div",{style:b.section,children:[e.jsx("h3",{style:b.sectionTitle,children:"Cortex Actions"}),Oe.map(u=>{const j=l===u.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:u.label}),e.jsx("div",{style:{fontSize:"0.8rem",color:"#a0a0c0"},children:u.desc})]}),e.jsx("button",{style:u.dangerous?b.buttonDanger:b.button,disabled:l!==null,onClick:()=>i(u),children:j?"Running…":"Run"})]},u.key)}),g&&e.jsx("div",{style:b.blocked,children:"Setup Cortex actions are disabled. Enable MEGACOMPACT_VC9B to run them."}),o&&!g&&e.jsx("p",{style:{color:"#f44336",fontSize:"0.85rem",marginTop:"0.5rem"},children:o}),c&&e.jsxs("div",{style:b.warning,"data-testid":"cortex-action-result",children:[e.jsxs("strong",{children:["Result (",c.action,"):"]})," ",c.message,c.logName&&e.jsxs("span",{style:{...b.mono,marginLeft:"0.5rem"},children:["log: ",c.logName]}),c.tail!==null&&e.jsxs("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:"0.75rem",maxHeight:"12rem",overflow:"auto",marginTop:"0.5rem"},children:[c.tail,c.complete===!1&&`
|
|
2
|
-
… (truncated)`]})]}),!t?.enabled&&!g&&e.jsx("p",{style:{color:"#a0a0c0",fontSize:"0.8rem",marginTop:"0.5rem"},children:"Cortex status unavailable — actions may not be schedulable."})]})}function $e(){const[t,r]=V(),[s,l]=n.useState([]),a=n.useCallback(f=>{l(f)},[]),c=n.useCallback(()=>{r()},[r]);return e.jsxs("div",{style:b.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(Ie,{data:t.data,error:t.error}),e.jsx(_e,{blockers:t.data?.blockers??[],highlight:s}),e.jsx(De,{data:t.data,onBlocked:a,onAction:c})]})}const We=[{id:"embedder",label:"Embedder"},{id:"thresholds",label:"Thresholds"},{id:"config",label:"Config"},{id:"game",label:"Game Mode"},{id:"achievements",label:"Achievements"}],Ue={id:"cortex",label:"Cortex"};function Ve(){const[t,r]=n.useState("embedder"),[s]=V(),l=n.useMemo(()=>{const a=[...We];return ze(s.data)&&a.push(Ue),a},[s.data]);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:l.map(a=>e.jsx(de,{pressed:t===a.id,onClick:()=>r(a.id),children:a.label},a.id))}),t==="embedder"&&e.jsx(ke,{}),t==="thresholds"&&e.jsx(Ee,{}),t==="config"&&e.jsx(pe,{}),t==="game"&&e.jsx(he,{}),t==="achievements"&&e.jsx(fe,{}),t==="cortex"&&e.jsx($e,{})]})}export{Ve as default};
|
|
3
|
-
//# sourceMappingURL=SetupTab-G-MkdQiR.js.map
|