Compare commits

..
391 Commits
Author SHA1 Message Date
zeekayandClaude Opus 4.8 cf3a9cb1e9 fix(deploy): git BFF as /git/[...path] catch-all so it wins over the SPA page (8.4.74)
v8.4.73 moved the git BFF to a top-level /git path (right — /v1/* is gateway-routed
away from Next), but used STATIC route handlers (app/git/accounts, app/git/repos).
Origin verify (pod-direct) showed the (dashboard)/[...slug] catch-all PAGE shadows a
static sibling route handler → /git/accounts served the SPA HTML, not JSON.

Fix: use the PROVEN top-level-BFF shape — a [...path] CATCH-ALL route handler
(app/git/[...path]/route.ts), exactly like /cloud, /ai, /paas, /cms. A catch-all
route handler wins over the catch-all page. One handler dispatches /git/accounts +
/git/repos. Client paths unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 18:03:40 -07:00
zeekayandClaude Opus 4.8 b0f6d6dbdf fix(deploy): serve connect-git BFF at top-level /git/* (gateway shadows /v1/*) (8.4.73)
Live verify of v8.4.72 showed the deploy hub renders in dark Tamagui (hero,
Service/Static/Container target selector, App name/Project composer, Connect-a-Git
card, Start-from-a-template card — all present, no error boundary), but
/v1/git/accounts 404'd: console.hanzo.ai's ingress routes ALL /v1/* to
hanzoai/gateway (bypassing Next), so the /v1/git/* route handlers were shadowed and
hit cloud-api (no such route → 404) — the same class the v8.4.70 CMS fix documents.

Fix: move the git BFF to the top-level Next-served path /git/* (like /cloud, /ai,
/paas, /cms), and point the GitApi client at /git/{accounts,repos}. Verified
/git/accounts reaches Next (x-powered-by: Next.js). The connect-git dropdown now
resolves the IAM-linked GitHub token server-side and lists the user's real repos
(honest "Connect GitHub" when unlinked).

The 403 on /v1/platform/projects is the honest "platform access not provisioned for
this org" path — the hub degrades to new-project mode (no crash), by design.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 17:56:05 -07:00
zeekayandClaude Opus 4.8 2335e88426 feat(deploy): "Let's build something new" hub — uniform new-project/service/site deploy (8.4.72)
Bring console's deploy-a-new-project flow up to the hanzo.app/new experience: a
single "Deploy something new" hub (Tamagui, true-black dark) that leads with
repo→deploy against the REAL per-org Hanzo PaaS, plus a real connect-git dropdown
and the real template gallery.

- New "Deploy" entry (id: new) at the top of the Platform category → DeployHub.
- Composer: paste a Git repo URL (or image ref) + target selector — Service
  (git→build→run), Static site (git→static), Container (image→run). Each maps to a
  real PaasApi.createApp shape (buildType nixpacks/static/image); no invented targets.
  Deploy watches Queued→Building→Deploying→Live on the live RailwayDeploy pipeline.
- Connect-git dropdown is REAL: ports hanzo.app's /v1/git/{accounts,repos} BFF into
  console (resolves the IAM-linked GitHub token server-side via the cloud session
  cookie; token never reaches the browser). Honest "Connect GitHub" CTA when unlinked.
- Templates: real /v1/templates gallery with "Open in builder" (hanzo.app deep-link)
  and "Browse all" → in-console /templates.
- DRY: one deploy orchestration (paas/deploy.ts launchDeploy) shared by the hub and
  the Applications New-app form; pure per-target mapping in paas/logic.ts (unit-tested).
- 33 unit tests (logic targets/detectors + launchDeploy order + git relativeTime); tsc clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 17:29:35 -07:00
hanzo-dev 8ee5d0289b docs(cms): v8.4.70 routing fix + S3-backend-500 infra note (LLM.md) 2026-07-03 17:23:41 -07:00
hanzo-dev a8b2a41d73 feat(integrations): customer-facing Connect page over /v1/integrations
Org-authed Integrations page: a logged-in org connects Slack/GitHub via
Connect buttons (card grid) that run the OAuth flow through the canonical
/v1 client — answers 'I can't just hit an API endpoint unauthed'.

- src/lib/api/integrations.ts (+.test.ts): IntegrationsApi (list/get/connect/
  disconnect) over originV1Url('integrations/...') + pure defensive normalizers,
  mirroring crm.ts. 9 tests.
- OrgIntegrationsModule.tsx: PageHeader + wrapping flexWrap card grid; per-card
  ProviderLogo/StatusTag/connectedAt + Connect (nav to authorizeUrl) / Disconnect
  (confirm+refetch); ?connected/?error callback-return toasts; available:false →
  disabled Connect + 'Not yet available'. Honest loading/BackendStateCard/empty.
- ProviderLogo: inline-SVG Slack (4-color hash) + GitHub (octocat) marks.
- StatusTag: 'connected' → green.
- registry: repoint 'integrations' entry → OrgIntegrationsModule (category
  Settings, slug /integrations = callback target); removed the old read-only
  DataTable surface (one integrations surface).
- Allow-listed 'integrations' in next.config.mjs CLOUD_V1_HEADS + proxy-allow.ts
  CLOUD_HEADS (defense in depth).

typecheck clean; vitest 1448/1448; next build ✓ (14/14).
2026-07-03 17:18:32 -07:00
hanzo-dev c458efa8f2 fix(client): re-add cloudProxyV1Url — the framework/s3 clients import it (v8.4.70 build fix)
v8.4.70's framework + storage clients import cloudProxyV1Url to address the /cloud
bearer proxy explicitly (a bare /v1/framework or /v1/s3 hits hanzoai/gateway with no
principal → 403). But that helper had been deleted from client.ts by the earlier
/v1-canonicalization, so the build failed: "'cloudProxyV1Url' is not exported from
'./client'". Re-add cloudProxyBase + cloudProxyV1Url (the <origin>/cloud/v1/<path>
builder) so the CMS/ERP/Help framework calls and the media DAM S3 calls resolve and
reach the working proxy. next build green (14/14).
2026-07-03 16:58:34 -07:00
hanzo-dev 1b07d623bf fix(s3): storage client uses the /cloud bearer proxy, not bare /v1 (CMS media DAM)
Same ingress-bypass class as the framework fix: StorageApi built its URLs with
originV1Url → `/v1/s3/*`, which console.hanzo.ai's ingress routes DIRECTLY to
hanzoai/gateway (bypassing Next), so the request lands with no principal → 403
"valid principal required". This broke BOTH the S3 file-manager product AND the CMS
media DAM (media-upload.ts presigns uploads via StorageApi).

Fix: cloudProxyV1Url → `/cloud/v1/s3/*` (the `/cloud` route reaches app/cloud's
bearer proxy; `s3` is allow-listed in proxy-allow.ts CLOUD_HEADS). Presigned PUT/GET
URLs are absolute S3 and unaffected — only the minting calls (buckets/objects/
presign) move to the proxy. Tests updated to the corrected /cloud/v1/s3 path (15
pass). Ships in v8.4.70 alongside the framework fix.
2026-07-03 16:52:22 -07:00
hanzo-dev 8b278dc279 fix(cms): framework client must use the /cloud bearer proxy, not bare /v1 (v8.4.70)
The CMS "Content" page showed "Not enabled for your account" for a real user whose
org HAS the cms module installed. Root cause: the framework client built its URLs
with originV1Url → `/v1/framework/*`, but on console.hanzo.ai the INGRESS routes
`/v1/*` DIRECTLY to hanzoai/gateway (bypassing the Next.js app), so the next.config
`/v1/framework → /cloud/v1/framework` rewrite never runs. The gateway has no
principal for that path and returns 403 "valid principal required" → the module
renders its honest access-denied card.

Fix: build framework URLs with cloudProxyV1Url → `/cloud/v1/framework/*` (the same
per-tenant bearer-proxy path CRM/Prompts/Agents use, allow-listed as the `framework`
head in proxy-allow.ts). The `/cloud` route DOES reach Next's app/cloud proxy, which
mints a short-lived user-bound token and forwards to cloud-api with the org resolved
from the token owner. Verified live: `/cloud/v1/framework/doctypes` = 200 with the
real doctypes for maxpower; `/v1/framework/doctypes` = 403 (gateway). One-line import
swap to an already-exported, already-used helper; tsc clean, framework client tests
pass.
2026-07-03 16:49:08 -07:00
hanzo-dev f930c0f504 release: v8.4.69 — branch integration (trading-bots, 7stars/yotoda brands, nodes-chains #71, inference-log-detail #58); 14 superseded branches verified already in main 2026-07-03 16:42:47 -07:00
hanzo-devandGitHub 1edd87c226 feat(inference): clickable log rows open a real per-call detail drawer (v8.4.39) (#58)
The Inference · Logs view already streamed the org's REAL recorded inference
calls (one commerce-usage-ledger row per billed call), but the rows were not
clickable and the LogLine projection discarded the rich per-call fields. Close
that gap — each row now opens the shared DetailPane showing what actually
happened for that call: model, provider, outcome, cost, prompt/completion/total
tokens, streamed, tier, product/agent attribution (only when the ledger tagged
it), request + transaction id, and time — every value REAL from the ledger
record, honest em-dash for absent. The full prompt/response TEXT is not on the
ledger row, so it is honestly stated as streaming from observability once its
trace runtime is connected — never fabricated.

DRY, no new surface: enrich LogLine with its source UsageRecord + one pure
logDetailFacts projection (logic.ts), one openLogDetail slide-over over the
existing DetailPane (panes.tsx, identical descriptor form to openEndpointDetail),
and wire onRowPress + a chevron affordance (LogsView.tsx). Reuses the shared Fact
row, StatusDot, and PrimaryButton — same look and feel as every other detail
surface.

Verification: tsc --noEmit clean; vitest 1136/1136 (+4 logDetailFacts /
LogLine.record); next build compiled successfully. Live authenticated render is
gated behind the console's server-cookie AuthGate (no backend session locally),
so verified via the component prop-level tests + a clean /[...slug] compile that
serves /inference/logs 200 in the dev server.
2026-07-03 16:38:46 -07:00
c100ba40c7 feat(nodes): surface primary-network chains per network (getBlockchains) (#71)
The Nodes surface (Network category, enabled on lux/zoo/pars + hanzo) showed
validators + peers per luxd primary network, but not the network's chains. This
adds the live primary-network chain set — the letter chains X C D Q A B T Z G K
plus the P-Chain — read from `platform.getBlockchains` through the same
same-origin, session-gated, method-allowlisted `/nodes` proxy.

- `/nodes` proxy: `platform.getBlockchains` added as the 5th (and only new)
  allowlisted luxd read method. A network counts as reporting if validators,
  peers, OR chains answered; chains are best-effort (a network can report
  validators yet not answer getBlockchains → honest empty chain list, never
  fabricated chains).
- `nodes.ts`: `RawBlockchain`/`ChainInfo` types + PURE `normalizeChains`
  (prepends the P-Chain, which getBlockchains omits; preserves reported order;
  drops id-less chains). `NetworkInventory.chains` added.
- `NodesModule`: renamed to "Networks & Nodes"; per-network card gains a Chains
  count + live chain chips; a Chains table (Network · Chain · Blockchain ID · VM)
  renders above the validators/peers table, honoring the network filter.
- Tests: +3 normalizeChains cases over the real devnet wire shape (33/33 pass).

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 16:37:09 -07:00
9ae33beea4 fix(o11y): canonical /v1/o11y reads + un-trap Observations/Users nav (8.4.68) (#83)
The still-valid residual of #77 (which #81's canonicalization couldn't carry — #77
imported the now-deleted cloudProxyV1Url). Two real bugs, redone canonically on main:

1. o11y annotation-queues + users reads hit the DIRECT-cloud origin (`v1Url` ->
   config.cloudUrl). The o11y runtime scopes tenancy by the minted bearer's owner and
   403s a cookie-only call in prod, so those 4 reads (annotationQueues/annotationQueue/
   annotationQueueItems/users) were dead on the deployed console. Switched to the ONE
   canonical `originV1Url('o11y/…')` -> `/v1/o11y/…`; next.config rewrites the o11y head
   to the `/cloud` bearer proxy (server) and the static embed reaches it directly — the
   exact transport every other o11y read (ServiceMap/Alerts) already uses. The #41 sweep
   only missed these because they were `v1Url`, not the deleted prefixed helper.

2. The `observations` + `users` catalog entries were TRAPPED inside registry.tsx's
   opening JSDoc block (the `/**` never closed before them), so they never registered in
   nav/routing despite ObservationsModule/UsersModule existing, being imported, and
   fetching real data. Closed the comment and moved both entries into the active catalog
   under Observe (beside Annotation Queues), so they render in the sidebar and route via
   the catch-all like their siblings.

Supersedes #77 (unmergeable — it referenced the deleted helper). Verify: tsc --noEmit
= 0; vitest 1475/1475 (120 files); next build ✓ (14/14, the /[...slug] catch-all that
renders the catalog compiles). Authenticated visual e2e (the 4 o11y reads returning
real data; Observations/Users in the sidebar) is post-deploy.

Co-authored-by: Hanzo AI <ai@hanzo.ai>
2026-07-03 16:33:39 -07:00
dcc8a3f8dd feat(brands): add 7stars + yotoda white-label cloud tenants
Two new white-label brands recognized by the unified console so their hosts
render branded, mirroring lux/zoo/pars:

- config: BrandId gains '7stars' | 'yotoda'; BRANDS + HOST_BRANDS entries.
  Both are general Hanzo-cloud customers seeded AS ORGS in the hanzo IAM
  (hanzo.id) — they have NO own .id issuer, so iamUrl = https://hanzo.id with
  the per-brand iamOrgName (7stars/yotoda) + iamApp (7stars-cloud/yotoda-cloud).
  Login resolves against hanzo.id, org-scoped by the JWT owner (aud=<brand>-cloud),
  matching how the orgs/apps were provisioned. Own billing.<domain>/docs.<domain>.
  HOST_BRANDS suffixes 7stars.dev / yotoda.tech cover every subdomain
  (cloud.*, console.*, admin.*) via the endsWith('.'+suffix) match.

- brand-scope: BRAND_CATEGORIES null (FULL AI-cloud catalog, like hanzo — they
  are general cloud customers, not web3-only like the sovereign-chain brands).
  BRAND_NODE_NETWORKS [] — they own no chain, so the Nodes surface reports on no
  networks (never another brand's chain).

- branding/brands: BRANDS registry gains 7Stars/Yotoda with their own
  brandName/orgName/websiteUrl/adminDomain (adminDomain is the admin-gate email
  boundary — @7stars.dev / @yotoda.tech match the seeded owners z@7stars.dev /
  z@yotoda.tech). Logo falls back to the generic Hanzo blocky-H mark (no bespoke
  asset yet); swap logoContent when a real mark ships.

Tests: index.test.ts (host resolution, hanzo.id issuer, per-brand billing/docs,
admin app) + registry-brand.test.ts (full-catalog scope, zero node networks).
npm test 975/975 green. tsc/next build add zero new type errors (diff-proven
identical to origin/main; the pre-existing next/navigation nullable errors are a
local Node 26 vs CI Node 24 toolchain drift, not from these files).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 16:31:47 -07:00
hanzo-dev 105656e4fb fix(trading): DataTable onRowPress→onOpen (main's @hanzo/data API) 2026-07-03 16:23:25 -07:00
139a9890fd chore(console): v8.4.66 — Trading + Markets (Lux DEX bots + economy dashboard)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 16:23:25 -07:00
11370836a3 console(markets): Lux Economy dashboard — DeFiLlama-style DEX analytics
Adds a "Markets" product (Web3) — the analytics/management plane for the Lux DEX
economy, the twin of the Trading (deploy/manage) module.

- lib/api/economy.ts — client + pure normalizers for the `dex` subgraph
  (markets/fills/day-data). Honest to the CLOB reality: 24h volume, trades, book
  depth, best-bid/ask, last price are real fields; USD TVL is NOT fabricated (a
  CLOB has depth, not pooled TVL); the day-history series is empty until the
  subgraph's MarketDayData producer emits.
- overview/living: fromLuxIndexer adapter + a `lux-economy` LivingOverview config
  (KPIs, volume/trades/depth donuts, recent-trade feed, maker-health row) — the
  reusable board machinery, one config + one adapter, no new overview UI.
- app/economy/[...path]/route.ts — session-gated, brand-scoped GraphQL proxy to
  graphd's `dex` subgraph (ONE fixed query, no client GraphQL); honest not-reporting
  when unreachable.
- MarketsModule — the living board + the DeFiLlama-style per-market table, both over
  the /economy proxy. Registered under Web3 (lux.cloud shows it).

Data source: luxfi/graph `dex` subgraph (markets/fills) + the maker :2112 metrics.
Tests: 23 new (economy normalizers + fromLuxIndexer); full suite 1468 green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 16:23:25 -07:00
8a25a1c287 console(trading): Trading module — deploy + manage the Lux DEX bots as cloud apps
Adds a first-class "Trading" product under Web3: deploy the market-maker and
trader bots to the Hanzo PaaS from a config form, list the org's deployed bots,
watch each one's live quote quality (the maker's :2112 metrics) and DEX order
book, and control them (start/stop/redeploy/logs).

- lib/products/trading/templates.ts — the two deployable-app definitions
  (maker + trader) with a typed config schema; toCreateAppInput maps a filled
  config → a PaaS git app (BuildKit builds luxfi/{maker,trader} → GHCR).
  Signer keys are secretRef fields (KMS-synced), never typed in the browser.
- lib/api/trading.ts — pure Prometheus-metrics + order-book normalizers.
- app/trading/[...path]/route.ts — session-gated, brand-scoped, method-allowlisted
  proxy (mirrors /nodes): scrapes the maker :2112 metrics + reads the DEX book,
  honest not-reporting when unreachable.
- components/products/TradingModule.tsx (+ trading/{logic,DeployForm}) — the
  list/status/orderbook views + deploy/start/stop/redeploy/logs, over the existing
  PaasApi control plane (one deploy path; the bots are ordinary PaaS git apps).
- registry: Trading entry (Web3, brand-agnostic; data brand-scoped in the proxy
  so lux.cloud sees only Lux networks).

Tests: 34 new (templates/normalizers/logic), full suite 1311 green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 16:23:25 -07:00
hanzo-dev fb49a9522f feat(cms): finish the native CMS — Payload-parity Lexical WYSIWYG, content-type builder, DAM, project scope (v8.4.67)
Every /cms/* URL now renders the native DocType renderer over /v1/framework/* — no
iframe, no raw JSON, no 404. Fixes the live console.hanzo.ai/cms/collections/Article
-> {"error":"Not found"} bug (the deployed image lacked the wired CMS sub-routes, so
the catch-all resolved them to notFound() and a Next RSC navigation served a JSON
404). The routes were declared correctly; this ships them complete.

- Rich text = native Lexical (the same engine Payload's MIT richtext-lexical uses),
  built fresh + thin on core lexical@0.46.0 and registered over @hanzo/data's
  `richText` type in Provider.tsx (registerField override, no fork). Toolbar:
  bold/italic/underline, H1-3 + paragraph + quote, bullet/number lists, links,
  undo/redo. Stores the Lexical EditorState JSON; read view -> sanitized HTML via
  $generateHtmlFromNodes. Pure serialization round-trips + migrates legacy plain
  Text bodies (never throws). A DocType field typed RichText renders it.
- Content-type builder: "New collection" defines a DocType's name + typed fields
  on-page (add/remove/reorder/require/list, every framework fieldtype with the extra
  inputs each needs). Pure builder-logic.ts.
- Media = real DAM: drag/drop or pick -> uploads to the org's own S3 (cms-media
  bucket, the same /v1/s3 SeaweedFS presigned-PUT as Storage) -> Media doc with the
  stable object key -> thumbnails presigned on-view; delete removes doc + object.
- Publish/Unpublish (+ Submit/Cancel) in the record editor.
- Project scope: the org->project ScopeSwitcher filters the records list and stamps
  new records, only on collections that declare a `project` field. One engine,
  project is a filter — no per-project/per-org CMS instances.

tsc clean; vitest 1418 pass (+richtext/builder/media/project/richText round-trip);
next build 14/14. Needs cloud v1.786.52+ (RichText fieldtype) deployed to accept a
RichText field live.
2026-07-03 16:22:02 -07:00
hanzo-dev a743e75ae4 feat(console): surface Hanzo Auto (workflow automation) as an Automation tile
hanzoai/auto (auto.hanzo.ai) — visual AI workflow automation over 400+ MCP tools
and agents (the n8n/Zapier surface) — was not in the console. Add it to the AI
category as an external launch tile: it's a standalone app with its own full UI
on shared Hanzo IAM, so the tile opens it already-signed-in (like the Lux/Zoo
chain apps). Scoped brands:['hanzo'] so the auto.hanzo.ai URL never leaks onto a
Lux/Zoo white-label console.

Tests: 90 registry/brand tests pass; tsc clean.
2026-07-03 16:13:42 -07:00
62901a6f3a fix(console): finish /v1 canonicalization — delete the last 3 prefixed URL builders (#81)
The CTO contract is "nothing before /v1/". PR #79 (482251e) canonicalized 7 clients
but 3 helpers still hand-rolled a service-prefixed `<origin>/<svc>/v1/` URL —
aiV1Url (/ai), cloudProxyV1Url (/cloud), commerceProxyV1Url (/commerce) — fanning
out to 6 data-product clients AND ~13 product modules. DELETING them (not just
redefining) makes a non-canonical path COMPILER-IMPOSSIBLE: there is now ONE url
builder for the whole /v1 surface (originV1Url), exactly like billing/visor/
provisioning post-#79. Every remaining caller builds the bare, prefix-free
`/v1/<resource>`; next.config rewrites each head to its UNCHANGED same-origin BFF
proxy (app/ai, app/cloud, app/commerce — service-token / user-bearer injection intact).

- delete aiV1Url/cloudProxyV1Url/commerceProxyV1Url + aiBase/cloudProxyBase/
  commerceProxyBase; repoint all callers to originV1Url (compiler-enforced, no caller left).
- aicatalog/embeddings: /ai/v1/{pricing,plans,models,embeddings} -> /v1/… ; add
  `pricing`+`plans` to AI_V1_HEADS (already in the /ai proxy ALLOWED set).
- functions/paas/framework + Builds/Environments/Pipelines/Releases modules:
  /cloud/v1/<h> -> /v1/<h>; new CLOUD_PRODUCT_V1_HEADS (functions/framework/
  environments/pipelines/builds/releases) rewrites -> /cloud (already in proxy-allow
  CLOUD_HEADS). apm(o11y) + paas(platform) heads were already rewritten.
- commerce: /commerce/v1/<x> -> the canonical namespace /v1/commerce/<x>, ONE rewrite
  -> /commerce/v1/ (the billing twin) — collision-proof vs the generic store heads
  (product/order/user/store). Local cUrl() namespaces once, in one place.
- extend canonical-paths.test.ts: aicatalog/apm/commerce/embeddings/functions/paas each
  assert /v1/<resource> + never /<svc>/v1/. Realign functions.test + client-retry
  illustrative URLs to the canonical form.

grep -rE '/(cloud|vm|ai|billing|org|commerce)/v1' src/lib/api/*.ts is clean.
tsc --noEmit ok; vitest 1439 pass; next build ok. Every console API call is now /v1/<resource>.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-03 16:10:32 -07:00
f1e97b20f9 debrand: langfuse -> o11y/observability in our prose & comments (#80)
Drop the Langfuse brand from our own strings (code comments, docs,
config labels), mirroring the signoz->o11y product rename. Meaning preserved;
comments/docs/labels only, no functional change.

Intentionally KEPT (references to the external Langfuse product / upstream
dependency / integration contract, not our brand):
- LiteLLM success_callback/failure_callback ["langfuse"] + LANGFUSE_* env
  var names (the litellm langfuse-callback contract; renaming breaks emission)
- infra/k8s/langfuse/* (deploys upstream langfuse/langfuse:3 OSS image)
- o11y/langfuse-otlp-fanout.yaml + console-langfuse-keys (trace-fanout lane)
- console NOTICE (MIT attribution to Langfuse GmbH for clean-room UX)

Trace pipeline (ai emit -> collector -> backend -> console Observe) unchanged.

Co-authored-by: Hanzo AI <ai@hanzo.ai>
2026-07-03 16:06:18 -07:00
84b53753a6 fix(playground): image/video gen calls the /ai bearer proxy directly (v8.4.66)
On console.hanzo.ai the ingress routes /v1/* straight to cloud-api, bypassing the
keyless /ai bearer proxy — so a /v1 image call reaches cloud with NO user Bearer
and 401s (premium image gen requires auth). Call /ai/v1/images|videos/generations
directly (this app → forwardWithUserBearer mints the user-bound bearer) so the
Playground Image/Video tabs generate real, per-user-metered media.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 15:56:30 -07:00
hanzo-dev 8e2718f98d Merge native ERP + Help Center over the generic DocType renderer — kill the last iframe (console v8.4.66)
feat/erp-help-native (e2baba7): ERP + Help Center now render through the SAME
generic DocType renderer (src/components/doctype/*) that draws CMS, over the ONE
framework surface /v1/framework/*. Deletes the EmbeddedApp iframe subtree
entirely: EmbeddedApp.tsx, ProvisionPanel.tsx, embed-hosts, embed-probe,
api/embed, api/cms, api/erp, and the app/{cms,erp}/[...path] proxy routes
(-1872 lines). ERP + Help + CMS are ALL native now — zero iframe in the console.

Resolved package.json version to 8.4.66 (above live v8.4.65).
2026-07-03 15:54:44 -07:00
482251e389 fix(console): route all data-product clients through the canonical /v1/* client (#79)
Decomplect: make a non-canonical API path architecturally impossible for the
data-product surface. The 7 clients that hand-rolled a service-prefixed
/<svc>/v1/… path (billing, aimetrics, compute, visor, platform, provisioning,
storage) plus the Settlement component now build a bare /v1/<resource> via the
one originV1Url helper; next.config rewrites each head to its hardened
same-origin BFF proxy (service-token / user-bearer injection unchanged). Also
stamp X-Actor-Id (the signed-in user) in baseHeaders alongside
X-Org-Id/X-Project-Id, so org+project+user pass on EVERY call.

- billing/aimetrics: /billing/v1/<x> -> /v1/billing/<x>  (rewrite -> app/billing/v1)
- compute:  /cloud/v1/gpus[/alerts|/pools] -> /v1/gpus…  (rewrite -> /cloud)
- visor:    /cloud/v1/machines… -> /v1/machines…; /vm/v1/{regions,sizes} ->
            /v1/{regions,sizes}; /vm/v1/gpus (catalog) -> /v1/gpu-sizes
            (DISTINCT head: /v1/gpus is the cloud-api INVENTORY, not the catalog)
- platform: /cloud/v1/{clusters…,org/…/cluster} -> /v1/…  (rewrite -> /cloud)
- provisioning/storage: /cloud/v1/{sql,vector,…,s3/…} -> /v1/…  (rewrite -> /cloud)
- delete the per-client base-path builders (billingUrl / vm / clustersUrl-via-cloud);
  grep -rE '/(cloud|vm|ai|billing|org)/v1' src/lib/api/*.ts is clean (only the
  client.ts BFF-helper docs for the out-of-scope clients remain).
- X-Actor-Id sourced from a new lib/actor-scope (SessionProvider keeps it in
  lockstep with the resolved account: the auth twin of org-scope).

tsc --noEmit ok; vitest 1432 pass; next build ok.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-03 15:47:19 -07:00
79d495efe8 fix(console): honest machine-load errors, chat Enter-to-send, collapse chat reasoning, logs default tab (#78)
Frontend CX defects found in a live deep-test of console.hanzo.ai:

- Compute/Machines: a non-200 from /cloud/v1/machines (esp. 403/5xx) rendered
  the empty "Launch your first machine" state — a permission/load error
  masquerading as "you have none", the opposite of the page's "nothing is
  fabricated" promise. interpretVisorError now maps 401 -> sign-in, 403 ->
  honest permission state, and any other non-200 -> a retryable load error;
  CustomerMachines shows the empty/launch state ONLY on a real 200-with-zero.

- Chat: Enter did nothing but insert a newline. @hanzogui/input swallows the
  onKeyPress prop (never wired to the DOM) and forwards onKeyDown; the newline
  default fires on keydown, so the send handler must live there. Enter sends,
  Shift+Enter is a newline, IME composition never sends.

- Chat: model chain-of-thought leaked into the answer bubble. New pure
  splitThinking() separates a final answer from <think> reasoning (streaming-
  safe); the bubble renders only the answer with reasoning behind an optional,
  collapsed disclosure.

- Observe/Logs: landed on the empty "Application logs" tab while "Request
  activity" (always real for the org) had data. Request activity now leads and
  is the default tab.

Team members (#4) already routes through the single canonical /org/iam
get-users path at HEAD — no dead-endpoint waterfall remains to remove.

Build gate: tsc --noEmit, vitest (1418 tests), next build — all green.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-03 15:09:14 -07:00
z 3595ad2644 chore(console): v8.4.65 — release image + video playground tabs 2026-07-03 14:55:46 -07:00
hanzo-dev e2baba7c8e feat(erp+help): native ERP + Help Center over the generic DocType renderer; kill the last 2 iframes (8.4.64)
ERP and Help Center join CMS as NATIVE lanes on the Hanzo Framework — thin
hosts scoping the SAME generic renderer (components/doctype/*) to module=erp /
module=help, with ZERO per-doctype UI code (the DRY proof). This finishes the
Great Unification: CMS + CRM + ERP + Help all native DocTypes, all iframes dead.

- ErpModule/HelpModule rewritten as thin hosts (like CmsModule): collections
  browser + records list + record detail, routed under /erp/collections and
  /helpdesk/collections. Install CTA installs the lane's DocTypes/hooks;
  submit/cancel + status flow come from the schema (no ERP/Help-specific UI).
- registry: erp + helpdesk -> native module routes (collections/:doctype +
  :name), repo hanzoai/cloud, native descriptions.
- CollectionsBrowser: additive optional setupDescription/setupBullets so the
  pre-install empty state reads correctly per lane. CMS default byte-identical
  -- no behavior/permission/proxy change (the RED-passed path is unchanged).
- Kill the iframe/embed subtree ENTIRELY (finishes the unification): the
  Frappe/Payload proxy route handlers app/erp + app/cms are Next catch-alls that
  SHADOWED the native /*/collections SPA routes (a route handler wins over the
  [...slug] page) -> deleting them unshadows native ERP AND native CMS (CMS was
  latently shadow-broken since 8.4.63). Removed the now-dead EmbeddedApp /
  ProvisionPanel / EmbedApi / CmsApi / ErpApi + embed-hosts + embed-probe + their
  tests. No iframe/embed path remains anywhere in the console.

typecheck clean; vitest 1360/1360 (109 files); next build green (the /cms +
/erp proxy routes are gone from the manifest, so /*/collections reach the SPA).
2026-07-03 14:39:58 -07:00
zandClaude Opus 4.8 af7ae5a085 feat(playground): image + video generation tabs (text→image/video via /v1)
Adds Image and Video tabs to the Playground, symmetric to Audio/Chat:
- ImagePlayground: Zen image model + prompt + size → POST /v1/images/generations
  → renders the real image (hosted url or inline b64).
- VideoPlayground: Zen video model + prompt → POST /v1/videos/generations
  → renders the real clip (base64 MP4 blob or url).
- PlaygroundApi.images/videos (src/lib/api/playground.ts) ride the SAME keyless
  /ai bearer proxy chat/audio use; invalidateBalance() after each (metered).
- Open images/videos in the /ai proxy allow-list (route.ts) and the
  next.config.mjs AI_V1_HEADS rewrite. No new auth, no billing bypass.

Zen-brand model ids only; pickers filter to the image/video families.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 14:37:23 -07:00
hanzo-dev 6dfa9c0598 fix(catalog): consistent brand marks — Zen always ensō, real third-party logos
The model catalog rendered logos from each model's raw provider string, so the
Zen family flip-flopped (models tagged 'hanzo' → block-H, others → ensō) and
every third-party family fell through to a gray initials chip ('QW'). Fixes:

- Rows + detail now render the model's FAMILY brand (not raw provider), so a
  family is internally consistent: Zen is ALWAYS the ensō; Qwen/OpenAI/etc. each
  show one mark. (Directive: Zen provider always uses Zen.)
- Extract pure brand resolution into ui/brand.ts (normalizeBrand + BRANDS
  registry) — unit tested, no GUI deps. Every curated family key resolves to a
  real brand-colored tile (Qwen/OpenAI/DeepSeek/Meta/Mistral/Google + Anthropic/
  GLM/Kimi/MiniMax/Nvidia/xAI); only genuinely-unknown providers get neutral
  initials (honest, no fabricated trademark logos).
- Mobile: row hides the context column on phones + narrows numeric columns so
  rows never overflow (mobile-first, $md restores the desktop layout).

Tests: 27 pass (brand 6 + families 21). tsc --noEmit clean.
2026-07-03 14:19:27 -07:00
hanzo-dev 2d7f5b1512 feat(embeddings): Ingest surface (text/GitHub/crawl) — no bespoke jobs, async→Tasks
Replaces the 'Jobs' tab/JobsView (a bespoke async-tracker) with an Ingest surface over
the ONE /v1/docs/ingest endpoint: three real sources (pasted text · GitHub repo · website)
+ a target collection. Text indexes inline; a repo or crawl returns a durable hanzoai/tasks
workflow id and the UI links to the ONE Tasks product to track it ('Track in Tasks →',
/tasks/<org>/<wid>) — there is no second async system. Lower panel = the store's REAL
indexed files (get-files), reframed honestly as 'Indexed files' not a job log. Tab + subpage
renamed jobs→ingest. EmbeddingsApi gains ingestGitHub/ingestCrawl; IngestStats gains
async/workflowId. tsc clean.
2026-07-03 14:10:23 -07:00
hanzo-dev bb88a5bdbc feat(cms): native CMS on the Hanzo Framework — kill the Payload iframe (8.4.63)
Replaces the cms.<brand> Payload iframe/Studio embed with a NATIVE, metadata-
driven surface over the LIVE /v1/framework/* DocType engine. Ships the DRY
foundation the ERP/CRM/Helpdesk lanes reuse: ONE generic framework client + ONE
generic DocType renderer (the 'one engine + one renderer renders every app' model).

- src/lib/framework/{types,client,fields}.ts — the ONE FrameworkApi client
  (doctypes/records/modules/roles over the /cloud bearer proxy, allow-listed as
  the new 'framework' head) + the pure mapper DocType metadata <-> @hanzo/data
  FieldDefinition/record for EVERY fieldtype (relation/select/currency/attach/
  check/datetime/…), relation label enrichment, slugify (URL-safe names),
  publish/media/collection helpers. 32 pure unit tests.
- src/components/doctype/* — the generic renderer over @hanzo/data's RecordsView/
  RecordDetail/RecordForm: CollectionsBrowser (module doctypes + first-run install
  + new-collection), DocTypeRecords (table, or the MediaGrid gallery for a media
  doctype; inline edit sends the FULL validated body), DocTypeDetail (view/edit/
  create/delete + publish/unpublish + submit/cancel). Zero per-doctype code.
- CmsModule.tsx is now a thin host scoping the generic renderer to module=cms.
- proxy-allow: the 'framework' head; registry: cms native routes, repo hanzoai/cloud.

Names are slug/hex only (slugify + isValidDoctypeName) so they are space-/%-free —
correct on the live engine AND through the console's own pathIsClean bearer proxy.
Per-org + honest-empty by construction: the engine enforces tenancy (principal.
Tenant) + per-DocType permissions server-side.

Cloud side (hanzoai/cloud): the CMS content model (Page/Post/Article/Media/
Navigation/Author, module 'cms') + the generic app-lane install
(POST /v1/framework/modules/cms/install).

Verify: tsc clean; vitest (framework 32); next build ✓ (14/14 pages).
2026-07-03 12:43:15 -07:00
d00eef1853 feat(observe): wire Logs + trace-search to the live o11y (SigNoz) runtime (8.4.62) (#76)
o11y's last two query signals — application LOGS and trace search — are the
composite POST /api/v3/query_range (GET /api/v1/logs is a stub). Added to the
existing ApmApi (DRY, one o11y client, same /cloud/v1/o11y/* convention as
ServiceMap + Alerts): logs()/traceSearch() + pure builders/parsers
(listQueryPayload, parseListRows, toIso, normalizeLogRow/Logs, normalizeTraceSpan/
Spans). LogsModule is now two real lenses — Application logs (live o11y logs,
range + severity/service filters, honest RuntimeNotice/empty states) and the
prior Request activity ledger lens (kept, always-real fallback). Traces/
Observations stay on /v1/evals (LLM domain), Metrics on VictoriaMetrics — no
regression. tsc 0 errors; vitest 1373/1373 (+13 apm); next build ✓.

Co-authored-by: Hanzo AI <ai@hanzo.ai>
2026-07-03 12:20:13 -07:00
hanzo-dev 90c7501c8e chore(console): release 8.4.61 — fun adjective-animal name auto-fill on machine launch
The LaunchDrawer pre-fills a fun `adjective-animal` name (dark-llama, cosmic-axolotl,
turbo-wombat) so launch is click-and-go; a 🎲 button re-rolls it, it re-rolls after each
launch, and it stays fully editable. Pure curated word lists (src/lib/naming.ts), no deps.

tsc clean; vitest 1355/1355; next build ✓. Completes #43.
2026-07-03 11:21:28 -07:00
hanzo-dev 38a588f905 feat(machines): fun random name auto-fill on the launch form
Pre-fill the machine/GPU launch drawer's Name field with a Docker/Heroku-style
adjective-animal name (dark-llama, cosmic-axolotl, turbo-wombat) so a user can
click-and-go and rapid-launch. A 🎲 button re-rolls on demand, and the name
re-rolls after each successful launch so repeat-clicking Launch keeps getting a
fresh fun name. Still fully editable.

- src/lib/naming.ts — pure adjective-animal generator (curated lists, no deps);
  randomName({ suffix }) adds a short base36 token only when uniqueness is needed.
- LaunchDrawer: lazy useState(randomName) auto-fills on mount; post-launch
  re-roll (the drawer instance persists across the DetailPane close/reopen);
  the 🎲 re-roll button sits beside the field.

The launch POST already carries this name (VisorApi.launch → /v1/machines/launch);
end-to-end launch is gated on the in-flight /v1/machines gateway route.

tsc clean; vitest 1279/1279 (+3 naming); next build ✓.
2026-07-03 11:18:20 -07:00
hanzo-dev 98fcb41e13 feat(admin): operator cockpit surfaces — Customers/Revenue/Analytics + Enablement (8.4.60)
admin.hanzo.ai fleet management (admin:true, global-admin gated via getAdminGate aggregate proxy):
- Customers (fleet-customers): live customer list + detail + AUDITED actions (grant credit, suspend/reactivate).
- Revenue (fleet-revenue): balances/spend/MRR/ARPU + per-customer table + spend trend.
- Analytics (retention): cohort retention HEATMAP + growth/churn/DAU-WAU-MAU/ARPU, honest-empty via computed[] (no fabricated curves).
- Enablement (enablement): global off/beta/ga tri-state board (#30/#31).
- Beta features (customer, non-admin): self-service opt-in (scoped to caller's own org).

Wiring: +customers/revenue/analytics/enablement to ADMIN_V1_HEADS + ADMIN_AGGREGATE_HEADS; +enablement to
CLOUD_V1_HEADS + CLOUD_HEADS (user proxy); PUT on the admin aggregate route (enablement set). Client:
AdminCockpitApi (casibase) + EnablementApi (plain JSON). Reuses DataTable/Charts/MetricCard/States, @hanzo/gui v5.
Verify: tsc clean, vitest 1337/1337 (+3 wiring), next build ✓ (/admin/aggregate registered).
2026-07-03 10:30:04 -07:00
hanzo-devandGitHub 49eff594c1 feat(compute): user-facing PaaS over cloud /v1/platform (App Platform) (#75)
A minimal, honest console for the per-org Hanzo PaaS — cloud's native
/v1/platform control plane (hanzoai/cloud clients/platform). A signed-in org
member manages their OWN container apps: list + live status, deploy/stop/start,
source-tagged deployment logs (cloud#75), KMS-sealed env (secret values ALWAYS
masked), and verified custom domains (DNS challenge records + Verify).

DISTINCT from the admin `applications` fleet board (/v1/apps) and from
internal-admin platform.hanzo.ai. Org-scoped by the Bearer owner via the /cloud
bearer proxy (the raw session cookie never reaches cloud-api).

- lib/api/platform-apps.ts — typed plain-REST client for /v1/platform/* over
  originV1Url → /cloud proxy (`platform` already allow-listed in proxy-allow.ts;
  added to next.config CLOUD_V1_HEADS so /v1/platform/* rewrites to /cloud).
- components/products/PlatformAppsModule.tsx — list + SlideOver detail
  (overview/deploy, env masked, domains + verify, source-tagged logs). Honest
  states throughout: Loader, EmptyState (create-via-CLI), BackendStateCard for a
  /v1 failure — never fabricated rows.
- components/products/platform-apps/logic.ts (+ .test.ts, 9 tests) — pure view
  logic; maskedEnvRows ASSERTS a secret's plaintext never renders.
- registry: one new 'app-platform' Compute entry.

Verify: tsc --noEmit clean, vitest 1343/1343, next build ✓ compiled. Authed
visual e2e is post-deploy (console convention).
2026-07-03 09:43:13 -07:00
zeekayandClaude Opus 4.8 eca3c36e9f chore(console): release 8.4.59 — uniform BFF CSRF gate + wallet/training authz hardening
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 09:32:49 -07:00
zeekayandClaude Opus 4.8 098a236645 harden(console): uniform same-origin CSRF gate on every hand-rolled BFF route
The same-origin CSRF guard (`sameOriginOK`) was enforced ONLY inside the shared
`forwardWithUserBearer` (the user-bearer proxies: /cloud, /ai, /vm, /commerce,
/cms, /superbase, /tasksd, /admin/aggregate). Every HAND-ROLLED cookie-auth
mutating route lacked it — so a cross-site page carrying the victim's auto-sent
cookie could drive a state change: KMS secret create/rotate/delete (/admin/kms),
PaaS control-plane deploy/scale/delete (/paas), IAM user/org/project mutations
(/admin/iam, /org/iam), billing writes + wallet credit, key mint/revoke, org
onboard, waitlist join, login/logout. `hz_session` is SameSite=Lax, but the
fallback casibase cookie's SameSite is not controlled by the console — so this
defense-in-depth guard is required, not optional.

Decomplected into ONE guard, `csrfRefusal(req, shape)` (co-located with the pure
`sameOriginOK` in bearer-proxy.ts): null on a same-origin request or a safe
method, else a fail-closed 403 in the caller's error envelope. Reads only headers
(never the body), so it composes before any req.text()/json(). `forwardWithUserBearer`
now calls it too — one policy, one place, applied to the WHOLE BFF.

Applied at the top of: forwardIam (→ /admin/iam + /org/iam), /admin/kms, /paas,
/billing/v1, /billing/v1/topup/wallet, /training, /keys, /onboard, /waitlist,
/auth/{session,refresh,signup}.

Also hardened, same "never trust the client" principle:
- /training now server-resolves X-Org-Id via `orgFor` (pins a non-global admin to
  their own org) instead of forwarding the raw browser header — matches /paas +
  /admin/kms, so a brand admin can't drive another tenant's training jobs even if
  the backend trusted the forwarded header.
- /billing/v1/topup/wallet now requires a session (`resolveUser`) and credits the
  SERVER-RESOLVED billing subject, never the client-supplied `userId` (which let a
  caller credit an arbitrary account); stamps X-Org-Id for correct ledger
  namespacing. (Commerce must still dedupe on (network, txHash) — RED handoff.)

Tests: +6 csrfRefusal cases; full suite 1340 passing, tsc --noEmit clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 09:32:49 -07:00
8c95f1ba33 feat(embed): terminate console server routes at the cloud one-binary (task #41) (#74)
Retire the remaining standalone Next server routes so the console is a pure
static SPA calling same-origin /v1/console/* (served by the go:embed one-binary,
routed through the gateway in the split deploy — one way, both topologies):

  - waitlist, embed-status, billing/v1/topup/wallet -> ported to cloud
    /v1/console/{waitlist,embed-status,topup/wallet} (real server work: Go
    handlers land in hanzoai/cloud).
  - keys, onboard -> repointed to the already-merged cloud /v1/console/{keys,
    onboard} (completes cloud#74's console side; they were still calling the old
    /keys,/onboard handlers, which broke under the static export).
  - docs -> a client redirect page (app/docs/page.tsx): a host->docsUrl map the
    browser already has (config.docsUrl); no server work, so no handler. Resolves
    the brand in an effect (no SSR/CSR hydration mismatch). Replaces the 308
    route the static export cannot run.

All calls go through the central client's v1Url() (config.cloudUrl, same-origin),
so the error envelope, cookie creds, and retry/refresh are unchanged. The ported
route.ts handlers are deleted (build:embed already stashed every route.ts; these
simply no longer exist).

Verified: tsc --noEmit clean; vitest 1334/1334 green; `npm run build:embed`
emits the full static out/ (real @hanzo/gui bundle, /docs prerendered).

NOTE: deploy the cloud image carrying the /v1/console/* handlers BEFORE this
console build (the SPA now depends on them). The remaining BFF proxies
(/cloud,/ai,/commerce,/billing catch-alls) are a separate, larger repoint for
full embed functionality and are out of this change's scope.

Co-authored-by: Hanzo AI <ai@hanzo.ai>
2026-07-03 09:30:34 -07:00
zeekayandClaude Opus 4.8 14401da5ca chore(console): release 8.4.58 — design unification (Basel Grotesk + Geist Mono typography)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 08:58:26 -07:00
Hanzo AI edd24e3f31 chore: release 8.4.57 — in-console Square card top-up 2026-07-03 04:16:51 -07:00
Hanzo AI 0b86e0dd67 feat(billing): in-console Square card top-up → canonical ledger
Replace the external-portal / HUSD-only dead-end with a real card top-up IN the
console. 'Add credits' (BillingOverview, HomeSummary), 'Top up' (SidebarWallet),
and the Billing → Credits tab now open /billing/credits: a Square Web Payments
card form that credits the org's canonical cloud-credit balance — the SAME ledger
the gateway debits for AI usage.

- BillingCredits.tsx: amount picker + Square card iframe (PCI SAQ-A — the PAN is
  entered into Square's iframe and tokenized in-browser; we only ever hold the
  single-use nonce). Pay → POST /billing/v1/topup/token via the same-origin proxy
  (service token + server-pinned subject) → commerce charges + credits the org.
  Button locks in-flight (no double-submit); nonce is single-use (no double-charge);
  honest states (config-unavailable, decline, success). Sandbox badge + test-card
  hint when the deployment is Square sandbox.
- lib/billing/square.ts: typed Web Payments SDK surface, fail-safe env→CDN map
  (non-'production' → sandbox tokenizer), pure amount validators, idempotent loader.
- BillingApi.paymentConfig() + topupWithCard() over the existing /billing/v1 proxy.
- HUSD crypto stays a secondary option (link to /wallet); no external billing.hanzo.ai.

Tests: square.test.ts (11) green; tsc strict + next build clean; full suite 1324 green.
2026-07-03 04:16:51 -07:00
hanzo-dev e4b4ce0605 release: v8.4.56 — go-live UX fixes (signup, API-key CTA, per-org metrics/logs) 2026-07-03 04:06:38 -07:00
hanzo-dev 3fe306224b console: go-live UX — email signup, Get API key CTA, per-org Metrics/Logs 2026-07-03 04:05:20 -07:00
zandGitHub 178e447f04 Merge pull request #73 from hanzoai/feat/design-landings-ship
feat(design): RailwayDeploy animation + ProductLanding kit + embeddings uplift (8.4.55)
2026-07-03 03:13:48 -07:00
hanzo-dev d1ae703521 chore: release 8.4.55 — RailwayDeploy animation + ProductLanding kit + embeddings uplift 2026-07-03 03:13:41 -07:00
hanzo-dev 87341083d9 fix(landing): use maxW shorthand on the design-reference route
next build's strict type-check (onlyShorthandStyleProps) rejects the maxWidth
longhand on a Stack; tsc --noEmit did not surface it. Also relabel the route
honestly (it is a reachable design-reference, not 'not shipped').

(cherry picked from commit 9ce0625ce413e8c3e52eaadddd327c0d2f30a759)
2026-07-03 03:13:16 -07:00
hanzo-dev 5b05304535 wip(product-landings): pick up prior agent RailwayDeploy + ProductLanding kit + embeddings uplift
Preserved from prior agent (uncommitted) before rebase onto main.

(cherry picked from commit c05ccacffceef218e54db8e6b2f67afedb9df81f)
2026-07-03 03:13:16 -07:00
zandGitHub 249edbf5e0 Merge pull request #72 from hanzoai/fix/console-e2e-bugs
fix(console): live E2E product bugs — vector/chat/functions/sign-out (v8.4.54)
2026-07-03 02:34:27 -07:00
hanzo-dev 9b1d45ca7c fix(console): live E2E product bugs — vector/chat/functions/sign-out (v8.4.54)
Five "advertised-but-broken" surfaces the live E2E suite flagged, fixed honestly
in the client (no fabrication):

- Vector module rendered nothing: normalizeResourceList validates + unwraps the
  provisioning list at the transport boundary (bare array, or a
  data/items/results/resources/collections/list/rows wrapper incl. one level of
  nesting e.g. Qdrant result.collections), honest [] fallback. A wrapped 200 body
  was reaching the list view's for..of and throwing behind the error boundary while
  SQL/KV (bare arrays) rendered. ONE place, every kind.
- /chat reply now STREAMS token-by-token via AiApi.ragChatStream (grounded RAG
  headers ride PlaygroundApi.streamChat). SSE parser canonical home moved to
  lib/api/stream.ts (one definition, re-exported from playground/stream.ts). The
  error card's Retry now re-runs the last user turn (was a no-op).
- Functions list self-freshens: useReloadOnFocus refetches on window focus /
  tab-visible so an API/CLI-deployed function appears without a reload; + Refresh.
- Sign-out redirects deterministically to /signin after DELETE /auth/session
  (AuthGate's reactive redirect could be pre-empted by an in-flight session
  re-hydrate, stranding the user on /).
- CRM summary rollup lag is BACKEND (materialized rollup eventual consistency);
  the console already refetches /v1/crm/summary after every create/delete —
  flagged, NOT faked.

tsc --noEmit clean · vitest 1290/1290 (3 new suites) · next build ok.
2026-07-03 02:32:42 -07:00
zeekayandClaude Opus 4.8 47310fd53a chore(console): v8.4.53 — canonical Hanzo typography + no-blank model rows
Integrates the Basel Grotesk (UI) + Geist Mono (code) typography pass with the
family model-browser blank-row fix. Strict superset of v8.4.52.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 01:58:34 -07:00
zeekayandClaude Opus 4.8 4c722b11bc fix(models): no blank rows — exclude meta-routers + id fallback label
The Zen family showed two nameless rows: the gateway's meta-routers (router:general,
…) bucket into Zen by provider but carry no display name, and modelDisplayName
returns '' when a record has no name. Fix both: isChatModel now excludes router:*
(a routing policy, not a pickable model — it lives in the Routing tab), and the row
label falls back to the raw id when there's no display name (displayLabel). 21 unit
tests (router exclusion + never-blank label).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 01:58:12 -07:00
zeekayandClaude Opus 4.8 ef8f531319 design: Basel Grotesk (UI) + Geist Mono (code) typography
Converge the console onto the canonical Hanzo typography without ripping the
Tamagui mechanism:
- Self-host Basel Grotesk (Book 400 + Medium 500) via @font-face in
  app/globals.css and override the @hanzo/gui (Tamagui) v5 body + heading font
  family to 'Basel' in gui.config.ts, so every Text/Paragraph/H* renders Basel
  (one place, whole product). Replaces the default system-font stack.
- Geist Mono for code/data via CDN import + a code/pre/kbd/samp rule.

Sidebar toggle (lucide PanelLeft) + true-black tokens already shipped.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 01:49:19 -07:00
zeekay 7962ca05e6 Merge remote-tracking branch 'origin/main' into fix/console-true-black
# Conflicts:
#	app/globals.css
#	package.json
#	src/components/products/ModelCatalogModule.tsx
2026-07-03 01:42:46 -07:00
zeekayandClaude Opus 4.8 ea47eb0246 chore(console): v8.4.52 — unified family model browser + Linear-caliber craft
Release: the Models module is now the unified, family-grouped model browser at
chat parity (Zen first + Qwen/Meta Llama/DeepSeek/Mistral/Google Gemma/OpenAI
GPT-OSS), true-black surface-depth ladder, skeleton loading, tabular numerals
across all metric cards + the model browser.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 01:38:43 -07:00
zeekayandClaude Opus 4.8 fc96e45617 polish(console): Linear-caliber craft on the model browser + surface depth
CTO design bar (Linear/Vercel/Stripe): elevate the flagship model surface and the
whole shell's depth.

- Surface depth ladder over true-black: $color1 #050505 (resting panels), $color2
  #0a0a0a, $color3/$color4 #171717/#1f1f1f (interactive/elevated). Cards now read
  with real depth over the #000 canvas instead of flat black — applied globally, so
  every panel (agents, metrics, cards) gains the same layering. Text-contrast scale
  ($color10–12) untouched.
- Model browser: designed skeleton loading (shimmer family cards, no spinner),
  staggered fade-in entrance (40ms), tabular numerals on every numeric column
  (context / $-per-Mtok / counts / stats) so figures align, hairline stat dividers,
  tighter type scale (family $5/800, stat $7/800 -0.5 tracking, uppercase labels),
  crisp hover rows, and a proper icon empty state.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 01:37:35 -07:00
zeekayandClaude Opus 4.8 88d729ed01 style(console): pure #000 first paint (SSR bg + themeColor)
The <html> inline background and viewport themeColor were still #0a0a0a — a hair
off the true-black the .t_dark CSS override paints. Match them to #000000 so the
very first paint (before CSS) and the mobile browser chrome are pure black too,
consistent with hanzo.ai + hanzo.chat.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 01:34:09 -07:00
zeekayandClaude Opus 4.8 a2551bf302 feat(models): family-grouped model browser (chat parity)
Replace the flat 444-row catalog table with a family-grouped browser matching
hanzo.chat's picker exactly: collapsible sections per family — Zen first (with
zen5-mini flagged Default), then Qwen · Meta Llama · DeepSeek · Mistral · Google
Gemma · OpenAI GPT-OSS — each nesting its current-gen chat models with real
context, $/Mtok price, and live-vs-catalog availability. Click a model for the
full specs/pricing/features detail panel (unchanged). Search filters across every
family; a stats strip shows families / models / available-now. Reuses ProviderLogo
+ formatters; grouping is the pure, unit-tested groupByFamily. One console home for
model selection, the same families the user sees in chat.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 01:33:36 -07:00
zeekayandClaude Opus 4.8 ccbf455f53 feat(models): curated chat-family taxonomy + live-Zen catalog merge
The unified model browser groups the live catalog into hanzo.chat's exact 7
families — Zen (house brand) first, then Qwen · Meta Llama · DeepSeek · Mistral ·
Google Gemma · OpenAI GPT-OSS. Data-driven from /v1/pricing/models joined with
/v1/models: provider-defined families match the provider string; the named slices
(Gemma ⊂ Google, GPT-OSS ⊂ OpenAI) match an id slice, so provider-grouping's
Gemini/GPT-5 noise and the HuggingFace hub mirror stay out. Current-gen chat only
(drops zen4/qwen2 sunset gens + embedding/rerank/tts/asr/image/guard modalities +
:free dup aliases). Empty families are dropped — honest to what the gateway serves.

fetchCatalog now merges live-only models the older pricing bundle omits (the
current Zen set: zen5-flash/coder/nano-*), deduped by id and name, marked Available.

Pure + unit-tested (19 cases): chat-exact curation, distill disambiguation, slice
matching, sunset filtering, Zen-first ordering, zen5-mini default.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 01:30:35 -07:00
zandGitHub e3b174dac8 Merge pull request #70 from hanzoai/fix/build-embed-static-export
fix(embed): neutralize root-layout headers() so build:embed static export succeeds
2026-07-03 01:20:18 -07:00
hanzo-dev 32146f8cea fix(embed): neutralize root-layout headers() so build:embed static export succeeds
`output: 'export'` prerenders every page THROUGH app/layout.tsx, whose
generateMetadata reads the Host header (next/headers `headers()`) to brand the
SSR <title> per host. A static export has no request, so that request-time read
throws in the Server Components render for ALL pages — the export aborted on
/_not-found (and /signin), so `npm run build:embed` emitted no out/ and the
hanzoai/cloud one-binary silently shipped the fallback shell instead of the real
console.

build-embed.mjs now, for the export ONLY, drops the layout's next/headers import
and resolves the host to undefined (→ the build-time default brand; the embed is
same-origin and re-resolves the real brand client-side from window.location),
then restores the pristine layout in the finally. The normal `npm run build`
(server build, per-host SSR <title>) is untouched.

Verified: build:embed now emits out/ (index.html ~369 KB, /_next/static
assets); app/layout.tsx is restored to pristine after the run.
2026-07-03 01:17:03 -07:00
6b838994e6 feat(console): admin AI-Providers control board — enable/disable/set-primary over gated /v1/admin/providers (#67)
* feat(console): admin AI-provider control board — enable/disable + set-primary over gated /v1/admin/providers

Adds the platform-wide provider MANAGEMENT dashboard (admin.hanzo.ai) for the
shared-gateway upstream providers (do-ai, openrouter, fireworks, openai-direct,
zen): one row per provider with a working Enabled toggle, a Primary badge +
Make-primary action, model count, a key present/missing pill (NEVER the key),
and an honest DERIVED health verdict (enabled+keyPresent=Ready, enabled+no-key=
No key, disabled=Off — labeled derived, not a live probe). DISTINCT from the
customer 'providers' catalog entry (model catalog + BYOK per-org CRUD).

Server: 'providers' added to the global-admin-gated admin-aggregate heads
(ADMIN_AGGREGATE_HEADS + next.config ADMIN_V1_HEADS); the aggregate route now
exports POST (same getAdminGate fail-closed 403 + same-origin CSRF the shared
forwardWithUserBearer already enforces on any mutating method — no new trust
boundary). New originPost in client.ts pins the mutation to the console's OWN
origin so a split-origin NEXT_PUBLIC_CLOUD_URL can't route around the gate.

Client: typed ProviderAdminApi (list/toggle/setPrimary) + optional-safe
normalizers + a pure deriveHealth. keyPresent is strict-true (fail-closed — a
provider key is never modeled or surfaced).

Integration flag: disabling OpenRouter here also gates it out of the pricing
catalog (the DO-first ENABLE_OPENROUTER sync reads provider-enabled state).

Tests: provider-admin.test.ts (deriveHealth matrix, normalizer key-leak
safety, same-origin /v1/admin/providers URL shape for GET+POST, never the
cloud host) + admin-aggregate providers head. tsc --noEmit clean; vitest
1179/1179 (97 files); next build clean (17/17, /admin/aggregate + /[...slug]
registered). Authenticated visual e2e is post-deploy.

* fix(console): admin-aggregate proxy targets cloud /v1/admin/* (integration-path fix)

The console admin-aggregate proxy (app/admin/aggregate/[...path]/route.ts) rebuilt
the upstream path as `admin/<head>` and forwarded it verbatim to CLOUD_API_URL (an
origin, no /v1), so a browser call to /v1/admin/providers hit
cloud-api.hanzo.svc:8000/admin/providers. But cloud serves EVERY admin route under
/v1/admin/* (hanzoai/ai's `/v1/*` beego glob for /v1/admin/providers{,/toggle,/primary};
cloud's own clients/admin `app.Get("/v1/admin/{overview,finance,compute,...}")`). There
is no bare /admin/* route → the provider dashboard's list/toggle/primary all 404'd.
(The overview/finance/compute boards masked the same mis-path behind LivingOverview's
honest usage-ledger fallback; provider-admin has no fallback, so it was visibly broken.)

Fix (server-side upstream path only; the browser-facing clean /v1/admin/* is unchanged):
- route.ts: build `v1/admin/<head>` (was `admin/<head>`) so the verbatim forward lands
  on cloud's real /v1/admin/* route. The rewrite destination (/admin/aggregate/<head>)
  is the internal Next route and correctly carries no /v1/ — this handler adds it.
- admin-aggregate.ts allowAdminSurface: validate the exact forwarded shape
  `v1/admin/<allowed-head>` (segs[0]==='v1' && segs[1]==='admin' && ALLOWED.has(segs[2])),
  refusing v1/admin/iam, v1/admin/kms, bare v1/admin, the pre-fix bare admin/<head>, and
  every traversal. The two-layer pathIsClean + allow-list defense (raw AND WHATWG-normalized
  path) is intact on the new shape: v1/admin/providers/../iam is refused at layer 1 (literal
  ..) and its normalized form v1/admin/iam at layer 2 (iam not allowed).

Beneficial side-effect: overview/finance/compute/orgs/audit/products/usage now also target
/v1/admin/* correctly (all shared this one proxy). next.config.mjs is untouched — its rewrite
already fires for every ADMIN_V1_HEAD incl providers, GET and POST.

Also (RED LOW-1): ProviderAdminModule toggle no longer flips the row optimistically before
the server confirms — a slow 403 never briefly renders an unauthorized 'on'; the enabled
state changes ONLY on a 2xx (the switch is disabled via `busy` in flight).

Tests: admin-aggregate.test.ts rewritten to the v1/admin/<head> shape (+ refuses the
pre-fix bare admin/<head>); bearer-proxy.test.ts +7 end-to-end forward tests proving the
upstream URL is cloud/v1/admin/providers (not /admin/providers), GET+POST forward, and
traversal / iam / kms 404 without ever fetching. tsc --noEmit clean; vitest 1187/1187
(97 files); next build ✓ (/admin/aggregate/[...path] registered).

---------

Co-authored-by: Hanzo AI <ai@hanzo.ai>
2026-07-03 01:07:44 -07:00
zeekayandClaude Opus 4.8 f7d8d118c0 chore(console): v8.4.51 — true-black theme release
Bump past the live v8.4.50 so the true-black change ships as a clean immutable
semver tag (SEMVER-only build; a branch build without a bump collides with an
existing tag).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 00:58:33 -07:00
hanzo-dev c8a4e2db16 Merge remote-tracking branch 'origin/main' into feat/obs-ui-modules 2026-07-03 00:57:48 -07:00
hanzo-dev 9f54156829 feat(console): APM Service Map — per-service RED metrics + dependency graph
New 'Service Map' product (Observe) over the real o11y/SigNoz APM controllers
via the same-origin /cloud user-bearer proxy: /v1/o11y/v1/services (RED per
service), /dependency_graph (call edges), /service/top_operations. Every KPI/
row/edge folds over what the runtime returned — honest empty/RuntimeNotice on
503/404/403/401, never fabricated APM data. Tap a service row → detail rail
(RED overview, top operations, up/downstream deps).

- lib/api/apm.ts: ApmApi client + normalizers (services/deps/ops/hosts/pods/
  nodes/exceptions/dashboards) with a stable ApmWindow.
- observability/apm-format.ts: pure RED/number/duration formatters.
- ServiceMapModule.tsx: the mounted module; wired into registry as 'service-map'.
- index.ts: barrel exports (apm NodeRow aliased ApmNodeRow — distinct from the
  blockchain nodes.ts NodeRow).

Verified: 35/35 tests pass, tsc --noEmit clean (0 errors).
2026-07-03 00:56:53 -07:00
zeekayandClaude Opus 4.8 3d93e81f73 style(console): true-black dark theme to match hanzo.ai + hanzo.chat
Override the @hanzo/gui (Tamagui) .t_dark base --background to pure #000 so the
console reads as ONE black brand with the marketing site (--background:#000)
and hanzo.chat's OLED .dark theme. Panels sit a hair above pure black (#050505
press / #171717 hover-elevated) for depth. defaultTheme was already dark.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 00:48:04 -07:00
hanzo-devandGitHub e970fa4828 Merge pull request #68 from hanzoai/feat/console2-calm-shell
console: calm, spacious design language + responsive love (v8.4.50)
2026-07-03 00:00:51 -07:00
hanzo-dev c5ea2daa53 console: calm, spacious design language + responsive love (v8.4.50)
Refine the console toward a quiet, spacious, low-glare feel that's healthy to
work in for a full day (Linear-esque FEEL, our own @hanzo/gui tokens).

Calm tokens (app/globals.css, scoped html:root.t_dark/.t_light so they win over
the generated @hanzo/gui theme on specificity — DRY, whole app calms at once):
- softer cool-charcoal surfaces with gentle elevation STEPS so cards read as
  calm panels, not flat voids on pure black
- off-white primary text (no pure-#fff glare) + muted secondary steps
- low-contrast hairline borders; comfortable body line-height + antialiasing

Sidebar (DashboardShell):
- calm neutral section headers (Linear-style) instead of a saturated rainbow;
  per-product COLOR now lives only on the icons (restrained accent)
- softer active state ($color4, not the loud $color5 block)
- more breathing room: taller category headers, larger row + section gaps,
  responsive rail padding (collapsed vs expanded)

Big desktop: content is a centered, capped column (max 1680) with padding that
scales up at xl — wide screens read comfortably, not stretched full-bleed.

Responsive:
- PageHeader wraps (flex + minW) so long subtitles wrap on mobile instead of
  running off-screen; actions drop below the title when narrow (DRY, every page)
- Inference "Usage Overview" overlap fixed: MetricStat no longer flex-collapses
  (flex-basis:0 in an auto-height column made the label overlap the value)

typecheck 0 errors · 1167 tests · next build green.
2026-07-02 23:58:28 -07:00
hanzo-dev b39a3ae95c feat(models): model detail 'Try in Playground' preselects the model (deep-link ?p=)
The Model Catalog rows already open a rich detail pane, but the detail's primary
action pushed a bare /playground and DROPPED the model the user was looking at — it
looked wired but lost the selection. Now it deep-links /playground?p=<share> carrying
that model, so the Playground opens PRESELECTED on it (the composer restores the model
from the ?p= share state it already reads on mount). Same fix applied to the
Marketplace 'Try' CTA — both reuse ONE pure helper.

- New pure playgroundPathForModel(modelId) in playground/share.ts — the ONE way to
  deep-link the Playground onto a model (URI-safe; empty prompt, default settings).
- ModelCatalogModule detail: 'Open in Playground' → prominent 'Try in Playground'
  (theme=light) via the helper; routing/copy reuse the derived modelId.
- MarketplaceModule.open(): available model → playgroundPathForModel(id) (was bare
  /playground); catalog-only → /models. DRY, one deep-link path.

tsc clean; +2 share tests (round-trip + slash/space id), marketplace 16/16.
2026-07-02 23:56:32 -07:00
hanzo-dev d94e62e53d feat(base): Twenty-grade records surface (@hanzo/data 1.2.0); CRM = Base views
Base records (RecordsModule) now render the @hanzo/data RecordsView — table <-> board,
filter/sort/group, inline cell edit, kanban drag — over REAL per-org Base data via the
/superbase proxy (new base-data/CollectionView; inline edits + board moves persist through
BaseDataApi.updateRecord, honest error banner). CollectionTable superseded (one way).
RecordDetailView gains a titled detail panel; DnsModule onRowPress -> onOpen (new DataTable API).

CRM = Base views: CrmModule renders companies / contacts / opportunities through the SAME
RecordsView — CRM entities expressed as @hanzo/data FieldDefinition schemas + pure record
mappers (crm/collections: money->currency, epoch-s->ms, companyId->named relation chip);
opportunities get a stage PIPELINE board; company relation options injected for filter.
Live create stays; delete preserved + upgraded to bulk-delete via row selection. Read-only
views over live data (no /v1/crm update endpoint yet) — honest by construction.

@hanzo/data 1.1.0 -> ^1.2.0. Rebased on latest main (8.4.49 -> 8.4.50).
tsc clean; vitest 1198 green (+ crm/collections); next build green.
2026-07-02 23:56:07 -07:00
hanzo-dev 21a72fdd0f feat(gpus): tap-to-launch customer GPU catalog — every accelerator row opens the launch drawer preselected
The customer GPU catalog rendered as non-clickable rate rows (Overview 'Popular
accelerators', the GPUs-tab 'GPU catalog', and the Pricing tab) — real live visor
data, but it read like a static brochure. Now every accelerator row is TAP-TO-ACT:
tapping one opens the shared LaunchDrawer (kind=gpu) preselected on that accelerator's
size slug (the drawer already supports initialSize), so the price you see is the price
you launch. Same pattern as machines PR#57's MachineCatalog → onLaunch.

- launch() now takes an optional initialSize (memoized); launchGpu(row) = launch(row.slug).
- onRowPress wired on all three catalog DataTables + the Pricing tab (new optional onLaunch prop).
- Header / empty-state / settings 'Launch' buttons fixed to () => launch() (no event-as-size).
- Honest copy: 'tap to launch' hints; no fabricated data (empty catalog still honest).

tsc clean; gpus vitest 10/10.
2026-07-02 23:52:42 -07:00
bf8bd89f1e feat(console): Overlord admin god-view + Web Search/Crawl product panel (v8.4.49) (#66)
Two surfaces, both over the ONE /v1 surface with real data + honest states,
reusing the existing LivingOverview + design system (DRY, no new UI systems).

Surface 1 — admin.hanzo.ai "Overlord" overview (god-view of EVERYTHING):
- New living-overview config `overlord` + pure adapter `fromOverlord` composing
  THREE real sources: the operator inventory (PlatformApi.apps → the platform-wide
  PRODUCT HEALTH board + product/healthy/needs-attention counts + distinct-org
  count — the centerpiece), the all-orgs `/v1/admin/overview` aggregate
  (usage/spend/top-models/activity/alerts) when routed, and the real commerce
  usage ledger (all-orgs) as the honest fallback so the board is never blank.
- New `overlord` catalog entry (Observe, admin:true) rendered by the ONE
  LivingOverview. GLOBAL-ADMIN ONLY: hidden from every customer's nav/launcher/
  palette (visibleCatalog filters admin entries), the catch-all shows the managed
  notice for a non-admin, and `/v1/admin/overview` is server-gated by getAdminGate.
- Pure health-tally helpers (`healthTally`, `orgsFromApps`) — every product-count
  KPI is derived from the real inventory, never fabricated (empty → honest em-dash).

Surface 2 — Web Search + Crawl product panel (SearXNG + Crawl4AI, LIVE):
- New `WebSearchApi` (lib/api/websearch.ts) over cloud `/v1/websearch/*`; search
  wired same-origin prefix-free `/v1/websearch/search` → the hardened `/cloud`
  user-bearer proxy (added `websearch` to CLOUD_HEADS + CLOUD_V1_HEADS — minimal,
  additive; distinct arrays from the concurrent providers lane).
- New tabbed `SearchModule` (Overview · Try Search · API · Engines · Config) —
  a REAL live search box, honest live-probe health (no health endpoint exists),
  the two endpoints + copy-paste curl, the deployed engine set (read-only), and
  the honest deployed config. HONEST GAPS surfaced, not hidden: usage is not
  metered yet (no cloud_usage rows for websearch), and scrape is documented but
  NOT a live try-it (it needs the shared WEBSEARCH_API_KEY, not a user session —
  so the console can never drive a scrape; no secret is ever exposed).
- The `websearch` + `crawl` catalog entries render the one module (crawl upgraded
  from a native-overview stub — one product, cross-linked, no duplicate surface).
  Tab slugs are non-base (search/api/engines/config) so they never collide with
  the shared Settings/Status/Logs/Metrics per-product sub-pages.

Verification: tsc --noEmit clean; vitest 1191/1191 (98 files; +28: 7 Overlord
adapter, 8 websearch normalizers, 9 search logic, 1 websearch allow-list, +3
registry-consistency now covering the new configs); next build ✓ (all routes;
/overlord + /websearch/* + /crawl all resolve 200 on the dev server, catch-all
compiles clean). Live authenticated visual e2e (admin session) is post-deploy.

Co-authored-by: Hanzo AI <ai@hanzo.ai>
2026-07-02 23:39:47 -07:00
zandGitHub 11b622d454 Merge pull request #65 from hanzoai/fix/broken-links
fix: repair broken links (deep-audit workflow)
2026-07-02 23:02:28 -07:00
hanzo-dev 87c3df0de3 fix: correct 3 broken links (cost→billing route, embeddings docs path)
- SidebarWallet balance row: router.push('/cost') → '/billing' (no 'cost'
  module in the registry; billing is the canonical balance/spend surface).
- HomeSummary 'View cost' button: same /cost → /billing fix.
- Embeddings SettingsView docs button: docsUrl/embeddings → docsUrl/docs/embeddings
  (Fumadocs serves only under /docs/*; matches the docsUrl() /docs convention).

Also updated the stale SidebarWallet docstring that referenced the removed /cost.
2026-07-02 22:49:23 -07:00
d7d142fc04 fix(console): per-host brand in SSR <title> (white-label) + release 8.4.48 (#64)
The document <title> is SSR metadata resolved from the build-time default host,
so console.lux.cloud / console.zoo.cloud tabs read 'Hanzo Cloud Console' — a
white-label violation (Hanzo name on a Lux/Zoo surface). Read the request Host
header in generateMetadata and resolve the brand per host, so the tab title is
'Lux Cloud Console' / 'Zoo Cloud Console'. The visible shell was already correct
(client resolves brand from window.location); only the SSR title leaked.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 22:29:01 -07:00
zandGitHub b7ecab0c2f Merge pull request #63 from hanzoai/chore/release-8.4.47
chore(release): console 8.4.47 — customer Domains panel + Apps view
2026-07-02 22:02:45 -07:00
hanzo-dev daa24fa7a7 chore(release): console 8.4.47 — ship customer Domains panel + BYO custom-domain verify (#62) 2026-07-02 22:02:38 -07:00
zandGitHub 406aaa54bc Merge pull request #62 from hanzoai/feat/paas-domains
feat(paas): customer Domains panel — add/verify BYO custom domains from console
2026-07-02 22:01:45 -07:00
hanzo-dev 35e9d66247 feat(paas): customer Domains panel — add / verify BYO custom domains from console
Gap 1 (console self-serve domains UI) over the live /v1/platform/.../domains
surface (via the /cloud bearer proxy, org from the Bearer owner):

- lib/api/paas.ts: PaasDomain + listDomains/addDomain/verifyDomain/removeDomain.
- DomainsPanel.tsx: a Domains section on the app detail — lists the default host,
  org-subtree hosts, and BYO custom domains with an HONEST per-domain status from
  the operator CR (live / provisioning / awaiting deploy / unverified, never
  fabricated); an Add-domain form; per-domain Remove; and — for a pending custom
  domain — the exact DNS records to publish (TXT + CNAME, with copy) plus a Verify
  action that flips it live with TLS. Default host is non-removable.
- paas/logic.ts (+tests): pure isPendingCustom / canRemoveDomain / domainStatusLabel
  / orderDomains. Wired into PaasApplications AppDetail.

Drive-by: fix a pre-existing origin/main tsc error in overview/living/
open-edition.test.ts (vi.fn<[Args],Return> → single-function-type form the
installed vitest requires) so `tsc --noEmit` is green. Not caused by / related to
this feature; next build (which excludes tests) never surfaced it.

Verify: tsc --noEmit clean; vitest 1167/1167 (+12 domain logic); next build ✓.
2026-07-02 21:58:24 -07:00
hanzo-devandGitHub b4e3996a8c feat(embed): build:embed static export for the cloud one-binary (task #41) (#61)
The hanzoai/cloud Go binary go:embeds the console SPA and serves it at its own
web root; the Dockerfile already looks for `npm run build:embed` to produce the
static bundle. This adds that target — the last piece of 'True 1-binary FE'.

- next.config.mjs: CONSOLE_EMBED=1 → output:'export' + images.unoptimized and
  DROPS the aiSurfaceRewrites (a static export cannot run rewrites, and does not
  need them: the clean /v1/<head> the SPA already builds terminates directly at
  the embedded cloud's mounted /v1 subsystems, which is what the rewrites used to
  forward to via the Next BFF). The normal `npm run build` (server build) is
  UNCHANGED, so the standalone console deployment never regresses.
- scripts/build-embed.mjs: prepares the app for output:'export' for ONE build and
  ALWAYS restores it (finally block; main stays byte-identical):
    (1) stashes every app/**route.ts — a static export has no runtime for a
        server route handler; the BFF proxies collapse to cloud /v1/* and the two
        standalone routes (keys/onboard) are ported to cloud /v1/console/*.
    (2) overlays the two dynamic client pages ([...slug], discover/[id]) with a
        force-static server wrapper (generateStaticParams + dynamicParams=false)
        so they satisfy output:'export'; the real client body still ships in the
        JS bundle (client nav hydrates it) and deep links hit the host's SPA
        fallback (cloud/webui.go serveIndex → index.html) which re-resolves them.
- build:embed npm script.

Proven: `npm run build:embed` → out/ (47 files, 6 html incl. discover/ + the
SPA-shell index.html at 376 KB); working tree restored clean after.
2026-07-02 21:52:15 -07:00
hanzo-dev 872d5179df fix(base): drop the last competitor name from the assistant prompt + green main
The whole-repo sweep after v8.4.42 caught the one remaining user-facing Base
competitor reference: the built-in assistant's system prompt described Base as a
'Firebase-style backend' (from the v8.4.43 grounded-assistant lane). Rewrote it in
Hanzo's own voice — 'a realtime backend — spin up per-org Bases with content types,
records, and auth'. The console is now free of Supabase/Firebase user-facing copy.

Drive-by: open-edition.test.ts (#60) used the old vitest vi.fn<[Args],Return>() form
that vitest v3.2.4 rejects — main's tsc was RED. Migrated to the v3 single-fn-type
form. tsc clean, vitest 1163/1163, next build green.
2026-07-02 21:24:22 -07:00
hanzo-devandGitHub 77ad2ec7af feat(overview): Open Edition (run-for-pay) living overview + visual gate (#60)
Add the Open Edition / run-for-pay overview as a living-overview config
(add-a-product = 1 config) that renders from the REAL commerce usage
ledger scoped to the `open-edition` product tag. Spend billed = the
served-revenue figure R (cost + 25% resell margin) per the pricing spec.

- living/registry.ts: `openEditionOverview` config + `open-edition` map
  key. Reuses UsageApi.overview({ product: 'open-edition' }) + the
  existing fromCloudUsage adapter (DRY) — honest-empty when no run-for-pay
  usage, never a mock.
- products/registry.tsx: `livingOverviewModule('open-edition')` + a
  catalog entry (Observe category) → the board lives at /open-edition.
- living/open-edition.test.ts: behavioral proof the loader forwards the
  `open-edition` product scope, maps real data through fromCloudUsage,
  and rolls up honest-empty (4 tests).
- e2e/open-edition.spec.ts: dedicated Playwright visual gate asserting the
  run-for-pay header, the cost+25% Spend KPI caption, and the spend/tokens
  KPIs render; captures a full-page screenshot.
- e2e/pages.spec.ts: add `open-edition` to the all-pages screenshot sweep.

Canonical model: universe docs/architecture/run-for-pay-pricing.md (price)
+ run-for-pay-and-contributor-revenue.md (settlement).

Additive only (no deletions); does not touch the concurrent session's
staged adapters.ts / registry.test.ts.
2026-07-02 21:17:39 -07:00
hanzo-dev 2fdd72162c console: real per-product Status/Logs/Metrics/Settings — one metadata-driven system (v8.4.45)
Make every product's shared base sub-pages real, correct, and per-product via ONE
metadata source, no fabrication.

- Metrics: consolidate the ledger-scope decision to sources.ts metricsScopeFor (kill
  the dead MetricsFeed/O11Y_METRICS_PRODUCTS dup); every product filters by
  metadata.product===id (honest-empty, never the org total); the inference surface
  (inference/models/api/gateway) reads the whole ledger with an explicit honest
  'org-wide inference' banner + scope-aware subtitle.
- Status/Logs: verified SERVICE_OVERRIDE (models, bot->bot-gateway, helpdesk->help)
  grounded in the live /v1/apps inventory; fix console spec service console2->console;
  neutral+honest 'no operator row' copy; Logs-specific honest managed card.
- Settings: settingsConfigFor surfaces real product-specific config (reuse the overview
  spec facts+actions, else category default) — a real Configuration card, not a dead form.
- Overview: console spec health repointed; defaultSpec stays honest.

Only subpage/*, overview/*, overview/living/* + per-product metadata. Did NOT touch
AgentsModule/agents/* or assistant/*. tsc clean; vitest 1140/1140; next build green.
2026-07-02 21:16:26 -07:00
hanzo-dev 9daefa19bf fix(agents): key single-agent detail + delete on NAME not the display id (v8.4.44) 2026-07-02 21:15:03 -07:00
zandGitHub acdecfbef2 Merge pull request #59 from hanzoai/feat/compute-admin-clusters-functions
feat(compute): Clusters + Functions admin boards (kind spectrum)
2026-07-02 21:13:27 -07:00
hanzo-dev 0825f9b328 release(console): v8.4.43 — built-in assistant is a grounded Hanzo-suite expert
Make the console's built-in chat assistant a genuine expert on the whole Hanzo
suite, GROUNDED in real sources (the product registry + docs RAG), never
hallucinated — ONE shared system prompt across all three chat surfaces.

- src/lib/assistant/: decomplected into a PURE builder (prompt-content.ts,
  unit-tested) + a thin registry-bound wrapper (system-prompt.ts). Catalog
  section generated FROM the live registry (visibleCatalogByCategory) — all
  products, per-category, name+description+GCP-analog+deep-link; complete,
  current, brand-white-labeled, admin-gated for customers. Plus a curated
  accurate 'what Hanzo is' overview + an honest behavior contract (never invent;
  say so when Hanzo lacks a thing).
- Wired DRY into ChatConversation (=> FloatingChat bubble + full /chat page) via
  AiApi.ragChat, and CommandPalette >/? via commandBarSystemPrompt (base + NAV
  contract) — replaces the old nav-only prompt.
- AiApi.ragChat gains optional history (backward-compatible) for grounded
  multi-turn; X-Retrieval store 'docs' shared, degrades gracefully.

tsc clean; npm test 1142/1142 (+10); next build green. Rebased on v8.4.42.
2026-07-02 21:11:48 -07:00
hanzo-dev 9e7600529e feat(base): Bases manager — create/configure per-org Base instances, drop competitor copy
Base was a content-type dashboard over the SuperBase orchestrator's own
collections (contacts/tenants/users), so the org saw one shared Base and had no
way to make another — 'stuck with a single base'. Rework it into the Base
INSTANCES manager over the real tenants API (each row = a Base on its own
<slug>.base.hanzo.ai), so the user can SEE all their Bases, CREATE a new one, and
CONFIGURE one (name/size/status/delete). One Base binding — the /superbase proxy
(user bearer + X-Org-Id from the JWT owner, derive-once). Clean split from
Records (which browses a Base's collections + records).

- NEW lib/base-data/tenants.ts (BaseTenantsApi over the tenants collection)
- NEW base/bases-logic.ts (+test): slug/validate/size presets/status
- NEW base/BasesManager.tsx: list + New Base + configure
- BaseModule -> BasesManager; registry routes ''|new|:base
- Drop the Supabase/Firebase copy + gcp:'Firebase' from the Base entry
- Remove the superseded content-type dashboard (BaseDashboard/CollectionBuilder/logic)

Copy: no competitor names in the Base UI or docstrings.
2026-07-02 21:04:25 -07:00
hanzo-dev dbd42ef40b feat(compute): Clusters + Functions admin boards (kind spectrum)
Extend the admin compute-analytics boards from bot/machine to the full
kind spectrum so DOKS clusters, node pools and Functions surface in
admin.hanzo.ai like Bots/Machines.

- admin-compute.ts: widen ComputeKind to bot|machine|cluster|nodepool|
  function; asKind now canonicalizes over the whole spectrum (fallback
  machine, mirror of visor CanonicalKind) so a cluster/nodepool/function
  row never pollutes a sibling board via keepKind.
- ComputeModule.tsx: KIND_UI entries for cluster/nodepool/function;
  ClustersModule (kind=cluster) + FunctionsModule (kind=function) thin
  wrappers over the ONE ComputeBoard, mirroring Bots/Machines.
- registry.tsx: register cluster-fleet + function-fleet (admin:true,
  category Observe), distinct from the customer clusters/functions
  products (same split as vms vs machines).
- admin-compute.test.ts: cover the widened spectrum (cluster/nodepool/
  function fold + kind-filtering, unknown-kind fallback).

Honest-empty until the emitters + cloud read land. DRY: one ComputeBoard,
one datastore aggregate, one kind canonicalizer.
2026-07-02 20:39:24 -07:00
hanzo-dev f5a82a152d console: bump 8.4.41 (Authz + Settlement repoint) 2026-07-02 20:31:27 -07:00
hanzo-dev d30108ec04 console: repoint Authz→cloud /v1/authz/policies (real Casbin rules) + Settlement→commerce /v1/billing/payouts (real payout ledger)
- AuthzModule: off dead /paas onto /cloud user-bearer proxy → cloud authz
  subsystem (hanzoai/authz) GET /v1/authz/policies; per-org enforcer picked
  from the Bearer-derived X-Org-Id. Match FE type to the Casbin [sub,obj,act]
  tuple (effect always allow); honest-empty + PlatformStateCard on failure.
- SettlementModule: off dead /paas onto the existing /billing/v1 commerce
  proxy → GET /v1/billing/payouts (ListPayouts), org-scoped server-side.
  Match FE type to commerce payoutResponse (amount cents/currency, status,
  destinationType/Id, created). 501 when COMMERCE_TOKEN unset → honest card.
- authz head already admitted in proxy-allow CLOUD_HEADS + next.config
  CLOUD_V1_HEADS.
2026-07-02 20:30:53 -07:00
hanzo-dev cb6d3418ae feat(console): connect Indexer + Oracles pages to cloud /v1/*
Repoint the last two "not connected" chain-data pages off the admin
/paas proxy onto the native cloud user-bearer proxy, backed by the new
cloud clients/graph subsystem:

- IndexerModule: restGet(paas('indexers')) -> cloudProxyV1Url('indexers')
- OraclesModule: restGet(paas('oracles'))  -> cloudProxyV1Url('oracles')

Admit both heads on the /cloud proxy: add indexers,oracles to
next.config.mjs CLOUD_V1_HEADS and proxy-allow.ts CLOUD_HEADS. Bump
8.4.39 -> 8.4.40 so a fresh image builds.
2026-07-02 20:29:56 -07:00
hanzo-dev cb4be5be13 console: repoint Alerts to native o11y /v1/rules; honest Logs; bump 8.4.39
Alerts: restGet('/paas/alerts') -> cloudProxyV1Url('o11y/v1/rules'), the real
hanzoai/o11y alert-rule-states route (cloud mounts /v1/o11y/*, reverse-proxies to
the o11y Deployment which rewrites /v1/o11y/* -> /api/v1/rules; listRules ->
ListRuleStates). Normalize the flattened GettableRule envelope
{status,data:{rules:[…]}} to the flat Alert row: name<-alert, severity<-labels.
severity, status<-state (or 'disabled'), condition<-description. lastFired left
empty honestly (rule-list carries no last-fired timestamp).

Logs: kept honest. o11y's GET /v1/o11y/v1/logs is a hardcoded empty stub and the
only real log read is a composite POST query_range — no clean logs-list route to
repoint to. Copy now names the true gap (needs a real logs-list route) instead of
the stale "VictoriaLogs not deployed"; nothing fabricated.

Status: unchanged — already on native VictoriaMetrics up{} via /telemetry (real
data). Repointing to platform apps would regress to a different, empty concern.

Heads: add 'o11y' to next.config CLOUD_V1_HEADS + server/proxy-allow CLOUD_HEADS
so /cloud admits the o11y sub-surface.
2026-07-02 20:28:39 -07:00
hanzo-dev 773d1a6522 fix(theme+gpus): apply org accent via Tamagui props (className not forwarded on Button) + Pools honest-empty
Theme (the real apply): v8.4.36's accent used a CSS class (hz-accent-fill) on the
accent surfaces, but Tamagui does NOT forward className to a Button's DOM node
(only to Stacks), so the org's saved brand color never recolored anything. Rebuilt
the mechanism to be Tamagui-native and verified LIVE: src/lib/theme/accent.ts now
holds the resolved accent in a tiny external store (setOrgAccent, called on load by
OrgAccentProvider AND on save by SettingsModule) exposed via useAccent(); the genuine
accent surfaces (PrimaryButton, the active GPU/Settings tabs, the active sidebar nav
item) recolor with real @hanzo/gui props — inline bg + readable contrast text (light
accent -> black text, dark -> white), the nav via an accent left-bar — reverting to
the default monochrome when the org disables its theme or the hex is invalid.
Verified in a browser: enable green -> primary button green + white text; yellow ->
black text; disable -> reverts (no inline style). Dead globals.css accent block +
classNames removed.

GPUs Pools tab: now honest-empty 'No GPU node pools yet' whenever the org has no
reachable GPU clusters (none provisioned, or the native /cloud/v1/clusters endpoint
isn't live) — a pools-specific state distinct from the Clusters tab, never a
fabricated pool. (Pools are derived from the org's real clusters.)

Rebased on v8.4.37 (Inference dashboard) — strict superset. tsc clean; vitest
1132/1132 (+2 accentFor); next build green.
2026-07-02 19:55:49 -07:00
hanzo-dev 6307b49d3d feat(inference): rich endpoints dashboard + Status/Logs + shared per-product Metrics — all real data (v8.4.37)
Redesign the Inference page to the endpoints-dashboard mockup, wired to REAL sources
(honest '—'/empty where unexposed — never the mockup's placeholder numbers). Sidebar +
topbar untouched; only the Inference module content + the shared Metrics sub-page changed.

- Endpoints = managed model catalog (/v1/models) merged with the org's deployed KServe
  InferenceServices (cloud /v1/ml/models; new 'ml' /cloud head in proxy-allow + rewrite).
  Per-endpoint Requests(24h) + trend sparkline = REAL usage ledger by model id; KServe phase
  from live status.conditions; P95/uptime honest '—'.
- Hero 'Connected to Hanzo Cloud' (honest managed copy + purple SVG accent), purple Deploy
  Endpoint CTA (real POST /v1/ml/models), right rail Usage Overview (real ledger window +
  prior-period deltas) + Quick Actions + Need help (real routes/links).
- Inference OWNS Status + Logs as :tab views (health board + real recorded inference
  activity), declared as specific subpages so the router renders them.
- Shared per-product Metrics -> product-parameterized LivingOverview over the real usage
  ledger scoped by metadata.product; new byStatus + tokens breakdowns. P95 honest '—'.

tsc clean; vitest 1130/1130; next build green. Rebased on origin/main (v8.4.36) -> v8.4.37.
2026-07-02 19:25:56 -07:00
hanzo-dev d47424a5a7 fix(gpus): real tabbed customer GPU view + wire org accent theme
GPU tabs (the customer bug): a non-admin's GPU page rendered the same static
catalog for every sub-tab (Clusters/Pools/Pricing/Alerts all showed the GPU
catalog) because CustomerGpus was one static component with no tab bar. It is now
TABBED like AdminGpus — the shared GpuTabBar + GPU_TABS (one source of truth,
router.push navigation), active tab from params.tab — with DISTINCT, customer-
scoped, per-org content per tab:
 - Overview/GPUs: visor catalog (/vm /v1/gpus) + the org's own GPU machines.
 - Clusters: the org's own clusters (PlatformApi.listClusters -> user-bearer
   /cloud/v1/clusters), honest-empty; reuses ClustersTab (DRY).
 - Pools: GPU node pools derived from the org's real clusters (honest-empty).
 - Pricing: the REAL per-accelerator price list from the live visor catalog.
 - Alerts: real alerts derived from the org's own GPU machines' health; reuses
   AlertsTab (DRY), honest-empty when healthy.
 - Settings: honest per-org GPU settings + real counts.
AdminGpus behavior is unchanged (now shares GpuTabBar/GPU_TABS). Pure derivations
(gpuPoolsFromClusters/gpuAlertsFromMachines/catalog stats) are unit-tested — real
per-org data or honest-empty, never fabricated.

Theme accent (folded in): the org's saved brand color (themeData.colorPrimary +
isEnabled) was persisted but never applied. Added src/lib/theme/accent.ts
(applyOrgAccent -> one root --hz-accent CSS var + data-hz-accent) applied on load
(OrgAccentProvider) AND immediately on save (SettingsModule). Genuine accent
surfaces read the one var via hz-accent-fill/hz-accent-bar (PrimaryButton, active
sidebar nav, active tabs) — DRY, reverts to default when disabled/invalid.

tsc clean; vitest 1092/1092 (+16 new); next build green.
2026-07-02 19:20:58 -07:00
hanzo-dev 7821fda0f1 feat(nav): collapsible category accordion in the sidebar product nav (v8.4.35)
Each level-1 CATEGORY is now a collapsible section: the header is a clickable
button with an obvious rotating chevron (▸ collapsed, ▾ expanded), keyboard-
toggleable + aria-expanded, over its product rows revealed in order when open.
The ~120-item flat list condenses to 13 tidy topic headers so the nav stops
overwhelming the user.

- Pure model: src/lib/products/nav-accordion.ts (categoryIsOpen/toggleCategory,
  10 unit tests). Default COLLAPSED for most; the active route's category is
  always open (navigating reveals it, even if collapsed); filtering opens every
  matching group so search is never hidden; clearing search restores collapse.
- Persisted per-user via usePreferences (account-backed + localStorage cache,
  the existing sidebarCollapsed idiom) under navCategoriesOpen — survives reloads
  + navigations, never clobbers other choices.
- CategorySection in DashboardShell; body animates height (grid-rows 0fr<->1fr) +
  opacity via .hz-acc, chevron rotates via .hz-chevron, both reduced-motion-
  guarded; collapsed body is inert (out of tab order). Shared by the desktop
  sidebar AND the mobile drawer (one SidebarNav). Items/icons/colors/routes/
  active-state unchanged; only the grouping is now collapsible.

tsc 0 errors, vitest 1086/1086 (+10 nav-accordion), next build green.
2026-07-02 19:18:31 -07:00
hanzo-dev 84bebb264e fix: P0 fetch-binding regression + live-shape corrections + Playground multi-image/image-only (v8.4.34)
P0 [CRITICAL]: v8.4.33 resilientFetch called the global fetch as a METHOD
(deps.doFetch(url,init) → this=deps) → the browser threw 'Failed to execute fetch
on Window: Illegal invocation' on EVERY cloud/BFF call — the whole API layer broke
(Analytics/Models/CRM/CMS/... all 'Could not reach the backend'). The client-retry
unit tests passed because they injected a MOCK doFetch (no this requirement) — the
exact class a mock hides. Fixed: destructure const doFetch = deps.doFetch and call it
BARE (this=undefined) — works for a raw global fetch AND a wrapped one. New regression
test simulates a global-only fetch (throws unless this is the global) and asserts the
bare invocation. Live console was rolled back to v8.4.31 on detection; this is the fix.
LESSON: verify a shared-fetch refactor by RENDERING a live data page, not just unit tests.

live-shape (caught by the same live pass):
- CMS: Payload SQLite INTEGER ids ({id:3}) were read as strings → id='' (rowKey
  collisions); number-aware idStr. Media bytes url carries ?prefix=<tenant> that the
  filename-reconstruction dropped → cmsMediaSrc proxies the doc's real url through /cms.
- Commerce: /v1/store/current wraps the record as {store:{}} → currentStore unwraps .store.

RED LOW-1: /erp allow-list pinned to EXACTLY {Account, Item, Sales Order} (was any
DocType) so an entitled brand member can't over-read User/Salary Slip/etc. through the
shared ERP_API_TOKEN. RED verdict on v8.4.33: 0 crit/high/med, cross-tenant isolation
SOUND across CMS/ERP/Help/Analytics — SHIP.

Playground (coordinator, real user bugs):
- Multi-image upload: composer attachment (single) → attachments[] (append; multi-select
  dialog OR successive uploads/drag-drop accumulate); file input 'multiple'; thumbnail
  strip with count + per-image remove; buildRunMessages pushes one image_url part per image.
- 'Run does nothing' (image-only): validateRun now counts an attached image as user
  content — an image-only vision prompt is valid and Run proceeds; blocks ONLY a
  genuinely-empty message, and the reason renders PROMINENTLY right above the Run button.

tsc clean; vitest 1076/1076 (89 files); next build green.
2026-07-02 18:34:43 -07:00
hanzo-devandGitHub 4ad6691a4b fix(machines): interactive live catalog (tap-to-launch) + native cloud /v1 wiring (#57)
Customer Machines showed a real but NON-interactive catalog (region chips + every size row were static text) under the "launch your first machine" state, so a data-rich priced catalog you couldn't click read as "not clickable / fake." Make it a real launch surface; finish the last /paas->/cloud data wiring in the cluster path.

- MachineCatalog: every size row is now clickable -> opens the real LaunchDrawer preselected on that size (and region); region chips are selectable filters (filter the size list via pure filterSizes + preset the launch region). Rows reflow to a mobile-friendly 2-column layout (no fixed 4-column table). No fabricated data: with no onLaunch the rows stay informational and an empty catalog still renders nothing.

- LaunchDrawer: accepts initialSize/initialRegion to open preselected.

- CustomerMachines: one openLaunch(preset) opener feeds the header button, empty-state CTA, and the catalog.

- visor: capture the per-size regions[] visor already returns (was dropped in normalizeSize) + pure filterSizes(sizes, query, region), unit-tested.

- platform: repoint provisionCluster from the /paas service-token proxy to native cloud /v1 (/cloud/v1/org/{org}/cluster, user IAM session) - the last /paas call in the cluster path; cluster reads already use /cloud/v1/clusters.

tsc --noEmit clean; visor.test.ts 16/16 (added regions + filterSizes cases). Verified locally headless: tap a size -> drawer opens with the correct $24/mo quote; mobile 0px overflow. Live data lights up once the console redeploys (this branch's /cloud allow-list already admits machines/clusters/gpus) against cloud v1.786.26 which now serves GET /v1/machines.
2026-07-02 18:03:50 -07:00
hanzo-dev c5c72cd8e9 fix(api): resilient shared fetch — transient upstream errors auto-retry (v8.4.33)
Backend rolls invisible to customers. Root cause of a real 'Could not load — Upstream
service is unavailable' (Dave/maxpower, Models catalog): cloud is single-replica
Recreate, so a deploy-roll has a brief downtime window; a read landing in it got a
502/503/504 and the console showed a scary manual-Retry card.

Fixed in the ONE shared fetch (client.ts authedFetch → the pure, injectable
resilientFetch) that BOTH the casibase-envelope (request) and plain-REST (restRequest)
paths flow through — covers EVERY client fetch (Models, Overview, Billing, CRM, CMS,
ERP, commerce, analytics, agents, prompts, …), DRY.

- Transient upstream (502/503/504 or a network connection error) on an IDEMPOTENT read
  (GET/HEAD) → auto-retry with exponential backoff (300→900→2000ms, up to 3) BEFORE the
  honest 'Could not load' card, so a momentary roll self-heals; the card shows ONLY on a
  persistent outage (after retries exhaust).
- Genuine 4xx (401/403/404/402) → NOT retried (honest state immediately).
- Mutation (POST/PUT/PATCH/DELETE) → NOT auto-retried (a 5xx'd write may have applied —
  re-sending could double-create; the user retries manually).
- Caller-aborted request → honored, never retried.
- The 401 silent-refresh (v8.4.29) is preserved as the second orthogonal resilience,
  guarded against a refresh loop.

+13 tests (client-retry.test.ts): the exact Models-catalog 503→200 self-heal, budget
exhaust → honest error, network retry, 4xx/mutation no-retry, abort honored, 401 refresh
no-loop, + classification helpers.

v8.4.33 = the deployed superset (v8.4.32 native-apps set + this). tsc clean; vitest
1061/1061; next build green.
2026-07-02 17:57:04 -07:00
hanzo-dev b647d9832d feat(apps): native ERP/CMS/Analytics + real commerce over canonical backends (v8.4.32)
Maximize native app coverage in the console — bind ERP, Content (CMS), Analytics,
and Commerce to their canonical backends per-org / entitlement-gated, one canonical
way, no fabricated data. Contracts verified against source repos + live probes.

Analytics — rebound to the FOUR real cloud clients/analytics routes (overview/
timeseries/top/health; the module had called 5 non-existent endpoints with wrong
shapes). LLM lens is REAL live per-org data (hanzo.cloud_usage, prod ClickHouse);
web/commerce lenses honest-empty via the backend 'available' flag. Dropped the
fabricated Real-Time tab (no backend). Tabs: Overview + LLM (top models).

Content (CMS) — tabbed: NATIVE Collections + Media/DAM read live over Payload REST
through a new /cms user-bearer proxy. Payload's multi-tenant plugin isolates rows by
the IAM owner claim → each org reads ONLY its own (per-org, backend-enforced);
allow-list admits only the two tenant-scoped collections + media bytes, never the
users/tenants registry. Studio tab keeps the entitlement-gated admin embed.

ERP — tabbed + entitlement-gated (Frappe is single-tenant → brand-org/global-admin
only). Overview drives a REAL /v1/platform deploy of the ERPNext app (idempotent
create-project+app+deploy, live status). Accounting/Items/Sales are NATIVE Frappe
REST summary views (real erpnext-v15 DocType fields) over a new /erp proxy (Frappe
token auth, SSRF-clamped, read-only resource lists) — honest 'deploy ERP' until an
instance is live. Desk embeds the real desk once reachable.

Commerce — Products full CRUD (create+delete over /v1/product; validator needs
name+sku+slug); Store settings reads the org's real storefront (/v1/store/current).
Orders/Customers/Inventory/Promotions stay real per-org reads. Via the /commerce
bearer proxy (org from token owner). hanzoai/commerce is the ONE authority — NOT Medusa.

GPUs (drive-by) — KPI reconciled: was distinct-model count (6) vs the catalog table +
Launch drawer configs (9); now shows launchable configs with model count in the sub.

tsc clean; vitest 1050/1050 (+22); next build green (/cms + /erp routes registered).
2026-07-02 17:47:32 -07:00
hanzo-dev 9cff39e59f console: repoint ServiceMesh + Edge to native /v1 (close zt loose end)
The zt cloud client bound /v1/mesh/services + /v1/edge/nodes and the heads +
proxy-allow landed, but the two module fetches were left on the /paas proxy.
Switch both to cloudProxyV1Url (the user-bearer /cloud proxy) like the other
repointed modules. Networks already used /v1/networks. Now all 12 infra pages
(compute/DO/platform/zt) read the native cloud /v1 gateway.
2026-07-02 17:43:07 -07:00
hanzo-dev 0e20f0322e feat(console): wire 9 cloud modules to native /v1 (repoint /paas → /cloud)
The unified cloud binary now serves these surfaces per-org at /v1/*; repoint
each module from the /paas control-plane proxy to the native cloud /v1 gateway
via the user-bearer /cloud proxy (org resolved from the Bearer owner).

Compute (visor-backed):
- Machines: VisorApi.machines/quote/launch → /cloud/v1/machines[/launch];
  add terminate (DELETE /v1/machines/:id) + a Terminate action on the customer
  view. Catalog (regions/sizes/gpus) stays on visor /vm.
- GPUs: ComputeApi.gpus/alerts/pools → /cloud/v1/gpus[/alerts|/pools].
- Clusters: PlatformApi.listClusters/getCluster → /v1/clusters (org-scoped by
  the Bearer owner; drop the org arg — 5 callers updated); add node-pool
  add/scale/delete (POST/DELETE /v1/clusters/:cid/pools[/:pid[/scale]]) + a
  Node pools management UI. apps() + provisionCluster() stay on /paas.

DO-native (full CRUD):
- VPC: list + create + delete (GET/POST/DELETE /v1/vpcs[/:id]).
- Load Balancers: list + create + delete (GET/POST/DELETE /v1/load-balancers[/:id]).

Platform aggregates (list-only, read-only):
- Environments / Pipelines / Builds / Releases: restGet(cloudProxyV1Url(...)).

Heads: add machines,gpus,clusters,vpcs,load-balancers,environments,pipelines,
builds,releases to proxy-allow CLOUD_HEADS; add vpcs,load-balancers to
next.config CLOUD_V1_HEADS.

tsc --noEmit clean; compute/visor/logic/proxy-allow tests pass.
2026-07-02 17:39:07 -07:00
zandGitHub e19aea466d Merge pull request #56 from hanzoai/feat/console-apps
feat(console): Apps — hanzo.app buildable-sites round-trip over /v1/projects
2026-07-02 17:37:56 -07:00
hanzo-dev 897a0986c7 feat(web3): brand-scoped launch tiles for the deployed Lux/Zoo chain-app suite
Surface the standalone, already-deployed Lux/Zoo web3 apps (Explorer,
Exchange, Bridge, Faucet, Safe, DEX, Wallet) as launch tiles in the Web3
category — not rebuilt in-console, opened at their own domains.

Modeled as a restored `kind: 'external'; href` CatalogEntry member (the
honest sum type for a standalone app that owns no in-console route) — it
slots into the `kind !== 'module'` fail-closed guards the module-only
collapse deliberately preserved, so productSubpages/resolveProductView/
destinationsFor/productModules never manufacture a dead route for it.
`openProduct` becomes the ONE opener: a module navigates to `/<id>`, an
external opens `href` in a new tab. Every card seam (nav, launcher, ⌘K,
category page, level-2 siblings) routes through it, so no external tile
can 404.

Per-entry brand scope (`brands?: BrandId[]` + pure `entryInBrandScope`,
mirroring `nodeNetworksForBrand`) keeps the two suites from cross-leaking
inside the shared Web3 category: Lux tiles show only on lux, Zoo only on
zoo. Every href is a real, verified deployment — no fabricated URLs.

Tests: per-entry brand-scope predicate (no cross-leak); tsc clean; full
suite 1019 passing.
2026-07-02 17:37:08 -07:00
hanzo-dev 095c2250a6 feat(console): Apps — the org's hanzo.app buildable-sites over /v1/projects, with Edit-in-hanzo.app deep-links
Closes the console→app round-trip: a Platform › Apps module lists the org's
buildable/deployed sites from the shared org-scoped cloud clients/projectsvc
store (/v1/projects, same-origin user-bearer /cloud proxy — the exact per-tenant
path Agents/CRM use). Per row: Open site (liveUrl) + Edit in hanzo.app
(/dev?project=<slug>). Honest loading/empty/BackendState; never fabricates rows.

- src/lib/api/apps.ts        AppsApi (list/get/deployments) + defensive projectView/
                             deploymentView normalizers + injection-safe builderEditUrl
- src/lib/api/apps.test.ts   normalizers + /v1/projects route contract + deep-link (9)
- AppsModule.tsx             org-scoped list (Site/Framework/Status/Updated/actions) +
                             per-site deploy-history detail rail (:slug route)
- registry.tsx               ONE Platform entry id:apps (distinct from IAM Projects
                             scope + Compute Applications PaaS)

tsc --noEmit clean; vitest 1023/1023 (85 files); next build ✓ (17/17).
2026-07-02 17:36:29 -07:00
zandGitHub 99e600d5fd Merge pull request #55 from hanzoai/feat/console2-admin-fleets
feat(console): Bots + Machines — per-org/app/project compute analytics from the datastore
2026-07-02 17:21:19 -07:00
hanzo-dev 592bf16a03 feat(console): Bots + Machines — per-org/app/project compute analytics from the datastore
Two GLOBAL-ADMIN operator boards on admin.hanzo.ai (Observe, beside Business +
Finance), two lenses over ONE datastore table split on `kind`: Bots (kind=bot —
@hanzo/bot agents booted, gateway-connected) and Machines (kind=machine — raw VMs
visor opens). Each surfaces per-org/app/project count, active, and spend, grouped
org -> app -> project, sourced from the unified datastore (ClickHouse) via a new
`compute` admin-aggregate head. `/v1/admin/compute?kind=` is server-gated by
getAdminGate (the RED-H1 gate) and rewritten to app/admin/aggregate — no new proxy
or trust boundary.

- lib/api/admin-compute.ts: kind-parameterized, optional-safe client + pure
  foldEvents/buildTree over both pre-aggregated {leaves} and raw {events} (9-col
  datastore schema: org, app, project, kind, event, machine_id, size, price_cents,
  ts). Rollup {count,active,spendCents}; normalizeCompute(raw, kind) filters to kind.
- components/products/ComputeModule.tsx: ONE ComputeBoard({kind}); BotsModule /
  MachinesModule are thin wrappers (collapsible org->app->project tree + KPIs,
  honest loading/403/404/empty states — honest-empty until the emitter lands).
- registry: `bots` + `vms` (Machines) entries, admin:true; the admin machines module
  is aliased to avoid the clash with the per-org customer Machines (visor).
- admin-aggregate.ts + next.config.mjs: `compute` added to the admin read heads.
- Pairs with cloud GET /v1/admin/compute (hanzoai/cloud#62).

tsc clean; npm test 1012/1012; next build green.
2026-07-02 17:07:37 -07:00
hanzo-dev 896d6584f5 fix(auth): two cookies — small identity (Path=/) + chunked refresh (Path=/auth) — browser-safe (v8.4.31)
Casdoor refresh tokens are ALSO ~3.6KB full-user JWTs, so v8.4.30 sealed cookie
was still 5560 bytes (> browser 4KB cap → a real browser would reject it). Split:
- hz_session (Path=/, sealed {access-exp, projected claims}, ~1KB): resolveUser/BFF.
- hz_rt (Path=/auth, sealed refresh token, chunked hz_rt0/hz_rt1): sent ONLY to
  /auth — never to /v1 or the BFF, so no header bloat / gateway-431 risk.
Both sealed (integrity). Live-verified: establish/GET/refresh-rotate all 200.
2026-07-02 17:05:57 -07:00
hanzo-dev 0fbcdad02b fix(auth): seal PROJECTED claims + refresh (not the ~10KB access JWT) — browser-safe hz_session cookie (v8.4.30)
The v8.4.29 sealed cookie held the raw Casdoor access token (whole user object,
~9.8 KB) which exceeds the browser 4 KB per-cookie limit → a real browser would
reject it (curl does not). sealSession now projects to the small display/authz
claim set + refresh token + exp → a bounded ~1 KB cookie. Live-verified.
2026-07-02 16:50:17 -07:00
hanzo-dev d758305ee3 feat(auth): silent token-refresh — durable console OAuth session, no mid-task logout (v8.4.29)
Adds a console-owned hanzo-console OAuth session (access + rotating refresh, sealed
AES-256-GCM in httpOnly hz_session) as the preferred identity source for the AuthGate
and the /cloud bearer-proxy, silently refreshed via grant_type=refresh_token
(proactive timer + reactive single-flight on 401 + self-heal-on-load). Casibase
session kept as the graceful fallback; strictly additive, zero regression.

- src/lib/server/session.ts: token manager (password/refresh grants, AEAD seal, claims)
- app/auth/session/route.ts: establish (gated, MFA-safe) / current / signout
- app/auth/refresh/route.ts: rotation-aware refresh, no-clear-on-fail (multi-tab safe)
- resolveUser prefers the console session; client proactive+reactive refresh
- +27 tests; tsc + next build green
2026-07-02 16:35:22 -07:00
hanzo-dev 089a58cba2 feat(kubeflow): real ML Pipelines module over the live Kubeflow bridge
The last ComingSoon stub is now a real module. The cloud mlsvc
(hanzoai/cloud clients/ml) fronts the Kubeflow-family CRDs as REST, so
KubeflowModule is the read-only orchestration + control-plane lens over
that live surface (distinct from Fine-tuning's train-my-model wizard):

- Control-plane health strip from a REAL probe (GET /v1/train/health) —
  which Kubeflow operators/CRDs (Trainer/trainjobs, Katib/experiments)
  are actually served; honest connected/degraded/not-reporting states.
- Pipelines = Katib Experiments (GET /v1/train/experiments).
- Runs = trainer TrainJobs (GET /v1/train/jobs).

Pipelines/runs REUSE TrainApi (one client, no duplication); the new
KubeflowApi adds only the control-plane probe the console lacked (a
tolerant fetch that reads the 503 body restGet would discard). The
/training proxy allowlist gains train/health (additive, read-only).
Registry: kubeflow flips soon -> enabled, routes -> KubeflowModule.
Honest states only, no fabricated data. tsc clean; 84 registry tests pass.
2026-07-02 16:16:30 -07:00
hanzo-dev 62644a072a test(e2e): pages pass signs in ONCE, reuses session (was 94 logins → rate-limit)
The 94-page screenshot sweep signed in per test (beforeEach), so ~94 logins as
z@hanzo.ai tripped IAM's 'too many login attempts' rate-limit around page 35 —
that's the security feature working, not a page failure. Switch to a shared
serial context: one signIn in beforeAll, every page reuses the cookie. Faster
(~1 login vs 94) and no rate-limit, so the full sweep completes.
2026-07-02 15:19:45 -07:00
hanzo-dev a409e8a71b test(e2e): fix 3 stale assertions surfaced by the live prod run
- off-list secrets path: accept 401 OR 404 (both block the tunnel; prod hits the
  auth gate → 401 before the 404 allow-list check). A 2xx would be the real bug.
- API key extraction: match only a FULL hk- token (16+ chars, no ellipsis) so it
  never grabs the masked 'hk-2f18…' account-card display as a credential.
- /v1/messages: pick a model that is ACTUALLY in /v1/models right now instead of
  hardcoding claude-sonnet-4-6 (not provisioned on DO → correct 'not available').
All verified against live prod; the surfaces themselves (proxy gating, key mint,
Anthropic-compat inference) already work — these were test-data/expectation drift.
2026-07-02 15:16:45 -07:00
hanzo-dev 7983dfb24c chore(release): console 8.4.28 — per-vendor COGS donut on the finance board 2026-07-02 14:47:26 -07:00
hanzo-dev b1096575f5 feat(finance): per-vendor COGS donut on the finance board (v8.4.27)
Extends the EXISTING finance living-overview to read the now-multi-vendor
/v1/admin/finance (cloud enriches its cost side from commerce /v1/costs):

- FinanceCost gains {configured, totalCents, vendors[], period}; margin/spend now
  reflect the whole-platform COGS (DO compute + LLM providers), not DO MTD alone.
- fromFinance projects cost.vendors onto a 'vendorCogs' distribution (donut) and
  makes the headline spend + margin the commerce COGS — decoupled from DO, so a
  missing DO_API_TOKEN no longer blanks COGS/margin (DO stays the credit/runway
  treasury view + burn-down series only).
- registry: 'COGS (all vendors)' headline + a 'COGS by vendor' donut beside the
  burn-down; profitability verdict now gates on commerce COGS, not DO.
- reads ONLY /v1/admin/finance — no console-side /costs proxy (the admin-cogs
  duplicate is superseded and dropped).
- tests: vendor donut, zero-line pruning, DO-off-COGS-still-flows, COGS-off honest
  empty. 380 unit tests + tsc + next build green.
2026-07-02 14:46:27 -07:00
hanzo-devandGitHub 3c6a3dddd4 Merge pull request #54 from hanzoai/feat/console2-record-form-refresh
Record-form data-loss fix + Memory/Datasets delete + 5-min-logout diagnosis (v8.4.27)
2026-07-02 14:26:07 -07:00
hanzo-dev a7a50312e9 fix(console): record-form data-loss (registerDefaultFields) + Memory/Datasets delete key fixes; flag 5-min session as backend TTL (v8.4.27) 2026-07-02 14:25:37 -07:00
zandGitHub 618c7339ff Merge pull request #53 from hanzoai/fix/console-qa
fix(console): wire Status/Metrics to VictoriaMetrics + fix all dropdowns (native select) + mobile
2026-07-02 14:21:24 -07:00
hanzo-dev abb385b461 fix(console): wire Status/Metrics to live VictoriaMetrics, fix broken FieldSelect dropdowns, mobile-scroll tables
Issue 1 — Status/Logs/Metrics not wired (o11y):
- /v1/o11y is NOT 503 (stale) — it's a 403 (auth) reverse-proxy to SigNoz, whose
  runtime is un-set-up (setupCompleted:false, no data). Status read /paas/apps which
  reports ZERO apps; Logs read /paas/logs which 401s (no such endpoint). Neither ever
  showed data. The live signal is VictoriaMetrics (up{job=*-health}, ~29 targets).
- New read-only same-origin proxy app/telemetry/[...path] -> VictoriaMetrics query API
  (authenticated, GET-only, allow-listed to /api/v1/query|query_range|series|labels|
  label/*/values, traversal-hardened, honest 501 when VM_URL unset).
- lib/api/telemetry.ts (pure parse + service-health helpers, unit-tested).
- StatusModule: real up{} service-health board (down-first, healthy/down counts).
- MetricsModule: real VM infra dashboard (KPIs, healthy/targets-over-time, health
  donut, down-now) — replaces the unwired 'metrics' NativeOverview; distinct from
  AI Metrics. LogsModule: honest 'no log store deployed' state (no fabricated grid).

Issue 2 — launch-machine form: FieldSelect used @hanzo/gui <Select native>, which in
gui 7.3.0 emits bare <option> with NO <select> wrapper — every dropdown app-wide (27
usages) rendered as a non-interactive flat list. In the launch drawer this buried the
Quote + Launch button. FieldSelect now renders a real native <select> (theme-var
styled, native mobile picker), fixing the region picker and all other dropdowns.

Issue 3 — mobile: the FieldSelect fix repairs every form's pickers; DataTable now
scrolls horizontally on overflow instead of clipping wide tables (cut-off columns).

Verified live (VictoriaMetrics + real z@hanzo.ai session): Status 29 services/22
healthy/7 down, Metrics dashboard, Logs honest state, launch drawer native region
select with Launch visible, mobile table scroll. tsc clean; 964 vitest pass.

Also: dev-only next.config rewrite (DEV_CLOUD_ORIGIN, inert in prod) to run the
console locally against a real backend; removed orphaned observability/metrics.ts.
2026-07-02 14:17:42 -07:00
11ae61d541 feat(templates): visual preview banners + a clear one-click deploy flow (#46)
The Templates gallery cards were text-only and dead-ended after fork
("Draft — deploy it to go live" with no action). Two fixes:

1. Preview banner: render the gallery screenshot (t.preview) with a branded
   gradient fallback (stable per category + framework glyph) when it's absent
   or 404s — cards are visual immediately and auto-upgrade to the real shot
   once gallery.hanzo.ai serves it. No broken images, no fabricated screenshots.
2. Deploy flow: fork→draft now shows a clear "Deploy" button that ships the
   project live via projectsvc git deploy (POST /v1/projects/:slug/deploy
   {source:git}); building → "Check status" → "Open site" (liveUrl). Each
   phase shows exactly one next step, so "how to deploy" is never ambiguous.

TemplatesApi gains deploy()/status()/isLive()/normalizeDeployResult over the
existing same-origin /v1 surface. 18 vitest tests, next build green (14/14).

Co-authored-by: Hanzo AI <ai@hanzo.ai>
2026-07-02 13:26:46 -07:00
zandGitHub 25550dd595 Merge pull request #51 from hanzoai/feat/fork-to-builder
feat(fork): Open-in-builder — fork a starter → customize by prompt → talk-and-edit
2026-07-02 13:06:09 -07:00
hanzo-dev 85ef4cdfe6 feat(templates): fork → 'Open in builder' loop (customize by prompt)
Add an 'Open in builder' primary CTA to each starter card that deep-links to
the hanzo.app builder pre-seeded to customize this template by prompt:
<app>/dev?template=<source>&prompt=<seed>&action=edit. A small inline input
takes an optional free-text customization; the seed prompt carries the template
context (title/framework/description) so the builder auto-starts the first
generation.

- buildBuilderUrl(template, userText, appBase) + customizePrompt(): pure,
  injection-safe (single URL-encoded query params), unit-tested (+7 tests).
- config.appUrl (NEXT_PUBLIC_APP_URL, default https://hanzo.app).
- 'Fork / deploy' kept as the secondary action + honest 404 gallery fallback.

tsc --noEmit clean; vitest 881/881.
2026-07-02 13:04:39 -07:00
hanzo-devandGitHub a7d1938fd6 Merge pull request #50 from hanzoai/feat/console2-honest-states
Honest-state punch-list — signed-in 403≠'sign in', read-402≠paywall, graceful re-auth, chunk self-heal (v8.4.25)
2026-07-02 12:45:17 -07:00
hanzo-dev 7f3ddfd709 fix(console): honest-state punch-list — signed-in 403≠'sign in', read-402≠paywall, graceful re-auth, chunk self-heal (v8.4.25) 2026-07-02 12:44:51 -07:00
hanzo-devandGitHub 647eeb6eee harden(console): server-side entitlement gate for CMS/ERP/Help embeds (v8.4.24) — RED (#49)
RED reviewed v8.4.22's embeds (0 critical; SSRF clamp, iframe SOP, no-credential-
injection, honest normalizers all REFUTED). Fixes the console residuals RED flagged:

- Server-side entitlement gate: /embed-status resolves the caller's org (token owner)
  and returns `entitled` per app. cms/erp/help are all brand-owned single instances,
  so a non-owning (customer) org gets entitled:false + NO embed URL + no probe -> the
  module shows the provision panel. Only a brand-org member / global admin embeds.
  This is now the AUTHORITATIVE gate (the client check was cosmetic). Client normalizer
  fails closed (entitled strict-true; stale server -> provision panel, never a frame).
- Help is brand-owned too (was embed-for-all) -> a customer never frames the shared
  Frappe Helpdesk (removes unverified cross-org ticket-visibility risk).
- Dropped the false 'org==tenant enforced server-side' claims in EmbeddedApp/
  embed-hosts/module docstrings (the console gates WHO it frames; the shared app still
  owes its own per-org isolation -> separate CMS-side fix).
- Trimmed the iframe sandbox (dropped allow-top-navigation-by-user-activation,
  allow-popups-to-escape-sandbox, clipboard-read).
- /waitlist: bind recorded email to the session account; stop forwarding forgeable XFF.

tsc clean; vitest 952/952 (+13 entitlement/brand-org/fail-closed); next build green.
2026-07-02 12:30:04 -07:00
hanzo-devandGitHub 9bb582d8cf Merge pull request #48 from hanzoai/feat/console2-subpages-base
Real per-product Status/Logs/Metrics/Settings + Base content-type builder + live PaaS Applications (v8.4.23)
2026-07-02 12:05:40 -07:00
hanzo-dev 69a9af6d51 feat(console): real per-product Status/Logs/Metrics/Settings + Base content-type builder + live PaaS Applications (v8.4.23) 2026-07-02 12:05:25 -07:00
hanzo-devandGitHub 638baf7fb5 feat(console): de-link-out Content + native ERP/Help Center — embedded Business-OS apps (v8.4.22) (#47)
CMS was a window.open link-out; ERP/Help were 'soon' placeholders. Port all three
into the console as EMBEDDED (SSO iframe) or HONEST-provision surfaces, binding to
the canonical Payload/Frappe backends (not reimplemented). CRM stays the native
/v1/crm reference; these are the embed half of the Business-OS.

- EmbeddedApp: the one way to frame a canonical app IN the console shell (full-height
  iframe, scoped sandbox, real loading + honest 'Open full screen' fallback — never a
  fabricated load verdict). ProvisionPanel: DRY honest pre-provision surface over the
  real /waitlist intake.
- embed-hosts.ts (PURE): white-label cms|erp|help.<brand> host derivation.
- /embed-status BFF + pure embed-probe.ts: session-gated reachability probe, NO
  god-mode, SSRF-clamped to known brand domains, AbortSignal-bounded.
- CmsModule: embed the Studio for a brand-org member/global admin ONLY (customer org
  gets an honest provision panel — no cross-tenant framing of the shared instance).
- ErpModule: erp.<brand> is 502 -> honest 'Deploy ERP' panel; SAME gate embeds the
  real desk once live. HelpModule: embeds the live shared brand support desk (Frappe
  scopes tickets per-user via SSO).
- registry: erp + helpdesk soon -> enabled native modules.

Verified against live cluster + repos (single shared HANZO_ORG=hanzo instances; no
per-customer-org isolation yet) so nothing claims tenancy it doesn't have.
typecheck 0 errors; vitest 914/914 (+21); next build green (/embed-status registered).
2026-07-02 11:53:45 -07:00
zeekayandClaude Opus 4.8 69eef199e7 harden(console): bound every request-time server fetch (no upstream can hang) — v8.4.21
Investigated the "brand host (cloud.lux.network) hangs during render, while
console.hanzo.ai is fast" report. It does NOT reproduce in the app and cannot by
design: the page-render path (app/layout.tsx + (dashboard)/layout.tsx, the only
server components) does ZERO per-brand network fetch — no next/headers, cookies(),
generateMetadata, or server-only render fetch. Brand resolves from window.location
in the browser; SSR uses the build-time NEXT_PUBLIC_DEFAULT_HOST, so the server
HTML is byte-identical for every brand host (verified: cloud.lux.network and
console.hanzo.ai return the SAME md5, <title>Hanzo Cloud Console</title>, HTTP 200
in ~4-18ms for lux/zoo/pars/hanzo). The prod origin difference is an ingress/
routing artifact, not app SSR (out of scope; app code only).

The real in-code "no timeout → the route wedges" hazard (the described failure
class) IS fixed: every request-time server fetch — the /v1/* BFF proxies plus IAM/
cloud identity resolution — had NO upstream timeout, so a reachable-but-silent
backend blocked the route until the client gave up.

Fix, DRY: one src/lib/server/fetch-timeout.ts (fetchWithTimeout) — a bounded
AbortSignal COMPOSED with any caller signal (init.signal / req.signal), so a
request aborts on EITHER a client disconnect OR the timeout. Default 10_000ms, env
HANZO_UPSTREAM_TIMEOUT_MS. On timeout it rejects like an aborted fetch, so every
existing catch keeps its honest fallback (resolveUser → null → 401; proxies → 502).
Threaded through identity.ts (all 5 IAM/cloud calls), bearer-proxy.ts (the shared
proxy engine → cloud/ai/vm/tasksd/commerce/superbase), iam-proxy.ts, and the
custom proxies (/paas, /training, /admin/kms, /billing, /billing/topup/wallet,
/waitlist). The /nodes per-brand luxd RPC probe was already bounded — left as-is.

Verification: npm run typecheck 0 errors; npm test 823/823 (69 files, +6 new
fetch-timeout tests); next build green (all routes); Host-header curl test returns
200 fast for BOTH cloud.lux.network and console.hanzo.ai.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 09:01:43 -07:00
16246565b7 fix(console): pin non-global admins to their own org, dropping stale cross-tenant scope (v8.4.20) (#45)
A tenant (non-global) admin like `hanzo/z` can only ever act in their OWN org —
the server pins them there and every cross-tenant call 403s. But `OrgGate`
restored a persisted "last org" (`hz_last_org` / `hanzo.console.org`) on sign-in
WITHOUT checking the user can access it. So a leftover `adnexus` scope (from a
prior global-admin switch) made every org-scoped call — e.g.
`/org/iam/get-organization-projects?organization=adnexus` — 403 for z.

Fix: in the OrgGate seed effect, a non-global admin is ALWAYS hard-pinned to
`owner`. If a stale cross-tenant scope is active it's reset and the page reloads
once (guarded on `currentOrg() !== owner`, so it can't loop) — self-healing
existing stale state and preventing recurrence. Global admins keep the
switch-and-restore behavior. Complements the v8.4.18/19 gates on the admin
aggregates; this closes the org-SCOPED 403s.

Co-authored-by: dev <dev@hanzo.ai>
2026-07-02 06:53:11 -07:00
Darkhorse7stars a24a14e1ae chore(console): v8.4.19 — complete the tenant admin 403 gate (get-organizations + org logo)
Follows v8.4.18 (#44), which gated only the overview aggregate + /paas probe.
This release also gates the OrgSwitcher/CommandPalette org list and BrandLogo's
org-logo lookup, so a per-org (non-global) admin's dashboard load fires ZERO
cross-tenant /admin/iam calls — no more 403 noise in the browser console.
2026-07-02 08:28:21 -05:00
Darkhorse7stars c61e422c86 fix(console): gate get-organizations + get-organization on isGlobalAdmin (complete the tenant 403 gate)
v8.4.18 (#44) gated the platform-overview loader (`/v1/admin/overview` + the
`/paas/apps` health probe) on `isGlobalAdmin`, but the dashboard chrome still
fired two more CROSS-TENANT admin calls for every user on every load:

  - `/admin/iam/get-organizations?owner=admin` — the OrgSwitcher + CommandPalette
    org list, server-gated to global (admin-org) admins.
  - `/admin/iam/get-organization?id=admin/<tenant>` — BrandLogo's org-logo lookup.

For a per-ORG admin who is NOT a global admin (e.g. `hanzo/z`) both 403, so a
tenant still saw a wall of red 403s in the browser console on every dashboard
load even after v8.4.18.

Gate them with the SAME `useIsGlobalAdmin` signal the overview loader + nav use:

  - OrgSwitcher / CommandPalette: skip `get-organizations` for a non-global-admin
    (they still see their current org + "Create organization"; just no cross-tenant
    switch list).
  - BrandLogo: a tenant reads its OWN org logo via the org-scoped `/org/iam` proxy
    (`TeamApi.organization`, which authorizes any member and pins to the caller's
    own org) instead of the admin-gated `/admin/iam` proxy — the logo still works,
    minus the 403.

Global admins are unchanged. No permission or server change; server gates still
enforce. typecheck + 887 tests + next build all green.
2026-07-02 08:28:13 -05:00
hanzo-dev 5339d28657 chore(console): v8.4.18 — release the tenant admin-overview 403 gate (#44) 2026-07-02 08:14:17 -05:00
d4a87ddfee fix(console): gate admin-overview + paas probe on isGlobalAdmin so tenant admins don't 403 (#44)
The platform overview home (`livingOverviewModule('overview')`) is the default
landing for every signed-in user, but its loader fired the CROSS-TENANT
`/v1/admin/overview` aggregate (and the `/paas/apps` health probe) for everyone.
Those are server-gated to global (admin-org) admins, so a tenant user — even an
org's OWN admin, e.g. `hanzo/z` — got a wall of repeated `403 (Forbidden)` in the
browser console on every dashboard load.

It "worked" only because the loader caught the 403 and fell back to the org-scoped
usage ledger; the board rendered, but spammed the console with doomed requests.

Fix: thread `isGlobalAdmin` (already resolved by `useIsGlobalAdmin`, the same
signal the nav/launcher use to hide admin surfaces) through the ONE loader call
site into `OverviewContext`, and in the platform-overview loader skip the admin
aggregate + apps probe for non-global-admins — going straight to the org-scoped
usage ledger (the exact source the catch-fallback already used). Global admins are
unchanged. `withHealth` gains an optional `probeApps` (default true) so the four
other, already admin-gated overviews are untouched.

Net: a tenant admin's overview renders identically, minus the 403 console noise;
no permission or server change.

Co-authored-by: dev <dev@hanzo.ai>
2026-07-02 06:08:48 -07:00
fddf5f3aec feat(console): Business-OS suite — CRM + Content + ERP/Help Center + Accessibility over native /v1 (v8.4.17) (#43)
* feat(console): consolidate CRM + Accessibility Business-OS modules over native /v1

CRM — the first Business-OS brick — as ONE canonical module over the native-Go
cloud /v1/crm surface (cloud clients/crm on Base/SQLite: companies, contacts,
opportunities; a port of Twenty's core model), per-org via the user-bearer /cloud
proxy. Consolidates the two competing CRM PRs (#38 feat/console2-crm and #39
crm-work): keeps #39's richer routed-tab views + defensive normalizers + tests,
re-paths its API from the explicit /cloud/v1 form to the canonical same-origin
originV1Url('crm') (matching Agents/Evals/Prompts — the one way), and grafts #38's
next.config `crm` head rewrite + per-row delete. crm.ts is the single typed mirror
of the /v1/crm contract (one method per route); every row is org-scoped SERVER-SIDE
from the token owner claim, with honest loading/empty/error states in @hanzo/gui.

Accessibility — a Wix-style WCAG scanner for the site being built. Runs Deque's
axe-core against the current page 100% client-side (engine lazy-loaded into its own
chunk, never the main bundle); pure sort/summarize/WCAG-label logic in
~/lib/a11y/scan is unit-tested without a browser or engine.

- next.config.mjs / proxy-allow.ts: allow-list the `crm` head on both the rewrite
  and the bearer proxy (same least-privilege path as the 5 existing surfaces).
- registry: CRM + Accessibility in the Apps catalog.
- version 8.4.16 -> 8.4.17; axe-core 4.12.1 (lazy import, own chunk).

typecheck clean; 887 unit tests pass (13 new: 9 crm + 4 a11y); next build green.

* feat(console): fold Content Studio + ERP/Help Center into the Business-OS suite (v8.4.17)

Consolidates the three overlapping Business-OS PRs into ONE canonical superset.
Onto the #39 base (canonical CRM over originV1Url → /v1/crm direct + per-row
delete, and the client-side axe-core Accessibility scanner), fold in #42's:
- CmsModule (Content Studio: honest in-console home for the live Payload CMS)
- registry entries cms (Content), erp + helpdesk (honest soon → ComingSoon)

Reconciliation: kept #39's originV1Url CRM (hits /v1/crm directly, the majority
agents/prompts/evals pattern) over #42's /cloud-prefixed cloudProxyV1Url; kept
#39's CrmModule (superset — adds delete); dropped #42's stray gcp:'Content';
regenerated package-lock.json for axe-core 4.12.1 (was package.json-only).

Supersedes #38, #39, #42.

---------

Co-authored-by: Hanzo AI <ai@hanzo.ai>
2026-07-02 05:32:16 -07:00
hanzo-dev 509daa10e9 test(e2e): finalize live billing-admin confirmation spec for v8.4.16
Deep-links /billing/reports (now unshadowed) and asserts the god-view gate matches
the account grant (z is a hanzo org-admin → honest 403 + managed fallback; an
admin-org member → 200 KPI board). No app change.
2026-07-02 01:14:15 -07:00
hanzo-dev 54f8182467 fix(billing): namespace data proxy under /billing/v1/* so tab URLs reach the SPA (v8.4.16)
The per-tenant commerce DATA proxy (app/billing/[...path]/route.ts) claimed the
whole /billing/* URL space; a Next route handler wins over the catch-all page for a
matching segment, so every billing tab except Overview (/billing/reports, budgets,
invoices, subscriptions, payment-methods, credits) resolved to the proxy and
returned commerce {"error":"not found"} / raw JSON instead of the UI. This
blocked the v8.4.15 Reports cost-dimension (product/agent) surface in production.

Namespace the data proxy under /billing/v1/* (the 'always /v1/' convention) so it
can never collide with a UI tab slug; tab URLs fall through to app/(dashboard)/[...slug].
- move app/billing/[...path] -> app/billing/v1/[...path]; topup/wallet likewise
  (forward target commerce/v1/billing/<path> unchanged — v1 is now a static segment)
- billingUrl() (billing.ts + aimetrics.ts) and wallet.ts appUrl() prepend v1/
- tests: aimetrics.test.ts asserts /billing/v1/usage; billing-isolation e2e fetches /billing/v1/<p>

tsc clean; 874/874 tests; next build green (routes /billing/v1/[...path],
/billing/v1/topup/wallet, /[...slug] catch-all serves the tabs).
2026-07-02 01:02:24 -07:00
zandGitHub 23f12107e0 Merge pull request #41 from hanzoai/feat/saas-finance
feat(admin): SaaS finance dashboard — DO burn-down + revenue + margin/runway (console2)
2026-07-02 01:00:37 -07:00
hanzo-dev e23b9722a4 feat(finance): admin-only SaaS profitability dashboard (Finance)
Add a global-admin-only Finance board to admin.hanzo.ai over the ONE
LivingOverview system — DigitalOcean credit burn-down (our primary ~$40k
venue), month-to-date spend, MRR, total revenue, gross margin %, runway,
and a profitability health verdict. TRUE by construction: every tile reads
the real `/v1/admin/finance` aggregate; no fallback fabricates numbers.

- lib/api/finance.ts: FinanceApi.finance() + normalizeFinance — optional-safe
  map of `/v1/admin/finance` onto Finance. Reads via originGet (same-origin
  `<origin>/v1/admin/finance`), so the request rides the global-admin-gated
  aggregate proxy. runwayDays preserves NULL (never coerced to 0 = fake alarm).
- overview/living/adapters.ts: fromFinance (payload → OverviewData, honest-empty
  on unconfigured DO / commerce) + pure financeHealth verdict (green profitable /
  yellow thin-margin <20% / red burning-faster / '' unknown when DO off).
- overview/living/registry.ts: `finance` living config — 6 KPI tiles + credit
  burn-down bar series + health/alerts. No try/catch fallback (finance is
  true-by-construction; a denied/not-routed backend renders the honest error).
- products/registry.tsx: `finance` catalog entry, `admin: true` (Observe) —
  hidden from every customer's nav/launcher/palette; the catch-all renders a
  managed notice for a non-admin. Reuses livingOverviewModule; no new UI.
- SECURITY: financial data is Hanzo-internal. Routed through the `/admin/
  aggregate` bearer proxy (getAdminGate: verified @hanzo.ai + IAM global-admin,
  fail-closed 403) — NOT the generic /cloud product proxy. `finance` added to
  ADMIN_AGGREGATE_HEADS (admin-aggregate.ts) + ADMIN_V1_HEADS (next.config.mjs);
  the allow-list still REFUSES admin/iam + admin/kms. A non-admin can never see
  or reach the board or the data.

tsc --noEmit: 0 errors. vitest: 874/874 (incl. +8 finance: normalizeFinance,
fromFinance, financeHealth, allowAdminSurface finance head). next build: ✓
compiled, 14/14 pages.
2026-07-02 00:57:59 -07:00
hanzo-dev aa507916ad fix(admin,billing): RED fixes — god-view server gate + attribution + row cap (v8.4.15)
H1 (HIGH): the admin business god-view had NO console-side server gate — /v1/admin/*
was not rewritten and rested solely on an unverified cloud-side gate. Add
app/admin/aggregate/[...path] behind getAdminGate (global-admin only, fail-closed
403) → forwardWithUserBearer; rewrite /v1/admin/{overview,usage,orgs,audit,products}
to it (iam/kms untouched). New originGet pins AdminApi to the console origin so a
split-origin NEXT_PUBLIC_CLOUD_URL can't bypass the gate. Least-privilege surface is
the pure, tested lib/server/admin-aggregate.ts (refuses admin/iam, admin/kms).

L1 (LOW, proven): agentUsageFor id-OR-name Set union conflated two agents within an
org. Prefer exact id, fall back to name only when id matched nothing. +collision tests.

L2 (LOW, proven): unbounded cost table under high agent/product cardinality. New pure
capRows (COST_ROW_CAP=100) bounds the DOM to top-by-spend with an honest Show-all
affordance (never hides real data). +tests.

RED-refuted vectors verified safe (fallback scope, metadata forgery, DoS, honest
state, client gating). typecheck clean; 853/853 tests; next build green (new route
registered).
2026-07-02 00:32:23 -07:00
hanzo-dev 738ebee6e6 feat(billing,admin): per-agent/product cost dimension + admin business board (v8.4.14)
Usage/billing visibility:
- aimetrics UsageRecord extracts metadata.{product,agent} (canonical contract);
  perAgent + agentUsageFor rollups over the SAME charged commerce ledger.
- Cost Reports add product + agent breakdowns (presentDimensions gates each on
  real data — honest until spend is tagged); BillingReports renders them.
- Agents detail pane shows per-agent cost from the ledger (agentUsageFor), not a
  hardcoded/registry metric; honest '—' until attributed.

admin.hanzo.ai business dashboard (global-admin only):
- New admin-business living overview (MRR/revenue/usage-cost/orgs/customers,
  revenue-by-product + plan-mix + top-agents-by-cost donuts, alerts, activity,
  fleet health) over /v1/admin/overview allOrgs, honest usage-ledger+operator
  fallback; reuses the ONE LivingOverview system.
- admin-overview gains an optional named-distributions map (revenue/plans/
  topAgents), present only when the backend sends it; fromAdminOverview projects
  each into distribution[key].
- Registry catalog entry 'business' (Observe, admin:true) — gated by getAdminGate
  + useIsGlobalAdmin; the aggregate is server-gated.

Mobile-responsive by construction (gui v5 shorthands + flexWrap rows, no fixed
grids). typecheck clean; 841/841 tests; next build green. /v1 only.
2026-07-02 00:32:23 -07:00
zandGitHub 29b9587914 Merge pull request #40 from hanzoai/feat/template-fork
feat(fork): template → project fork (console2)
2026-07-01 23:48:04 -07:00
hanzo-dev 7d6b2c8e25 feat(templates): Fork/deploy creates a real project from a template
The gallery "Fork / deploy" button now creates a REAL project in-console via
POST /v1/projects/fork (cloud projectsvc) instead of only opening the gallery
source URL — the ONE way to start a project from a template.

- lib/api/templates.ts: TemplatesApi.fork(slug, {name?}) POSTs to the
  same-origin /v1/projects/fork (originV1Url, no prefix) and normalizes the
  returned projectsvc Project (normalizeForkedProject, pure/tested).
- TemplatesModule: per-card idle -> forking -> created state; on success shows
  the new project (Open site when a liveUrl exists, else honest draft). On a 404
  (older backend without the fork route) it falls back to opening the gallery
  source, so the button is never dead.
- next.config.mjs + proxy-allow.ts: add the `projects` head so /v1/projects*
  (incl. /fork) routes through the hardened /cloud bearer proxy, org-scoped from
  the Bearer owner.

Tests: normalizeForkedProject + TemplatesApi.fork (exact same-origin URL, body
with/without name override, 404 ApiError for the fallback); proxy-allow admits
the projects fork subtree. tsc clean; vitest 834/834.
2026-07-01 23:42:03 -07:00
hanzo-dev c72ee8d5f0 feat(agent-builder): superset builder — hanzo.chat advanced config folded into the ONE builder
console2's canonical, decoupled agent builder becomes the true superset: its
host-injected loader seam (unchanged) + hanzo.chat (@hanzo/ai)'s advanced
generation config. One component over the ONE /v1/agents backend — hanzo.chat
and console v8 render the identical builder.

Contract (types.ts):
- AgentConfig: temperature/topP/topK/stream/thinking/useTools/webSearch +
  reasoningEffort, all with defaults; folded onto AgentSpec as OPTIONAL config +
  knowledge, so a simple agent is unchanged.
- ReasoningEffort = the full Hanzo/Claude ladder low·medium·high·xhigh·max·
  ultracode (ultracode = xhigh+workflows, top tier, use sparingly) — supersedes
  @hanzo/ai's old 3-level enum.
- AgentCreateBody: the pruned wire value the builder emits; createAgent now
  takes the body (no more 'as AgentSpec' cast at the call site).

Pure logic (logic.ts): defaultConfig/clampConfig/pruneConfig +
normalizeList(→tools,knowledge, DRY). toCreateBody prunes every default knob, so
opening Advanced never changes what a simple agent posts. clampNum fixed: NaN→min
but ±∞ clamp to the nearest bound (slider-to-top lands on max, not min).

UI (AgentBuilder.tsx): hidden-by-default Advanced section (sliders/switches/select
over the existing Field primitives). loaders.ts + NewAgentBody pass config+knowledge
through to POST /v1/agents.

Verified: all pure transforms proven via a standalone node harness (22/22 incl.
backward-compat, clamp edge cases, prune, ultracode). tsc/vitest run in CI.
2026-07-01 23:03:53 -07:00
hanzo-dev 9ce9a78f14 console: publish ghcr.io/hanzoai/console (drop the 2) — repo renamed console2→console
CI workflow now builds+pushes ghcr.io/hanzoai/console:v<version> directly
(no more console2→console retag hack). registry product source-links and the
build/deploy doc updated to the renamed repo. Image name == repo name, one way.
2026-07-01 19:58:18 -07:00
hanzo-dev f9e6c28e91 Merge remote-tracking branch 'origin/main' into feat/console2-observe-langfuse-port
# Conflicts:
#	next.config.mjs
#	package.json
2026-07-01 19:42:31 -07:00
hanzo-dev f3e32fa480 console: shared "Hanzo Cloud 8.4" product-release label (v8.4.12)
One product, two build lineages: console ships app-semver 8.4.x, cloud
ships its own Go-module v1.786.x (never above v1 — Go module semantics +
the standing rule). Unify only the STORY under a "Hanzo Cloud <MAJOR.MINOR>"
umbrella, single-sourced from the console app version (no second place holds
it): next.config injects NEXT_PUBLIC_APP_VERSION from package.json;
config derives branding.release ("8.4") + branding.productLine
("Hanzo Cloud 8.4"), shown on the sign-in screen. Convention documented in
LLM.md. Nothing in Go changes. typecheck clean, vitest 793/793.
2026-07-01 19:21:25 -07:00
hanzo-dev 10c9dad2cd templates: Gallery starter-kit browser (Apps › Templates) over /v1/templates — category filter + search + fork/deploy handoff 2026-07-01 19:18:23 -07:00
zeekayandClaude Opus 4.8 7e0683b4c1 release: v8.4.11 — verified-green build (typecheck 0 errors, 793 tests, next build)
Cut a fresh semver from a verified-clean main HEAD so CI publishes
ghcr.io/hanzoai/console2:v8.4.11. Tree already type-checks + builds
clean (concurrent lanes resolved the earlier RecordsModule maxW /
metrics.test null-type breakages); this bump is the publish trigger.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 19:17:33 -07:00
hanzo-dev 6143c61c2f fix(observe): close RED honesty findings — non-finite/negative enrichment + tag coercion
RED review of v8.4.9 (0 critical/high/medium): 2 LOW honesty one-liners + 1 INFO, all closed at the DRY adapter layer.

1. Non-finite/negative enrichment: toTrace/toObservation coerce latency/cost/tokens
   via nonNeg (Number.isFinite && >= 0 → null, else 0 for usage members), so a
   malformed row (1e999→Infinity, -5, NaN) degrades to an em dash and never skews
   metric folds. fmtLatency/fmtCost mirror the guard. toScore drops non-finite
   values (keeps legit negatives).
2. Tags: toTrace filters non-string tags (a non-string tag crashed TraceDetailView).
3. INFO: getTrace/session throw ApiError(404) on a hollow 200-empty instead of
   synthesizing a trace/session — honest not-found → BackendStateCard.

+6 pure-logic tests (1e999 / -5 / NaN / negative). tsc clean · vitest 795/795 ·
next build green.
2026-07-01 19:14:46 -07:00
hanzo-dev a2ac5244d5 prompts: Starter library browse+import over /v1/prompts/catalog (107 curated starters; honest org-empty until imported) 2026-07-01 18:56:20 -07:00
hanzo-dev 4af523b87b console2: rename the 'Object Storage' product to 'S3' (v8.4.10)
The user asked to call it just 'S3'. Rename the user-visible product
name everywhere it surfaces — the catalog entry (registry.tsx label +
description), the StorageModule page header title, and the Zero Trust
data-plane posture row — plus the two resource-console doc comments that
list the kinds. The provisioning kind id stays 's3' and the file-manager
backend (/v1/s3) is unchanged; this is a label rename only.

typecheck clean, vitest 778/778 green.
2026-07-01 18:51:16 -07:00
6dabff3e77 feat(records): browse + edit any Base collection as a CRM/CMS (click-through) (#37)
Makes Base usable BY CLICKING, not just via the API — the gap the live Playwright
check found (the base admin UI is read-only). A 'Records' product (Data category):
browse a collection, open a record, edit it, create new ones — all rendered from
the collection's OWN field schema through @hanzo/data (DataTable for the list,
RecordDetail/RecordForm for detail; every field type is now editable per
hanzoai/ui#232). Data flows through console2's per-user /superbase proxy (IAM
bearer minted server-side; the proxy allow-list gains the collections + records
paths). Routes: /records (index) · /records/:collection · /records/:collection/:id
(:id=new → create).

base-data/{api,fields} map Base schema → @hanzo/data FieldDefinition[] and do the
list/get/create/update/delete; CollectionTable + RecordDetailView are the views.
Registered next to Base (the backend) — Base is the store, Records is the app on
top. 19 base-data tests pass; RecordsModule + registry typecheck clean (the 4
remaining tsc errors are pre-existing: @hanzo/dash local-only + metrics.test).

Co-authored-by: zeekay <z@zeekay.io>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 18:51:12 -07:00
hanzo-dev 493dba9d0f feat(observe): retarget the Langfuse Observe surface to native /v1/evals (v8.4.9)
The whole Observe surface (Traces, trace-detail span-tree/waterfall, Observations,
Sessions, Scores, Score Configs, Datasets, Dataset Items, Dataset Runs, Metrics
dashboard) now reads the NATIVE cloud clients/eval /v1/evals contract instead of
the retired /v1/o11y proxy. One-way, no duplicate modules.

- evals.ts: the ONE native client — datasets/items/evaluators/score-configs/scores/
  traces(+detail)/observations/sessions/runs, mapping wire rows into the canonical
  Langfuse view-models (toTrace/toObservation/toScore) so SpanTree + metrics render
  unchanged. Missing enrichment → null (em dash); unbound endpoint → typed ApiError
  → honest BackendStateCard. Never a fabricated row.
- o11y.ts: O11yApi retargeted to delegate to EvalsApi (traces/sessions/observations/
  scores/score-configs native); annotation-queues/users stay on /v1/o11y. TraceDetail
  fixed to Omit observations/scores from Trace before intersecting. Trace gains
  totalTokens (Langfuse Usage column).
- DatasetsModule: wired to the real native endpoints (listDatasets/listDatasetItems
  per-dataset/listRuns) — no longer forward-compatible stubs.
- TracesModule: adds the Tokens column; format.ts adds shared fmtTokens.
- evals.test.ts: 11 pure-logic adapter tests (null-safety, ms→s, token/usage fold).
- NOTICE: MIT attribution for the Langfuse-derived screen layout/flows.

Static-export-safe (data via same-origin /v1 client fetches, no new server routes).
tsc clean · vitest 789/789 · next build 14/14.
2026-07-01 18:44:05 -07:00
hanzo-dev 2da0f024f4 revert: drop console dual-tag — unbreak the release build
The CI token can push the existing console2 ghcr package but lacks
write_package to CREATE a new ghcr.io/hanzoai/console package, so the atomic
buildx --push of both tags failed and v8.4.9 published NEITHER image. Back to
single console2 tag so releases build again. The console2 → console image
rename needs the ghcr  package created + repo-linked first (an
org/settings step), then the tag can be added.
2026-07-01 18:24:00 -07:00
hanzo-dev e135c81422 feat(analytics): native /v1/analytics Observe module (web+commerce+LLM over datastore)
Per-org Analytics product over cloud clients/analytics: Overview (hanzo.events +
events_daily), Real-Time (live sessions/feed), LLM (cloud_usage + observations).
Same-origin /v1/analytics/* via the /cloud bearer proxy; analytics head added to
proxy-allow CLOUD_HEADS + next.config CLOUD_V1_HEADS. Registered under Observe.
Every metric a real warehouse query; honest-empty otherwise.
2026-07-01 18:20:05 -07:00
hanzo-dev f9ced604dd release: v8.4.9 — publish ghcr.io/hanzoai/console:v8.4.9 (rename transition)
Dual-tag release so the console image exists at this version before the operator
CR + gateway cut over from console2 → console in one coordinated deploy.
2026-07-01 18:06:01 -07:00
hanzo-dev 373385b0b0 build: dual-tag ghcr console + console2 (rename step 1, additive)
'console2' was only ever a working name — the package is already @hanzo/console
and it's v8. Start the rename by publishing ghcr.io/hanzoai/console:<ver>
ALONGSIDE console2:<ver>. Purely additive — nothing consumes the console image
yet, so no rollout can break. The cutover (operator CR + gateway k8s Service
console2→console, in ONE deploy) and dropping the console2 tag follow once the
new image has published on a release.
2026-07-01 18:04:10 -07:00
hanzo-dev 3cff611498 feat(ai): console2 AI surface LIVE over same-origin /v1/* + canonical agent builder (v8.4.8)
Rebased onto main v8.4.7 (Prompts/Agents/Evals live via next.config /v1 rewrites,
dynamic model+prompt agent builder, ComboBox). Was fe3ee26 (v8.4.5).
Cross-tenant eval fix ships in cloud v1.786.10.
2026-07-01 16:49:19 -07:00
hanzo-dev 40001fb502 feat(compute): real Launch drawer (GPUs+Machines) + full live catalog + Hanzo-brand Tasks/Functions (v8.4.7)
Launch GPU/Machine opened docs — now opens a REAL launch flow (POST /vm/v1/machines/launch,
per-org, metered; proven live vs vm:0.1.10). ONE shared LaunchDrawer (kind cpu|gpu) in the
DetailPane from both pages: complete live catalog (172 sizes / 9 GPUs, searchable) + regions,
OUR market price ($/hr+$/mo == the dryRun quote == what launch charges, visor HanzoPrice one
source), 402→'add credits'. Docs demoted to secondary.

Pricing: fixed $/mo (was priceHourly×730=693.5, now authoritative priceMonthly=706.8).
Catalog: MachineCatalog shows ALL sizes (search+scroll) not top-6; GPUs shows all 9.
Branding: Tasks drops 'Temporal'→Hanzo Tasks; Functions drops 'Fission'→Serverless/Hanzo.

VisorApi.quote/launch added (casibase-envelope unwrap). tsc clean; vitest green; build 14/14.
2026-07-01 16:34:55 -07:00
hanzo-dev dbae61c06e feat(nav): per-category color-coding + category-overview color wiring (v8.4.6)
Products inherit a per-category color family by default (one color per category:
AI/Compute/Data/Security/…), user override still wins, no-category callers keep
their legacy curated pick. colorOf/keyOf thread the entry's category so the sidebar
icons, collapsed rail, and L2 header recolor per category in one place. Category
landing (/category/<slug>, CategoryOverview — already built) tiles + header glyph +
the L1/L2 category labels are tinted the category color. colors.ts pure + tested.

tsc clean, vitest 711/711, next build green.
2026-07-01 16:20:33 -07:00
hanzo-dev 0cb0763e9b feat(nav): persistent product filter at level 2 — quick-jump across products from any level (v8.4.5)
The sidebar product filter is hoisted out of the level-1 slide panel into a
persistent header above the two-level slide, so a user deep in a product's
sub-pages can filter + jump straight to another product without going Back.
showLevel2 yields to the product list while filtering; selecting a result
clears the filter and slides to that product's level-2 sub-nav. One input,
one predicate (entryMatches), one list. Mobile drawer inherits it.

tsc clean, vitest 706/706, next build green.
2026-07-01 16:01:09 -07:00
hanzo-dev 4e6ba0fbce test(billing): fix groupSpend provider assertion — openai(400)>hanzo(350) sorts first
groupSpend sorts cents-desc (see the by-model test); the provider test
asserted the reverse and had been red on main. No logic change.
2026-07-01 15:46:31 -07:00
hanzo-dev 5817ff5c92 feat(storage): native S3 file manager + KMS repoint to embedded cloud KMS (v8.4.2)
PRIORITY 1 — S3 file manager. Upgrades the 'Object Storage' catalog entry from
the generic provisioning resource card to a REAL S3 file manager over the
org-scoped /v1/s3 control plane in the unified cloud binary (hanzoai/cloud
clients/s3). One console, one backend — no external s3.hanzo.ai UI.

- src/lib/api/storage.ts (StorageApi): buckets list/create/delete, object list
  (folder-style via prefix), delete, and presigned upload/download. Metadata ops
  go through the same-origin /cloud user-bearer proxy (cloudProxyV1Url — s3 is
  already allow-listed in proxy-allow.ts). Upload/download use PRESIGNED URLs:
  the backend mints a time-boxed URL scoped to the exact bucket+key and the
  browser transfers bytes DIRECTLY to S3 — bypassing the proxy (which buffers the
  body as text + forces JSON content-type, corrupting binary) and never exposing
  the admin credential. Defensive normalizers (billing.ts style); org is
  server-authoritative (never a browser claim).
- src/components/products/StorageModule.tsx: bucket list (create/delete) plus an
  object browser with breadcrumb folder navigation, upload (file picker to
  presigned direct-to-S3), download, delete. Honest loading/empty(first-run)/
  BackendState (503/404/403) states — never a fabricated bucket/object. hanzo/gui
  v5 shorthands; mirrors FunctionsModule.
- registry.tsx: s3 entry now routes to StorageModule (repo hanzoai/s3).

PRIORITY 2 — KMS repoint. src/lib/server/identity.ts KMS_URL default
http://kms.hanzo.svc (legacy Infisical fork) to http://cloud.hanzo.svc:8000
(embedded cloud KMS serving /v1/kms/orgs/{org}/secrets natively, HIP-0106). The
/admin/kms proxy forwards to kmsBaseUrl + /v1/kms/orgs/{org}/secrets — matches.
CAVEAT (documented, not a blocker): the embedded KMS is health-only (secret ops
503) until CLOUD_KMS_MASTER_KEY_REF is provisioned + secrets migrated; the KMS
module shows its honest 'not initialized' state until then.

Tests: vitest storage.test.ts 15/15 (normalizers, folder detection, presign,
traversal-safe key encoding, /cloud-proxy URL construction, direct-to-S3 upload).
tsc --noEmit clean. next build green (14/14 pages). Version 8.4.1 to 8.4.2.
2026-07-01 15:42:31 -07:00
hanzo-dev 6adacc7e4e feat(commerce): Commerce store dashboard in the console — Products/Orders/Customers/Inventory/Promotions/Store, per-org (v8.4.3)
A new Commerce category surfaces the hanzoai/commerce merchant store natively
inside the console (no admin.commerce.hanzo.ai subdomain). Six pages —
Products, Orders, Customers, Inventory, Promotions, Store settings — each a
native module over the real commerce backend, scoped to the signed-in org.

- BFF: app/commerce/[...path]/route.ts forwards to commerce.hanzo.svc:8001 via
  forwardWithUserBearer (mints a short-lived user IAM token; commerce EdgeAuth
  resolves the org from the owner claim). Least-privilege allow-list
  (allowCommerceSurface / COMMERCE_HEADS): only the merchant REST heads
  (product/order/user/variant/discount/collection/store/…) — /billing, /checkout,
  /_/commerce/tenants are NOT reachable (money stays on the /billing proxy).
- Client: src/lib/api/commerce.ts (CommerceApi) — defensive normalizers over the
  real {count,models,facets} envelope; empty store → honest empty, never faked.
- UI: one CommerceResource list (fetch → loading/empty/error via BackendStateCard)
  + six thin pages; Store settings notes Square/Billing. @hanzo/gui v5 shorthands.
- Category: 'Commerce' added to brand-scope (hanzo shows it; web3 brands don't).
- No Stripe, no new DB, no billing-engine change. Payments remain Square via
  hanzoai/commerce /v1/billing.

Verification: tsc --noEmit clean; vitest 52 green (commerce/logic/proxy-allow/
brand-scope); next build ✓ (/commerce/[...path] compiled). The one failing test
(billing/logic.ts groupSpend ordering) is pre-existing on origin/main, unrelated.
2026-07-01 14:56:23 -07:00
hanzo-dev d13dc49e69 fix(compute): make every Compute page read CONNECTED as a customer (v8.4.2)
Live browser pass as Dave (maxpower) found pages that were connected-but-read-as-broken:
- Machines: /vm/v1/machines 403s for a signed-in customer (visor authorizes the
  public catalog but denies the per-org list) → the page said 'Sign in to view your
  machines' next to the real region/size catalog. interpretVisorError now maps 403→
  connected-managed (only 401 = sign-in); CustomerMachines shows 'Launch your first
  machine' + the live catalog, never a sign-in wall.
- platform/state forbidden: reframed to 'Connected · managed by Hanzo' (green check, no
  warning triangle, no Retry) so Containers/Edge/Applications read connected, not error.
- Applications: repointed from casibase IAM OAuth apps (get-applications) to the DEPLOYED
  app services (/v1/apps) — connected/managed/empty states + deploy-via-Functions/Agents.
- Agents: 'Connected · no agents yet' banner on the live 200-empty state.
- Proxy defaults hardened (vm/cloud/tasksd): '|| default' (not '??') so an env
  reconciled to an EMPTY string still resolves the in-cluster service.

tsc clean; vitest green (visor test updated for 403→connected).
2026-07-01 14:42:53 -07:00
hanzo-dev ec75af5859 feat(compute): wire all Compute pages per-org to real backends + rich Agents dashboard (v8.3.2)
Agents: rebuilt AgentsModule into a rich dashboard over /cloud/v1/agents (was
/paas): 5 stat cards, invocations area chart, health donut, agents table with
status tabs + pagination + version badges, recent-activity feed, top-agents bar
list, 30d resource-usage panel. Every number real/derived; polished
create-first empty state + real New-Agent flow. New lib/api/agents.ts (+22 tests)
+ agents/{parts,forms}.tsx.

Machines: customer branch shows the real visor region/size catalog + pricing
(MachineCatalog) under the launch state — never blank.

GPUs: role-routed like Machines — customer sees the real visor GPU catalog +
their GPU machines (CustomerGpus); admin keeps the /paas fleet. Overview route
is role-aware (GpusOverview). +4 visor catalog normalizer tests.

Containers: surface the apps 403 as a graceful 'Managed control plane' card
(was a masked bare-empty table). Edge: honest coming-soon/managed state.

platform/state.tsx: split 401/403 (forbidden → 'Managed control plane') from
501 (not-configured → admin token hint) so customers never see the false
PAAS_SERVICE_TOKEN message across every /paas module.

visor.ts: add regions()/sizes()/gpus() catalog + normalizers.

tsc clean; vitest 639+ green; next build 14/14.
2026-07-01 13:47:15 -07:00
hanzo-dev 8cc9baa514 release: billing center — GCP-grade unified billing (Overview/Reports/Budgets/Invoices/Subscriptions/Payments/Credits) + billing-only shell mode for billing.hanzo.ai 2026-07-01 13:30:51 -07:00
hanzo-dev 10fef57400 Merge remote-tracking branch 'origin/feat/billing-center' into integrate/billing-center
# Conflicts:
#	LLM.md
2026-07-01 13:30:51 -07:00
hanzo-dev bfad0b8bf6 feat(billing): unified GCP-grade Billing Center + billing-only shell mode
Part A — Billing Center (one `billing` catalog entry, tabbed):
- Consolidate the scattered Cost/Subscriptions/Payment-methods entries into ONE
  `BillingModule` (registry ''+:tab) under Observe. Delete superseded CostModule.
- Overview: balance/credits + month-to-date spend + clearly-labelled linear
  projection + daily-spend trend (real /v1/billing/usage ledger, pure logic.ts).
- Reports: cost breakdown by real ledger dimension (model/provider — no invented
  project/SKU), filterable table + BarChart + spend-share Donut over a range.
- Budgets: REAL create+list over commerce spend-alerts (GET/POST /v1/billing/
  spend-alerts). Edit/delete withheld pending commerce per-alert ownership check.
- Invoices: GET /v1/billing/invoices + download; honest empty.
- Subscriptions/Payment methods/Credits: reuse existing modules verbatim as tabs.
- Add `scopedBillingBody` (billing-scope) so a write body's subject is pinned
  server-side — create-budget works without the browser knowing its subject and a
  forged body subject can't widen scope. Wired into the /billing proxy write path.

Part B — billing-only shell (billing.<brand> = same image, filtered):
- config.billingOnly (host billing.<brand> OR NEXT_PUBLIC_BILLING_ONLY=1).
- visibleCatalog / DashboardShell nav filter to the Billing Center sub-pages,
  full chrome kept; default route redirects / -> /billing.
- cmd+K + AppLauncher source from visibleCatalog so scoping is consistent.

Honest states everywhere; no fabricated data. New unit tests: billing/logic,
scopedBillingBody, config billing-only host. e2e/pages.spec updated for the
consolidation. Docs in LLM.md.
2026-07-01 13:25:45 -07:00
hanzo-dev b27f7165a0 release: console2 v8.3.1 — Nodes + DNS Network modules consolidated onto main
Build Docker Image / docker (push) Successful in 2m59s
One authoritative build ending the deploy-war. Two genuinely-unmerged Network
modules land (nodes: per-node luxd validators/peers; dns: per-org managed DNS);
all other session branches were already on main (git cherry-verified) and are
pruned, not re-merged. The api.hanzo.ai-gateway default change was rejected (CR
documents in-cluster CF-403 on public hosts; safe default is cloud.hanzo.svc).
Fixed pre-existing observability/metrics.test.ts null-override types so
tsc --noEmit is fully green.

tsc --noEmit clean; next build is the authoritative Node-24 gate (on-cluster
Kaniko, no GitHub builders).
2026-07-01 13:22:39 -07:00
hanzo-dev 4038efd556 fix(registry): dedupe DNS — render real DnsModule from the Network-cluster entry, drop the duplicate
The DNS module cherry-pick (bee05edc) added a second id:'dns' catalog entry while
main already carried a DNS overview stub in the Network cluster. Upgrade that
well-placed stub to render the real DnsModule (zones/records over /v1/dns) and
remove the duplicate — one id, one entry, one way.
2026-07-01 13:19:16 -07:00
1ca63e1836 feat(nodes): per-node blockchain infrastructure module (validators + peers)
Add a real `nodes` catalog entry (Network category) surfacing individual luxd
node infrastructure — validators (P-chain platform.getCurrentValidators) + peers
(info.peers) — across networks, wired to LIVE luxd RPC. Complements the Bootnode
`networks` module (network-level counts) with per-NODE inventory. REAL data only;
honest "not reporting" per unreachable network, honest empty otherwise.

- app/nodes/[...path]/route.ts: same-origin proxy mirroring the /bootnode security
  pattern — session-gated, brand/org-aware (brandFromHost), least-privilege. Only
  path is v1/inventory; only the four read methods getCurrentValidators/peers/
  getNodeVersion/getHeight are called server-side. Per-network RPC hosts in a small
  env-overridable map; unreachable host -> honest not-reporting, never fake rows.
- lib/api/nodes.ts (extended; cluster-capacity logic untouched): pure
  normalizeValidators/normalizePeers/combineInventory -> uniform NodeRow, dedupe by
  nodeID (validator wins, version enriched from peer), parseUptimePct/parseHeight/
  fmtWeight; NodesApi browser client over the proxy.
- lib/products/brand-scope.ts: nodeNetworksForBrand DATA scope — hanzo=all networks
  (super-admin/infra view), lux/zoo/pars scoped to their own chain. Nodes lives in
  Network so category scope admits it on every brand.
- components/products/NodesModule.tsx: per-network summary cards + network filter +
  DataTable (Network/Role/Node ID/Version/Status/Uptime/Height); BackendStateCard/
  EmptyState honest states.
- Confirmed live (2026-07-01): lux mainnet/testnet/devnet, pars-mainnet. zoo has no
  confirmed public host yet -> honest not-reporting.

Tests: nodes normalizers (real captured wire shapes) + brand->network scoping.
typecheck clean, vitest 404/404 (37 files), next build green. package 8.2.1->8.2.2.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 13:17:15 -07:00
865833e049 feat(dns): per-org DNS module — zones + records over /v1/dns (hanzodns)
A Network-category console module: lists org-scoped DNS zones and their records
on the unified /v1/dns surface (api.hanzo.ai gateway → hanzodns → CoreDNS +
Cloudflare sync). Honest BackendStateCard states (401/404/503) until the route
is bound — never fabricates a zone/record. Mirrors the Networks module; uses
@hanzo/data DataTable + the X-Org-Id the cloud client stamps.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 13:14:11 -07:00
hanzo-dev cbfe1c090b release: console UX batch — model catalog logos+providers, cmd+K scroll, docs links, editable branding, Linear icons, category overviews, org-wide observability
Consolidates 5 reviewed branches (PRs #24 #25 #28 #29 #35):
- Model catalog: real Zen ensō + Hanzo H marks; Providers link
- cmd+K: scrolls (mouse + keyboard-follow); docs deep links resolve (/docs)
- Settings: editable org branding (name/logo/colors/theme) with real save
- Linear-style ProductIcon tiles across cmd+K, sidebar, overview headers
- Per-category overview pages (12) + the AI hub
- Observability org-wide on login (Langfuse metrics, no per-project gate)
2026-07-01 12:05:21 -07:00
hanzo-dev 3e7db2c7e1 Merge remote-tracking branch 'origin/fix/console-observability' into integrate/console-ux-batch 2026-07-01 12:03:58 -07:00
hanzo-dev 23e9df90aa Merge remote-tracking branch 'origin/feat/console-category-overviews' into integrate/console-ux-batch 2026-07-01 12:03:58 -07:00
hanzo-dev c18cada283 Merge remote-tracking branch 'origin/fix/console-branding-and-icons' into integrate/console-ux-batch 2026-07-01 12:03:58 -07:00
hanzo-dev 087f35d0d0 Merge remote-tracking branch 'origin/fix/cmdk-scroll-and-docs-links' into integrate/console-ux-batch 2026-07-01 12:03:58 -07:00
hanzo-dev c654b714b2 Merge remote-tracking branch 'origin/fix/console-model-catalog' into integrate/console-ux-batch 2026-07-01 12:03:58 -07:00
hanzo-dev 4a9ba2af8f fix(console): observability is org-wide on login (Langfuse metrics, no per-project gate)
The Langfuse-derived views (metrics/logs/traces/sessions/scores/observations)
share the o11y REST client. Document + lock the tenancy contract: every call
stamps X-Org-Id (currentOrg(), always set on login) and adds X-Project-Id ONLY
when a project is selected — so these views are ORG-WIDE by default and narrow to
a project only when one is picked. No project required to 'just log in and see
metrics'. Adds a real MetricsModule (org rollups over /v1/o11y + /v1/metrics),
pure metrics logic, and its test. Honest states preserved (loading / not-
initialized 503 / empty) — no fabricated data.
2026-07-01 12:02:18 -07:00
098b04b75d fix(base): transpile @hanzo/dash (was @hanzo/dashboard) — unbreak build; lockfile + v8.2.13 (#33)
next.config transpilePackages still listed the OLD package name, so Next parsed
@hanzo/dash's shipped TSX source as plain JS → 'Unexpected token' on export type.
Rename the transpile entry, regenerate the lockfile onto @hanzo/dash@0.3.0.

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-01 11:54:24 -07:00
hanzo-devandGitHub 9ea65311a5 Merge pull request #32 from hanzoai/claude/wallet-live-balance
fix(wallet): live cloud-credit balance — refetch on focus + after completion/top-up (v8.2.12)
2026-07-01 11:50:09 -07:00
987dee1e08 Base: show 'Bases' scoped to Org → Project (IAM-native) via @hanzo/dash@0.3.0 (#31)
* feat(base): render Bases under Org → Project (drop the 'tenant' noun)

A superbase tenant IS a full Hanzo Base instance → label the page 'Bases' + show
the Org → Project scope (top-bar ScopeSwitcher) as a breadcrumb, consistent with
every resource module. Passes labels + context to the shared @hanzo/dashboard
screens (props added in superbase feat/base-labels-context). Needs that package
republished + a version bump here to build.

* chore: @hanzo/dashboard → @hanzo/dash@0.3.0 (coherent SDK name) + Base labels/context

Renames the dashboard SDK dep + imports to the canonical @hanzo/dash (was the
incoherent @hanzo/dashboard). 0.3.0 carries the labels/context props so the Base
page renders 'Bases — <org> / <project>' (Org → Project scope) instead of the
'Tenants' noun.

* chore: v8.2.12 — Bases-under-Org via @hanzo/dash@0.3.0 (merge main)

---------

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-01 11:49:27 -07:00
hanzo-dev bcc6d41bba fix(wallet): live cloud-credit balance — one shared store, refetch on focus + after completion/top-up (v8.2.12)
Dave (maxpower) saw his real $99.74 on mount but it never CHANGED without a
reload — "not seeing increase in the wallet view". The balance READ path was
correct (every surface hits /billing/balance, server-scoped to the caller's
commerce subject = maxpower, the exact subject the gateway debits), but liveness
was missing: SidebarWallet only polled 30s; WalletModule, CostModule fetched on
mount only; nothing refetched on window focus or after a balance-affecting
action. So a completion (debit) or an external billing.hanzo.ai top-up (credit)
was invisible until a manual refresh/reload.

Fix — ONE shared reactive balance store (src/lib/billing/live-balance.ts):
- owns the single /billing/balance fetch (in-flight de-dupe + freshness window
  so N mounted consumers cause ONE call);
- refetches on mount, on window focus + tab-visibility (returning from the Square
  top-up portal now shows the new balance with no reload), and on ONE ref-counted
  30s poll (paused when hidden);
- invalidateBalance() forces an immediate refetch after any balance-affecting action.
useCloudBalance() (useSyncExternalStore) is consumed by SidebarWallet, the Wallet
page cloud-credit card, and the Cost page balance card — every money surface now
shows the SAME live number.

Wire the completion seam: PlaygroundApi.chat (Chat/Playground/cmd-K) and the
streaming runner both invalidateBalance() on a finished completion, and the wallet
top-up success does too — so spend/credit reflects immediately.

Also: /billing proxy responses now send Cache-Control: no-store (a per-tenant
money response must never be cached). And drop the broken self-referential
node_modules 120000 symlink that origin/main re-tracked (it breaks
npm install / vitest / next build locally).

Tests: new live-balance.test.ts (10 — dedupe, freshness, phase mapping,
invalidate, no-flicker). tsc clean, vitest 573/573, next build green (14 pages).
2026-07-01 11:48:17 -07:00
hanzo-devandGitHub 19536e947a harden(security): pathIsClean rejects any surviving %XX + matrix-param (RED final, defense-in-depth, v8.2.11) (#30)
RED's final re-review: double-encoded traversal CLOSED, recommends ship. Two LOW
residuals remained — both inert against the Go backend fleet, but Blue closes them
so the boundary is robust INDEPENDENT of any downstream decode behavior (don't rely
on 'the upstream is Go, single-decodes'):
- R1: N>=3 encoding (%25252e) / overlong UTF-8 (%c0%ae) — pathIsClean now rejects
  ANY surviving percent-escape /%[0-9a-f]{2}/i (a legit segment carries none after
  Next's single decode; a residual %XX is a multi-encoding/overlong tell). Does NOT
  over-reject literal-% names (50%off -> %of, 'o' not hex -> allowed).
- R2: '..;' matrix-param traversal — reject any ';' segment (matrix params unused by
  these REST APIs).

The authoritative post-normalization new URL() gate (v8.2.10) is unchanged; this is
the fast defense-in-depth first gate. Non-blocking per RED. RED INFO (/paas + /billing
bypass bearer-proxy) is by-design — they have their own gates (admin+service-token /
billing-scope.ts).

NOTE: local tsc/vitest are down (env upgraded to Node v26 mid-session + shared
node_modules symlink loop); change is a monotonic regex broadening over the
563-test-passing v8.2.10 guard. Validated via CI next build (Node 24) + live (%252e->404,
clean->401 no over-reject).
2026-07-01 11:26:55 -07:00
hanzo-dev 078cebdcf1 feat(console): per-category overview pages + an AI hub
Each product CATEGORY now has its own landing page at a stable
`/category/<slug>` route (AI, Compute, Data, Network, Security, …) — the
category-level twin of the native product overview. It shows the category name,
an honest one-line description of what the category is, and a grid of every
product in it (each card opening the product's native route). `soon` products
are shown with the existing SOON affordance — never hidden, never faked.

The "AI" overview is the hub for all things AI: it groups Models, Providers,
Inference, Agents, Embeddings, Playground, and Prompts, and leads with prominent
shortcuts to the Model Catalog and Providers.

- Routing follows the SAME pattern as products: one `ProductModule` with a
  `:slug` `ProductRoute` (`categoryRouteModule`) in `productModules`, resolved by
  the same `resolveRoute` and rendered by the same catch-all. It is deliberately
  NOT a `catalog` entry — a category is a grouping of products, not a product, so
  it never appears as a card in the nav / home / launcher. Unknown or
  out-of-brand slugs `notFound()` (propagated cleanly by ProductErrorBoundary).
- All content is derived from the registry (`visibleCatalogByCategory`, brand-
  and admin-scoped) — zero fabricated data. A new product appears on its
  category page for free.
- Nav wiring: the sidebar level-1 category headers, the sidebar level-2
  "More in <category>", and the catalog-home category headers all link to the
  category overview. Breadcrumbs render `Home / Category / <Name>`.
- Pure taxonomy helpers `categorySlug` / `categoryFromSlug` / `CATEGORY_SUMMARY`
  in brand-scope.ts (dependency-free), re-exported from the registry; unit-tested
  in registry-brand.test.ts (round-trip, unique slugs, complete summaries).

No version bump.
2026-07-01 11:07:28 -07:00
hanzo-dev 755389b935 fix(console): editable org branding + Linear-style product icon tiles
Branding (Settings → Branding was read-only host config):
- BrandingTab is now an editable org-branding form (display name, website,
  logo URL, favicon URL, primary color + "apply custom theme") with a real
  Save that round-trips the FULL org record to Hanzo IAM via
  TeamApi.updateOrganization → the /org/iam self-service proxy. Honest states:
  saving / saved / error; a non-admin sees the fields read-only with a gated
  notice (the server proxy 403 surfaced as the same honest access message).
  No fake success. The prior host-runtime values stay as a read-only
  "Runtime (resolved per host)" section.
- Server: /org/iam proxy now allows update-organization (org-admin-only via
  requireAdminForWrite), pinned to the caller's OWN org by BOTH the ?id name
  and the record's body name (forwardIam), so a brand admin can't retarget
  another tenant. admin.ts adds a ThemeData type + Organization.themeData.

Icons (Linear-style):
- New src/components/ui/ProductIcon.tsx — a rounded-square tile filled with the
  product's accent color and the glyph knocked out in near-white (the same
  raw-hex fill + #fff glyph technique as SwatchButton / ProviderLogo); neutral
  $color12/$color1 chip when no color.
- Swapped into CatalogRow (CommandPalette), the sidebar NavRow collapsed +
  expanded and its L2 detail header (DashboardShell), and the NativeOverview
  product header — each preserving the product's colorOf() accent.

Tests: iam-proxy.test adds org-name body extraction (the parsing the new
update-organization write guard depends on).
2026-07-01 11:07:22 -07:00
hanzo-devandGitHub f44b575c45 fix(security): close double-encoded (%252e) path-traversal bypass — RED re-review HIGH (v8.2.10) (#27)
RED's re-review confirmed 4/5 fixes closed but found a residual HIGH: pathIsClean
validated the PRE-normalization string, so a double-encoded %252e%252e (Next decodes
once -> %2e%2e, survives the guard) then normalized to real ../ inside undici's URL
parser at fetch time -> reached /v1/get-account, Base _superusers, escaped CLOUD_HEADS
on /cloud /vm /superbase. Live-proven (401 = passed the guard).

Robust fix (validate what fetch ACTUALLY sends):
- forwardWithUserBearer now re-parses the built target URL with new URL() and runs the
  AUTHORITATIVE pathIsClean + allow() gate on the NORMALIZED pathname (relative to the
  target base), then fetches that normalized dest — so %2e, double-encoding, and any
  future encoding are all gated on the exact path undici will request. One-way, DRY:
  fixes every helper proxy (/cloud, /vm, /superbase, /tasksd) at once.
- pathIsClean also now rejects %2e (not just %2f) as a fast defense-in-depth first gate
  (catches the Next-single-decoded %2e%2e before URL construction).

New tests: 4 double-encoded pathIsClean cases (red today, green now). typecheck clean,
vitest 563/563, next build green. RED re-review of bearer-proxy path validation requested.
2026-07-01 10:59:43 -07:00
hanzo-dev bc5b35c0b8 fix(console): real Zen/Hanzo marks in model catalog + Providers link
- ProviderLogo rendered first-party (Zen/Hanzo) models with a generic Sparkles
  glyph. Now render the REAL marks knocked out of a filled rounded tile: the Zen
  ensō (identical geometry to @zenlm/logo) and the Hanzo block-H (@hanzo/logo) —
  so zen models show the proper logo and read on-brand (Linear-style cut-out).
- Add a 'Providers' button to the Model Catalog header → /providers. Models and
  providers are one AI surface; this makes it easy to get back to providers.
2026-07-01 10:52:55 -07:00
hanzo-devandGitHub a1e0f8e792 Merge pull request #26 from hanzoai/claude/console2-route-error-boundary
fix(console): product-route error boundary — direct-load/refresh never white-screens (v8.2.9)
2026-07-01 10:49:30 -07:00
hanzo-dev 1608de5fd9 fix(console): product-route error boundary — direct-load/refresh never white-screens (v8.2.9)
Product modules mount CLIENT-ONLY under the catch-all route (the authed shell
renders a loader during SSR, so the /playground server HTML carries no module
markup — verified). With NO error boundary anywhere in the app, a throw in one
module's first client render bubbled to Next's root fallback and white-screened
the whole console with "Application error: a client-side exception has occurred"
— but only on a DIRECT load / REFRESH; in-app nav re-renders fresh and hid it.
That matches the reported /playground, /prompts, /gpus crashes exactly.

Fix (one place, closes the class for every product route — DRY):
- ProductErrorBoundary wraps the resolved module in the catch-all page. A module
  throw now keeps the shell + nav and shows an honest, retryable card instead of
  a white screen. Re-throws Next control flow (notFound/redirect/CSR bailout) so
  routing still works; auto-recovers a ChunkLoadError (rolling-deploy skew) with
  ONE guarded reload (no loop).
- app/(dashboard)/error.tsx: Next-native backstop for throws above the module
  (the resolver), rendered inside the shell.
- boundary-logic.ts: pure decisions (chunk detect / control-flow detect / reload
  gate), 11 unit tests. Proven end-to-end against a production build: a real
  throw renders the card with zero uncaught pageerror (screenshots).

e2e/deeplink-refresh.spec.ts locks the reported scenario: /playground, /prompts,
/gpus (+ controls) must render on direct load AND refresh with no white-screen.

tsc clean · vitest 562/562 · next build green.
2026-07-01 10:48:48 -07:00
hanzo-dev 8f60abb1a6 fix(console): real Zen/Hanzo marks in model catalog + Providers link
- ProviderLogo rendered first-party (Zen/Hanzo) models with a generic Sparkles
  glyph. Now render the REAL marks knocked out of a filled rounded tile: the Zen
  ensō (identical geometry to @zenlm/logo) and the Hanzo block-H (@hanzo/logo) —
  so zen models show the proper logo and read on-brand (Linear-style cut-out).
- Add a 'Providers' button to the Model Catalog header → /providers. Models and
  providers are one AI surface; this makes it easy to get back to providers.
2026-07-01 10:47:20 -07:00
3318ca32a9 refactor(auth): call the account surface under /v1/iam/* (#20)
* refactor(auth): call the account surface under /v1/iam/*

Pairs with hanzoai/ai serving signin/signout/get-account/update-preferences
under the organized /v1/iam/ namespace. The client account calls (account.ts)
and the server-side session resolve (identity.ts resolveUser) now target
/v1/iam/*; all remaining references (doc comments) updated for accuracy.

Deploy order: cloud-api (with V1IamRewriteFilter) MUST ship before this, so
/v1/iam/* resolves. No top-level fallback is kept — forward-perfect.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(cloud): default to cloud.hanzo.svc, drop the cloud-api alias name

The API binary Service is canonically `cloud` (universe renamed cloud-api →
cloud; the cloud-api ClusterIP is a transitional alias). The console2 CR already
sets CLOUD_API_URL=cloud.hanzo.svc, but the server-route code DEFAULTS still
named the dead alias — so any deployment without the explicit env (local dev)
would dial a name slated for removal. Point both defaults (identity.ts,
training proxy) at cloud.hanzo.svc — one name.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: zeekay <z@zeekay.io>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 10:35:14 -07:00
hanzo-dev 03523a317c fix(console): cmd+K scrolls + keyboard-follows; docs deep links resolve
Command palette (cmd+K):
- The results list clipped instead of scrolling: the body had maxH:420 but the
  inner ScrollView had no flex bound. Add overflow:hidden on the body + flex:1
  on the ScrollView so the list scrolls (mouse/trackpad) past the fold, and show
  the scroll indicator.
- Keyboard ↑/↓ moved selection off-screen with no follow. Tag the active row
  (id=cmdk-active) and scrollIntoView({block:'nearest'}) on selection change, so
  arrowing always keeps the highlighted item visible. All 50 results are now
  reachable and discoverable.

Docs deep links:
- docs.hanzo.ai serves the Fumadocs site under the /docs base path
  (docs.hanzo.ai/docs/<slug>), but the console linked bare docs.hanzo.ai/<slug>
  → every 'Full docs' / resource docs link 404'd. Point DOCS (registry) and
  docsUrl(kind) (resource/logic) at .../docs. Matches the created product pages.
2026-07-01 10:33:33 -07:00
hanzo-devandGitHub 289d51f37f fix(security): RED findings — cross-tenant projects + %2f allow-list bypass (v8.2.8) (#23)
* fix(vm proxy): default VISOR_URL to visor.hanzo.svc:19000 (was :80)

Cosmetic source fix — the live CR + universe already set VISOR_URL to :19000, which
governs runtime. This corrects the fallback constant so an env-less run also targets
the port visor actually serves (its Service exposes :19000 only; :80 → 502 upstream
unreachable). No version bump; rides the next build (the compute session owns /vm).

* fix(security): RED findings — cross-tenant projects, %2f allow-list bypass, scope headers, error DNS (v8.2.7)

Adversarial review (RED, PR#18/#19) found live holes in the BFF auth path. Fixes:

- [CRITICAL] Cross-tenant project enumeration. /org/iam/get-organization-projects
  with an OMITTED/empty ?organization passed the 'validate-if-present' check
  (ownerOk(null)=true), and IAM drops its WHERE on empty -> returned EVERY org's
  projects (IAM bypasses Casbin for project routes, so the proxy is the only gate).
  CONFIRMED LIVE (Dave/maxpower saw dhd, 7stars-dev projects). Fix: forwardIam now
  PINS ?organization to the caller's orgScope for a non-global admin on org-keyed
  segments (pinnedSearch, server-authoritative like X-Org-Id); global admins
  unrestricted. Org-keyed WRITES must carry owner+organization == own org (no
  owner='' junk rows). New orgParamSegments={get-organization-projects,add/delete-project}.
- [HIGH] %2f + .. allow-list bypass on /cloud, /superbase, /tasksd. Next decodes
  %2f into segments without re-normalizing dot-segments, and fetch() collapses '..'
  AFTER the allow-list -> 'functions%2f..%2f..%2fiam' slipped a foreign head past
  allowCloudSurface. Fix: forwardWithUserBearer now rejects any '', '.', '..' or
  surviving %2f segment (pathIsClean) BEFORE the allow-list, and trims trailing
  slashes. One guard fixes every helper-based proxy; /ai was already immune (exact-match Set).
- [MEDIUM] Dropped forwardScope on /cloud + /vm — no longer forward browser-controlled
  X-Project-Id/X-Environment (org is authoritative via the Bearer owner; the resources
  are org-keyed). A project-scoped feature must validate membership first.
- [LOW] Redacted 502 bodies (were leaking internal svc host/port) -> generic message +
  server-side console.error. Both bearer-proxy and iam-proxy.
- [bundled] /vm default VISOR_URL -> visor.hanzo.svc:19000 (was :80; visor serves :19000).

New pure tests: pinnedSearch (4), pathIsClean (3). typecheck clean, vitest 551/551,
next build green. Re-review by RED requested.
2026-07-01 10:31:40 -07:00
hanzo-dev b736e97595 release: console2 v8.2.7 (KMS + IAM Users/Roles full CRUD live)
Advance prod (operator-pinned v8.1.1) to current main: KMS secret CRUD, IAM
Users CRUD, IAM Roles CRUD, 89-page e2e harness. Build publishes
ghcr.io/hanzoai/console2:v8.2.7; operator CR bump follows once the image lands.
2026-07-01 10:27:12 -07:00
hanzo-dev 5e1ea787fe Revert "release: console2 v8.2.7 — KMS + IAM Users/Roles full CRUD in-console"
This reverts commit 63acec3982.
2026-07-01 10:25:44 -07:00
hanzo-dev 63acec3982 release: console2 v8.2.7 — KMS + IAM Users/Roles full CRUD in-console
Cuts a release so prod (operator-pinned) can advance from v8.1.1 to include:
- KMS secret management (create/reveal/delete)
- IAM Users CRUD (create/promote/delete)
- IAM Roles CRUD (create/delete)
- 89-page screenshot e2e harness
All auth via /v1/iam/* + cookie-session /v1/*. Build publishes
ghcr.io/hanzoai/console2:v8.2.7.
2026-07-01 10:22:44 -07:00
hanzo-dev bd2641feb4 chore: gitignore test-results artifacts 2026-07-01 10:21:02 -07:00
hanzo-dev cc19ebb8db console2(iam): Roles full CRUD — completes the IAM management surface
IAM already serves /v1/iam/{add,update,delete}-role (iam controllers/role.go) —
I was wrong that it needed a backend. Wire it: allowlist the 3 role mutations in
the /admin/iam proxy, add addRole/updateRole/deleteRole to IamAdminApi, and give
the Roles tab a create/delete view (RolesAdminView, mirrors UsersAdminView).
All auth flows through /v1/iam/* per the one-path rule. Typecheck clean.

IAM is now fully CRUD in-console: Orgs (list), Users (create/promote/delete),
Roles (create/delete), Applications + Providers (add/edit/delete) — no link-out
for the common lifecycle.
2026-07-01 10:20:13 -07:00
hanzo-devandGitHub 5eed0f5a2f feat(shell): delightful mobile + customizable sidebar — right-side SlideOver drawer/DetailPane, colorful per-product icons, grouped drag-reorder pins, full-screen mobile ⌘K, L2 category links, customer compute via visor (v8.2.6) (#21)
- SlideOver: ONE transform-driven right-side overlay (drawer + DetailPane + account menu); enter+exit animate, backdrop cross-fade, Escape, scroll-lock, focus return, reduced-motion. Full-screen <lg, fixed-width lg+.
- DetailPane: descriptor-driven item detail/edit pane (products write a descriptor, not their own pane).
- Colorful Linear-style icons: pure colors.ts palette (override > curated > hash), per-user overridable; applied in sidebar/palette/launcher.
- Pins: pure pins-core model (groups + order); usePins over account prefs; grouped display + drag-reorder (pointer DnD, no deps) + groups in the Manage/Customize panes.
- Mobile: nav drawer now RIGHT with ⌘K/AI-search + Apps at top; palette full-screen on mobile.
- L2 sub-nav: category breadcrumb + 'More in <category>' sibling jumps.
- #9: customer Machines via user-scoped /vm visor (real machines or graceful 'launch one') — infra 'PAAS_SERVICE_TOKEN' message gated to global admin only.
- favorites reimplemented over usePins (one store). +39 tests (colors/pins-core/Reorder/visor). tsc+vitest(540)+next build green.
2026-07-01 10:17:05 -07:00
hanzo-devandGitHub e50efd1f43 fix(projects): route the Projects page through the /org/iam Bearer proxy (v8.2.4) (#19)
Projects rendered 'not routed' because ProjectApi hit the cloud /v1 cookie path
for IAM endpoints: console.hanzo.ai/v1/iam/get-organization-projects → the gateway
sends /v1/* to the CLOUD binary, which does NOT serve IAM → 404. Proven live:
that exact URL returns 404, while IAM serves the endpoint.

Fix (same BFF-Bearer pattern, existing infra — no new mega-router):
- projects.ts now calls the same-origin /org/iam proxy via makeIamClient, which
  mints a user-bound Bearer server-side and forwards to iam.hanzo.svc. Org resolves
  from the token owner claim (per-tenant), the member-roster pattern.
- /org/iam allow-list gains get-organization-projects (GET) + add-project,
  delete-project (POST, org-admin only via requireAdminForWrite).
- SECURITY: forwardIam now also pins the ?organization param AND the body
  organization field to the caller's org (ownerOk), closing the cross-tenant gap
  for the projects lister/CRUD (ownerOk(null) is a no-op for segments without it,
  so no regression to get-users/get-roles). bodyOwner generalized to bodyField.

typecheck clean, vitest 505/505 (+4 new: projects.test.ts, iam-proxy.test.ts),
next build green. Auth-mint/proxy path touched → hand to RED.
2026-07-01 09:56:13 -07:00
hanzo-dev d5e94b9a7a fix(api): drop dead X-IAM-Org-Id stamp; X-Org-Id is the one canonical org header
The ai data-scoping filters (GetEffectiveOrg, controllers/org_resolver.go)
and the provisioning sub-service both read `X-Org-Id` — NOT `X-IAM-Org-Id`.
cloud mints X-IAM-Org-Id OUTBOUND toward commerce from the validated
principal, so the browser stamp was inert dead weight (and the old comment
claiming GetEffectiveOrg reads X-IAM-Org-Id was drift). Keep the required
X-Org-Id stamp; drop X-IAM-Org-Id; note X-Project-Id is the canonical
project sub-scope evalsvc now reads.
2026-07-01 09:53:19 -07:00
2c352a373b feat(bff): user-bound Bearer for every service proxy — cookie→BFF→Bearer (v8.2.3) (#18)
The data + serverless surfaces (vector/sql/kv/s3/docdb/datastore/search,
functions/prompts/agents) and visor compute now resolve org from the Bearer
JWT owner claim; a cookie-only browser call 403s ('X-Org-Id required'). The
console BFF now mints a short-lived user-bound IAM token server-side (the
proven /ai + /keys pattern) and forwards it, so the browser path works
end-to-end, per-org — no token in the browser, org never browser-supplied.

- src/lib/server/bearer-proxy.ts — ONE shared forwardWithUserBearer(req, opts):
  resolveUser (session cookie) -> adminBearer (shared per-user token cache in
  identity.ts) -> forward with Authorization: Bearer + X-Org-Id=owner, cookie
  NEVER forwarded (dodges the public-gateway 431), response STREAMED (SSE/JSON/
  204). Pure errorBody/upstreamHeaders + proxy-allow.ts allow-lists, unit-tested.
- app/cloud/[...path] — user-bearer proxy to cloud-api for the data + serverless
  heads (allowCloudSurface); provisioning.ts + functions.ts repointed to
  <origin>/cloud/v1/* (was the cookie-only direct path that 403s).
- app/vm/[...path] — user-bearer proxy to visor (allowVisorSurface) for the
  compute surface (regions/gpus/machines); ready for the compute UI.
- DRY: /ai, /tasksd, /superbase refactored onto the shared helper — 3 duplicate
  issue-user-token caches deleted, one adminBearer cache for every proxy.

typecheck clean, vitest 464/464 (+14 new), next build green (/cloud + /vm compiled).

Co-authored-by: Hanzo AI <ai@hanzo.ai>
2026-07-01 09:36:17 -07:00
hanzo-dev 03a6167613 chore(release): v8.2.2 — immutable tag for all-pages + living-overview HEAD 2026-07-01 09:29:40 -07:00
8ceffc76e8 console2: all-pages production build — native control planes, no external link-outs (#16)
* feat(console2): make all 14 external products native in-console overviews

The registry declared 14 products with kind:'external' (gateway, dns, cdn,
mpc, cli, sdks, api, ide, desktop, registry, metrics, crawl, studio, console),
but open.ts / match-core / NativeOverview / overviewFor were already collapsed
to a no-external world. Result: those 14 pushed /${id} which resolveProductView
returned notfound → HARD 404 dead links from the overview grid + app launcher.

Convert each external entry to kind:'module' routes:overviewRoutes(id), rendering
the existing NativeOverview (bespoke OVERVIEW_SPECS already merged — real header,
live platform-app health, key facts, native actions, INLINE docs, zero link-out).
Collapse CatalogEntry union to module-only and ProductStatus to enabled|soon;
remove the dead external branches in DashboardShell + OverviewModule and the stale
ext/href config. One way to open anything: a native route.

resolve.test.ts already pins all 14 specs + native-route actions; match-core.test
updated to assert the kind-guard fails closed for a non-module entry.
typecheck 0 errors, 381 vitest pass.

* feat(console2): Subscriptions + Payment Methods + Marketplace pages (real feeds)

Three new production-complete control-plane pages, all backed by REAL /v1 data,
matching the console taxonomy — no new backend needed (they ride existing feeds).

Billing sub-pages (category Observe, alongside cost/plans):
- SubscriptionsModule → GET /v1/billing/subscriptions (commerce, via the /billing
  per-tenant proxy: server-injected COMMERCE_TOKEN, org-scoped, client can't widen).
  Plan / status / seats / price / renewal. Read-only; manage links to the portal.
- PaymentMethodsModule → GET /v1/billing/payment-methods. Card-data MASKED by
  construction: normalizer extracts only brand+last4+expMonth/Year+isDefault — a
  PAN/CVV/token in the payload is dropped and never reaches the display object
  (dedicated leak test asserts it). Renders '••••  last4'. Read-only; add links to portal.
- billing.ts: Subscription+PaymentMethod types + normalizeSubscriptions/
  normalizePaymentMethods (handle Stripe snake_case AND camelCase, nested card obj,
  Unix seconds/ms dates). billing.test.ts: +9 tests incl the PAN/CVV/token leak guard.

Marketplace (category Apps, alongside chat/bot/search):
- MarketplaceModule → the storefront over the REAL model catalog (aicatalog.
  fetchCatalog → GET /v1/pricing/models via the authed /ai proxy). Category tiles,
  featured shelf (real catalog flag), filterable listings w/ real per-Mtok pricing,
  Try-it→Playground CTA. Reuses the existing aicatalog client + ProviderLogo — a
  distinct storefront view over the SAME catalog, not a duplicate of Model Catalog.
- marketplace/logic.ts (categorize/featured/applyFilters/marketStats) + 16 tests
  incl a regex-injection safety test (search is a literal substring filter).

Hardening across all three: read-only, org-scoped (IDOR-proof), no secrets in the
bundle, XSS-safe (plain <Text>, no dangerouslySetInnerHTML), honest loading/empty/
error states (BackendStateCard/ErrorState), every number a real field or '—' —
nothing fabricated. Tamagui shorthand only, dark design language.

typecheck 0 errors · 406 vitest pass (+25 from the new suites).

* docs(console2): document the all-pages build in LLM.md (external→native + billing/marketplace + honest scope)

* fix(console2): billing-proxy tenant isolation — X-Org-Id + full subject-key pinning (RED HIGH)

RED found the /billing proxy's tenant scoping was INERT — a cross-tenant IDOR:
1. It stamped X-Hanzo-Org, but commerce reads X-Org-Id on the service-token path
   (commerce/middleware/accesstoken.go) — the header silently fell back to the
   service org, so every tenant shared one commerce namespace.
2. It pinned only ?user=, but subscriptions filter ?userId=
   (commerce/api/billing/subscriptions.go) — with no userId the query returned
   EVERY subject's subscriptions in the namespace (cross-tenant read).

Fix, mirroring commerce's own edge-auth exactly:
- Send X-Org-Id (like the exemplary /ai proxy) so the namespace resolves per-tenant.
- Pin the FULL subject-key set {user,userId,customerId} to the server-resolved
  subject (= commerce/middleware/edgeauth.go billingSubjectKeys) so NO billing
  endpoint is left unfiltered whichever param it reads; ?org= is still dropped.
- Extract the scoping to a pure src/lib/server/billing-scope.ts (scopedBillingSearch
  + billingSubject) — testable without the Next runtime, same pattern as ai-proxy.ts.
- Defense-in-depth: normalizePaymentMethods clamps last4 to the last 4 digits even
  if commerce puts a full PAN there.

Tests: billing-scope.test.ts (11) — client-forged-subject overwrite, two-tenant
disjointness, non-subject passthrough; billing.test.ts +1 (last4 PAN clamp);
e2e/billing-isolation.spec.ts — live two-tenant disjoint subscription/payment sets;
the 3 new pages added to the 89-route render pass. typecheck 0, 487 vitest, next build ✓.

Rebased on latest main (living-overview #17).

---------

Co-authored-by: Hanzo AI <ai@hanzo.ai>
2026-07-01 07:00:04 -07:00
zeekayandClaude Opus 4.8 4863c4f1e7 refactor(web3): drop /bootnode proxy prefix — Networks uses unified /v1/networks
Per the 'one /v1, no extraneous prefix' rule: the Networks module now calls
same-origin /v1/networks (gateway-routed to the bootnode control plane), not a
per-backend /bootnode/* proxy. Deletes app/bootnode. Honest states unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 06:19:05 -07:00
f472e6385c feat(overview): reusable "living overview" — animated, real-data, config-driven across products (#17)
The admin Platform Overview is now a REUSABLE `LivingOverview` component system
(one component, many configs), not a one-off. Videogame-like: count-up KPIs, live
sparklines, a streaming/virtualized activity feed, throttled polling — tasteful,
60fps, reduced-motion-guarded. Backed by REAL /v1 data, no mocks; every missing
feed renders its honest empty/skeleton/em-dash, never fabricated numbers.

System (src/components/products/overview/living/):
- config.ts   declarative LivingOverviewConfig: tiles in rows + one real-data
              load() => OverviewData + a live block (pollMs/countUp).
- motion.ts   pure count-up/sparkline-ring/poll-clock math (unit-tested).
- hooks.ts    thin rAF/interval drivers (useCountUp animates from the current
              on-screen value on retarget; usePoll/useReducedMotion/usePageHidden),
              all self-cleaning — no leaked frames/timers.
- logic.ts    pure tile decisions: unit-aware formatMetric, deltaOf ("—" w/o basis),
              hasTrend, status/health colors, mergeActivity (stream dedupe),
              windowRows (virtualization), worst/tally (unit-tested).
- tiles.tsx   the 6 animated tiles (reuse ui/Charts verbatim; skeleton/empty/error).
- LivingOverview.tsx  the driver: one throttled poll loop (5s floor, paused when
              hidden/errored), reqRef race guard, background refetch never blanks a
              board with real data. globals.css: hz-skeleton/hz-pulse/hz-row-in.

Real data (adapters.ts, pure + tested): fromCloudUsage (commerce usage ledger),
fromAdminOverview (new lib/api/admin-overview.ts — /v1/admin/overview, optional-safe,
degrades to honest empty on 404), fromFunctions, healthFromApps (operator inventory).

Wired (overview/living/registry.ts — declarative catalog): overview (platform
centerpiece at / and /overview; admin aggregate w/ honest fallback to usage+health),
ai-metrics, functions, gpus. Product route '' renders livingOverviewModule(id); tabbed
products keep :tab, reachable via the sidebar sub-nav (declared subpages) — no dead-end.
Adding a product overview = one config, no UI.

Deletes the superseded OverviewModule + AiMetricsModule (+ aimetrics/{StatTile,
UsageChart,format}) — one overview system, DRY.

typecheck clean (0 errors), 449/449 tests (42 files), next build green (14/14).
Visual proof via headless Playwright: full board renders w/ count-up + live sparklines
+ streaming + donut + health tally, values change across a 5s poll, reduced-motion
snaps to real values, functions/gpus render honest empty/error states w/o crashing.

Co-authored-by: Hanzo AI <ai@hanzo.ai>
2026-07-01 06:17:25 -07:00
hanzo-dev 355112b403 e2e: screenshot + render-check every console page (89 routes)
Drives a signed-in session over every registered product route, asserts each
mounts without a hard crash (no Next error overlay, non-blank body, <500), and
captures a full-page screenshot to e2e/screenshots/<id>.png. The 'screenshot it
all, verify every page is wired FE↔BE' pass. Gitignores screenshots/test-results.

Running it against live console.hanzo.ai surfaced a P0: the cloud /v1 backend is
returning 502/503, so sign-in (/v1/signin) fails for all users.
2026-07-01 06:13:07 -07:00
hanzo-dev 864788b42f console2(iam): full user CRUD in-console (casdoor surface, no link-out)
IamModule's Users tab was read-only + linked out to the external casdoor console,
but IamAdminApi already has add/update/delete-user (and the /admin/iam proxy
allowlists those mutations). Surface them: create user (name/email/password,
argon2id-hashed by IAM), promote/demote global-admin (shield toggle), and delete
— all scoped to the active org through the server-gated proxy. Honest states
(loading / operator-required 403 / error / empty). Typecheck clean.
2026-07-01 06:06:32 -07:00
hanzo-dev f6b8b51daa console2(kms): full secret management in-console (one FE for all)
The KmsModule listed metadata and linked OUT to the standalone kms.hanzo.ai
console for everything else. But the /admin/kms proxy + KmsAdminApi already
support full CRUD (list/reveal/create/rotate/remove) over /v1/kms/orgs/{org}/
secrets. Surface it: create/upsert form (path/name/env/value, secure), per-row
reveal (one value, shown once, audited, never cached/listed), and delete — all
through the server-gated admin proxy, scoped to the active org. Keeps the
zero-knowledge stance (no bulk value listing). Removes the external link-out, so
console2 is the single KMS management surface. Typecheck clean.
2026-07-01 05:57:57 -07:00
hanzo-dev 35627404fc fix(tasksd): default TASKS_URL to :7243 (tasks REST port; :80 doesn't exist) — Tasks page now shows real workflows/namespaces 2026-07-01 05:24:21 -07:00
zeekayandClaude Opus 4.8 5a0db2c6dd test(e2e): expand public suite — proxy security gates + routes (no creds)
Adds 4 credential-free live tests proving production posture: root serves
(200/dark #0a0a0a) + /base resolves; server proxies (superbase/bootnode/keys)
reject unauth with 401; proxy allow-lists reject off-list paths with 404 (no
tunnel); unknown route never 5xxs. 5/5 green vs console.hanzo.ai — real CI signal
without the prod superuser password.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 23:02:21 -07:00
zeekayandClaude Opus 4.8 215354b47a test(brand): prove per-brand catalog scope + extract pure brand-scope (v8.2.1)
Extract the taxonomy + per-brand scope into dependency-free src/lib/products/
brand-scope.ts (pure, brand-passed-in) so it's unit-testable without hostname
mocking or loading the React-heavy registry. registry re-exports it (no API
change). New registry-brand.test.ts PROVES: hanzo=all 12 categories; lux/zoo/
pars=ONLY Web3/Network/Security/Dev/Settings (web3/bootnode), hiding every
AI-cloud category; Networks(Web3) surfaces on lux/zoo. 12 tests green, 381 total,
typecheck + next build clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 22:43:53 -07:00
zeekayandClaude Opus 4.8 f0ad2e0a91 feat(web3): Bootnode Networks module — blockchain-network admin in console (v8.2.0)
The core bootnode ('Web3 Backend in a Box') primitive, ported into console2 so
the lux/zoo web3 consoles manage real blockchain networks (chain/nodes/status/
RPC). Reads the live bootnode control plane via a new per-user /bootnode proxy
(mints the user's IAM bearer; least-privilege to the networks surface + launch/
rpc/scale), rendered with @hanzo/data's DataTable. Honest states on 401/404/503.
Retires the old bootnode-admin app — one console (hanzoai/console), brand-scoped.
typecheck + build + 352 tests green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 22:24:24 -07:00
Hanzo AI 81af20b738 fix(console): Overview reads real commerce spend + API keys list minted key (8.1.1)
Two customer-facing bugs found in a live real-tenant e2e audit of
console.hanzo.ai, both making the "backend-aware FE" partially broken.

BUG 1 — Overview usage/spend widget showed no spend.
  The Overview called cloud `/v1/get-cloud-usages`, which returns 200 with
  {"status":"error","msg":"usage ledger unavailable: datastore peer not
  connected"} — the cloud usage-ledger's o11y datastore peer is down. Repoint
  `UsageApi.overview()` at the REAL commerce ledger `/v1/billing/usage` (via the
  existing per-tenant `/billing/*` proxy — the SAME source the Cost page and the
  gateway debit against, X-Hanzo-Org scoped). New pure `usage-adapter.ts` rolls
  the raw records up into the rich `CloudUsageOverview` the dashboard already
  renders (totals, prior-period deltas, dense time series, top-N + Other
  spend-by-model, paginated inference activity) — reusing the ONE canonical
  aimetrics parse, so Overview and Cost agree to the cent. Overview UI unchanged.
  Verified live: commerce returns 158 real records for hanzo/z; cloud ledger is
  dead. `UsageRecord` gains additive premium/stream/status/requestId (from the
  commerce metadata) for faithful activity rows.

BUG 2 — API Keys never listed a minted key (uncopyable/unrevocable, re-minted).
  `POST /keys` mints a real working hk- key (User.AccessKey in IAM), but
  `GET /keys` derived hasKey from the cloud `get-account` session claim, which
  returns accessKey='' for a freshly-minted key → the page reverted to the empty
  "Create" state on reload. Read the key AUTHORITATIVELY from IAM
  `get-user?id=<owner>/<name>` (new `getUserKey` server helper) instead. Verified
  live: IAM holds z's accessKey=hk-eeedb378-... while get-account returns ''. The
  key now lists (prefix + last created/rotated date) and revoke works.

- No mocks/fixtures; honest states preserved. Coordinated admin/per-host/ingress
  files untouched. tsc clean, 369 vitest pass (22 new adapter tests), next build green.
2026-06-30 20:48:00 -07:00
zeekayandClaude Opus 4.8 48efb20cfa feat(brand): per-brand catalog scope — lux/zoo/pars = web3/bootnode admin (v8.1.0)
console.hanzo.ai = full AI cloud; console.lux.cloud / console.zoo.cloud /
console.pars.* = web3/bootnode admin only (Web3 + Network + Security + Dev +
Settings — on-chain, networks/nodes/peering, keys/HSM/authz, dev keys, org).
ONE knob: BRAND_CATEGORIES in registry, filtered at the single catalog-consumption
point (visibleCatalog/catalogByCategory/visibleCatalogByCategory) via inBrand +
brandCategoryOrder. Settings already shows brand-resolved info (brand/name/IAM/
billing per host). Hanzo unchanged. typecheck + 345 tests green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 20:17:42 -07:00
Hanzo AI cfef594484 chore(console2): 8.0.4 — per-host admin login client on admin.<brand> 2026-06-30 20:17:00 -07:00
blueandHanzo AI 3b4a66999e feat(config): per-host admin login client (admin.<brand> → admin-console)
On an admin console host (admin.hanzo.ai) resolve the OAuth client to the
admin-org app `admin-console` so IAM login resolves the global-admin identity
(owner=admin); every normal host keeps the brand cloud client (hanzo-cloud).

Isolated to src/config: `adminApp` per brand (ONE global admin-console app for
the reserved admin org), `isAdminHost()`, and a HOST-keyed cache (admin.hanzo.ai
and cloud.hanzo.ai are the same brand but must resolve to different clients — a
brand-keyed cache would collide). iamAppName + iamClientId travel together;
NEXT_PUBLIC_* overrides still win. Composes with the admin-mode UI (untouched).

+7 vitest (admin/normal host resolution, cache isolation, strict admin. prefix);
tsc --noEmit clean.
2026-06-30 20:17:00 -07:00
zeekayandClaude Opus 4.8 41b5385f73 test(e2e): ungate public sign-in smoke (runs without HANZO_PASSWORD)
The whole suite gated on HANZO_PASSWORD, so CI got zero signal without the prod
superuser secret. Split the credential-free sign-in render check into its own
describe so it always runs — asserts email/password + GitHub/Google + passkey.
Verified green against live console.hanzo.ai. Authenticated flows still gate on
HANZO_PASSWORD.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 20:01:43 -07:00
Hanzo AI bdd27ec829 fix(test): cast entry() helper to CatalogEntry (union-spread) — 8.0.3 build green 2026-06-30 18:19:56 -07:00
Hanzo AI bd68c0ee23 fix: resolve package.json conflict → 8.0.3 2026-06-30 18:18:01 -07:00
Hanzo AI 20f1097810 merge(shell-ia): 2-level nav + Team/Settings + admin↔customer gating + /org/iam hardening → 8.0.3 2026-06-30 18:17:23 -07:00
Hanzo AI f3cb76e35b feat(console): 2-level shell IA + uniform sub-page contract + Team/Settings/Profile + admin↔customer gating (v8.0.1)
Shell + information architecture (owns DashboardShell, nav, header, registry
category/sub-page contract, ⌘K, Team/Settings/Profile). No product content
modules touched (referenced by id).

1. Two-level sidebar nav (Linear-style). Level 1 = categorized product list;
   clicking a product slides into its sub-nav (level 2) with a Back affordance;
   the open product follows the route. CSS-transform slide (.hz-slide,
   reduced-motion aware).
2. Uniform sub-page contract. Every product gets Overview · Settings · Status ·
   Logs · Metrics plus its declared specifics (productSubpages, match-core).
   A sub-page with no backend renders an honest ProductSubpageStub — never a
   404, never fabricated.
3. ⌘K jumps to ANY level. searchDestinations indexes products + declared
   specifics ("queues" → Compute › Tasks › Queues).
4. Category restructure. Deploy→Platform; new Training (Fine-tuning + ML
   Pipelines) and Settings (Team/Settings/Profile); Compute gains
   Kubernetes/Clusters/Tasks; Async category + Jobs entry KILLED (Tasks
   replaces Jobs). Dev/Web3 retained (real products).
5. Sidebar chrome. H mark only (no wordmark), no in-sidebar collapse toggle
   (moved to header), animated collapse (.hz-collapse, 264↔64).
6. Header cleanup. Removed user name + Sign out from the header; Sign out now in
   the footer wallet under Top up; footer user row → Profile; kept org/project/
   network(env) switchers + theme + help + notifications(bell→/alerts).
7. Team (org member mgmt: list/invite/role/remove + read-only Roles), org
   Settings (General/Branding), Profile (Account/Security/API Keys). Member
   mgmt runs over a NEW org-scoped /org/iam proxy so an ORG admin (not only a
   global admin) manages their own org — tenant-isolated server-side, with the
   body-owner cross-tenant write gap closed in a shared forwardIam (also
   hardens /admin/iam). DRY IAM envelope client (iam-envelope).

Admin↔customer surface gating (systemic): admin-only products (Providers, IAM,
KMS, Secrets, Audit, Clusters, Kubernetes) + admin sub-pages (Models › Routing)
are hidden from a customer's nav/launcher/⌘K and render a graceful "Managed by
Hanzo" notice on direct access instead of a hostile 403. Signal = global-admin
(isGlobalAdminAccount, DRY with OrgGate). Customer surfaces (Models browse,
Playground, Chat, API keys, Cost, Team, Compute/data) fully work per-org.

Network×org×project scope was already first-class (client.ts stamps X-Org-Id +
X-IAM-Org-Id + X-Project-Id + X-Environment; ScopeSwitcher env picker) — kept
as-is.

Verify: tsc clean · vitest 308 (incl. new sub-page/routing/destinations/org-
policy tests) · next build green (/org/iam route compiled) · Playwright desktop
+ 390px mobile, both personas.
2026-06-30 17:57:23 -07:00
Hanzo AI 1a8061bc34 chore: console 8.0.2 — Compute (K8s/Containers/Tasks/Training, no async/Jobs) + Playground UX 2026-06-30 17:53:29 -07:00
Hanzo AI c91a641fa9 Merge remote-tracking branch 'origin/feat/playground-ux' into deploy/console-8.0.2 2026-06-30 17:53:06 -07:00
Hanzo AI 0ca75cae70 Merge remote-tracking branch 'origin/feat/compute-pages' into deploy/console-8.0.2
# Conflicts:
#	src/lib/products/registry.tsx
2026-06-30 17:53:06 -07:00
Hanzo AI cbffe1dde4 feat(compute): Kubernetes, Containers, Training & Temporal Tasks consoles (v8.0.1)
Four resource consoles wired to REAL backends with honest states (never fabricated).

- Kubernetes (Compute): real DOKS clusters via PlatformApi (/paas → platform);
  stat cards + cluster table with provisioned CPU/RAM DERIVED from node-pool slugs
  (honest "—" for GPU/unknown); Import (honest) + Create → real provisionCluster.
- Containers (Compute): apps-inventory Workloads + Pods/Images/Namespaces/Events as
  :tab sub-routes over /paas (tolerant shapes, honest states); cluster-detail sidebar.
- Training (AI/Fine-tuning): live mlsvc /v1/train/{jobs,experiments} + /v1/ml/models
  via generalized /training proxy; stat cards, jobs table, training-loss chart,
  checkpoints, models, configs; New-job panel (base model from real aicatalog) →
  POST /v1/train/jobs (402 ResourceMeter surfaced honestly); Save-as-config.
- Tasks (Compute): Temporal console over hanzoai/tasks tasksd via NEW /tasksd
  minted-Bearer proxy; Workflows/Schedules/Queues/Workers/Activities :tab sub-routes;
  stat cards; workflow detail panel + step graph + 8 sub-tabs; engine-health /
  throughput / queue-util / recent rail. Public tasks TLS not live yet → honest
  states until the in-cluster engine is reachable.

Registry: removed the Async category + the Jobs entry; Tasks & Kubernetes → Compute.
Shared: promoted console primitives to ui/Metric.tsx (DRY; gpus/charts re-exports);
nodes.ts capacity derivation (+12 unit tests). tsc 0 / vitest 304 / next build green.
2026-06-30 17:44:21 -07:00
Hanzo AI d1a537c32c feat(playground): UX fixes — provider→model cascade, stop, markdown, per-user history, mobile (v8.0.1)
Fixes Dave's live-Playground complaints on console.hanzo.ai/playground.

- ModelPicker: rebuilt as a keyboard-navigable provider→model CASCADE (Zen-first
  provider rail + model pane with real context badge + $/Mtok + live dot;
  searchable; free-text fallback). New pure providers.ts (Zen-first grouping) +tests.
- ResponsePanel: render the completion as real markdown (new pure markdown.ts
  tokenizer + MarkdownView: fenced code blocks w/ copy, inline code, bold/italic,
  lists, headings, links) instead of plaintext; add a clear Stop control in the
  panel header during streaming (AbortController was already wired end-to-end).
- history.ts: namespace per user (owner/name), auto-persist every completed run
  so History auto-populates; one account never sees another's runs (+tests).
- ModelSettings: consolidated into a collapsible side-pane ATTACHED to the prompt
  builder (desktop) and a bottom sheet on mobile (new SettingsSheet, reusing the
  shell Dialog drawer pattern); shrink the oversized slider thumb + thin the track.
- ChatPlayground/Composer: responsive 3-zone layout stacks cleanly at ~390px with
  no horizontal scroll; a settings toggle opens the desktop pane / mobile sheet.

Verified: tsc --noEmit clean, vitest 311/311, next build green; Playwright desktop
+ 390px (cascade, keyboard nav, stop, markdown, mobile stack, settings sheet).

Wallet "Top up" deliberately NOT rerouted to pay.hanzo.ai: it is ALSO broken
(GET /v1/commerce/tenant -> 404 "unknown tenant", so the Square Web Payments SDK
never initializes). Breakage not moved; root cause reported for a backend fix.
2026-06-30 17:25:14 -07:00
2f1ae6b7c2 Native control planes (zero external link-outs) + Hanzo Functions dashboard (#15)
* feat(console2): native control planes (zero external link-outs) + Hanzo Functions dashboard

Three deliverables, one PR, all over the one /v1 surface.

1) No external link-outs (priority). The catalog's `external` kind is removed:
   CatalogEntry is module-only, ProductStatus is 'enabled' | 'soon'. The 14
   products that used to open another domain (Gateway, DNS, CDN, MPC, CLI, SDKs,
   API, IDE, Desktop, Registry, Metrics, Crawl, Studio, Console) are now native
   in-console routes rendering ONE shared NativeOverview (overviewFor(id) +
   overviewRoutes(id), the DRY twin of soonRoutes): header + summary, a REAL
   health band (probes PlatformApi.apps() with honest not-deployed/not-reporting
   states), key-fact cards, native-route actions, and INLINE docs. Content is a
   pure OverviewSpec per product (overview/spec.ts + resolve.ts, with a
   catalog-derived defaultSpec fallback). The external branches in open.ts,
   DashboardShell, AppLauncher, CommandPalette, ProductInterstitial, and
   OverviewModule are removed.

2) Hanzo Functions dashboard. FunctionsModule rebuilt into a tabbed product
   (Overview · Functions · Deployments · Triggers · Secrets · Settings) over the
   rich lib/api/functions.ts (GET /v1/functions*). Branded "Hanzo Functions" with
   the honest Fission engine badge. Overview: 6 KPI cards derived from real rows
   (deriveOverview, honest "—"), real-series sparklines + trendPct deltas, an
   "Invocations over time" LineChart with 1H/6H/24H/7D/30D toggles, an "Invocation
   status" Donut, and the shared FunctionsBrowser (table + DetailRail). Secrets is
   names-only. Reuses functions/{FunctionsTable,DetailRail,parts}.tsx unchanged.

3) Overview "Explore products" drops the enablement gate: no more
   Enabled/External/Soon badge; every product is open-for-all with Open (native) +
   a "Learn more" affordance to the native /discover/:id interstitial.

Idiom: strictly @hanzo/gui v5 shorthands. New tests: overview/resolve.test.ts.
npm run typecheck clean (0 errors); npm test 298/298 (31 files); every route
compiles + 200s on the dev server.

Drive-by: remove the bogus tracked node_modules self-symlink blob that broke
npm install/vitest (.gitignore already ignores node_modules/).

* docs(console2): fix overviewFor comment reference

---------

Co-authored-by: Hanzo AI <ai@hanzo.ai>
2026-06-30 17:06:23 -07:00
zeekayandClaude Opus 4.8 48f3c170a0 fix(ci): base image public.ecr node:24-alpine (ghcr hanzoai/nodejs 403'd the runner)
The arcd runner can't pull ghcr.io/hanzoai/nodejs:24-alpine (403) — broke every
build since v0.7.32. Use the public ECR Docker-library mirror (no auth, no rate
limit), the v0.7.9 pattern; align the workflow pre-pull to 24-alpine.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 16:33:27 -07:00
zeekay 9144dc6aba chore: sync lockfile for @hanzo/dashboard + @hanzo/data on 8.0.0 2026-06-30 16:31:09 -07:00
zeekayandClaude Opus 4.8 277abb5e15 feat(base-data): render real Base records via @hanzo/data
Wire published @hanzo/data@1.1.0 (peer @hanzo/gui 7.3.0) into the Base UI
as a composable, honest collection viewer.

- next.config.mjs: transpile @hanzo/data (ships TSX source, like @hanzo/gui)
- src/lib/base-data/fields.ts: pure baseCollectionToFields() mapping a Base
  collection schema -> @hanzo/data FieldDefinition[]. Covers text/number/bool/
  email/url/editor/date/autodate/select+multiSelect/json/relation/file/geoPoint;
  skips hidden+system fields (keeps id); handles modern `fields` and legacy
  `schema`/nested `options`.
- src/lib/base-data/api.ts: tiny BaseDataApi over a Base /v1 (listCollections,
  listRecords) -- raw REST + optional bearer, shares the app's typed ApiError.
- src/components/base-data/CollectionTable.tsx: client component; schema ->
  fields -> records -> @hanzo/data DataTable with honest
  loading/empty/error/not-found states (no fabricated rows).
- src/lib/base-data/fields.test.ts: 10 vitest cases for the mapping.

Verify: `npm run typecheck` clean; `npm test` 58/58.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 16:27:18 -07:00
zeekayandClaude Opus 4.8 b7595715ff feat(console2): embed Hanzo Base + Base look-and-feel (v0.7.11)
Base product module rendering the shared @hanzo/dashboard screens (published
on npm) via a per-user /superbase proxy (mints the user's IAM bearer); catalog
entry + page /base · /base/new. Plus the Base look: black #0a0a0a surface
aligning to the zinc-on-black identity. Consumes @hanzo/dashboard@0.2.0.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 16:26:59 -07:00
592e575ae3 feat(chat): demo-ready visual polish (presentation only) (#14)
Polish the Chat UI without touching any data wiring — Chat still calls the
real /v1/chat/completions through the keyless /ai proxy, and every state/API
call, prop, and honest empty/down state is preserved.

- Bubbles: assistant turns read as open text with a sparkle medallion +
  name + timestamp and comfortable line-height (dropped the heavy bordered
  card); the user turn is a refined right-aligned accent bubble. Both render
  light markdown — fenced code blocks (monospace, tinted card, optional lang),
  inline code chips, and bold.
- Markdown: new dependency-free renderer (chat/markdown.tsx) reusing the
  existing `fontFamily: 'monospace'` idiom — no heavy remark/rehype tree added
  (console2 ships no markdown lib).
- Welcome/empty state: sparkle avatar + "How can I help?" + 3–4 clickable
  suggested-prompt chips that fill the composer on click.
- Composer: one rounded, elevated input with a code-insert ({}) and a circular
  send affordance (hover/press states) over a subtle muted hint row.
- ChatView: read-only history thread matches the new bubble look + markdown.
- ChatListView: name cell reads as a link (weight + hover); table unchanged.

All Tamagui shorthands (bg/maxW/rounded/items/justify/self/p/px/py/gap) per
onlyShorthandStyleProps. tsc --noEmit clean; 245 vitest tests pass.

Co-authored-by: Hanzo AI <ai@hanzo.ai>
2026-06-30 16:04:25 -07:00
Hanzo AI 68cfbc1cd5 chore: console2 v0.7.32 — Playground parity (single-model 3-col compose) onto org-switcher main 2026-06-30 16:00:11 -07:00
Hanzo AI fa52cc74e1 Merge remote-tracking branch 'origin/feat/playground-parity' into deploy/playground-0.7.32 2026-06-30 15:59:54 -07:00
Hanzo AI 48e84ee58d feat(playground): single-model 3-column composer to mockup parity (v0.7.31)
Redesign the Playground from the multi-model compare board into the polished
3-zone surface in the mockup, reusing the existing AI binding (runner/stream/
PlaygroundApi) — nothing about model output, tokens or cost is fabricated.

Layout (per mockup):
- Header "Playground" + subtitle + Save prompt / </> code / Share actions.
- Tabs: Chat · Completions · Embeddings · Audio · Vision.
- Composer (left): model chip with a REAL "context" badge + searchable picker
  over the live catalog (aicatalog.fetchCatalog, 375 models), System prompt +
  user/assistant turns with char counts, and a footer of Add message / Upload
  (image→vision) / {} Variables / Run (⌘↵ + caret). Completions collapses to a
  single Prompt card.
- Examples (labelled starters w/ model chips) + History (real local prior runs,
  honest-empty) beneath the composer.
- Right rail: Response/Logs panel (real completion, USAGE tokens + COST from the
  model's real $/Mtok, "—" when absent) and Model settings (Temperature 0.7,
  Top P 0.9, Max tokens, Stop, Advanced: freq/presence penalty + seed).

Real behaviors, no backend: Save prompt (local library → Examples), Code (real
cURL/JSON request preview), Share (encode composer into ?p= link, restore on
load), {{variables}} substitution, ⌘↵ to run.

Wiring: Temperature/top-p/max-tokens/stop + advanced penalties/seed flow through
paramsOf into the request (sent only when set). Removes the compare-only files
(ComparePlayground/CompareColumn/AddModel/useCompare/SettingsControls).

Tests: +37 unit tests (params/variables/share/prompts/request-preview/compose/
relative); 282 total green. tsc clean, next build green.
2026-06-30 15:40:45 -07:00
Hanzo AI 11763882f8 fix(org): working org switcher + create-org (multi-tenant onboarding)
The OrgSwitcher collapsed to a STATIC non-clickable label whenever the admin-gated
org list returned empty (every tenant: /admin/iam is global-admin-only → 403), and
there was NO create-org affordance. Now: the trigger is ALWAYS an interactive
Popover (current org always shown + filter + switch), with a 'Create organization'
flow that posts to /onboard and scope-switches into the new org. /onboard relaxed:
an existing-org user can create an ADDITIONAL org (created WITHOUT moving them — a
move would strip a global admin's status + orphan their current org); zero-org
first-run still creates+joins. v0.7.31
2026-06-30 15:03:37 -07:00
6a74c141d5 Debrand: replace Casdoor name with Hanzo IAM in comments/docs/aliases (#13)
Co-authored-by: Hanzo AI <ai@hanzo.ai>
2026-06-30 14:57:27 -07:00
Hanzo AI df5bf34218 feat(data): KV/SQL/Datastore/Object Storage/Vector pages to mockup parity
Decomplect the shared resourceModule factory (backs all managed-data kinds)
into ONE spec-driven console, upgrading every data page at once:

- resource/logic.ts   pure per-kind ResourceSpec + fleet/status/endpoint/
  snippet helpers (RESOURCE_SPECS, 16 unit tests). The list API carries
  lifecycle facts only, so usage metrics are honest "absent" (null -> "—"),
  never fabricated.
- resource/parts.tsx  ResourceStat (honest "—" + "Awaiting metering"),
  StatusDonutCard, TabBar, SnippetBlock, CopyField, SectionCard.
- resource/ResourceListView.tsx  the polished home console: REAL fleet stat
  row + tabs (Overview / <instances> / Access / Metrics / [tool] / Settings)
  + right rail (status donut, quick actions, quick start) + the real create
  flow (POST /v1/<kind>, password shown once).
- resource/ResourceInstanceView.tsx  tabbed single-instance console
  (Overview / Access / Settings) with a real confirmed delete.
- ResourceModule.tsx  thin router; same resourceModule/resourceRoutes
  exports -> zero registry churn, all 5 graded kinds (+docdb/search) tuned.

Honest by construction: status breakdown from real lifecycle, create/delete
real, the data-plane tool tab (Query/Browser/Explore) is an explicit
"coming soon" with the real connect snippet — never a fake success.

Gates: tsc --noEmit clean, vitest 245 pass, next build 14/14. Bump 0.7.30.
2026-06-30 14:16:22 -07:00
Hanzo AI 3c54be90f7 feat(catalog): unify model/provider/plan client; Models & Providers parity
One spine for the Models, Providers, and (later) hanzo.ai / @hanzo/dev / desktop
surfaces, all read through the authenticated /ai proxy. Real data, honest states.

aicatalog (the spine):
- Joins the TWO real catalog record shapes — first-party Zen (`context`+`name`)
  and third-party (`contextWindow`+`id` like openai/gpt-5). Fixes context showing
  "—" on 339/375 models and cross-references availability by the stable id.
- Adds priceBucket/matchesQuery/modelTypes/CONTEXT_BUCKETS filters, the provider
  `verified` flag, modelDisplayName (strips "OpenAI: " row prefixes), and
  fetchPlans() reading the real /v1/plans subscription tiers (rpm/tpm/quota),
  honest-empty on 401/404.

Components (self-contained, prop-driven, liftable to @hanzo/ui):
- ProviderLogo — monochrome avatar resolved by provider name: first-party Sparkles
  mark, curated known-provider glyphs, initials chip otherwise. No external URLs.
- SelectMenu — reusable Popover dropdown for the Providers filter row.

Models page: ProviderLogo in rows + provider column, search box, collapsible
type/provider/pricing filters, stacked in/out pricing, real context via the join,
and subscription-plan badges in the detail (model tier -> /v1/plans limits).

Providers page: Explore / My Providers / Custom Models / BYO Weights tabs (the
latter three honest, pointing at the real add/deploy flow), search + type/context/
pricing/verified/sort row, ProviderLogo + Verified badge on cards and detail.

/ai proxy: allow v1/plans through the authenticated proxy (least-privilege add).
Overview: already at parity on the real usage ledger — verified, not rebuilt.

Gates: tsc --noEmit clean, 230/230 vitest (incl. 12 new aicatalog tests),
next build green (14/14). Bump 0.7.28 -> 0.7.29.
2026-06-30 13:21:49 -07:00
Hanzo AI 38c035022f Merge remote-tracking branch 'origin/feat/mobile-responsive-chat'
# Conflicts:
#	package.json
2026-06-30 13:03:06 -07:00
Hanzo AI b9e200f58a Merge remote-tracking branch 'origin/feat/playground-multi-model' 2026-06-30 13:03:06 -07:00
Hanzo AI 1552bb1874 Merge remote-tracking branch 'origin/feat/finetuning-unsloth-class'
# Conflicts:
#	src/components/products/FinetuningModule.tsx
2026-06-30 13:03:06 -07:00
Hanzo AI ca8017f958 fix(ci): base → ghcr.io/hanzoai/nodejs:24-alpine (ghcr-only policy)
Re-pin off public.ecr.aws (rate-limited builds + violates ghcr-only). nodejs is the
Node.js runtime mirror (hanzoai/node is the blockchain node). COPY-before-install
(the real Kaniko --single-snapshot fix) is preserved.
2026-06-30 13:02:43 -07:00
hanzo-dev 1d2b2b040d feat(routing): cloud.hanzo.ai is the canonical console host
- default SSR/build host -> cloud.hanzo.ai (was console.hanzo.ai); brand still
  resolves by hostname suffix, so console.hanzo.ai/console2.hanzo.ai (which now
  301 to cloud.hanzo.ai at the gateway) still map to brand hanzo.
- cloudUrl() stays SAME-ORIGIN: the SPA calls cloud.hanzo.ai/v1, and the gateway
  routes that /v1 to the cloud package (global IAM-JWT + rate-limit) — so
  "everything goes through the gateway" holds with the cookie first-party (no CORS).
- console product + experiments external links -> cloud.hanzo.ai.
2026-06-30 12:35:48 -07:00
hanzo-devandGitHub e3a400b1ac Merge pull request #12 from hanzoai/fix/console2-base-image
fix(ci): console2 base image → public ECR node:22-alpine (unblock v0.7.28 build)
2026-06-30 12:28:40 -07:00
Hanzo AI 62fad7cb48 fix(ci): base image → public ECR node:22-alpine (the one CI pre-pulls)
The v0.7.26/27/28 image builds 403'd: today's base-image thrashing pointed the
Dockerfile at ghcr.io/hanzoai/nodejs:24-alpine, which is PRIVATE — the host
builder's ghcr login is scoped to console2's own package and can't read the
separate nodejs package (403 Forbidden on the base pull).

build-image.yml still pre-pulls + caches public.ecr.aws/docker/library/node:
22-alpine (its comment even says the Dockerfile uses it). Re-align the Dockerfile
to that public base: no auth, no 403, and the warm ARC runner serves it straight
from the cache the pre-pull step populates. node 22 is the version v0.7.25
shipped on. The Kaniko COPY-before-install + retry-hardened npm install fixes are
untouched.
2026-06-30 12:28:32 -07:00
hanzo-devandGitHub 6470f8e41b Merge pull request #11 from hanzoai/feat/zero-trust-landing
feat(zero-trust): operational landing — KPIs, post-quantum posture, mesh topology
2026-06-30 12:24:19 -07:00
Hanzo AI 7a6e3f3f62 Merge remote-tracking branch 'origin/main' into feat/zero-trust-landing
# Conflicts:
#	package.json
2026-06-30 12:23:52 -07:00
Hanzo AI 890d98d32d feat(zero-trust): operational landing — KPIs, PQ posture, mesh topology
Upgrades the Zero Trust surface from five plain tabbed tables into a cloud-console
landing page (the Image #11 operational style), wired to the REAL /v1/zt/* mesh:

- Overview: KPI cards (routers/services/identities/sessions/policies — real
  counts or honest em-dash), a router→service→identity topology strip (only
  nodes that came back; status-coloured), and a post-quantum POSTURE card tying
  the data plane together: Object Storage (S3) ⇄ Zero Trust over Hanzo zap
  (ML-KEM-768 key exchange · ML-DSA-65 signatures). PQ-session % shows only when
  the backend reports a real cipher — never guessed.
- Honest by construction: each of the 5 sections loads independently; when the
  zt backend isn't mounted on this host every section degrades to ONE
  BackendStateCard while the (true) PQ posture still shows. No fabricated rows,
  trends, or telemetry.
- DRY: the five detail tabs reuse the SAME zeroTrustSurfaces + ForwardSurface
  (now exported from ConsoleFeatureModule) — one zero-trust surface, not two.
  ZeroTrustModule moved out of the generic table shell into its own rich module
  (mirrors Embeddings/Overview); registry repointed.
- Pure logic in zt/logic.ts (counts, topology, posture) with vitest coverage.

tsc --noEmit (strict) clean. v0.7.26.
2026-06-30 12:23:08 -07:00
Hanzo AI ef8e8fbdf6 fix(ci): COPY before npm install — Kaniko --single-snapshot dropped node_modules
ROOT CAUSE (proven in the build log): the install's own 'test -f next/dist/bin/next'
PASSED, then 'COPY . .' ran, then the build RUN couldn't find next. Under Kaniko
--single-snapshot, a COPY that follows RUN npm install in the same stage drops the
RUN's freshly-created node_modules. The old multi-stage Dockerfile avoided this (no
COPY after install); my single-stage reorder reintroduced it. Fix: COPY all source
FIRST, then install, then build — node_modules is created by the last RUNs so nothing
clobbers it. This (not the base registry or the .bin symlink) was the real blocker.
2026-06-30 12:21:00 -07:00
Hanzo AI d78dd1ff52 fix(ci): retry-hardened install + assert next is present (self-heal partial tree)
The full @hanzo/gui dep tree intermittently installs ~80 packages short (incl next)
— npm reports success but skips them, surfacing later as 'next not found'. Now:
retry-hardened fetch, an explicit 'npm install next' repair if its bin is missing,
and a hard 'test -f' assert so a partial install fails loudly at the install step
(with a clear cause) rather than at build.
2026-06-30 12:15:02 -07:00
Hanzo AI cf4c66e977 fix(ci): base → ghcr.io/hanzoai/nodejs:24-alpine + invoke next directly
Two fixes for the broken builds:
1. Base image: use ghcr.io/hanzoai/nodejs:24-alpine (our mirror of node:24-alpine)
   per the ghcr-only policy. (public.ecr.aws rate-limited; mirror.gcr.io was a
   stopgap. hanzoai/node is the blockchain node — nodejs is the Node.js runtime.)
   Bumped 22→24.
2. Invoke next via node_modules/next/dist/bin/next, not the .bin/next symlink: the
   @hanzo/gui RN dep tree intermittently drops the symlink under the build npm
   ('sh: next: not found') even though the next package installs. Direct invocation
   is symlink-independent. Build + runner CMD both updated.
2026-06-30 12:07:14 -07:00
Hanzo AI 15b2dedd42 fix(ci): base image → mirror.gcr.io (ECR-public was rate-limiting builds)
public.ecr.aws/docker/library/node:22-alpine started returning TOOMANYREQUESTS on
the base-image pull (the real cause of the build failures — a partial pull also
surfaced as the misleading 'next: not found'). mirror.gcr.io/library/node:22-alpine
is Google's Docker Hub mirror — reliable, not rate-limited. Combined with the
single-stage install+build, the v0.7.27 admin-fix build is unblocked.
2026-06-30 11:58:13 -07:00
Hanzo AI 117f19e6cf fix(ci): single-stage install+build — stop losing node_modules/.bin/next in Kaniko
The deps→build cross-stage COPY of node_modules intermittently dropped
node_modules/.bin/next under Kaniko (sh: next: not found at 'npm run build',
despite a clean install adding ~850 packages). Reproduced: local install is fine,
so it's the cross-stage symlink handoff. Install + next build now run in ONE stage
on the same filesystem — the seam is gone. Runner stage unchanged (runtime next
start worked through its COPY all along). Unblocks the v0.7.27 admin-fix build.
2026-06-30 11:53:36 -07:00
Hanzo AI 69c2b3535d chore: v0.7.27 — admin redirect-loop fix 2026-06-30 09:47:18 -07:00
Hanzo AI e703c25bc6 fix(console): P0 admin.hanzo.ai redirect-loop — admin-org membership = global admin
IAM never populates isGlobalAdmin AND admin-org members carry isAdmin=false, so the
gate's '&& isAdmin' made NO ONE a global admin → every legitimate admin was bounced
from admin.hanzo.ai to the console (redirect loop). Fix: membership in the reserved
'admin' org alone = global admin. Client OrgGate + server identity.ts. Tenants
(owner!=='admin') stay non-global → admin remains locked to them. v0.7.26
2026-06-30 09:46:54 -07:00
z 8435eb6fa1 merge origin/main (metrics-led Overview) — lead home with the comprehensive OverviewDashboard
Resolve the home-lead fork to the full OverviewModule (Image-#3 vision: metric
cards + sparklines + tokens/spend/by-model charts + activity + quick actions +
wallet + system status) over the narrower AiMetricsModule lead. AiMetrics stays
its own route. One home dashboard, one way.
2026-06-30 00:34:18 -07:00
z a5da0bd863 merge Functions — canonical ui/Charts.tsx wins (its dup was unused orphan; removed)
Functions' add/add ui/Charts.tsx was dead code (no consumer imported CHART_COLORS/
STATUS_COLORS). Take the canonical superset (Sparkline/LineChart/BarChart/Donut/
BarRows). One chart module, one palette name, no backwards-compat alias. Fixed the
legend swatch to the file's own styled-div idiom (was a themed bg with a hex).
2026-06-30 00:29:29 -07:00
Hanzo AI 47f296b2fb feat(console): metrics-led Overview — lead home with the real AI usage dashboard
The Overview was a product grid; now it leads with the same tested AI Metrics
dashboard (requests/tokens/spend over time + per-model breakdown, real per-org
data) — the Langfuse-style project home — with the product catalog below for
navigation. DRY: reuses AiMetricsModule exactly. v0.7.25
2026-06-30 00:29:22 -07:00
z 584a73ff53 Merge remote-tracking branch 'origin/feat/gpus-page' into integrate/console2-v0.7.23 2026-06-30 00:26:56 -07:00
z c4ba6846b8 Merge remote-tracking branch 'origin/feat/machines-page' into integrate/console2-v0.7.23 2026-06-30 00:26:48 -07:00
z 286b1af431 merge main (v0.7.24: AI Metrics + mobile shell) → v0.7.25 2026-06-30 00:26:48 -07:00
z 884772402c console2: consolidate Overview+Embeddings charts → one ui/Charts.tsx (DRY)
Merge Overview + Embeddings; collapse the two duplicate chart implementations
(components/charts/Charts.tsx + components/ui/Charts.tsx) into ONE canonical
ui/Charts.tsx superset built on pure @hanzo/gui primitives (promotable to the
shared @hanzo/gui package as a charts category). Repoint OverviewModule +
embeddings/OverviewView. tsc clean.
2026-06-30 00:26:37 -07:00
z 53f188d131 console2: Functions — serverless (OpenFaaS-class) on real /v1, honest states
Compute → Functions (6 tabs: Overview/Functions/Deployments/Triggers/Secrets/
Settings): functions table, invocations-over-time, status donut, selected-function
detail rail (about/triggers/recent invocations + View/Edit/Delete). Wired to the
real functions backend with honest not-configured/empty/error states; metrics from
the usage ledger degrade to '—'. currentOrg-scoped; destructive actions confirm /
honest-disabled. Fixed 2 leftover tsc errors (icon→ReactElement; dropped dead
?? true after non-nullish !bool). tsc clean.
2026-06-30 00:22:32 -07:00
z 7f0f7a683f console2: GPUs — real GPU/cluster inventory + honest derived/not-configured states
Compute → GPUs (7 tabs): GPU model+count derived from cluster nodeSize slug
(gpuSpecOf, pure+tested), per-GPU rows/telemetry from /paas/gpus when present.
Three honest renders: not-configured (501) · clusters-only (real derived counts +
distribution donut + top-clusters) · inventory-live (full table+telemetry).
Telemetry-only metrics (util/mem/temp/sparklines) and GPU-hours have no backend →
'—'. Est-cost reads the usage ledger, degrades to '—' (never relabels account
total as GPU cost). New compute.ts (zero platform.ts edits); registry gpus entry
upgraded. tsc clean · next build 14/14 · 18 compute tests green.
2026-06-30 00:20:31 -07:00
z ddd5aeda18 console2: Machines — real DOKS-cluster-node inventory, honest states
Compute → Machines as one node of a real DOKS cluster pool (GET /v1/org/{org}/
cluster → machinesFromClusters: sum(pool.count) rows, vCPU/RAM from the DO slug,
monthly cost from the platform bill-from table labeled 'est.'). 8 tabs, 7 metric
cards, status donut, machine table, selected-machine right rail. Per-node CPU%/
MEM%/GPU/uptime/IP the control plane doesn't expose → '—' (never fabricated).
Reboot/Terminate honest-disabled (no real endpoint at that altitude). currentOrg-
scoped; not-configured (501, PaaS token disabled) is the honest first state.
Additive platform.ts only. tsc clean · 20 machines tests green.
2026-06-30 00:20:11 -07:00
Hanzo AI b78f48e0b3 Merge branch 'feat/ai-metrics-o11y' 2026-06-30 00:18:54 -07:00
Hanzo AI c75da83217 feat(console): AI Metrics page + fix Cost usage mapping (real model/tokens, cents)
The /v1/billing/usage ledger carries per-request rows (metadata.model, totalTokens,
amount in CENTS). The Cost page flattened it with a generic reader → every row
'Usage', no tokens, and cost ×100 ($1.06 shown as $106). Now: looksLikeLedger()
+ perModel() roll up by real model name with correct cents — shared (DRY) with the
new AI Metrics module (StatTiles: requests/tokens/spend/balance, usage-over-time,
per-model breakdown, recent activity) reading the same real per-org data. o11y
RuntimeNotice points at AI Metrics (which has data) when traces are uninitialized.
32 unit tests (billing/aimetrics/format), tsc+build green.
2026-06-30 00:18:52 -07:00
z 4679d1af14 release(console2): v0.7.23 — Playground multi-model + UX sweep live to prod
Ships the merged work (multi-model compare Playground with abort-safe billing,
the unified EmptyState/Cost sweep) as a public semver. Overview/Embeddings/
Machines/GPUs/Functions land in v0.7.24 as the conflict integration completes.
2026-06-30 00:08:07 -07:00
Hanzo AI f084d89918 Merge remote-tracking branch 'origin/feat/embeddings-page' into integrate/console2-v0.7.23
# Conflicts:
#	app/(dashboard)/page.tsx
#	src/components/products/stores/StoreListView.tsx
2026-06-30 00:02:06 -07:00
Hanzo AI d284a8e076 Merge remote-tracking branch 'origin/feat/overview-dashboard' into integrate/console2-v0.7.23
# Conflicts:
#	app/(dashboard)/page.tsx
2026-06-30 00:00:16 -07:00
Hanzo AI 55e14e85f3 feat(console): mobile/responsive shell + floating AI chat + wallet identity → v0.7.23
Comprehensive responsive pass so the console works at phone/tablet/laptop/
desktop, plus a floating assistant reachable from every page and a wallet that
doubles as the signed-in identity + a click-through to in-console billing.

P1 — Mobile/responsive shell (DashboardShell.tsx)
- Layout responsiveness is CSS-driven (Tamagui v5 media style props:
  `display="none"` + `$lg={{ display:'flex' }}`), NOT a JS `useMedia()` branch —
  the server and the client's first paint emit identical markup, so there is no
  hydration mismatch and no flash of the compact layout on a wide screen.
- < lg (1024px): the persistent sidebar is HIDDEN behind a hamburger in the
  topbar that opens the SAME nav as a left drawer (closes on select/backdrop);
  the topbar condenses — org/scope/user/sign-out fold into one right-side menu
  so nothing overflows at 375px; the Apps button collapses to icon-only.
- ≥ lg: the persistent sidebar is always on (collapsible) with the full inline
  topbar controls.
- Fixed the collapsed-rail icons (20px, 44px hit targets — were too small).
- The nav body (SidebarNav) is shared by the desktop sidebar and the drawer (DRY).
- Responsive content padding ($md), wallet always reachable.

P2 — Floating AI chat (FloatingChat.tsx, mounted once in the dashboard layout)
- A chat bubble fixed bottom-right on every page. Click → opens the assistant:
  a full-screen sheet < lg, a ~380×560 popover ≥ lg (sizing is CSS-driven too).
- REUSES the one working chat surface (ChatConversation → AiApi.chat → the
  keyless /ai proxy). No AI rebuilt. A new `compact` mode on ChatConversation
  drops the page header + fixed min-height so it fills the sheet; "History"
  deep-links to the full /chat page.

P3 — Wallet as identity + billing click-through (SidebarWallet.tsx)
- The wallet now shows the signed-in user's avatar (IAM photo, else initials)
  + display name from useSession, alongside the live balance.
- Clicking the wallet/identity routes into the in-console Cost module (/cost:
  balance, usage, invoices). "Top up" still deep-links to the brand billing
  portal (billing.hanzo.ai) — payment is never rebuilt.

Verification
- `tsc --noEmit` clean; `next build` succeeds (14/14 pages).
- Playwright (headless) verified live at 375/768/1024/1440 with the backend
  mocked: persistent-sidebar↔hamburger swap, drawer open/close, full-screen chat
  sheet, account menu, wallet identity — all PASS, and NO React hydration
  mismatch. Apps-label collapse confirmed (icon-only 375 / labeled 1440).
2026-06-29 23:52:56 -07:00
z 44435ca291 console2: Embeddings — 6-tab vector product on real /v1, honest-empty (upgrade StoresModule)
Upgrades the thin StoresModule in place into the Embeddings product (Overview·
Explore·Collections·Jobs·Models·Settings): collections=per-org vector stores
(get-stores), Explore=POST /v1/search on {owner}-{store}-docs (server-resolved
owner — store is only a query param), Models+generate=/v1/models + /v1/embeddings
via the keyless /ai proxy. currentOrg-scoped throughout; no secret reaches the
browser; /ai allow-list NOT widened. Honest-empty everywhere a field/endpoint is
absent (get-cloud-usages not merged yet → metric cards degrade to —; RRF drops
score → —; no vector point-lookup → empty) — never fabricated. Deletes the dead
StoresModule/StoreListView (registry was the only consumer); reuses StoreEditView.
Drive-by: corrects the stale 'built-in' admin-policy assertion to false (gate code
untouched). tsc clean · vitest 67/67 · next build 14/14.
2026-06-29 23:48:33 -07:00
39d88d0cfd feat(console): side-by-side multi-model compare Playground (#7)
* feat(console): side-by-side multi-model compare Playground

Tabbed Playground (Chat/Completions/Embeddings/Audio/Vision) whose marquee is a
side-by-side compare board: ONE shared System+User (or Prompt) broadcasts to N
model columns that run in PARALLEL through the keyless /ai proxy, each streaming
its own output while reporting REAL tokens, cost (catalog $/Mtok) and latency
(time-to-first-token + total). Per-column model + optional settings override with
a sync-across-all toggle; one column erroring/stopping never disturbs the others.
Single-model mode is one column. Examples seed the prompt; History records a run.

- app/ai/[...path]: stream the upstream body through (real TTFT) instead of
  buffering; allow-list v1/audio/speech for the Audio (TTS) tab. Both additive +
  backward-compatible for existing non-streaming callers.
- lib/api/playground.ts: add streamChat (SSE, stream_options.include_usage),
  embeddings, speech — additive to PlaygroundApi.
- Models selectable from the LIVE catalog (CloudModelApi → /ai/v1/models +
  /v1/pricing/models), the same source the Models page uses. No mocks.
- Pure, unit-tested core (cost/SSE-parse/runner/history): 28 vitest tests.

* fix(console): cancel upstream on abort + release reader + honest stopped state

Red review follow-ups on the compare Playground (no scope creep):

1. [MED] Client abort now cancels upstream generation (stops over-billing the
   user's own org + leaking N sockets after Stop/tab-switch/unmount):
   - app/ai/[...path]/route.ts: pass `signal: req.signal` to the gateway fetch so
     a browser->proxy abort propagates proxy->gateway.
   - ComparePlayground: useEffect cleanup calls compare.cancel() on unmount;
     cancel() aborts every column's AbortController.

2. [MED] runner.ts: wrap the SSE read loop in try/finally with
   `reader.cancel().catch(()=>{})` so the ReadableStream + connection are
   released on every exit — normal [DONE], a thrown mid-stream error chunk, or an
   abort. New test asserts the reader is cancelled on a mid-stream error chunk.

3. [LOW] An aborted run no longer renders/records as success: new 'stopped'
   RunPhase, CompareColumn shows a Stopped state, History uses
   ok = !error && !aborted and shows a 'stopped' badge.

tsc --noEmit clean; vitest 29 playground tests green (28 + new MED-2 test).

---------

Co-authored-by: Hanzo AI <ai@hanzo.ai>
2026-06-29 23:45:35 -07:00
Hanzo AI 1fc3c6eca6 fix(console): cancel upstream on abort + release reader + honest stopped state
Red review follow-ups on the compare Playground (no scope creep):

1. [MED] Client abort now cancels upstream generation (stops over-billing the
   user's own org + leaking N sockets after Stop/tab-switch/unmount):
   - app/ai/[...path]/route.ts: pass `signal: req.signal` to the gateway fetch so
     a browser->proxy abort propagates proxy->gateway.
   - ComparePlayground: useEffect cleanup calls compare.cancel() on unmount;
     cancel() aborts every column's AbortController.

2. [MED] runner.ts: wrap the SSE read loop in try/finally with
   `reader.cancel().catch(()=>{})` so the ReadableStream + connection are
   released on every exit — normal [DONE], a thrown mid-stream error chunk, or an
   abort. New test asserts the reader is cancelled on a mid-stream error chunk.

3. [LOW] An aborted run no longer renders/records as success: new 'stopped'
   RunPhase, CompareColumn shows a Stopped state, History uses
   ok = !error && !aborted and shows a 'stopped' badge.

tsc --noEmit clean; vitest 29 playground tests green (28 + new MED-2 test).
2026-06-29 23:43:16 -07:00
Hanzo AI 86e26e5e54 feat(console): mobile/responsive shell + floating AI chat + wallet identity → v0.7.23
Comprehensive responsive pass so the console works at phone/tablet/laptop/
desktop, plus a floating assistant reachable from every page and a wallet that
doubles as the signed-in identity + a click-through to in-console billing.

P1 — Mobile/responsive shell (DashboardShell.tsx)
- Layout responsiveness is CSS-driven (Tamagui v5 media style props:
  `display="none"` + `$lg={{ display:'flex' }}`), NOT a JS `useMedia()` branch —
  the server and the client's first paint emit identical markup, so there is no
  hydration mismatch and no flash of the compact layout on a wide screen.
- < lg (1024px): the persistent sidebar is HIDDEN behind a hamburger in the
  topbar that opens the SAME nav as a left drawer (closes on select/backdrop);
  the topbar condenses — org/scope/user/sign-out fold into one right-side menu
  so nothing overflows at 375px; the Apps button collapses to icon-only.
- ≥ lg: the persistent sidebar is always on (collapsible) with the full inline
  topbar controls.
- Fixed the collapsed-rail icons (20px, 44px hit targets — were too small).
- The nav body (SidebarNav) is shared by the desktop sidebar and the drawer (DRY).
- Responsive content padding ($md), wallet always reachable.

P2 — Floating AI chat (FloatingChat.tsx, mounted once in the dashboard layout)
- A chat bubble fixed bottom-right on every page. Click → opens the assistant:
  a full-screen sheet < lg, a ~380×560 popover ≥ lg (sizing is CSS-driven too).
- REUSES the one working chat surface (ChatConversation → AiApi.chat → the
  keyless /ai proxy). No AI rebuilt. A new `compact` mode on ChatConversation
  drops the page header + fixed min-height so it fills the sheet; "History"
  deep-links to the full /chat page.

P3 — Wallet as identity + billing click-through (SidebarWallet.tsx)
- The wallet now shows the signed-in user's avatar (IAM photo, else initials)
  + display name from useSession, alongside the live balance.
- Clicking the wallet/identity routes into the in-console Cost module (/cost:
  balance, usage, invoices). "Top up" still deep-links to the brand billing
  portal (billing.hanzo.ai) — payment is never rebuilt.

Verification
- `tsc --noEmit` clean; `next build` succeeds (14/14 pages).
- Playwright (headless) verified live at 375/768/1024/1440 with the backend
  mocked: persistent-sidebar↔hamburger swap, drawer open/close, full-screen chat
  sheet, account menu, wallet identity — all PASS, and NO React hydration
  mismatch. Apps-label collapse confirmed (icon-only 375 / labeled 1440).
2026-06-29 23:41:42 -07:00
Hanzo AI a2c925ab7b feat(finetuning): Unsloth-class, HuggingFace-native cloud training UI
Upgrades the Fine-tuning module from a read-only job list into a full training
surface wired to the cloud broker (hanzoai/ai /v1/finetune/*) via a same-origin,
user-scoped proxy.

- app/training/[...path]/route.ts  same-origin proxy → /v1/finetune/* (cookie
                                   forward, the get-account pattern; allow-listed
                                   sub-paths; org re-resolved server-side). No key
                                   or HF token ever reaches the browser.
- src/lib/api/finetune.ts          typed client (unwraps the {status,msg,data}
                                   envelope incl. the HTTP-200 error shape)
- finetuning/HfPicker.tsx          browse/search HuggingFace models + datasets;
                                   private/gated flagged; pick → start a job
- finetuning/NewJobPanel.tsx       base-model + dataset pickers, LoRA/QLoRA/full,
                                   Recommended preset that just works, GPU with a
                                   live time/cost estimate, Start + Save-as-config
- finetuning/JobsView.tsx          jobs list (honest empty/error states)
- finetuning/JobDetail.tsx         live status polling, checkpoints, GPU-hours,
                                   Deploy-to-inference, Cancel
- finetuning/logic.ts(+test)       pure formatters + cost mirror + config store (17
                                   vitest cases)
- FinetuningModule.tsx             tabbed shell (Jobs/New/Models/Datasets/Configs);
                                   internal nav, no new registry routes

tsc --noEmit clean · 17 finetuning vitest pass · next build clean.
2026-06-29 23:37:33 -07:00
Hanzo AI a3f7412653 feat(overview): real-data Overview dashboard — the cloud coherence centerpiece
Build the Overview page wired end-to-end to live data (no mock data):
- metrics / charts / spend-by-model / recent activity ← /v1/get-cloud-usages
  (the hanzo.cloud_usage ledger), org-scoped by the X-Org-Id header;
- wallet balance ← commerce /v1/billing/balance (WalletApi.cloudBalance);
- quick actions ← the real product registry (no dead links).

- src/lib/api/usage.ts: typed UsageApi.overview client (+ allOrgs god-view).
- src/components/charts/Charts.tsx: dependency-free SVG charts (sparkline, line,
  bar, donut) — console2 ships no chart lib; these theme to the dark shell and
  render in the Next web DOM alongside @hanzo/gui.
- src/components/products/OverviewModule.tsx: the dashboard — time range
  (24H/7D/30D/Custom), 4 metric cards w/ sparkline + "vs prior" delta, tokens
  line, spend bar, spend-by-model donut + ranked list, recent activity (filter
  tabs + pagination), quick actions, honest system-status footer, wallet.
  Uniform loading/empty/error states; honest "—" for data with no live source
  (GPU/latency → linked to the Status page rather than faked).
- app/(dashboard)/page.tsx: the home renders the Overview (the Explore-products
  catalog is kept below).
- src/lib/products/registry.tsx: 'overview' module at /overview — also the
  all-orgs admin surface via <OverviewDashboard allOrgs/>.
2026-06-29 23:25:54 -07:00
Hanzo AI d3a47c44d6 feat(console): side-by-side multi-model compare Playground
Tabbed Playground (Chat/Completions/Embeddings/Audio/Vision) whose marquee is a
side-by-side compare board: ONE shared System+User (or Prompt) broadcasts to N
model columns that run in PARALLEL through the keyless /ai proxy, each streaming
its own output while reporting REAL tokens, cost (catalog $/Mtok) and latency
(time-to-first-token + total). Per-column model + optional settings override with
a sync-across-all toggle; one column erroring/stopping never disturbs the others.
Single-model mode is one column. Examples seed the prompt; History records a run.

- app/ai/[...path]: stream the upstream body through (real TTFT) instead of
  buffering; allow-list v1/audio/speech for the Audio (TTS) tab. Both additive +
  backward-compatible for existing non-streaming callers.
- lib/api/playground.ts: add streamChat (SSE, stream_options.include_usage),
  embeddings, speech — additive to PlaygroundApi.
- Models selectable from the LIVE catalog (CloudModelApi → /ai/v1/models +
  /v1/pricing/models), the same source the Models page uses. No mocks.
- Pure, unit-tested core (cost/SSE-parse/runner/history): 28 vitest tests.
2026-06-29 23:23:03 -07:00
Hanzo AI 937ef0f0d8 chore(console): model + provider click-through detail pages → v0.7.22 2026-06-29 23:08:39 -07:00
Hanzo AI 75064e8d42 feat(console): provider detail page (metadata + provider's model list)
Click a provider card → ProviderDetailPanel: provider name + stats (models, max
context, from-price, available) + the provider's full model list (name, type,
context, in/out price, status). Pairs with the model click-through. v0.7.21
2026-06-29 23:08:39 -07:00
a464a12efb feat(console2): unified EmptyState + cost/billing + wired AI pages (#6)
* fix(ai): tenant-scope Providers/Stores/Models/Apps to the org + restore RAG retrieval

The AI/data admin views (ProviderListView, StoreListView/EditView,
ModelRouteList/EditView, ApplicationListView) used account.name (the USERNAME)
or a hardcoded 'admin' as the casibase owner. casibase entities are org-owned:
get-* scopes to the session org (GetScopedOwner) and honors the owner param only
for global admins, and AddStore trusts the body owner. So a username owner broke
global-admin org switching and orphaned newly-created stores. Switch all six
call sites to currentOrg() — the one active org-scope value (also stamped as
X-Org-Id), matching the v0.7.0 org-as-a-value model.

Also stamp X-IAM-Org-Id alongside X-Org-Id in the cloud client: the casibase
header-scoped filters (GetEffectiveOrg: usage/vectors/activities) read
X-IAM-Org-Id, so org switching now re-scopes those too (honored only for the
principal's own org or a global admin — safe).

RAG: the keyless /ai proxy rebuilt upstream headers from scratch and dropped
X-Retrieval/X-Retrieval-Store, so AiApi.ragChat silently degraded to a plain
answer. Forward the allow-listed retrieval headers (extracted to the pure,
tested lib/server/ai-proxy). 4 new tests; typecheck clean, 52 tests pass.

* console2: unified empty-state + cost/billing + wired AI pages (one way, forward-only)

The DRY pass toward 'every page real + useful': ONE EmptyState (the honest
first-run onboarding surface every module reuses instead of a dead screen), ONE
CostModule + billing client (real wallet/spend from commerce), and the AI pages
(Providers/Agents/Inference/Fine-tuning) wired to real data with that shared
empty state. Aligned the stray longhand maxWidth→maxW (onlyShorthandStyleProps:
one way, the redundant alias is off) and narrowed EmptyAction.icon to ReactElement.
tsc --noEmit clean (0 errors). Salvaged + verified from the throttled agent's tree.

---------

Co-authored-by: Hanzo AI <ai@hanzo.ai>
Co-authored-by: Hanzo <z@hanzo.ai>
2026-06-29 23:05:59 -07:00
z 1823b4e94f console2: unified empty-state + cost/billing + wired AI pages (one way, forward-only)
The DRY pass toward 'every page real + useful': ONE EmptyState (the honest
first-run onboarding surface every module reuses instead of a dead screen), ONE
CostModule + billing client (real wallet/spend from commerce), and the AI pages
(Providers/Agents/Inference/Fine-tuning) wired to real data with that shared
empty state. Aligned the stray longhand maxWidth→maxW (onlyShorthandStyleProps:
one way, the redundant alias is off) and narrowed EmptyAction.icon to ReactElement.
tsc --noEmit clean (0 errors). Salvaged + verified from the throttled agent's tree.
2026-06-29 23:05:26 -07:00
Hanzo AI f5ff37fc34 feat(console): click-through model detail (specs/pricing/features + config actions)
Catalog rows are clickable → ModelDetailPanel: full specs (arch/params), context,
all pricing (input/output/cache read+write), tier, features, status + actions
(Open in Playground, Configure routing → /models/routing/<name>, Copy ID). v0.7.20
2026-06-29 23:04:19 -07:00
Hanzo AI 39d690072f fix(console): ChunkGuard — auto-recover stale-deploy chunk errors
Open tabs reference the prior build's hashed chunks after a deploy; those URLs
fall through to the app shell (HTML), so the browser throws ChunkLoadError /
'Unexpected token <' and blanks. ChunkGuard catches that exact failure and does
ONE guarded full reload to pull fresh HTML + current chunks. v0.7.19
2026-06-29 22:50:23 -07:00
Hanzo AI d4c361f3b5 fix(console): carry available-count in ProvidersExplore state (RichModel has no .available) 2026-06-29 22:40:39 -07:00
Hanzo AI 330c247bfb feat(console): polished Models + Providers on real rich catalog
- aicatalog: ONE source (/v1/pricing/models via /ai proxy) — 444 real models,
  15 real providers, with context/pricing/specs/tier/provider. No fabrication.
- Model Catalog: polished table (model+params, type, context, in/out $/Mtok,
  TRUE provider, live Available status) + stats bar. Fixes the qwen/glm 'Hanzo
  (Zen)' mislabel — real provider per model.
- Providers: Explore grid (action cards + real provider cards + stats), was
  '0 built-in'. /providers/manage keeps the custom-provider CRUD.
- Brand: our models show as 'Zen', never 'Hanzo (Zen)'. v0.7.18
2026-06-29 22:39:11 -07:00
Hanzo AI 43062cfa5e Merge remote-tracking branch 'origin/fix/ai-surfaces-tenant-scope-rag' into feat/console2-complete-cloud-ux 2026-06-29 22:21:35 -07:00
Hanzo AI 8c5d4e5902 fix(console): add missing SidebarWallet import (v0.7.17 build) 2026-06-29 22:08:30 -07:00
Hanzo AI a382542fd7 feat(console): always-visible wallet (balance + top-up) bottom-left of sidebar
Pinned wallet widget on every page — per-tenant balance via the /billing proxy +
Top-up deep-links to billing.hanzo.ai/topup (pay.hanzo.ai Square/crypto checkout),
never rebuilds payment. Collapsed mode = wallet icon. v0.7.17.
TODO: promote to @hanzo/ui as a reusable cross-app component (one way, composable).
2026-06-29 22:07:12 -07:00
Hanzo AI 92c8155ee9 fix(ai): tenant-scope Providers/Stores/Models/Apps to the org + restore RAG retrieval
The AI/data admin views (ProviderListView, StoreListView/EditView,
ModelRouteList/EditView, ApplicationListView) used account.name (the USERNAME)
or a hardcoded 'admin' as the casibase owner. casibase entities are org-owned:
get-* scopes to the session org (GetScopedOwner) and honors the owner param only
for global admins, and AddStore trusts the body owner. So a username owner broke
global-admin org switching and orphaned newly-created stores. Switch all six
call sites to currentOrg() — the one active org-scope value (also stamped as
X-Org-Id), matching the v0.7.0 org-as-a-value model.

Also stamp X-IAM-Org-Id alongside X-Org-Id in the cloud client: the casibase
header-scoped filters (GetEffectiveOrg: usage/vectors/activities) read
X-IAM-Org-Id, so org switching now re-scopes those too (honored only for the
principal's own org or a global admin — safe).

RAG: the keyless /ai proxy rebuilt upstream headers from scratch and dropped
X-Retrieval/X-Retrieval-Store, so AiApi.ragChat silently degraded to a plain
answer. Forward the allow-listed retrieval headers (extracted to the pure,
tested lib/server/ai-proxy). 4 new tests; typecheck clean, 52 tests pass.
2026-06-29 22:04:41 -07:00
Hanzo AI fb2a276496 chore(console): scrub upstream brand names from comments — 'admin' org + IAM, our way. v0.7.16 2026-06-29 21:59:21 -07:00
Hanzo AI 9b59decccf chore(console): standardize the global-admin org on 'admin' (drop casdoor built-in dual-recognition) — matches commerce/ai/gateway. v0.7.15 2026-06-29 21:57:24 -07:00
Hanzo AI 9289698825 fix(console): admin.hanzo.ai = GLOBAL admins only (org admins were leaking in)
SECURITY: an org owner (Dave/maxpower, org-level isAdmin) could reach the admin UI.
- gateAllows (server authority for /admin/* proxies): require isGlobalAdmin, NOT
  isAdminGranted (which accepted org-level isAdmin). Verified brand-email stays as
  2nd factor. Org admins now 403 on admin ops even with @adminDomain email.
- OrgGate: redirect non-global-admins OFF admin.hanzo.ai to the console host +
  render-guard so the admin console never flashes. Banner already isGlobalAdmin.
- isGlobalAdmin now recognizes BOTH metadata orgs (admin + built-in), matching
  admin-policy ORG_METADATA_OWNERS.
Bundles v0.7.13 (models owner/name token fix + banner gate). v0.7.14.
2026-06-29 21:51:58 -07:00
Hanzo AI ad4d6ca8aa fix(console): models 'wrong token count' + admin banner leak to org admins
1. identity.ts: user.id must be <owner>/<name> (IAM GetOwnerAndNameFromId), not the
   bare casdoor UUID — fixes Model Catalog 'Could not authorize: wrong token count
   for ID <uuid>' for org-member accounts (Dave/maxpower) that carry an id field.
2. OrgGate.tsx: the admin.hanzo.ai ops banner gated on isAdmin (org-level) so an
   ORG owner (Dave/maxpower) saw it. Gate on isGlobalAdmin (admin/built-in org) —
   org admins are not cross-tenant admins. v0.7.13.
2026-06-29 21:46:56 -07:00
Hanzo AI 790c65b951 feat(billing): per-tenant billing BFF — Wallet/Cost show real balance/usage/invoices
The one remaining cross-service gap (v0.7.x already proxies AI/IAM/KMS). wallet
still hit cookie-only /v1/billing/balance -> 404. New app/billing/[...path] proxy
forwards /billing/* -> commerce with the service token + server-resolved own-org
scope (X-Hanzo-Org + BillingSubject; client cannot widen). Matches the /admin/*
proxy pattern + resolveUser. Wallet.cloudBalance repointed same-origin. v0.7.12.
2026-06-29 21:31:25 -07:00
hanzo-dev 55819f81d4 fix(console2): register @hanzogui/core config augmentation; tsc clean (0 errors)
gui.d.ts was augmenting @hanzogui/web which is not a direct dep (resolves only
via pnpm .pnpm path). Add @hanzogui/core augmentation (which is a direct dep) so
GuiCustomConfig → Conf flows through and shorthand props (bg/px/py/items/justify
etc.) are typed correctly. Also fix Button `color=` → `theme=` in OrgGate banner.

Before: 371 type errors. After: 0.
2026-06-29 13:56:38 -07:00
hanzo-dev 76a4380d9e feat(console2): ProviderListView shows global built-in + per-org custom providers (v0.7.11)
List both get-global-providers (Hanzo platform-keyed, read-only, Built-in badge)
and per-org custom providers in one view. Users see all providers enabled out of
the box via Hanzo's DO-AI keys; adding a custom provider overrides/extends per org.
2026-06-29 13:53:37 -07:00
hanzo-dev 6c745bc4dc fix(console2): OrgGate — admins get banner not hard-block; add Playwright e2e (v0.7.11)
- OrgGate: replace hard hard-block for hanzo-org users with a dismissible
  amber banner pointing at admin.hanzo.ai; staff can use console.hanzo.ai
  normally for cloud work (models, API keys, AI inference etc.)
- OrgGate: restore last selected org from localStorage on sign-in so the
  scope remembers where the user left off
- Add e2e/ Playwright tests: sign-in, admin banner, API key create/confirm,
  /v1/models verification, OpenAI + Anthropic inference tests
- Add playwright.config.ts targeting https://console.hanzo.ai by default
- package.json: add e2e + e2e:headed scripts
2026-06-29 13:50:10 -07:00
zeekayandClaude Opus 4.8 8da1f80314 feat(console2): complete console IA parity port — feature-module shells (v0.7.10)
Port the remaining old-console surfaces into console2 as forward-compatible
modules: Zero Trust, Integrations, Referrals, Experiments, Dashboards,
Score Analytics, plus prompt-create/metrics and dataset items/runs sub-modules.

Each surface points at its real/planned /v1 endpoint and renders real rows when
present; a 404/405/503 collapses to the shared honest BackendState card (no demo
rows). console2 now carries the old console's full information architecture while
backend routes light up independently.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 01:13:14 -07:00
zeekay 55409ef473 ci(console2): avoid Docker Hub base image pulls (v0.7.9) 2026-06-29 00:21:41 -07:00
zeekay ad5f082926 feat(console2): first-run org onboarding and waitlists (v0.7.8) 2026-06-29 00:19:12 -07:00
hanzo-dev 88d4c68c2a ci(console2): raw buildx on host builder — fix Docker Hub 429 + artifact quota
Builds were red: docker/setup-buildx-action + docker/build-push-action
spin up an ephemeral buildkit container that can't see the host image
cache, so it re-pulled node:22-alpine from Docker Hub every run and hit
the unauthenticated 429 pull-rate limit; the action's build-summary
artifact upload also hit the Actions storage quota.

Switch to the canonical hanzoai/ci pattern: raw `docker buildx build
--push` on the host builder, which reuses the cached base layer (no
re-pull, no artifact upload). Adds a cache-aware base-image guard that
retries a cold pull with linear backoff. SEMVER tag + GHCR push unchanged.
2026-06-28 23:15:26 -07:00
hanzo-dev 3e0325bb14 feat(console2): scope the PaaS surface by org → project → environment
The /paas proxy forwarded only the god-mode service token, so PaaS
resources couldn't scope per tenant. Now it forwards the full tenant
path the browser stamps:

- X-Org-Id is RE-RESOLVED server-side via the admin policy (orgFor): a
  global admin's switched org (the X-Org-Id it already sends) is honored,
  a brand admin is pinned to their own — authoritative, never the raw
  spoofable claim. Same trust boundary as the IAM/KMS admin proxies.
- X-Project-Id + X-Environment pass through verbatim as sub-scopes within
  that org.

Forward-correct: the control plane scopes by tenant once it reads these,
harmless until then. Adds scope.test.ts (9 tests: store round-trip, merge
semantics, persistence, projectEnvironments intrinsic-3 + custom). 38 green.
2026-06-28 23:10:40 -07:00
hanzo-dev ce67bb16e8 fix(console2): staff gate — collapse "admin. <domain>" gap + header "<Brand> Admin"
The staff redirect button passed two children ("Go to admin." + the
{adminDomain} expression); Tamagui Button lays children out with its
icon-gap, so the two text nodes rendered with a stray space
("Go to admin. hanzo.ai"). Collapse to a single template-literal child.
Header retitled "<Brand> staff" → "<Brand> Admin" (white-label via brand).
2026-06-28 23:07:32 -07:00
hanzo-dev 75f78e1a17 feat(console2): org → project → environment multi-tenancy scope
Projects under the org, each with intrinsic mainnet/testnet/devnet
environments (+ custom), scoping every module at once.

- lib/scope.ts: module-level active { org, project?, environment } the
  non-React API client reads synchronously to stamp headers. Org pinned
  to the brand org; STOCK_ENVIRONMENTS = mainnet/testnet/devnet.
- lib/api/client.ts: baseHeaders stamps X-Project-Id (when a project is
  selected) + X-Environment on every cloud call — one change scopes all
  existing modules (o11y, api-keys, deploys, …) with no per-module edits.
- lib/api/projects.ts: ProjectApi over the REAL Hanzo IAM contract
  (/v1/iam/get-organization-projects | add-project | delete-project),
  keyed (owner, name) with indexed organization = the brand org.
- lib/scope-context.tsx: ScopeProvider — loads the org's projects once,
  holds the active selection, mirrors it into the module scope +
  localStorage, derives per-project environments. Honest: an unrouted
  projects endpoint resolves to org-level only, never a fabricated row.
- components/ScopeSwitcher.tsx: project + environment pickers in the top
  bar (next to OrgSwitcher); env dots keyed to network tier.
- components/products/ProjectsModule.tsx: projects CRUD + "Use" to set
  active scope; honest not-routed/empty states, no fakes.
- registry: Projects flips external → in-console module (Deploy).

Environments are a console-side scoping dimension (IAM Project has no
environments column); X-Environment is sent canonically for backend
adoption. tsc --noEmit clean.
2026-06-28 23:04:49 -07:00
zeekay 98a7088be7 feat(console2): models-first, docs-out, collapsible+filterable sidebar, cmd+K actions (v0.7.4)
Build Docker Image / docker (push) Successful in 3m5s
The 'I don't see any models' wave + sidebar/command UX.

- Models is catalog-first: the default tab is the LIVE model list (~49 Zen
  models via the /ai proxy); routing policy moves to a secondary 'Routing' tab
  (/models/routing). Retires the duplicate empty-by-default 'Model Catalog' nav
  entry — one product, real models on the obvious click.
- Docs are EXTERNAL (brand docsUrl, new tab): a top sidebar 'Docs' entry, the
  header '?' icon, and a server /docs -> docs.<brand> redirect (no in-app 404).
  ComingSoon's API-docs link repointed off the 404-ing ${cloudUrl}/docs.
- Sidebar collapses/expands from the brand 'H' mark (icon-only <-> full),
  persisted to the account; the grid launcher stays. A filter box narrows the
  whole sidebar to find any product fast; Overview/Docs are fixed top links.
- cmd+K runs ACTIONS too (toggle theme, browse all apps, open settings, switch
  org, ask AI / search docs, sign out, per-org switch), ranked alongside catalog
  nav — no dead entries. Removed unused openMode.
- DRY: switchOrg() shared by the switcher + palette; pure match-core (resolveRoute
  + entryMatches) is unit-tested without the GUI tree. Default pins fixed
  (dead 'billing' -> 'models','chat'). tsc + 29 vitest + next build clean.
2026-06-28 22:44:30 -07:00
zeekay 28c186b508 fix(console2): customer console scopes to the user's own org (v0.7.3)
The org-scope module defaults the active org to the brand org (for the cross-org
admin). On a customer host, seed the signed-in user's OWN org as the active scope
the first time (only when no explicit switch is in effect), so the OrgSwitcher
chip and X-Org-Id reflect the real tenant (e.g. maxpower) instead of the brand
org. Never clobbers an admin's deliberate switch.
2026-06-28 22:16:30 -07:00
zeekay bba56046e4 fix(console2): mask the password field on the sign-in form (v0.7.2)
The @hanzo/gui Input ignores the RN secureTextEntry/keyboardType props on web,
so the password rendered as type=text (visible while typing). Set the web input
type explicitly (type="password") so it masks; also corrects autoComplete to
current-password.
2026-06-28 21:58:56 -07:00
zeekay 948a627c72 ci(console2): resolve semver tag without node (ARC runner has no node)
The build step used `node -p require('./package.json').version`; node is not on
the ARC runner PATH, so the substitution silently yielded the tag `:v` and the
operator deploy 404'd. Resolve the version with grep/sed and fail-loud if empty.
2026-06-28 21:45:33 -07:00
zeekay bdda312f5e feat(console2): multi-tenant login (org by email) + /paas admin gate (v0.7.1)
Login resolves the user's ORG from their email instead of pinning the brand's
own org: a customer in any org signs into the brand console with email+password.

- iam-login.ts: POST /v1/iam/login with organization: (cross-org email
  resolution) → OAuth code → existing completeSignIn → /v1/signin exchange.
  Replaces the SDK org-pinned redirect that made non-brand-org users
  un-signinable. MFA (NextMfa/RequiredMfa) hands off to IAM's same-site hosted
  flow — IAM sets iam_session_id SameSite=Lax, so cross-site fetch MFA can't
  complete here; no faked inline step.
- SignInForm: email+password state machine; social (getProviderSigninUrl) kept.
- OrgGate: the console runs in the user's CUSTOMER org — blocks the internal
  brand org (owner===config.iamOrgName → admin.<domain>) and the zero-org case.
- SECURITY /paas/[...path]: gate with getAdminGate (403 if not a brand admin) +
  runtime nodejs. The forwarded PAAS_SERVICE_TOKEN is control-plane god-mode and
  was previously reachable by any authenticated browser.
- getAdminGate: orgScope=user.owner (was brand.id) so the IAM/KMS proxies pin a
  non-global admin to their OWN org; require a VERIFIED email (authoritative IAM
  recheck for thin claims). admin-policy + tests updated (14 pass).
2026-06-28 21:37:42 -07:00
zeekay 4cfcd1f779 Merge remote-tracking branch 'origin/main'
# Conflicts:
#	package-lock.json
#	package.json
2026-06-28 21:23:02 -07:00
zeekay b3fc76186f feat(console2): live admin data + org switching (v0.7.0)
Root cause of empty models + broken org switcher: /v1/{iam,kms,models} 404/401
(cookie-only) on the console host. Route every privileged call through console2's
own server proxies (user bearer + admin gate), and make org scope a switchable value.

- models-catalog: repoint /v1/models -> /ai proxy (shared aiV1Url in client.ts);
  catalog now populates with live Zen models. playground reuses the shared aiBase.
- org-scope.ts: currentOrg/setCurrentOrg/isScopedAway/filterOrgs. client.ts stamps
  X-Org-Id: currentOrg() so data modules re-scope on switch.
- OrgSwitcher: lists ALL visible orgs, filter box, in-place re-scope (set+reload).
- IamModule/AuditModule read currentOrg(); KmsModule now a names-only inventory
  over KmsAdminApi.list (the /admin/kms proxy), values never fetched.
- admin-policy.ts: pure gateAllows/ownerAllowed/orgFor extracted from the gate +
  routes (decomplect) so the shipped predicate is the tested one.
- vitest: 22 tests RED->GREEN (gate allow/deny+scoping, scope+filter, catalog /ai).
  tsc --noEmit + next build clean.
2026-06-28 21:19:50 -07:00
hanzo-dev fecaf7d49d fix(console2): Pager props + O11yUser barrel export (tsc clean) 2026-06-28 20:53:43 -07:00
hanzo-dev 1d9c2a9225 feat(console2): port Observations + Users observability views from old console
Two more old-console pages as real o11y modules: Observations (the flat
cross-trace span/generation view, GET /v1/o11y/observations) and Users (per-user
analytics rollup, GET /v1/o11y/users). O11yApi extended with both endpoints +
the O11yUser type. Same paged DataTable + honest RuntimeNotice pattern as the
other o11y modules; registered under Observe. tsc clean.
2026-06-28 20:52:55 -07:00
hanzo-dev 7a3b13d55e feat(console2): build the 25 remaining products into real modules
Flip every 'soon' product (ComingSoon stub) to a real, enabled in-console module
— attestations/oracles/indexer/tokens/settlement, alerts/logs, pipelines/
releases/builds/environments, hsm/authz/service-mesh/load-balancer/vpc, jobs/
edge/functions/containers/machines/gpus, agents/inference/finetuning. Each
follows the established module pattern: typed restGet over the same-origin /paas
proxy, DataTable, honest interpretPlatformError→PlatformStateCard not-configured
state, Refresh. Registry: status soon→enabled + routes wired. Full tsc clean.

Catalog is now 61 enabled modules + 16 external; no 'soon' stubs remain.
2026-06-28 20:06:44 -07:00
z bc7f92665e docs(brand): add hero banner 2026-06-28 20:05:13 -07:00
z 509e511b6e chore(brand): dynamic hero banner 2026-06-28 20:05:12 -07:00
hanzo-dev ab9f8751b7 feat: brand-aware animated logo in console loader/sign-in
The mark now follows config.brand — each brand's OWN published, interactive
animated SVG (@hanzo/logo, @luxfi/logo, @zooai/logo: getAnimatedSVG, load→hover→
press). Static block-H during SSR/first paint (no hydration mismatch). The logo
is now the brand's playable 'AI' on every loading + sign-in surface.
2026-06-28 19:49:01 -07:00
zeekay 5ea5cde253 feat(console2): add MPC product (Security) so console.hanzo.ai shows IAM/KMS/MPC/PaaS
MPC = threshold signing & multi-party computation, external→mpc.hanzo.ai.
Completes the 4 platform apps the launcher surfaces: IAM (module), KMS (module),
MPC (external), PaaS (projects→platform.hanzo.ai, embedded PlatformModule).
Verified locally: dev recompiled clean, tsc --noEmit clean.
2026-06-28 19:26:29 -07:00
zeekay f28d79673a wip(console2): agent admin-console IAM/KMS savepoint (proxy+gate+branding, in progress) 2026-06-28 19:20:38 -07:00
zeekay 40a6236aa3 fix(console2): API keys — drop reload() that unmounted the view via AuthGate (v0.6.1)
Build Docker Image / docker (push) Successful in 2m37s
The mint/revoke success path called useSession().reload(), which flips the
session loading flag -> AuthGate renders its Loader -> the dashboard (and
ApiKeysView) unmounts -> the freshly-minted key (local newKey state) is lost on
remount, so 'Your new API key' never showed. The session masks accessKey anyway,
so the reload provided no benefit. Show the new key from local state only.

Verified live (v0.6.0): /keys POST 200 + /ai chat proxy 200 (real 'PONG'/Hanzo
answer); only the keys UI render was affected.
2026-06-28 18:54:02 -07:00
zeekay 97c385f5ca feat(console2): working AI (keyless proxy) + API keys + chrome polish (v0.6.0)
Build Docker Image / docker (push) Successful in 2m25s
P0 — make it work for Dave:
- Root cause of 'chats/playground don't work': /v1/chat/completions requires
  Authorization: Bearer; the browser sent cookie-only -> rejected. Fixed with a
  keyless server-side AI proxy (app/ai/[...path]) that mints a short-lived
  user-bound IAM token (issue-user-token, hanzo-console app-on-behalf) and
  forwards to the gateway. No key in the browser, no rotation per turn.
- API keys: app/keys route mints/rotates/revokes the per-user hk- key via IAM
  (mint-user-keys/revoke-user-keys); ApiKeysModule is now create/copy/rotate/
  revoke with show-once secret handling.
- Chat is interactive (ChatConversation) over AiApi.chat; honest 402 billing state.
- src/lib/server/identity.ts: server-only trust boundary (resolveUser + IAM ops).

P1 — chrome polish:
- Header/sidebar show the Hanzo H mark + 'Console' (HanzoMark, BrandLogo with
  org-logo fallback).
- Fullscreen Launchpad-style app launcher (AppLauncher) with filter, from the
  header 'Apps' button, sidebar grid icon, and the command palette.
- cmd+K palette gains a 'Browse all apps' affordance.

Verified end-to-end (curl, real creds): minted hk- key + issued user JWT both
200 on api.hanzo.ai/v1/chat/completions. typecheck + next build clean.
2026-06-28 18:19:38 -07:00
zeekay 7cf8015c07 chore(console2): remove unused lib/zap client + @zap-proto deps
Zero importers (grep lib/zap = 0). Drops src/lib/zap/* and the
@zap-proto/{web,zap} deps. typecheck + build clean. One-way hygiene.
2026-06-28 05:45:21 -07:00
zandGitHub 5874ec5acc Merge pull request #4 from hanzoai/feat/memory-tasks-modules
feat: Memory + Tasks modules (v0.5.0) — unify work/tasks/memory in the console
2026-06-27 22:16:00 -07:00
zeekay 01844deb23 catalog: Tasks under appended Async category (Tasks/Temporal)
Async is the canonical home for Tasks per the org taxonomy. Appended as an 11th
category so the ten GCP-equivalent groups keep their exact labels and order
(no reorder); catalogByCategory is data-driven, so it renders generically.
2026-06-27 22:11:27 -07:00
zeekay f7a90ffe65 release: v0.5.0 — Memory + Tasks modules 2026-06-27 22:06:52 -07:00
zeekay 7f7a9341da feat(console): Memory + Tasks modules in the unified catalog
Memory (Data): list + search (kind filter + text) + detail/edit + add/delete,
honest 'initializing' card until /v1/memory deploys. Tasks (Compute, GCP Cloud
Tasks): namespace selector + Workflows/Schedules tabs + cluster strip, workflow
detail + durable history, on the LIVE /v1/tasks engine. Both render honest
states on a gated/absent route; mutations report through the shared toast.
Entries appended (no reorder); grouped by category.
2026-06-27 22:06:48 -07:00
zeekay 13978c0ca9 feat(api): Memory + Tasks /v1 clients
Memory (hanzoai/ai /v1/memory): remember/search/list/recall/update/remove/facts
over restGet/restPost; per-user, server-scoped. Tasks (hanzoai/tasks /v1/tasks):
namespaces/workflows/workflow/history/schedules + cluster health, contract
verified against pkg/tasks/embed.go. Both plain-REST, cookie-credentialed; org
scoping is server-side.
2026-06-27 22:06:41 -07:00
zandGitHub d564d3c488 Merge pull request #3 from hanzoai/feat/shell-foundation
feat: shell foundation v0.4.0 — cmd+K, AI assist, toasts, theme, org-switcher, breadcrumbs
2026-06-27 21:47:44 -07:00
zeekay bd933e5984 chore: v0.4.0 2026-06-27 21:45:52 -07:00
zeekay c0da836191 feat(shell): mount the foundation blocks once in the dashboard shell
Dashboard layout wraps the shell in ToastProvider + CommandPaletteProvider. The
shell top bar gains the command search box (opens the palette), theme toggle, a
help launcher (opens the palette in docs mode), and the org switcher; a breadcrumb
bar sits below it. ResourceModule create/delete now report through the toast, so
the one feedback primitive is actually used.
2026-06-27 21:45:48 -07:00
zeekay abb45c9481 feat(console): command palette + org switcher
CommandPalette is ONE command surface (Cmd/Ctrl+K) with modes selected by the
query: default fuzzy-filters the catalog and jumps to any product; > asks the AI
to find a product (NAV <id>) or answer; ? asks the docs knowledge store (RAG).
searchCatalog is the dependency-free fuzzy ranker. OrgSwitcher shows the account's
org and, only for a real multi-brand membership, switches to that brand's console
host. Honest throughout — AI/RAG/IAM failures degrade to truthful states.
2026-06-27 21:45:41 -07:00
zeekay a09e9483c8 feat(ui): toast, theme toggle, breadcrumbs primitives
Toast is the one feedback primitive — ToastProvider + useToast() with a portalled
top-right viewport, theme-aware accents, auto-dismiss. ThemeToggle flips dark/light
via next-theme. Breadcrumbs derive Home/Category/Product/detail from the route +
catalog, so a new product gets correct crumbs for free. GUI primitives only.
2026-06-27 21:45:35 -07:00
zeekay 5a61a9571c feat(api): one AI client over the cloud /v1 (chat + ragChat docs + listModels)
AiApi composes the single OpenAI-compatible gateway binding (PlaygroundApi):
plain chat, listModels, and ragChat grounded in a knowledge store (docs by
default) via the built-in retrieval path — the X-Retrieval-Store header turns
on RAG and names the store; the org owner is resolved server-side. restPost and
PlaygroundApi.chat gain an optional headers arg so RAG and plain chat share ONE
binding. No parallel AI client; failures throw ApiError for honest states.
2026-06-27 21:45:29 -07:00
zandGitHub 7b9a02ab9a Merge pull request #2 from hanzoai/feat/billing-per-brand-url
Per-brand billingUrl (lux->billing.lux.cloud, zoo->billing.zoo.cloud)
2026-06-27 20:01:54 -07:00
zeekay 03d80356bf feat(config): per-brand billingUrl (lux->billing.lux.cloud, zoo->billing.zoo.cloud)
billingUrl moves from SHARED to the per-brand BRANDS table, resolved like
iamUrl. Each brand's console (Cost product, PlansModule manage-billing) links
to ITS billing host, scoped to ITS org by the brand JWT. Cloud backend stays
shared/multi-tenant.
2026-06-27 19:24:08 -07:00
zeekay 35e0ea4c30 merge: page-port wave 2 (trace-graph tree, score-configs, annotation-queues) — v0.3.0
Build Docker Image / docker (push) Successful in 2m25s
2026-06-27 18:52:04 -07:00
zeekay cf44eff091 feat(console2): port-wave2 — span tree, score-configs, annotation-queues (v0.3.0)
Native @hanzo/gui modules over the REAL /v1/o11y REST surface; honest
RuntimeNotice on 503/404 — no fabricated data.

- Traces detail: flat observations table -> nested span TREE waterfall
  (SpanTree) built from parentObservationId, with a Tree|Table toggle.
  Orphans/cycles surface as roots so every observation appears once.
- Score Configs: new Observe module on /v1/o11y/score-configs (read-only).
- Annotation Queues: new Observe module on /v1/o11y/annotation-queues
  (real public REST list — contradicts the earlier 'no backend' finding).

Skipped (honest, no usable Hanzo backend or would duplicate/fake):
dashboards/widgets + score-analytics (no saved-dashboard REST, charts
would be fabricated), llm-connections/mcp (covered by Providers/ModelCatalog),
agents (backend not routed at gateway — real paths 404), org/projects deep
settings (already covered by Settings + IAM, no write endpoints), and the
Langfuse integration surfaces (feature-flags/entitlements/automations/
batch-exports/developer-tools/slack/mixpanel/blobstorage).

catalog 73 -> 75 entries; appended only (no reorder).
2026-06-27 18:44:19 -07:00
Hanzo AI e3c4d52bb4 build: cap Node heap (NODE_OPTIONS=6144) to fix Next build OOMKill (exit 137) 2026-06-27 18:35:53 -07:00
zeekay da83b67e89 release: v0.2.0 — consolidate page-port wave 1 (o11y traces/sessions/scores, playground/evals/datasets/prompts, settings/models/api-keys)
Build Docker Image / docker (push) Successful in 2m45s
Merges port-{settings-models,prompts-evals,o11y-core}. 73 catalog entries across the 10 categories; new modules wired to real /v1 backends with honest states (o11y 503 until runtime init). tsc + next build green.
2026-06-27 18:19:45 -07:00
zeekay a13de116e8 merge: port-o11y-core (Traces/Sessions/Scores)
# Conflicts:
#	src/lib/api/index.ts
#	src/lib/products/registry.tsx
2026-06-27 18:17:56 -07:00
zeekay 725beb1d98 merge: port-prompts-evals (page-port wave 1)
# Conflicts:
#	src/lib/products/registry.tsx
2026-06-27 18:17:16 -07:00
zeekay 21c1016292 merge: port-settings-models (page-port wave 1) 2026-06-27 18:16:09 -07:00
Hanzo AI bc76e6fc76 release: v0.1.9 — REST client fix over v0.1.8 (working REST, not dead ZAP /zap WS) 2026-06-27 18:10:23 -07:00
Hanzo AI 24f9b14e69 fix(providers): use working REST client, not the dead ZAP /zap WS
ProviderListView/ProviderEditView imported ~/lib/zap, but the cloud /zap
WebSocket face is not served (edge returns SPA HTML, not a WS upgrade — per
lib/zap/client.ts LIVE STATUS), so Providers rendered 'Failed to load
providers'. Switch both to ~/lib/api (identical surface). Part of v0.1.8.
2026-06-27 17:46:04 -07:00
zeekay ac0ecfcb84 feat(console2): port prompts/playground/datasets/evals as native @hanzo/gui modules
Port the old console (Langfuse-fork) eval surfaces into console2 as native
modules on @hanzo/gui + @hanzogui/lucide-icons-2 — no antd/shadcn/tremor.
Wired to the REAL cloud /v1 backend; honest loading/empty/unavailable states
on 404/503 (NEVER fabricated prompts/datasets/scores).

- Playground (AI): GET /v1/models + POST /v1/chat/completions — fully working
  model run (system prompt, message thread, sampling params, token usage).
- Evals (Observe): POST /v1/evals/runs (real per-item run summary) +
  GET /v1/evals/scores (real scores list), Run/Scores tabs.
- Datasets (Observe): POST /v1/evals/datasets + /v1/evals/dataset-items (real
  create); forward-compatible GET list with honest unavailable card.
- Prompts (AI): forward-compatible GET /v1/prompts probe; honest deep-link card
  (no /v1 prompts route mounted yet).

Shared: ModelPicker (one way to pick a gateway model), BackendState (honest
/v1 error → card). API: lib/api/{playground,evals}.ts via the REST client.
Registry: playground+evals stubs upgraded in place (no reorder); prompts+
datasets appended. tsc --noEmit + next build both green.
2026-06-27 17:43:45 -07:00
zeekay e547011c96 feat(console2): native Traces/Sessions/Scores modules under Observe
Port the old console's observability core (Langfuse-shaped) to native
@hanzo/gui modules:
- Traces: list + detail (overview, I/O, observations, scores) at /o11y
- Sessions: list + detail (overview + traces) at /sessions
- Scores: list at /scores

All read the REAL /v1/o11y endpoints and render honest states (loading /
runtime-initializing / empty) on 503/404 — never fabricated traces or
charts. Replaces the Traces deep-link placeholder (ObservabilityModule
removed); appends Sessions + Scores entries (no reorder of existing).
tsc --noEmit and next build both pass.
2026-06-27 17:43:28 -07:00
zeekay 164f073b50 feat(console2): shared observability primitives
DRY pieces for the o11y surfaces: pure formatters (date/latency/cost/
score value/JSON), shared detail parts (DetailRow/Badge/Tags/JsonCard),
the honest RuntimeNotice (503 not-initialized / 404 unrouted / access /
error), and the list Pager. No fabricated data.
2026-06-27 17:43:16 -07:00
zeekay 6df405adcd feat(console2): o11y API client (traces/sessions/scores)
Typed client for the /v1/o11y surface over the plain-REST transport
(restGet/v1Url): list endpoints return { data, meta }, detail endpoints
one object. 503/404 surface as typed ApiError so callers render honest
states. Tenancy is server-side (cookie credentials only).
2026-06-27 17:43:16 -07:00
zeekay f50dbdd9a6 feat(console2): port settings + model catalog pages as native @hanzo/gui modules
Port hanzoai/console's deep settings + models pages into console2 as native
modules wired to the REAL /v1 + /v1/iam endpoints. Honest loading/404/401/503
states everywhere — never fabricates keys, models, or settings.

New modules (registry, appended — no reorder):
- Model Catalog (AI): real GET /v1/models + best-effort /v1/pricing/models
  overlay; provider filter, premium tier, $/Mtok columns. Read-only catalog
  (routing lives in Models, credentials in Providers).
- API Keys (Dev): the account's real cloud credential (accessKey/accessSecret
  from get-account), masked by default with explicit reveal + copy; honest
  "managed by gateway" state when no key material is exposed to the browser.
- Settings (Security): tabbed General / API Keys / Members / Branding. General
  reads real account (get-account) + org (/v1/iam/get-organization); Members
  reads /v1/iam/get-users; API Keys embeds the shared ApiKeysView (DRY);
  Branding shows the real per-host runtime config. Identity mutations deep-link
  to IAM rather than being re-implemented.

Shared + API:
- ui/States.tsx: one honest async-state renderer (honestError + ErrorState +
  asApiError) with per-surface copy overrides. AdminModule refactored onto it
  (removes its duplicate honestError/ErrorCard).
- api/models-catalog.ts: CloudModelApi over the REST (non-envelope) /v1/models.
- api/admin.ts: IamAdminApi.organization(name) single-org getter.

Shell: top-bar account name now links to /settings (canonical account menu).

Gates: tsc --noEmit exit 0; next build exit 0.

Skipped (no real console2 backend — porting as shells would be slop): Langfuse
feature-flags (2 internal flags), developer-tools (Langfuse-branded copy),
automations/batch-exports/integrations (tRPC+Prisma only). Members/Audit/
Secrets/LLM-connections/Billing already exist as IAM/Audit/KMS/Providers/Cost.
2026-06-27 17:40:53 -07:00
Hanzo AI b4274bda4a release: v0.1.8 (cumulative — supersedes parallel v0.1.7) 2026-06-27 17:37:11 -07:00
Hanzo AI c9adc16cad merge: integrate fix/paas-live-data (CTO v0.1.7 paas wiring) into main
main already supersedes it: same real platform contract (/v1/apps +
/v1/org/{org}/cluster) PLUS X-Org-Id (resource modules), Bot/Wallet honest
states, Clusters real-contract rewrite, and the PaaS token fix. Recording the
integration so the line is single; cutting v0.1.8 as the cumulative release.
2026-06-27 17:36:51 -07:00
Hanzo AI f30cdbbee5 fix(modules): wire every embedded module to the real /v1 backend + cut v0.1.7
Live Playwright verification surfaced real wiring bugs; fixed all in console2
(honest states everywhere, no fakes):

- client.ts: stamp X-Org-Id (brand org) on every cloud call — the provisioning
  service 403'd 'X-Org-Id required' on the direct cloud-api path. Fixes the 7
  data modules (vector/sql/kv/s3/datastore/docdb/search) → real data / empty.
- platform.ts: rework to the REAL platform contract — GET /v1/apps (apps
  inventory) + GET|POST /v1/org/{org}/cluster; drop dead /v1/clusters + k8s
  passthrough. Status = real health board; Kubernetes = real workloads per
  cluster; Clusters = real dedicated-DOKS list (honest empty).
- platform/state.tsx: upstream 401/403 → honest 'not configured'.
- BotModule: /v1/bot/health 404 → honest 'not routed on this host'.
- WalletModule: /v1/billing/balance 404 → honest 'not available'.
- StatusTag: understand platform health verdicts (green/yellow/red).

typecheck + build clean. Operator CR token repointed (universe) to the correct
paas-console-token (the old hanzo-paas/MASTERTOKEN is rejected by platform).
2026-06-27 17:34:03 -07:00
zeekay a307d64b07 fix(paas): wire Clusters/Kubernetes/Status to real platform /v1 surface
Build Docker Image / docker (push) Successful in 2m36s
The PaaS modules targeted an assumed platform surface (/v1/clusters,
/v1/org/{org}/cluster/{id}/k8s/{kind}) that does not exist — the live
platform.hanzo.ai/v1 REST API serves /v1/org/{org}/cluster (org-scoped
dedicated clusters) and /v1/apps (the workload/drift board). Re-point the
single data layer (src/lib/api/platform.ts) at the real endpoints:

- listClusters → /v1/org/{org}/cluster (unwrap {clusters}); org from config.
- add AppsApi.listApps → /v1/apps (unwrap {apps}) — the live deploy data.
- drop the dead k8s-browse client (no backend) + CLUSTER_ROUTES guess.

Status + Kubernetes now render the real /v1/apps workloads (cluster,
namespace, image, health) instead of gating on a non-existent k8s-browse
behind a (for hanzo) empty dedicated-cluster list. StatusTag tones the
drift-board health (healthy/warning/down). Auth is unchanged: the /paas
proxy already sends Authorization: Bearer; the fix is the token VALUE
(operator CR → paas-console-token) + these paths.
2026-06-27 17:28:37 -07:00
zeekay c32bb30154 docs: correct catalog home comment for the 3-state enablement model 2026-06-27 16:44:35 -07:00
zeekay c27a62d271 catalog: canonical 10-category Open AI Cloud (GCP-compatible) + all-services Status
Build Docker Image / docker (push) Successful in 2m33s
Rebuild the product catalog to the canonical ten categories, in order:
AI · Compute · Data · Network · Security · Dev · Deploy · Observe · Web3 · Apps.
66 entries; each names its Google Cloud equivalent. Honest 3-state enablement:
enabled (23, in-console modules) / external (16, live Hanzo surfaces) / soon (27).
Every real working module is preserved (recategorized, not broken).

Add Status (Observe): live health of every Hanzo service across clusters, from
REAL data only — composes PlatformApi.listClusters + KubernetesApi deployments
over the /paas control plane, with honest not-configured/unavailable/empty
states and no fabricated dots.

Decomplect: one coming-soon surface for all soon leaves; delete the dead
duplicate PaaS client (PlatformModule + lib/paas) and the unused coming-soon
factory. Release v0.1.6.
2026-06-27 16:43:30 -07:00
zeekay 102a37a48c release: v0.1.5
Build Docker Image / docker (push) Successful in 4m57s
Phases 1-5: nine-category catalog (mirrors hanzo.ai), in-console admin
(Identity/Secrets/Audit), Kubernetes workloads browser + real Clusters over
/paas, and an honest Observability category. tsc --noEmit + next build green.
2026-06-27 16:10:25 -07:00
zeekay 6beb670744 o11y: honest Observability category (traces/evals/prompts)
Phase 5 — add the Observability category with truthful entries, no fake charts:

- Observability (/o11y): console-native module that probes the REAL /v1/o11y
  runtime and reports status (online / not-initialized 503 / not-routed 404 /
  access / error), deep-links to the full observability surface for traces,
  evals, and prompts, and marks the native in-console browser as coming
  (HIP-0106). Never renders placeholder telemetry.
- Insights (external) + Analytics (relocated here) round out the category.

This is the staged first step for the largest old-console surface; the deeper
native port is honestly deferred, not faked.
2026-06-27 16:06:34 -07:00
zeekay 82e81ddf75 k8s: Kubernetes workloads browser + real Clusters over /paas
Phase 4 — one platform transport: route ALL control-plane calls through the
same-origin /paas proxy (server-side token injection, no CORS, honest 501
when unset) instead of direct cross-origin platform.hanzo.ai.

- platform.ts: clusters now go via /paas; add KubernetesApi over
  /v1/org/{org}/cluster/{id}/k8s/{deployments,pods,services,ingresses,events,crs}.
- KubernetesModule: cluster picker + resource tabs, defensive per-kind columns,
  honest loading/not-configured/backend-unavailable/error/empty states.
- ClustersModule: flip 'soon' -> real; render the shared honest state card for
  not-configured (501) / backend-unavailable (404).
- New shared platform/state.tsx interprets /paas errors one way.
2026-06-27 16:01:25 -07:00
zeekay 1ad8ff3fa0 admin: in-console Identity, Secrets (KMS), and Audit modules
Phase 3 — wire the console to the existing identity/secrets subsystems over
the canonical /v1 surface (HIP-0111), each an honest module:

- Identity (/iam): tabbed Organizations / Users / Roles (RBAC) over Hanzo
  IAM /v1/iam/get-{organizations,users,roles} (casdoor envelope). One generic
  AdminListView drives all three; 404/401/empty are explicit honest states.
- Audit (/audit): identity & access event log over /v1/iam/get-records.
- Secrets (/kms): KMS is zero-knowledge (encrypted names+values, token/ZAP
  auth, no list-values endpoint) — the module states the model, probes the
  real /v1/kms surface to report reachability, and deep-links to the KMS
  console. It never fabricates a secret table.

iam/kms flip from external links to modules; ext.iam/ext.kms removed.
2026-06-27 15:56:31 -07:00
zeekay 631dc417b2 catalog: mirror hanzo.ai's nine product categories
Replace the ad-hoc AI/Data/Apps/Identity/Infrastructure/Commerce grouping
with the exact nine categories + order from the marketing site product
dropdown (navigation-data.ts productsNav): AI & Agents, Developer, Apps,
Compute, Data, Async, Platform, Observability, Web3. One taxonomy across
every Hanzo surface. Empty groups don't render (catalogByCategory skips them).
2026-06-27 15:50:57 -07:00
zeekay 57371b1c9d feat(console2): Wallet & HUSD top-up module + verify-and-record endpoint; v0.1.4
Build Docker Image / docker (push) Successful in 2m47s
- WalletModule (Commerce): connect a non-custodial wallet on Hanzo Mainnet
  (36900) via ethers/EIP-1193, show wallet HUSD + cloud credit balances, and
  top up credit with HUSD. Honest states throughout (no wallet, HUSD greenfield,
  chain unreachable, endpoint unconfigured) — never a fabricated balance.
- src/lib/wallet/hanzo-evm.ts: one canonical Hanzo Mainnet + HUSD definition
  (ethers v6), env-overridable RPC; HUSD address is public (NEXT_PUBLIC), never
  a secret.
- src/lib/api/wallet.ts: cloud balance via the real GET /v1/billing/balance, and
  recordWalletTopup → the console's own POST /billing/topup/wallet.
- app/billing/topup/wallet/route.ts: server route (mirrors /paas) — verifies the
  HUSD transfer on-chain, then records to commerce as a husd crypto payment and
  credits the balance. Hosted here because billing.hanzo.ai is a static export
  and commerce is owned elsewhere. Server-only config (KMS, never NEXT_PUBLIC).
- registry: wallet entry; api/index: WalletApi export. Adds ethers 6.17.0.
2026-06-27 14:56:35 -07:00
zeekay 0076f411b0 console2: per-product discover interstitials (docs + GitHub OSS + dividends); v0.1.3
Build Docker Image / docker (push) Successful in 2m29s
'Interstitial screens to discover guides/docs/how-tos + link to GitHub OSS for
each product' + the OSS-gets-paid hook:
- /discover/<id> route + ProductInterstitial: identity + open/get-started CTA,
  Docs & guides + Open-source (GitHub) link cards, and an 'Open source gets paid'
  card stating the model (25% of cloud revenue -> OSS contributors, computed from
  each deployment's SBOM, settled on-chain in HUSD) with Contribute + OSS-dividends
  links. Catalog cards gain a Learn-more (info) affordance; non-enabled Get-started
  routes to the interstitial.
- OSS_PROGRAM constant (one source of truth: 25% / HUSD / SBOM / dividends dashboard),
  aligned with hanzo.ai sbomRevenueConfig + the commerce contributor/payout system.

tsc clean; next build green (/discover/[id] live).
2026-06-27 14:22:42 -07:00
zeekay 9b04ea848c ci: semver image tags only (no sha, no :latest); v0.1.2
Build Docker Image / docker (push) Successful in 2m32s
Per directive 'use proper semver for all, no sha': build-image.yml now tags
ghcr.io/hanzoai/console2 with the semver version only — a v* git tag publishes
that exact version, a main push publishes v<package.json version> (bump to
release). Drops the sha-<sha7> and floating :latest tags. Bump 0.1.1 -> 0.1.2
(GCP-grade resource detail + Plans & Pricing + Team launcher).
2026-06-27 13:58:21 -07:00
zeekay e30e9c7b3e console2: GCP-grade resource detail + Plans & Pricing + Team launcher
The 'manage/create databases ala GCP' + 'discover, enable, pay' surface,
all on REAL backend contracts (no invented controls):

- ResourceModule gains an instance DETAIL view (list+detail in one component,
  mirroring ProvidersModule's params.name): click a resource -> GET /v1/<kind>/<name>
  overview (status/kind/endpoint/user/db/created) + connection guidance + danger-zone
  delete. New resourceRoutes() helper binds index + :name to one instance (DRY);
  the 7 data products (sql/vector/datastore/kv/search/s3/docdb) use it. Resources
  are serverless/create-by-name (POST /v1/<kind> takes only {name}) — no fake
  tier/size/region knobs.
- PlansModule: GCP-style Plans & Pricing on the live rate card (GET /v1/pricing):
  per-tier cards (vCPU/RAM/SSD/transfer, monthly+hourly, feature bullets, free/popular
  badges) + block-storage metering. Paying delegates to config.billingUrl (the one
  money surface, never reimplemented). New typed PlansApi (plans.ts).
- Team launcher: hanzo.team catalog entry (Apps, external team.hanzo.ai).

tsc --noEmit clean; next build green (9/9).
2026-06-27 13:26:41 -07:00
zeekay f057352fc3 feat(console2): Bot module — in-console /v1/bot status + operator deep-links
Flip the existing 'bot' catalog entry from an external link to an in-console
module. New BotModule reports live gateway status from /v1/bot/health (via a
small BotApi on the REST layer, since the bot speaks plain JSON, not the
casibase envelope) and deep-links the operator surfaces (bot home, control UI,
docs, source). Backend (hanzoai/bot -> bot-gateway) is already routed at
/v1/bot/* by the unified gateway.
2026-06-27 12:45:58 -07:00
zeekay a0db49f282 fix(console2): cloud fallback → api.hanzo.ai (gated gateway), not the SPA host
Found via testing: cloud.hanzo.ai serves the SPA catch-all (200 text/html for any /v1 path), NOT the backend; the real /v1 is behind the unified gateway api.hanzo.ai (hanzoai/ingress→hanzoai/gateway v2.13.0 → cloud / separate services / per-org k8s, rate-limited+gated+priced). Browser uses same-origin /v1 (each console host's ingress proxies to the gateway); this SSR fallback now points at the gateway.
2026-06-27 12:21:14 -07:00
zeekay c09943eb08 feat(console2): one image, multi-brand by hostname (hanzo/lux/zoo)
Resolves the brand at RUNTIME from the request hostname (console.hanzo.ai→hanzo, console.lux.cloud→lux, console.zoo.cloud→zoo). Tenancy: ONE cloud /v1 backend serves all orgs (same-origin per host → first-party cookie, no CORS), each brand authenticates against its OWN live IAM (hanzo.id / lux.id / zoolabs.id / pars.id; client_id <org>-cloud per HIP-0111). config is a brand-aware Proxy so the /v1 client + IAM SDK go per-host with no consumer changes; cloudUrl is same-origin (window.origin); NEXT_PUBLIC_* still override. Dockerfile + CI no longer bake NEXT_PUBLIC_* (that pinned one brand) → one brand-agnostic image (sha-<sha7>+latest). Fixed a 'Hanzo' subtitle brand-leak. Verified: tsc clean + next build green. NOTE: cloud backend must accept all brand issuers/auds; each console host's ingress must proxy /v1 to the backend + register the redirect URI in that brand's IAM app.
2026-06-27 12:11:09 -07:00
Hanzo AI 0e2ee1f394 feat(console2): brand polish — favicon, monochrome, sized loader, social sign-in
- favicon: canonical hanzo.app ▼/H mark via app-router icon files
  (favicon.ico, icon.svg, apple-icon.png); viewport themeColor #000000
- loader: monochrome HanzoMark ~40–48px centered (not viewport-filling),
  replacing the oversized @hanzo/gui Spinner in AuthGate + OAuth callback
- monochrome: black/white/grey chrome, white (theme="light") primary
  buttons; drop every blue/green/red/yellow/violet theme + $color accent
  across products, status tags, dashboard badges, default store color
- sign-in: dedicated GitHub + Google buttons (provider_hint) + Hanzo ID,
  all via hanzo.id OIDC (client_id=hanzo-cloud); IAM owns provider OAuth,
  console never reconstructs github.com/accounts.google.com URLs
2026-06-26 19:22:26 -07:00
Hanzo AI c6f55d8646 docs(LLM): canonical issuer hanzo.id + hanzo-cloud app + deploy reality [skip ci] 2026-06-26 18:27:53 -07:00
Hanzo AI 14519c41c5 fix(ci): emit sha+latest tags via GITHUB_OUTPUT heredoc
The mainnet branch wrote a two-line tags value with $'\n', which GitHub
Actions rejects for key=value outputs ("Invalid format ...:latest") —
so every Build Docker Image run failed at 'Compute per-env config' and
no image was ever produced by CI. Use the multi-line heredoc output form
so build-push-action receives both newline-separated tags.
2026-06-26 18:15:50 -07:00
Hanzo AI 1f80429f97 fix(auth): sign-in via canonical issuer hanzo.id, not iam.hanzo.ai
NEXT_PUBLIC_IAM_URL is inlined at build time, so the deployed image sent
the browser authorize redirect to https://iam.hanzo.ai — which mints
iss=https://iam.hanzo.ai, a different issuer than the canonical
https://hanzo.id that the cloud /v1 backend validates. Sign-in dropped
on iam.hanzo.ai and never round-tripped back to console2.

- src/config, .env.example, Dockerfile ARG, mainnet CI build-arg: point
  the browser at https://hanzo.id (the value baked into the image).
- Align iamAppName/iamClientId source defaults to hanzo-cloud (was the
  stale hanzo-console / empty), matching the cloud-api backend binding
  (iamApplication / IAM_AUDIENCE = hanzo-cloud). A default build now
  targets the correct app instead of a non-existent one with no client.

App/client stay hanzo-cloud on purpose: console2 is a front-end of the
shared cloud /v1 backend, which exchanges the code and validates aud as
hanzo-cloud — it is not its own IAM principal.
2026-06-26 18:14:12 -07:00
Hanzo AI 800b3481d7 feat(console2): 10-category cloud axis + embedded PaaS, no fakes
Job 2: reorganize the catalog into the canonical 10-category CLOUD AXIS
(AI/Compute/Data/Network/Security/Dev/Deploy/Observe/Chain/Apps) so console2
reads like a cloud console. Three entry kinds (module/external/soon) => zero
dead links, zero fakes; 'soon' primitives render an honest ComingSoon overview.

Job 3: PaaS embedded natively under Deploy (PlatformModule) wired to the real
platform.hanzo.ai control plane via a same-origin /paas proxy (service token
server-side from KMS). Real apps + declared/running/drift + redeploy; honest
loading/not-configured/empty states.

Job 4: catalog honest by construction; PaaS shows only real data. No placeholder
cards, demo projects, or lorem stats.
2026-06-26 14:48:16 -07:00
Hanzo AI 7e3fa15425 Merge feat/cloud-taxonomy-10cat into main (union)
Union merge — feature's categorized catalog architecture is canonical, with
main's data/storage products + status badges folded in (lose nothing):

- registry.tsx: feature's CatalogEntry discriminated union (category + kind +
  admin + derived productModules) as the base; FOLD IN main's data/storage cloud
  products (vector, sql, datastore, kv, search, s3, docdb, base, clusters) as
  categorized 'module' entries via resourceModule/comingSoon — these are the
  console frontend for cloud's /v1 provisioning control plane. Extend
  ProductStatus to 'enabled'|'available'|'soon'|'waitlist' and add repo? so the
  folded products keep their status badges. Resolve the id 'search' collision:
  managed Search data product keeps id 'search' (owns the route, maps to the
  provisioning kind); feature's external search.hanzo.ai becomes 'ai-search'.
- DashboardShell.tsx: feature's Pinned + categorized NavRow shell; FOLD main's
  SOON/WAITLIST status badge into NavRow (feature had dropped it).
- page.tsx: feature's grouped ProductCard grid; extend StatusBadge to render
  Soon/Waitlist (blue/yellow) alongside Enabled/Available (folds main's badge).

Verify: tsc --noEmit strict CLEAN; next build green (6/6 pages). The repo's
untracked PaaS WIP (ComingSoon/PlatformModule/paas — another agent's, in neither
branch) is left untouched and excluded from this commit.
2026-06-26 14:47:11 -07:00
07db3af7fe feat(products): register full data/storage catalog + enablement status (#1)
* feat(products): register full data/storage catalog + enablement status

Adds `status` ('enabled'|'soon'|'waitlist') + `repo` to every ProductModule so
the console tracks enablement of all Hanzo cloud products in ONE place. Registers
the OSS-Google-Cloud data/storage suite as modules — Vector, SQL, Datastore, KV,
Search, S3, Base (soon) and DocDB (waitlist) — each a ZAP-native Hanzo fork mapped
to its repo, with a ComingSoon placeholder (repo link + status) until its admin
module lands. Nav + dashboard cards render the status badge.

Products → repos: Vector=hanzoai/vector (Qdrant-compat), SQL=hanzoai/sql,
Datastore=hanzoai/datastore (ClickHouse-compat), KV=hanzoai/kv (Redis-compat),
Search=hanzoai/search, S3=hanzoai/s3, Base=hanzoai/base, DocDB=hanzoai/docdb.

* feat(products): add Clusters module (shared Hanzo Cloud vs BYO DOKS)

The data/storage products (Vector/SQL/Datastore/KV/Search/S3/Base/DocDB) are
all live on hanzo-k8s via the operator. Adds the one new control-plane surface
the platform needs: Clusters — choose where workloads run (shared multi-tenant
Hanzo Cloud, or your own/Hanzo-provisioned DOKS cluster, reconciled by the same
operator). Deploy-any-repo stays under Applications.

* feat(products): working data/storage + clusters admin modules

Replace the comingSoon() placeholders for sql/vector/datastore/kv/search/s3/
docdb with a DRY resourceModule() factory over the provisioning REST contract
(POST/GET/DELETE /v1/<kind>): list, create-with-once-shown connectionString +
password reveal ("store this now"), and per-row delete. Tenancy is server-side
(gateway injects X-Org-Id), so the browser sends cookie creds only.

- lib/api/client.ts: plain-REST helpers (restGet/restPost/restDelete + v1Url)
  beside the casibase envelope path — provisioning + platform speak raw JSON /
  201 / 204 / DELETE, reusing the same cookie creds + ApiError. One transport.
- lib/api/provisioning.ts: ProvisioningApi keyed by ResourceKind.
- lib/api/platform.ts: PlatformApi (DOKS clusters) with centralized
  CLUSTER_ROUTES + DOKS region/size options; base = NEXT_PUBLIC_PLATFORM_URL.
- components/products/ResourceModule.tsx: the factory (list/create/delete,
  copyable masked secret reveal, slug validation, loading/empty/error).
- components/products/ClustersModule.tsx: list + provision DOKS + attach (name
  + kubeconfig) against the platform control plane.
- components/ui/StatusTag.tsx, lib/slug.ts: shared/DRY across both modules.
- registry: swap routes to the working modules and clear 'soon'/'waitlist'
  status so nav badges clear. Base stays a placeholder (no single-resource).
- fix two pre-existing type errors in ComingSoonModule (maxWidth->maxW,
  theme active->blue) so the branch typechecks clean.

kind map: sql->databases, vector->vector, datastore->datastore, kv->kv,
search->search, s3->storage, docdb->docdb.

Verified: npm ci + tsc --noEmit => 0 errors (CI-equivalent flat install).

* console: native product naming + gate Clusters to coming-soon

Native naming (Hanzo brand rule — product name only, no upstream OSS
name in any surface):
- ResourceKind wire kinds align to the cloud /v1 contract exactly:
  databases→sql, storage→s3 (vector/datastore/kv/search/docdb unchanged).
- Strip every upstream name from product descriptions + connectionHints
  (Postgres/Qdrant/ClickHouse/Redis/Meilisearch/Mongo/-compatible → the
  Hanzo product name). Zero forbidden names remain in registry.tsx.

Clusters: register as status:'soon' rendering the coming-soon placeholder
(repo hanzoai/operator). The platform attach/provision endpoints in
platform.ts are unconfirmed (PR not merged), so we don't ship a button to
a non-existent endpoint. ClustersModule.tsx + platform.ts stay in the tree
(unreferenced from the live route) to flip back to enabled in one line once
the platform surface lands. Data products (sql/vector/datastore/kv/search/
s3/docdb) stay ENABLED — their /v1 kinds are real and shipping now.

tsc --noEmit: clean.

---------

Co-authored-by: zeekay <z@zeekay.io>
2026-06-26 13:20:20 -07:00
Hanzo AI 85e68e433e feat(console): unified product hub — catalog, pinnable favorites, account-backed prefs
Turn console2 into the one place to see, enable, and manage every Hanzo
product, with billing → billing.hanzo.ai for all.

- registry: ONE product catalog (categories + module-vs-external + enablement
  status), the single source of truth for nav, overview, and router. Adding a
  product = one CatalogEntry.
- favorites: pin products to the sidebar. Built on a new account-backed
  preferences layer (usePreferences) — customizations persist to the IAM user
  account, so they follow the user across every device/login and product.
  localStorage is only a fast-paint cache.
- shell: Pinned section + categorized catalog; exact-match active (no
  double-highlight); each row opens (in-console route or external tab) + pin toggle.
- overview: product catalog grouped by category with status, pin, and
  Open/Get-started.
- api: AccountApi.updatePreferences → POST /v1/update-preferences (self-scoped).

Typecheck + next build clean.
2026-06-26 11:15:21 -07:00
Hanzo AI 5527bb30dd fix(docker): npm install over npm ci for the @hanzo/gui dep tree
npm ci failed in CI (node:22-alpine npm 10.9) with EUSAGE 'Missing:
react-native-worklets@0.8.3 from lock file' — @hanzo/gui's react-native
optional/platform deps resolve differently across npm versions, so a
lockfile built by one npm is rejected by another's strict ci. npm install
reconciles deterministically for the build platform.
2026-06-25 13:57:42 -07:00
Hanzo AI 1b03d838db deps(console2): declare @zap-proto/web, @zap-proto/zap, superjson
The ZAP-native data layer (src/lib/zap/{client,transport,providers}.ts)
imports @zap-proto/web/client, @zap-proto/zap, and superjson; declare them
so a clean `npm ci` in CI resolves them (the prior build failed: 'Module
not found: @zap-proto/web/client' because the lockfile lacked them).
2026-06-25 13:48:28 -07:00
Hanzo AI 42f591214c feat(providers): cut Providers module to ZAP-native transport
Swap the Providers views from the REST `~/lib/api` to the ZAP-native
`~/lib/zap` (one import line each) — proving the @hanzo/gui + @zap-proto/web
go-forward: same call surface, binary ZAP over WebSocket instead of
JSON-over-HTTP, zero view-component changes.

- src/lib/zap/index.ts: barrel re-exporting ProviderApi (= ProviderApiZap),
  ApiError, Provider — the drop-in twin of ~/lib/api.
- ProviderListView/ProviderEditView: import from ~/lib/zap.
- providers.ts list(): return { rows, total } to match the REST getList
  contract exactly (true drop-in; fixes the list-view shape).

tsc --noEmit (strict) clean. Backs onto cloud's new /zap WS face which
dispatches each call into the same /v1 casibase handlers.
2026-06-25 13:44:26 -07:00
Antje Worring 668f6b8951 ci: env-aware image build (mainnet/testnet/devnet)
workflow_dispatch input 'env' bakes per-env NEXT_PUBLIC_* + tags the image
:dev/:test (mainnet stays :sha-+:latest). Hosts follow svc.env.hanzo.ai. Adds
NEXT_PUBLIC_BILLING_URL build-arg (per-env billing portal).
2026-06-22 03:17:50 -07:00
Antje Worring 7895e104b0 feat(nav): Billing link to the existing billing portal (no rebuild)
Billing is owned by hanzoai/commerce (backend) + hanzoai/billing (portal at
billing.hanzo.ai) — the console must not reimplement payments/balance. Add an
externalLinks registry (orthogonal to product modules) and render it in the
shell; Billing opens config.billingUrl (NEXT_PUBLIC_BILLING_URL, default
https://billing.hanzo.ai) in a new tab.
2026-06-22 02:44:56 -07:00
Antje Worring bfd2a2dd37 fix(auth): treat casibase anonymous-user as logged-out
The backend auto-creates an anonymous-user session for the chat product, so
get-account returns status:ok even with no real sign-in. As an ADMIN console
that made AuthGate show the dashboard for an unauthenticated visitor, while
admin endpoints (get-providers, etc.) rejected the anon session with 'Please
sign in first'. Treat type==='anonymous-user' as null so the console requires
a real IAM sign-in.
2026-06-22 00:39:44 -07:00
Antje Worring cf5d3094ae feat(console2): Models, Applications, Stores, Chat admin surfaces (@hanzo/gui /v1)
Mirror the Providers pattern: product-module + list/edit views on @hanzo/gui +
typed /v1 API modules, registered in the nav. tsc 0 errors, next build green.
2026-06-21 15:58:05 -07:00
Antje Worring 7a3dd59128 fix(ci): ensure public/ exists in image build + skip provenance artifacts
- Dockerfile: mkdir -p public before build (git doesn't track empty public/,
  so the runner COPY /app/public was failing)
- build-image: provenance/sbom false (avoid GitHub artifact-quota upload)
2026-06-21 15:05:32 -07:00
Antje Worring f117a01fac ci: Dockerfile + build-image workflow → ghcr.io/hanzoai/console2
Next.js 15 multi-stage build; NEXT_PUBLIC_* baked at build (same-origin /v1,
IAM client_id=hanzo-cloud to match cloud-api's /v1/signin). Self-hosted ARC
runner, push to ghcr.io/hanzoai/console2.
2026-06-21 15:01:36 -07:00
hanzo-dev 2b4d64c9cf feat: Hanzo Cloud Console (console2) on @hanzo/gui over the unified /v1 backend
Next.js 15 (app router) + @hanzo/gui consumed at runtime via transpilePackages.
Typed /v1 client (Provider/ModelRoute/Application/Store/Chat/Account), Hanzo IAM
OIDC auth, extensible product-module registry, and a full Providers admin surface
(list + view/edit) ported clean from hanzoai/ai onto Gui. BSD-3-Clause.
2026-06-21 14:58:20 -07:00
1872 changed files with 121159 additions and 166202 deletions
-4
View File
@@ -1,4 +0,0 @@
[codespell]
skip = .git,*.pdf,*.svg,package-lock.json,*.prisma,pnpm-lock.yaml
ignore-words-list = afterall,vertx,notIn
-8
View File
@@ -1,8 +0,0 @@
Dockerfile
.dockerignore
node_modules
npm-debug.log
README.md
**/.next
.git
**/node_modules
-92
View File
@@ -1,92 +0,0 @@
# When adding additional environment variables, the schema in "/src/env.mjs"
# should be updated accordingly.
# Prisma
# https://www.prisma.io/docs/reference/database-reference/connection-urls#env
DIRECT_URL="postgresql://postgres:postgres@localhost:5432/postgres"
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/postgres"
# Clickhouse
CLICKHOUSE_MIGRATION_URL="clickhouse://localhost:9000"
CLICKHOUSE_URL="http://localhost:8123"
CLICKHOUSE_USER="clickhouse"
CLICKHOUSE_PASSWORD="clickhouse"
CLICKHOUSE_MIGRATION_CLUSTER_DISABLED="true"
# Next Auth
# You can generate a new secret on the command line with:
# openssl rand -base64 32
# https://next-auth.js.org/configuration/options#secret
# NEXTAUTH_SECRET=""
NEXTAUTH_URL="http://localhost:3000"
NEXTAUTH_SECRET="secret"
# Langfuse Cloud Environment
NEXT_PUBLIC_LANGFUSE_CLOUD_REGION="DEV"
# Langfuse experimental features
LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES="true"
# Salt for API key hashing
SALT="salt"
# Email
EMAIL_FROM_ADDRESS="" # Defines the email address to use as the from address.
SMTP_CONNECTION_URL="" # Defines the connection url for smtp server.
# DON'T PANIC: The Azurite Secrets are well-known and meant to be hard-coded
# S3 storage
S3_ENDPOINT=http://localhost:10000/devstoreaccount1
S3_ACCESS_KEY_ID=devstoreaccount1
S3_SECRET_ACCESS_KEY=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==
S3_BUCKET_NAME=langfuse
S3_REGION=auto
## Necessary for minio compatibility
S3_FORCE_PATH_STYLE=true
# S3 Media Upload LOCAL
LANGFUSE_S3_MEDIA_UPLOAD_ENABLED=true
LANGFUSE_S3_MEDIA_UPLOAD_BUCKET=langfuse
LANGFUSE_S3_MEDIA_UPLOAD_ACCESS_KEY_ID=devstoreaccount1
LANGFUSE_S3_MEDIA_UPLOAD_SECRET_ACCESS_KEY=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==
LANGFUSE_S3_MEDIA_UPLOAD_REGION=auto
LANGFUSE_S3_MEDIA_UPLOAD_ENDPOINT=http://localhost:10000/devstoreaccount1
## Necessary for minio compatibility
LANGFUSE_S3_MEDIA_UPLOAD_FORCE_PATH_STYLE=true
LANGFUSE_S3_MEDIA_UPLOAD_PREFIX=media/
# S3 Event Bucket Upload
## Set to true to test uploading all events to S3
LANGFUSE_S3_EVENT_UPLOAD_ENABLED=true
LANGFUSE_S3_EVENT_UPLOAD_BUCKET=langfuse
LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID=devstoreaccount1
LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==
LANGFUSE_S3_EVENT_UPLOAD_REGION=auto
LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT=http://localhost:10000/devstoreaccount1
## Necessary for minio compatibility
LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE=true
LANGFUSE_S3_EVENT_UPLOAD_PREFIX=events/
LANGFUSE_USE_AZURE_BLOB=true
# Set during docker build of application
# Used to disable environment verification at build time
# DOCKER_BUILD=1
REDIS_HOST="127.0.0.1"
REDIS_PORT=6379
REDIS_AUTH="myredissecret"
# openssl rand -hex 32 used only here
ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000
# speeds up local development by not executing init scripts on server startup
NEXT_PUBLIC_LANGFUSE_RUN_NEXT_INIT="false"
LANGFUSE_READ_FROM_POSTGRES_ONLY=false
LANGFUSE_RETURN_FROM_CLICKHOUSE=true
LANGFUSE_READ_DASHBOARDS_FROM_CLICKHOUSE=true
LANGFUSE_READ_FROM_CLICKHOUSE_ONLY=true
LANGFUSE_ASYNC_INGESTION_PROCESSING="true"
LANGFUSE_ASYNC_CLICKHOUSE_INGESTION_PROCESSING="true"
-89
View File
@@ -1,89 +0,0 @@
# When adding additional environment variables, the schema in "/src/env.mjs"
# should be updated accordingly.
# Prisma
# https://www.prisma.io/docs/reference/database-reference/connection-urls#env
DIRECT_URL="postgresql://postgres:postgres@localhost:5432/postgres"
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/postgres"
# Clickhouse
CLICKHOUSE_MIGRATION_URL="clickhouse://localhost:9000"
CLICKHOUSE_URL="http://localhost:8123"
CLICKHOUSE_USER="clickhouse"
CLICKHOUSE_PASSWORD="clickhouse"
CLICKHOUSE_CLUSTER_DISABLED="true"
# Next Auth
# You can generate a new secret on the command line with:
# openssl rand -base64 32
# https://next-auth.js.org/configuration/options#secret
# NEXTAUTH_SECRET=""
NEXTAUTH_URL="http://localhost:3000"
NEXTAUTH_SECRET="secret"
# Langfuse Cloud Environment
NEXT_PUBLIC_LANGFUSE_CLOUD_REGION="DEV"
# Langfuse experimental features
LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES="true"
# Salt for API key hashing
SALT="salt"
# Email
EMAIL_FROM_ADDRESS="" # Defines the email address to use as the from address.
SMTP_CONNECTION_URL="" # Defines the connection url for smtp server.
# S3 storage
S3_ENDPOINT=http://localhost:9090
S3_ACCESS_KEY_ID=minio
S3_SECRET_ACCESS_KEY=miniosecret
S3_BUCKET_NAME=langfuse
S3_REGION=us-east-1
## Necessary for minio compatibility
S3_FORCE_PATH_STYLE=true
# S3 Media Upload LOCAL
LANGFUSE_S3_MEDIA_UPLOAD_ENABLED=true
LANGFUSE_S3_MEDIA_UPLOAD_BUCKET=langfuse
LANGFUSE_S3_MEDIA_UPLOAD_ACCESS_KEY_ID=minio
LANGFUSE_S3_MEDIA_UPLOAD_SECRET_ACCESS_KEY=miniosecret
LANGFUSE_S3_MEDIA_UPLOAD_REGION=us-east-1
LANGFUSE_S3_MEDIA_UPLOAD_ENDPOINT=http://localhost:9090
## Necessary for minio compatibility
LANGFUSE_S3_MEDIA_UPLOAD_FORCE_PATH_STYLE=true
LANGFUSE_S3_MEDIA_UPLOAD_PREFIX=media/
# S3 Event Bucket Upload
## Set to true to test uploading all events to S3
LANGFUSE_S3_EVENT_UPLOAD_ENABLED=true
LANGFUSE_S3_EVENT_UPLOAD_BUCKET=langfuse
LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID=minio
LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY=miniosecret
LANGFUSE_S3_EVENT_UPLOAD_REGION=us-east-1
LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT=http://localhost:9090
## Necessary for minio compatibility
LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE=true
LANGFUSE_S3_EVENT_UPLOAD_PREFIX=events/
# Set during docker build of application
# Used to disable environment verification at build time
# DOCKER_BUILD=1
REDIS_HOST="127.0.0.1"
REDIS_PORT=6379
REDIS_AUTH="myredissecret"
# openssl rand -hex 32 used only here
ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000
# speeds up local development by not executing init scripts on server startup
NEXT_PUBLIC_LANGFUSE_RUN_NEXT_INIT="false"
LANGFUSE_READ_FROM_POSTGRES_ONLY=false
LANGFUSE_RETURN_FROM_CLICKHOUSE=true
LANGFUSE_READ_DASHBOARDS_FROM_CLICKHOUSE=true
LANGFUSE_READ_FROM_CLICKHOUSE_ONLY=true
LANGFUSE_ASYNC_INGESTION_PROCESSING="true"
LANGFUSE_ASYNC_CLICKHOUSE_INGESTION_PROCESSING="true"
-81
View File
@@ -1,81 +0,0 @@
# When adding additional environment variables, the schema in "/src/env.mjs"
# should be updated accordingly.
# Prisma
# https://www.prisma.io/docs/reference/database-reference/connection-urls#env
DIRECT_URL="postgresql://postgres:postgres@localhost:5432/postgres"
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/postgres"
# Clickhouse
CLICKHOUSE_MIGRATION_URL="clickhouse://localhost:9000"
CLICKHOUSE_URL="http://localhost:8123"
CLICKHOUSE_USER="clickhouse"
CLICKHOUSE_PASSWORD="clickhouse"
CLICKHOUSE_CLUSTER_ENABLED="false"
# Next Auth
# You can generate a new secret on the command line with:
# openssl rand -base64 32
# https://next-auth.js.org/configuration/options#secret
# NEXTAUTH_SECRET=""
NEXTAUTH_URL="http://localhost:3000"
NEXTAUTH_SECRET="secret"
# Langfuse Cloud Environment
NEXT_PUBLIC_LANGFUSE_CLOUD_REGION="DEV"
# Langfuse experimental features
LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES="true"
# Salt for API key hashing
SALT="salt"
# Email
EMAIL_FROM_ADDRESS="" # Defines the email address to use as the from address.
SMTP_CONNECTION_URL="" # Defines the connection url for smtp server.
# S3 storage
S3_ENDPOINT=http://localhost:9090
S3_ACCESS_KEY_ID=minio
S3_SECRET_ACCESS_KEY=miniosecret
S3_BUCKET_NAME=langfuse
S3_REGION=us-east-1
## Necessary for minio compatibility
S3_FORCE_PATH_STYLE=true
# # S3 Media Upload LOCAL
LANGFUSE_S3_MEDIA_UPLOAD_ENABLED=true
LANGFUSE_S3_MEDIA_UPLOAD_BUCKET=langfuse
LANGFUSE_S3_MEDIA_UPLOAD_ACCESS_KEY_ID=minio
LANGFUSE_S3_MEDIA_UPLOAD_SECRET_ACCESS_KEY=miniosecret
LANGFUSE_S3_MEDIA_UPLOAD_REGION=us-east-1
LANGFUSE_S3_MEDIA_UPLOAD_ENDPOINT=http://localhost:9090
## Necessary for minio compatibility
LANGFUSE_S3_MEDIA_UPLOAD_FORCE_PATH_STYLE=true
LANGFUSE_S3_MEDIA_UPLOAD_PREFIX=media/
# S3 Event Bucket Upload
## Set to true to test uploading all events to S3
LANGFUSE_S3_EVENT_UPLOAD_ENABLED=true
LANGFUSE_S3_EVENT_UPLOAD_BUCKET=langfuse
LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID=minio
LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY=miniosecret
LANGFUSE_S3_EVENT_UPLOAD_REGION=us-east-1
LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT=http://localhost:9090
## Necessary for minio compatibility
LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE=true
LANGFUSE_S3_EVENT_UPLOAD_PREFIX=events/
# Set during docker build of application
# Used to disable environment verification at build time
# DOCKER_BUILD=1
REDIS_HOST="127.0.0.1"
REDIS_PORT=6379
REDIS_AUTH="myredissecret"
# openssl rand -hex 32 used only here
ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000
# speeds up local development by not executing init scripts on server startup
NEXT_PUBLIC_LANGFUSE_RUN_NEXT_INIT="false"
+28
View File
@@ -0,0 +1,28 @@
# Hanzo Cloud Console — environment.
# Copy to .env.local and adjust. All values are public (NEXT_PUBLIC_*) since the
# console is a browser app that talks to the unified /v1 backend with cookies.
# Unified Hanzo Cloud backend (the casibase /v1 API). Default: production.
# Local backend: http://localhost:14000
NEXT_PUBLIC_CLOUD_URL=https://cloud.hanzo.ai
# Hanzo PaaS (platform.hanzo.ai) — DOKS cluster control plane for the Clusters module.
NEXT_PUBLIC_PLATFORM_URL=https://platform.hanzo.ai
# hanzo.app builder — target of the Templates gallery "Open in builder" deep-link
# (fork a starter → customize by prompt in the builder). Default: production.
NEXT_PUBLIC_APP_URL=https://hanzo.app
# Hanzo IAM (OIDC authority). Canonical issuer is https://hanzo.id — tokens are
# minted with iss=https://hanzo.id, which the cloud /v1 backend validates against.
# iam.hanzo.ai is the legacy zone (iss=https://iam.hanzo.ai) and MUST NOT be used
# by the browser, or sign-in drops on iam.hanzo.ai with an issuer mismatch.
NEXT_PUBLIC_IAM_URL=https://hanzo.id
# IAM application console2 authenticates as. console2 is a front-end of the
# shared Hanzo Cloud /v1 backend, which exchanges the OIDC code and validates the
# token as app `hanzo-cloud` (aud=hanzo-cloud) — so the front-end presents the
# same app/client_id. Must match the cloud-api binding, not a console-only app.
NEXT_PUBLIC_IAM_APP_NAME=hanzo-cloud
NEXT_PUBLIC_IAM_ORG_NAME=hanzo
NEXT_PUBLIC_IAM_CLIENT_ID=hanzo-cloud
-22
View File
@@ -1,22 +0,0 @@
# When adding additional environment variables, the schema in "/src/env.mjs"
# should be updated accordingly.
# Prisma
# https://www.prisma.io/docs/reference/database-reference/connection-urls#env
DIRECT_URL="postgresql://postgres:postgres@db:5432/postgres"
DATABASE_URL="postgresql://postgres:postgres@db:5432/postgres"
# Next Auth
NEXTAUTH_SECRET="secret"
NEXTAUTH_URL="http://localhost:3000"
# feature flag to enable experimental features locally
LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES="false"
SALT="salt"
# Redis
REDIS_HOST="127.0.0.1"
REDIS_PORT=6379
REDIS_AUTH="myredissecret"
# openssl rand -hex 32 used only here
ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000
-258
View File
@@ -1,258 +0,0 @@
# More information: https://langfuse.com/docs/deployment/self-host
# When adding additional environment variables, the schema in "/src/env.mjs"
# should be updated accordingly.
# Prisma
# https://www.prisma.io/docs/reference/database-reference/connection-urls#env
# DATABASE_URL supports pooled connections, but then you need to set DIRECT_URL
DATABASE_URL="postgresql://postgres:postgres@db:5432/postgres"
# DIRECT_URL="postgresql://postgres:postgres@db:5432/postgres"
# SHADOW_DATABASE_URL=
# optional, set to true to disable automated database migrations on Docker start
# LANGFUSE_AUTO_POSTGRES_MIGRATION_DISABLED=
# Next Auth
# NEXTAUTH_URL does not need to be set when deploying on Vercel
NEXTAUTH_URL="http://localhost:3000"
# For each of these, you can generate a new secret on the command line with:
# openssl rand -base64 32
NEXTAUTH_SECRET="secret" # https://next-auth.js.org/configuration/options#secret
SALT="salt" # salt used to hash api keys
# API level encryption for sensitive data
# Must be 256 bits, 64 string characters in hex format, generate via: openssl rand -hex 32
ENCRYPTION_KEY="0000000000000000000000000000000000000000000000000000000000000000"
# Use CSP headers to enforce HTTPS, optional
# LANGFUSE_CSP_ENFORCE_HTTPS="true"
# Configure base path for self-hosting, optional
# Note: You need to build the docker image with the base path set and cannot use the pre-built docker image if you set this.
# NEXT_PUBLIC_BASE_PATH="/app"
# Docker only, optional
# PORT=3000
# HOSTNAME=localhost
# Opentelemetry, optional
OTEL_EXPORTER_OTLP_ENDPOINT="http://localhost:4318"
OTEL_SERVICE_NAME="langfuse"
# Default role for users who sign up, optional, can be org or org+project
# LANGFUSE_DEFAULT_ORG_ID=
# LANGFUSE_DEFAULT_ORG_ROLE=
# LANGFUSE_DEFAULT_PROJECT_ID=
# LANGFUSE_DEFAULT_PROJECT_ROLE=
# Logging, optional
# LANGFUSE_LOG_LEVEL=info
# LANGFUSE_LOG_FORMAT=text
# Enable experimental features, optional
# LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES=true
# Auth, optional configuration
# AUTH_DOMAINS_WITH_SSO_ENFORCEMENT=domain1.com,domain2.com
# AUTH_IGNORE_ACCOUNT_FIELDS=foo,bar
# AUTH_DISABLE_USERNAME_PASSWORD=true
# AUTH_DISABLE_SIGNUP=true
# AUTH_SESSION_MAX_AGE=43200 # 30 days in minutes (default)
# SSO, each group is optional
# AUTH_GOOGLE_CLIENT_ID=
# AUTH_GOOGLE_CLIENT_SECRET=
# AUTH_GOOGLE_ALLOW_ACCOUNT_LINKING=false
# AUTH_GOOGLE_ALLOWED_DOMAINS=langfuse.com,google.com # optional allowlist of workspace domains that can sign in via Google
# AUTH_GITHUB_CLIENT_ID=
# AUTH_GITHUB_CLIENT_SECRET=
# AUTH_GITHUB_ALLOW_ACCOUNT_LINKING=false
# AUTH_GITHUB_ENTERPRISE_CLIENT_ID=
# AUTH_GITHUB_ENTERPRISE_CLIENT_SECRET=
# AUTH_GITHUB_ENTERPRISE_BASE_URL=
# AUTH_GITHUB_ENTERPRISE_ALLOW_ACCOUNT_LINKING=false
# AUTH_GITLAB_CLIENT_ID=
# AUTH_GITLAB_CLIENT_SECRET=
# AUTH_GITLAB_ALLOW_ACCOUNT_LINKING=false
# AUTH_GITLAB_ISSUER=
# AUTH_AZURE_AD_CLIENT_ID=
# AUTH_AZURE_AD_CLIENT_SECRET=
# AUTH_AZURE_AD_TENANT_ID=
# AUTH_AZURE_ALLOW_ACCOUNT_LINKING=false
# AUTH_OKTA_CLIENT_ID=
# AUTH_OKTA_CLIENT_SECRET=
# AUTH_OKTA_ISSUER=
# AUTH_OKTA_ALLOW_ACCOUNT_LINKING=false
# AUTH_AUTH0_CLIENT_ID=
# AUTH_AUTH0_CLIENT_SECRET=
# AUTH_AUTH0_ISSUER=
# AUTH_AUTH0_ALLOW_ACCOUNT_LINKING=false
# AUTH_COGNITO_CLIENT_ID=
# AUTH_COGNITO_CLIENT_SECRET=
# AUTH_COGNITO_ISSUER=
# AUTH_COGNITO_ALLOW_ACCOUNT_LINKING=false
# AUTH_KEYCLOAK_CLIENT_ID=
# AUTH_KEYCLOAK_CLIENT_SECRET=
# AUTH_KEYCLOAK_ISSUER=
# AUTH_KEYCLOAK_ALLOW_ACCOUNT_LINKING=false
# AUTH_CUSTOM_CLIENT_ID=
# AUTH_CUSTOM_CLIENT_SECRET=
# AUTH_CUSTOM_ISSUER=
# AUTH_CUSTOM_NAME=
# AUTH_CUSTOM_SCOPE="openid email profile" # optional
# AUTH_CUSTOM_ALLOW_ACCOUNT_LINKING=false
# AUTH_CUSTOM_ID_TOKEN=false # optional, default is true
# Transactional email, optional
# Defines the email address to use as the from address.
# EMAIL_FROM_ADDRESS=
# Defines the connection url for smtp server.
# SMTP_CONNECTION_URL=
# S3 storage, optional, used for exports from the UI
# S3_ENDPOINT=
# S3_ACCESS_KEY_ID=
# S3_SECRET_ACCESS_KEY=
# S3_BUCKET_NAME=
# S3_REGION=
# BATCH_EXPORT_DOWNLOAD_LINK_EXPIRATION_HOURS=
# S3 storage for events, optional, used to persist all incoming events
# LANGFUSE_S3_EVENT_UPLOAD_ENABLED="true"
# LANGFUSE_S3_EVENT_UPLOAD_BUCKET=
# Optional prefix to be used within the bucket. Must end with `/` if set
# LANGFUSE_S3_EVENT_UPLOAD_PREFIX=events/
# The following four options are optional and fallback to the normal SDK credential provider chain if omitted
# See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
# LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT=
# LANGFUSE_S3_EVENT_UPLOAD_REGION=
# LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID=
# LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY=
# Exports are streamed to S3 in pages to avoid memory issues
# The page size can be adjusted if needed to optimize performance
# DB_EXPORT_PAGE_SIZE=1000
# Automated provisioning of default resources
# LANGFUSE_INIT_ORG_ID=org-id
# LANGFUSE_INIT_ORG_NAME=org-name
# LANGFUSE_INIT_PROJECT_ID=project-id
# LANGFUSE_INIT_PROJECT_NAME=project-name
# LANGFUSE_INIT_PROJECT_PUBLIC_KEY=pk-1234567890
# LANGFUSE_INIT_PROJECT_SECRET_KEY=sk-1234567890
# LANGFUSE_INIT_USER_EMAIL=user@example.com
# LANGFUSE_INIT_USER_NAME=User Name
# LANGFUSE_INIT_USER_PASSWORD=password
### START Enterprise Edition Configuration
# Allowlisted users that can create new organizations, by default all users can create organizations
# LANGFUSE_ALLOWED_ORGANIZATION_CREATORS=user1@langfuse.com,user2@langfuse.com
# UI Customization Options
# LANGFUSE_UI_API_HOST=https://api.example.com
# LANGFUSE_UI_DOCUMENTATION_HREF=https://docs.example.com
# LANGFUSE_UI_SUPPORT_HREF=https://support.example.com
# LANGFUSE_UI_FEEDBACK_HREF=https://feedback.example.com
# LANGFUSE_UI_LOGO_LIGHT_MODE_HREF=https://static.langfuse.com/langfuse-dev/example-logo-light-mode.png
# LANGFUSE_UI_LOGO_DARK_MODE_HREF=https://static.langfuse.com/langfuse-dev/example-logo-dark-mode.png
# LANGFUSE_UI_DEFAULT_MODEL_ADAPTER=Anthropic # OpenAI, Anthropic, Azure
# LANGFUSE_UI_DEFAULT_BASE_URL_OPENAI=https://api.openai.com/v1
# LANGFUSE_UI_DEFAULT_BASE_URL_ANTHROPIC=https://api.anthropic.com
# LANGFUSE_UI_DEFAULT_BASE_URL_AZURE_OPENAI=https://{instanceName}.openai.azure.com/openai/deployments
### END Enterprise Edition Configuration
### START Envs to be deprecated in Langfuse v3.0
# Disable the expensive analytics queries and related features
# LANGFUSE_DISABLE_EXPENSIVE_POSTGRES_QUERIES="true"
### END Envs to be deprecated in Langfuse v3.0
### START Langfuse Cloud Config
# Used for Langfuse Cloud deployments
# Not recommended for self-hosted deployments as these are NOT COVERED BY SEMANTIC VERSIONING
# NEXT_PUBLIC_LANGFUSE_CLOUD_REGION="US"
# NEXTAUTH_COOKIE_DOMAIN=".langfuse.com"
# LANGFUSE_TEAM_SLACK_WEBHOOK=
# LANGFUSE_NEW_USER_SIGNUP_WEBHOOK=
# Posthog (optional for analytics of web ui)
# NEXT_PUBLIC_POSTHOG_HOST=
# NEXT_PUBLIC_POSTHOG_KEY=
# Sentry
# NEXT_PUBLIC_LANGFUSE_TRACING_SAMPLE_RATE
# NEXT_PUBLIC_SENTRY_DSN=
# NEXT_SENTRY_ORG=
# NEXT_SENTRY_PROJECT=
# SENTRY_AUTH_TOKEN=
# SENTRY_CSP_REPORT_URI=
# Cloudflare Turnstile
# NEXT_PUBLIC_TURNSTILE_SITE_KEY=
# TURNSTILE_SECRET_KEY=
# Demo project that users can use to try the platform
# NEXT_PUBLIC_DEMO_ORG_ID=
# NEXT_PUBLIC_DEMO_PROJECT_ID=
# Crisp chat
# NEXT_PUBLIC_CRISP_WEBSITE_ID=
# Admin API
# ADMIN_API_KEY=
# Redis
# REDIS_HOST=
# REDIS_PORT=
# REDIS_AUTH=
# REDIS_CONNECTION_STRING=
# REDIS_ENABLE_AUTO_PIPELINING=
# Cache configuration
# LANGFUSE_CACHE_API_KEY_ENABLED=
# LANGFUSE_CACHE_API_KEY_TTL_SECONDS=
# LANGFUSE_CACHE_PROMPT_ENABLED=
# LANGFUSE_CACHE_PROMPT_TTL_SECONDS=
# Rate limiting
# LANGFUSE_RATE_LIMITS_ENABLED=
# Stripe
# STRIPE_SECRET_KEY=
# STRIPE_WEBHOOK_SIGNING_SECRET=
### END Langfuse Cloud Config
## START Langfuse V3 Ingestion
# Clickhouse
# CLICKHOUSE_MIGRATION_URL=
# CLICKHOUSE_URL=
# CLICKHOUSE_USER=
# CLICKHOUSE_PASSWORD=
# Ingestion
# LANGFUSE_INGESTION_QUEUE_DELAY_MS=
# LANGFUSE_INGESTION_CLICKHOUSE_WRITE_BATCH_SIZE=
# LANGFUSE_INGESTION_CLICKHOUSE_WRITE_INTERVAL_MS=
# LANGFUSE_INGESTION_CLICKHOUSE_MAX_ATTEMPTS=
# LANGFUSE_LEGACY_INGESTION_WORKER_CONCURRENCY=
# LANGFUSE_ASYNC_INGESTION_PROCESSING="true"
# QUEUE_CONSUMER_LEGACY_INGESTION_QUEUE_IS_ENABLED="true"
## END Langfuse V3 Ingestion
-4
View File
@@ -1,4 +0,0 @@
node_modules
**/node_modules
build
coverage
-2
View File
@@ -1,2 +0,0 @@
# Currently inactive
# * @langfuse/maintainers
-11
View File
@@ -1,11 +0,0 @@
body:
- type: textarea
attributes:
label: Describe the feature or potential improvement
description: Please describe the change as clear and concise as possible. Remember to add context as to why you believe this is needed.
validations:
required: true
- type: textarea
attributes:
label: Additional information
description: Add any other information related to the change here. If your idea is related to any issues or discussions, link them here.
-35
View File
@@ -1,35 +0,0 @@
name: 🐞 Bug Report
description: Create a bug report to help us improve
title: "bug: "
labels: ["🐞❔ unconfirmed bug"]
body:
- type: textarea
attributes:
label: Describe the bug
description: A clear and concise description of the bug, as well as what you expected to happen when encountering it.
validations:
required: true
- type: textarea
attributes:
label: To reproduce
description: Describe how to reproduce your bug. Please provide detailed steps, code snippets, reproduction repos etc.
validations:
required: true
- type: textarea
attributes:
label: SDK and container versions
description: If you're experiencing an issue with an integration or SDK, please ensure you're using the latest version. If you're self-hosting Langfuse, check that you're running the most recent version. If updating isn't an option, please provide the specific versions you're currently using.
- type: textarea
attributes:
label: Additional information
description: Add any other information related to the bug here, screenshots if applicable.
- type: dropdown
id: contribute
attributes:
label: Are you interested to contribute a fix for this bug?
description: If this is a confirmed bug, the maintainers are happy to support with guidance and review.
options:
- "No"
- "Yes"
validations:
required: true
-7
View File
@@ -1,7 +0,0 @@
contact_links:
- name: 💡 Feature Request
url: https://github.com/orgs/langfuse/discussions/new?category=ideas
about: Suggest any ideas you have using our discussion forums.
- name: 🤗 Get Help
url: https://github.com/orgs/langfuse/discussions/new?category=support
about: If you cant get something to work the way you expect, open a question in our discussion forums.
-36
View File
@@ -1,36 +0,0 @@
## What does this PR do?
<!-- Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change. -->
Fixes # (issue)
<!-- Please provide a loom video for visual changes to speed up reviews
Loom Video: https://www.loom.com/
-->
## Type of change
<!-- Please delete bullets that are not relevant. -->
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] Chore (refactoring code, technical debt, workflow improvements)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
- [ ] Refactor (does not change functionality, e.g. code style improvements, linting)
- [ ] This change requires a documentation update
## Mandatory Tasks
- [ ] Make sure you have self-reviewed the code. A decent size PR without self-review might be rejected.
## Checklist
<!-- Remove bullet points below that don't apply to you -->
- I haven't read the [contributing guide](https://github.com/langfuse/langfuse/blob/main/CONTRIBUTING.md)
- My code doesn't follow the style guidelines of this project (`npm run prettier`)
- I haven't commented my code, particularly in hard-to-understand areas
- I haven't checked if my PR needs changes to the documentation
- I haven't checked if my changes generate no new warnings (`npm run lint`)
- I haven't added tests that prove my fix is effective or that my feature works
- I haven't checked if new and existing unit tests pass locally with my changes
-48
View File
@@ -1,48 +0,0 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
- package-ecosystem: npm
directory: "/" # Location of package manifests
rebase-strategy: "disabled" # use dependabot-rebase-stale
open-pull-requests-limit: 10
schedule:
interval: "daily"
versioning-strategy: "increase"
commit-message:
prefix: chore
prefix-development: chore
include: scope
ignore:
- dependency-name: "@types/node"
- dependency-name: "@trpc/*"
groups:
prisma:
patterns:
- "prisma"
- "@prisma/client"
next:
patterns:
- "eslint-config-next"
- "next"
lodash:
patterns:
- "lodash"
- "@types/lodash"
express:
patterns:
- "express"
- "@types/express"
observability:
patterns:
- "dd-trace"
- "@opentelemetry/*"
- "@appsignal/opentelemetry-instrumentation-bullmq"
- "@prisma/instrumentation"
- "@sentry/*"
radix-ui:
patterns:
- "@radix-ui/*"
+9
View File
@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="640" viewBox="0 0 1280 640" role="img" aria-label="console2">
<rect width="1280" height="640" fill="#0A0A0A"/>
<svg x="96" y="215" width="210" height="210" viewBox="0 0 67 67"><path d="M22.21 67V44.6369H0V67H22.21Z" fill="#fff"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z" fill="#fff"/><path d="M22.21 0H0V22.3184H22.21V0Z" fill="#fff"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z" fill="#fff"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z" fill="#fff"/></svg>
<text x="378" y="276" font-family="Inter,system-ui,-apple-system,sans-serif" font-size="78" font-weight="800" letter-spacing="-2" fill="#ffffff">console2</text>
<rect x="378" y="338" width="806" height="3" rx="1.5" fill="#ffffff" opacity=".9"/>
<text x="378" y="390" font-family="Inter,system-ui,sans-serif" font-size="24" font-weight="600" fill="#ffffff" opacity=".5">github.com/hanzoai</text>
<text x="1184" y="390" text-anchor="end" font-family="Inter,system-ui,sans-serif" font-size="24" font-weight="600" fill="#ffffff" opacity=".5">hanzo.ai</text>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

-75
View File
@@ -1,75 +0,0 @@
name: WorkflowCall - Deploy to ECS Service
on:
workflow_call:
inputs:
environment:
type: string
description: Deployment environment
required: true
service:
type: string
description: Name of the service to be deployed, e.g. web-ingestion, web, or worker.
required: true
jobs:
ecs-deploy:
runs-on: ubuntu-latest
environment: ${{ inputs.environment }}
steps:
- name: Get app name
uses: winterjung/split@v2
id: split
with:
msg: ${{ inputs.service }}
separator: "-"
- name: Checkout code
uses: actions/checkout@v4
- name: Authenticate with AWS
# GitHub/AWS recommend to use OIDC here: https://github.com/aws-actions/configure-aws-credentials?tab=readme-ov-file#oidc
# Probably more painful to configure, but would remove all long-lived credentials.
uses: aws-actions/configure-aws-credentials@v4
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
- name: Login to AWS ECR
id: login-ecr
uses: aws-actions/amazon-ecr-login@v2
- name: Build, tag, and push Docker image
env:
REGISTRY: ${{ steps.login-ecr.outputs.registry }}
REPOSITORY: ${{ steps.split.outputs._0 }}
IMAGE_TAG: ${{ github.sha }}
run: |
docker build \
-t $REGISTRY/$REPOSITORY:$IMAGE_TAG \
-f ./${{ steps.split.outputs._0 }}/Dockerfile \
--build-arg NEXT_PUBLIC_LANGFUSE_CLOUD_REGION=${{ vars.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION }} \
--build-arg NEXT_LANGFUSE_TRACING_SAMPLE_RATE=${{ vars.NEXT_LANGFUSE_TRACING_SAMPLE_RATE }} \
--build-arg NEXT_PUBLIC_SENTRY_ENVIRONMENT=${{ vars.NEXT_PUBLIC_SENTRY_ENVIRONMENT }} \
--build-arg NEXT_PUBLIC_DEMO_ORG_ID=${{ vars.NEXT_PUBLIC_DEMO_ORG_ID }} \
--build-arg NEXT_PUBLIC_DEMO_PROJECT_ID=${{ vars.NEXT_PUBLIC_DEMO_PROJECT_ID }} \
--build-arg NEXT_PUBLIC_SENTRY_DSN=${{ vars.NEXT_PUBLIC_SENTRY_DSN }} \
--build-arg NEXT_PUBLIC_BUILD_ID=${{ github.sha }} \
--build-arg NEXT_PUBLIC_POSTHOG_KEY=${{ vars.NEXT_PUBLIC_POSTHOG_KEY }} \
--build-arg NEXT_PUBLIC_POSTHOG_HOST=${{ vars.NEXT_PUBLIC_POSTHOG_HOST }} \
--build-arg NEXT_PUBLIC_CRISP_WEBSITE_ID=${{ vars.NEXT_PUBLIC_CRISP_WEBSITE_ID }} \
--build-arg SENTRY_AUTH_TOKEN=${{ secrets.SENTRY_AUTH_TOKEN }} \
--build-arg SENTRY_ORG=${{ vars.SENTRY_ORG }} \
--build-arg SENTRY_PROJECT=${{ vars.SENTRY_PROJECT }} \
.
docker push $REGISTRY/$REPOSITORY:$IMAGE_TAG
- name: Render AWS ECS Task Definition
id: render-task-definition
uses: aws-actions/amazon-ecs-render-task-definition@v1
with:
container-name: ${{ inputs.service }}
image: ${{ steps.login-ecr.outputs.registry }}/${{ steps.split.outputs._0 }}:${{ github.sha }}
task-definition-family: ${{ inputs.environment }}-${{ inputs.service }}
- name: Update AWS ECS Service
uses: aws-actions/amazon-ecs-deploy-task-definition@v2
with:
task-definition: ${{ steps.render-task-definition.outputs.task-definition }}
service: ${{ inputs.environment }}-${{ inputs.service }}
cluster: ${{ inputs.environment }}-cluster
wait-for-service-stability: true
+78
View File
@@ -0,0 +1,78 @@
name: Build Docker Image
# Builds + pushes ghcr.io/hanzoai/console on the self-hosted ARC runner. ONE
# brand-agnostic image serves every brand: console resolves the brand at RUNTIME
# from the request hostname (console.hanzo.ai → hanzo, console.lux.cloud → lux,
# console.zoo.cloud → zoo; src/config/index.ts), and /v1 is same-origin per host.
# So NO NEXT_PUBLIC_* are baked — baking them would pin the image to one brand.
# Tags: SEMVER ONLY (no sha, no :latest) — a `v*` git tag publishes that exact
# version; a main push publishes `v<package.json version>` (bump to release).
#
# Build muscle: RAW `docker buildx build` on the host builder — the canonical
# hanzoai/ci pattern. We deliberately do NOT use docker/setup-buildx-action +
# docker/build-push-action: that pair spins up an EPHEMERAL buildkit container
# that cannot see the host's image cache, so it re-pulled `node:22-alpine` from
# Docker Hub every run and tripped the unauthenticated 429 pull-rate limit (and
# its build-summary artifact upload hit the Actions storage quota). The host
# builder reuses the cached base layer instead — no re-pull, no artifact upload.
# The Dockerfile uses the ECR Public Docker-library mirror for the Node base image
# so a cold runner does not depend on Docker Hub's unauthenticated pull budget.
on:
push:
branches: [main]
tags: ['v*']
workflow_dispatch:
concurrency:
group: docker-image-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
packages: write
jobs:
docker:
runs-on: [hanzo-build-linux-amd64]
steps:
- uses: actions/checkout@v4
- name: resolve semver tag
id: ver
run: |
if [[ "$GITHUB_REF" == refs/tags/v* ]]; then
echo "tag=${GITHUB_REF_NAME}" >> "$GITHUB_OUTPUT"
else
# node is NOT on the ARC runner PATH — resolve the version with grep/sed
# (a missing `node` silently produced the tag `:v` and a 404 deploy).
ver=$(grep -m1 '"version"' package.json | sed -E 's/.*"version"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/')
[ -n "$ver" ] || { echo "could not resolve version from package.json"; exit 1; }
echo "tag=v${ver}" >> "$GITHUB_OUTPUT"
fi
- name: Log in to ghcr.io
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GH_PAT || secrets.GITHUB_TOKEN }}
- name: Ensure base image (reuse host cache)
# No-op on a warm runner (the host builder reuses the cached base). Only a
# cold runner pulls. Use the same ECR Public Docker-library mirror as the
# Dockerfile to avoid Docker Hub's unauthenticated pull-rate limits.
run: |
set -u
base=public.ecr.aws/docker/library/node:24-alpine
if docker image inspect "$base" >/dev/null 2>&1; then
echo "base $base already cached on runner"; exit 0
fi
for i in 1 2 3 4 5; do
if docker pull "$base"; then exit 0; fi
echo "pull failed (attempt $i/5) — backing off"; sleep $((i * 30))
done
echo "could not pull $base after retries"; exit 1
- name: Build & push (host builder — reuses base cache, no artifact upload)
run: |
set -euo pipefail
docker buildx build \
--platform linux/amd64 \
--push \
-t ghcr.io/hanzoai/console:${{ steps.ver.outputs.tag }} \
-f Dockerfile .
-69
View File
@@ -1,69 +0,0 @@
name: CI
on:
pull_request:
branches: ["*"]
push:
branches: ["main", "cloud"]
# You can leverage Vercel Remote Caching with Turbo to speed up your builds
# @link https://turborepo.org/docs/core-concepts/remote-caching#remote-caching-on-vercel-builds
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
jobs:
build-lint:
env:
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/postgres
SHADOW_DATABASE_URL: postgresql://postgres:postgres@localhost:5432/postgres
DIRECT_URL: postgresql://postgres:postgres@localhost:5432/postgres
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v4
- name: Start containers
run: docker compose -f "docker-compose.yml" up -d --build
- name: Setup pnpm
uses: pnpm/action-setup@v2.2.4
- name: Setup Node 18
uses: actions/setup-node@v4
with:
node-version: 18
- name: Get pnpm store directory
id: pnpm-cache
run: |
echo "pnpm_cache_dir=$(pnpm store path)" >> $GITHUB_OUTPUT
- name: Setup pnpm cache
uses: actions/cache@v3
with:
path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Install deps (with cache)
run: pnpm install
# Normally, this would be done as part of the turbo pipeline - however since the Expo app doesn't depend on `@acme/db` it doesn't care.
# TODO: Free for all to find a better solution here.
- name: Deploy db
run: pnpm turbo db:deploy
- name: Generate Prisma Client
run: pnpm turbo db:generate
- name: Build, lint and type-check
run: pnpm turbo build lint type-check
env:
SKIP_ENV_VALIDATION: true
# FIXME: Add this back once we have an Expo SDK supporting React 18.2
# - name: Check workspaces
# run: pnpm manypkg check
-92
View File
@@ -1,92 +0,0 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"
on:
push:
branches: ["main", "production", "v*"]
pull_request:
branches: ["main", "production", "v*"]
schedule:
- cron: "31 13 * * 0"
jobs:
analyze:
name: Analyze (${{ matrix.language }})
# Runner size impacts CodeQL analysis time. To learn more, please see:
# - https://gh.io/recommended-hardware-resources-for-running-codeql
# - https://gh.io/supported-runners-and-hardware-resources
# - https://gh.io/using-larger-runners (GitHub.com only)
# Consider using larger runners or machines with greater resources for possible analysis time improvements.
runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }}
permissions:
# required for all workflows
security-events: write
# required to fetch internal or private CodeQL packs
packages: read
# only required for workflows in private repositories
actions: read
contents: read
strategy:
fail-fast: false
matrix:
include:
- language: javascript-typescript
build-mode: none
# CodeQL supports the following values keywords for 'language': 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'swift'
# Use `c-cpp` to analyze code written in C, C++ or both
# Use 'java-kotlin' to analyze code written in Java, Kotlin or both
# Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both
# To learn more about changing the languages that are analyzed or customizing the build mode for your analysis,
# see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning.
# If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how
# your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages
steps:
- name: Checkout repository
uses: actions/checkout@v4
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
build-mode: ${{ matrix.build-mode }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
# queries: security-extended,security-and-quality
# If the analyze step fails for one of the languages you are analyzing with
# "We were unable to automatically build your code", modify the matrix above
# to set the build mode to "manual" for that language. Then modify this step
# to build your code.
# ️ Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
- if: matrix.build-mode == 'manual'
shell: bash
run: |
echo 'If you are using a "manual" build mode for one or more of the' \
'languages you are analyzing, replace this with the commands to build' \
'your code, for example:'
echo ' make bootstrap'
echo ' make release'
exit 1
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{matrix.language}}"
-27
View File
@@ -1,27 +0,0 @@
---
name: Codespell
on:
push:
branches:
- "main"
tags:
- "v*"
pull_request:
branches:
- "**"
merge_group:
permissions:
contents: read
jobs:
codespell:
name: Check for spelling errors
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Codespell
uses: codespell-project/actions-codespell@v2
@@ -1,18 +0,0 @@
name: Rebase Dependabot stale PRs
on:
push:
branches:
- main
workflow_dispatch:
jobs:
rebase-dependabot:
runs-on: ubuntu-latest
environment: "protected branches"
steps:
- name: "Rebase open Dependabot PR"
uses: orange-buffalo/dependabot-auto-rebase@v1
with:
api-token: ${{ secrets.GH_ACCESS_TOKEN }}
repository: ${{ github.repository }}
-105
View File
@@ -1,105 +0,0 @@
on:
push:
branches:
- main
- production
workflow_dispatch:
inputs:
service:
description: 'Service to be deployed'
type: choice
options:
- all
- web
- web-ingestion
- worker
required: true
environment:
description: 'Environment to deploy to'
type: choice
options:
- staging
- prod-eu
- prod-us
required: true
concurrency:
# Support concurrent `push` and `workflow_dispatch`` actions
group: deploy-${{ github.event_name }}-${{ github.ref }}
cancel-in-progress: true
name: Deploy to ECS
jobs:
affected-services:
runs-on: ubuntu-latest
outputs:
services: ${{ steps.affected-services.outputs.result }}
steps:
- name: Get affected services
id: affected-services
uses: actions/github-script@v7
with:
script: |
if (context.eventName === "workflow_dispatch") {
if (context.payload.inputs.service === "all") {
return `["web", "web-ingestion", "worker"]`
}
return `["${context.payload.inputs.service}"]`
}
if (context.eventName === "push") {
return `["web", "web-ingestion", "worker"]`
}
return "[]"
result-encoding: string
- name: Print services to build
uses: actions/github-script@v7
env:
services: ${{ steps.affected-services.outputs.result }}
with:
result-encoding: string
script: |
console.log('Services', `${process.env.services}` ?? 'n/a');
affected-environments:
runs-on: ubuntu-latest
outputs:
environments: ${{ steps.affected-environments.outputs.result }}
steps:
- name: Get affected environments
id: affected-environments
uses: actions/github-script@v7
with:
script: |
if (context.eventName === "workflow_dispatch") {
return `["${context.payload.inputs.environment}"]`
}
if (context.eventName === "push") {
if (context.ref === "refs/heads/main") {
return `["staging"]`
}
if (context.ref === "refs/heads/production") {
return `["prod-eu", "prod-us"]`
}
}
return "[]"
result-encoding: string
- name: Print environments to build
uses: actions/github-script@v7
env:
environments: ${{ steps.affected-environments.outputs.result }}
with:
result-encoding: string
script: |
console.log('Environments', `${process.env.environments}` ?? 'n/a');
ecs-deploy:
uses: ./.github/workflows/_deploy_ecs_service.yml
needs: [affected-services, affected-environments]
secrets: inherit
strategy:
matrix:
service: ${{ fromJson(needs.affected-services.outputs.services) }}
environment: ${{ fromJson(needs.affected-environments.outputs.environments) }}
with:
service: ${{ matrix.service }}
environment: ${{ matrix.environment }}
-49
View File
@@ -1,49 +0,0 @@
name: License Compliance Check
on:
workflow_dispatch:
push:
branches:
- "main"
merge_group:
pull_request:
branches:
- "main"
jobs:
license_check:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup node
uses: actions/setup-node@v4
with:
node-version: 18
- name: Install license-checker
run: npm install -g license-checker
- name: Install yui-lint
run: npm install yui-lint
- name: Generate license-checker CSV file
run: license-checker --production --csv > npm-license-checker.csv
- name: Check license-checker CSV file without headers
id: license_check_report
uses: pilosus/action-pip-license-checker@v2
with:
external: "npm-license-checker.csv"
external-format: "csv"
external-options: "{:skip-header true}"
fail: "WeakCopyleft,StrongCopyleft,NetworkCopyleft"
fails-only: true
totals: true
verbose: 1
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Echo error
if: failure()
run: echo "::error::${{ steps.license_check_report.outputs.report }}"
- name: Delete license-checker CSV file
run: rm npm-license-checker.csv
-489
View File
@@ -1,489 +0,0 @@
name: CI/CD
on:
workflow_dispatch:
push:
branches:
- "main"
tags:
- "v*"
merge_group:
pull_request:
branches:
- "*"
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
with:
version: 9.5.0
- uses: actions/setup-node@v4
with:
node-version: 20
cache: "pnpm"
cache-dependency-path: "pnpm-lock.yaml"
- name: install dependencies
run: |
pnpm i
- name: Load default env
run: |
cp .env.dev.example .env
- name: lint web
run: pnpm run lint
test-docker-build:
timeout-minutes: 20
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME_READ }}
password: ${{ secrets.DOCKERHUB_TOKEN_READ }}
- name: Set NEXT_PUBLIC_BUILD_ID
run: echo "NEXT_PUBLIC_BUILD_ID=$(git rev-parse --short HEAD)" >> $GITHUB_ENV
- name: Build and run both images from compose
run: |
docker compose -f docker-compose.build.yml up -d
sleep 5 # Wait for PostgreSQL to accept connections
- name: Ensure no unhealthy status
run: |
if docker-compose ps | grep "(unhealthy)"; then
echo "One or more services are unhealthy"
exit 1
else
echo "All services are healthy"
fi
- name: Check worker health
run: |
timeout 10 bash -c 'until curl -f http://localhost:3030/api/health; do sleep 2; done'
- name: Check server health
run: |
timeout 10 bash -c 'until curl -f http://localhost:3000/api/public/health; do sleep 2; done'
tests-web-sync:
timeout-minutes: 20
runs-on: ubuntu-latest
name: tests-web-sync (node${{ matrix.node-version }}, pg${{ matrix.postgres-version }})
strategy:
matrix:
node-version: [20]
postgres-version: [12, 15]
steps:
- name: Set Swap Space
uses: pierotofy/set-swap-space@master
with:
swap-size-gb: 10
- uses: actions/checkout@v4
- name: Install golang-migrate for Clickhouse migrations
run: |
curl -L https://github.com/golang-migrate/migrate/releases/download/v4.18.2/migrate.linux-amd64.tar.gz | tar xvz
sudo mv migrate /usr/bin/migrate
which migrate
- uses: pnpm/action-setup@v3
with:
version: 9.5.0
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME_READ }}
password: ${{ secrets.DOCKERHUB_TOKEN_READ }}
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: "pnpm"
cache-dependency-path: "pnpm-lock.yaml"
- name: install dependencies
run: |
pnpm install
- name: Load default env
run: |
cp .env.dev.example .env
grep -v -e '^S3_BUCKET_NAME=' -e '^REDIS_HOST=' -e '^NEXT_PUBLIC_LANGFUSE_RUN_NEXT_INIT=' .env.dev.legacy.example > .env
- name: Run + migrate
run: |
docker compose -f docker-compose.dev.yml up -d
sleep 5 # Wait for PostgreSQL to accept connections
docker compose ps
env:
POSTGRES_VERSION: ${{ matrix.postgres-version }}
- name: Seed DB
run: |
pnpm run db:migrate
pnpm --filter=shared ch:up
- name: Build
run: pnpm run build
- name: Start Langfuse
run: (pnpm run start&)
env:
LANGFUSE_INIT_ORG_ID: "seed-org-id"
LANGFUSE_INIT_ORG_NAME: "Seed Org"
LANGFUSE_INIT_PROJECT_ID: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a"
LANGFUSE_INIT_PROJECT_NAME: "Seed Project"
LANGFUSE_INIT_PROJECT_PUBLIC_KEY: "pk-lf-1234567890"
LANGFUSE_INIT_PROJECT_SECRET_KEY: "sk-lf-1234567890"
LANGFUSE_INIT_USER_EMAIL: "demo@langfuse.com"
LANGFUSE_INIT_USER_NAME: "Demo User"
LANGFUSE_INIT_USER_PASSWORD: "password"
- name: run test-sync
run: pnpm --filter=web run test-sync
tests-web-async:
timeout-minutes: 20
runs-on: ubuntu-latest
name: tests-web-async (node${{ matrix.node-version }}, pg${{ matrix.postgres-version }}, mode${{ matrix.blob-provider }})
strategy:
matrix:
node-version: [20]
postgres-version: [12, 15]
blob-provider: ["", "-azure"]
steps:
- name: Set Swap Space
uses: pierotofy/set-swap-space@master
with:
swap-size-gb: 10
- uses: actions/checkout@v4
- name: Install golang-migrate for Clickhouse migrations
run: |
curl -L https://github.com/golang-migrate/migrate/releases/download/v4.18.2/migrate.linux-amd64.tar.gz | tar xvz
sudo mv migrate /usr/bin/migrate
which migrate
- uses: pnpm/action-setup@v3
with:
version: 9.5.0
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME_READ }}
password: ${{ secrets.DOCKERHUB_TOKEN_READ }}
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: "pnpm"
cache-dependency-path: "pnpm-lock.yaml"
- name: install dependencies
run: |
pnpm install
- name: Load default env
run: |
cp .env.dev${{ matrix.blob-provider }}.example .env
grep -v -e '^S3_BUCKET_NAME=' -e '^REDIS_HOST=' -e '^NEXT_PUBLIC_LANGFUSE_RUN_NEXT_INIT=' .env.dev${{ matrix.blob-provider }}.example > .env
- name: Run + migrate
run: |
docker compose -f docker-compose.dev${{ matrix.blob-provider }}.yml up -d
sleep 5 # Wait for PostgreSQL to accept connections
docker compose ps
env:
POSTGRES_VERSION: ${{ matrix.postgres-version }}
- name: Seed DB
run: |
pnpm run db:migrate
pnpm --filter=shared ch:up
- name: Build
run: pnpm run build
- name: Start Langfuse
run: (pnpm run start&)
env:
LANGFUSE_INIT_ORG_ID: "seed-org-id"
LANGFUSE_INIT_ORG_NAME: "Seed Org"
LANGFUSE_INIT_PROJECT_ID: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a"
LANGFUSE_INIT_PROJECT_NAME: "Seed Project"
LANGFUSE_INIT_PROJECT_PUBLIC_KEY: "pk-lf-1234567890"
LANGFUSE_INIT_PROJECT_SECRET_KEY: "sk-lf-1234567890"
LANGFUSE_INIT_USER_EMAIL: "demo@langfuse.com"
LANGFUSE_INIT_USER_NAME: "Demo User"
LANGFUSE_INIT_USER_PASSWORD: "password"
- name: run tests
run: pnpm --filter=web run test
tests-worker:
timeout-minutes: 20
runs-on: ubuntu-latest
name: tests-worker (node${{ matrix.node-version }}, pg${{ matrix.postgres-version }}, mode${{ matrix.blob-provider }})
strategy:
matrix:
node-version: [20]
postgres-version: [12, 15]
blob-provider: ["", "-azure"]
steps:
- name: Set Swap Space
uses: pierotofy/set-swap-space@master
with:
swap-size-gb: 10
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
with:
version: 9.5.0
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME_READ }}
password: ${{ secrets.DOCKERHUB_TOKEN_READ }}
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: "pnpm"
cache-dependency-path: "pnpm-lock.yaml"
- name: install dependencies
run: |
pnpm install
- name: Install golang-migrate for Clickhouse migrations
run: |
curl -L https://github.com/golang-migrate/migrate/releases/download/v4.18.2/migrate.linux-amd64.tar.gz | tar xvz
sudo mv migrate /usr/bin/migrate
which migrate
- name: Load default env
run: |
cp .env.dev${{ matrix.blob-provider }}.example .env
cp .env.dev${{ matrix.blob-provider }}.example web/.env
cp .env.dev${{ matrix.blob-provider }}.example worker/.env
- name: Run + migrate
run: |
docker compose -f docker-compose.dev${{ matrix.blob-provider }}.yml up -d
sleep 5 # Wait for PostgreSQL to accept connections
docker compose ps
- name: Ensure no unhealthy status
run: |
if docker compose ps | grep "(unhealthy)"; then
echo "One or more services are unhealthy"
exit 1
else
echo "All services are healthy"
fi
- name: Seed DB
run: |
pnpm run db:migrate
pnpm run db:seed
pnpm run --filter=shared ch:up
- name: Build
run: pnpm --filter=worker... run build
- name: run tests
run: pnpm --filter=worker run test
e2e-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
with:
version: 9.5.0
- uses: actions/setup-node@v4
with:
node-version: 20
cache: "pnpm"
cache-dependency-path: "pnpm-lock.yaml"
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME_READ }}
password: ${{ secrets.DOCKERHUB_TOKEN_READ }}
- name: install dependencies
run: |
pnpm install
- name: Load default env
run: |
cp .env.dev.example .env
cp .env.dev.example web/.env
- name: Run + migrate
run: |
docker compose -f docker-compose.dev.yml up -d
docker compose ps
sleep 5 # Wait for PostgreSQL to accept connections
- name: Seed DB
run: |
pnpm run db:migrate
pnpm run db:seed
- name: Build
run: pnpm run build
- name: Install playwright
run: pnpm --filter=web exec playwright install --with-deps
- name: Run e2e tests
run: pnpm --filter=web run test:e2e
e2e-server-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME_READ }}
password: ${{ secrets.DOCKERHUB_TOKEN_READ }}
- uses: pnpm/action-setup@v3
with:
version: 9.5.0
- uses: actions/setup-node@v4
with:
node-version: 20
cache: "pnpm"
cache-dependency-path: "pnpm-lock.yaml"
- name: install dependencies
run: |
pnpm install
- name: Install golang-migrate for Clickhouse migrations
run: |
curl -L https://github.com/golang-migrate/migrate/releases/download/v4.18.2/migrate.linux-amd64.tar.gz | tar xvz
sudo mv migrate /usr/bin/migrate
which migrate
- name: Load default env
run: |
cp .env.dev.example .env
echo "LANGFUSE_ASYNC_CLICKHOUSE_INGESTION_PROCESSING=true" >> .env
echo "LANGFUSE_ASYNC_INGESTION_PROCESSING=true" >> .env
echo "LANGFUSE_CACHE_API_KEY_ENABLED=true" >> .env
echo "LANGFUSE_CACHE_PROMPT_ENABLED=true" >> .env
- name: Run + migrate
run: |
docker compose -f docker-compose.dev.yml up -d
docker compose ps
sleep 5 # Wait for PostgreSQL to accept connections
- name: Ensure Docker dependencies are healthy
run: |
if docker-compose ps | grep "(unhealthy)"; then
echo "One or more services are unhealthy"
exit 1
else
echo "All services are healthy"
fi
- name: Seed DB
run: |
pnpm run db:migrate
pnpm --filter=shared run ch:up
pnpm run db:seed:examples
- name: Build
run: pnpm run build
- name: Run server
run: (pnpm run start&)
- name: Check worker health
run: |
timeout 10 bash -c 'until curl -f http://localhost:3030/api/health; do sleep 2; done'
- name: Check server health
run: |
timeout 10 bash -c 'until curl -f http://localhost:3000/api/public/health; do sleep 2; done'
- name: Run e2e tests
run: pnpm --filter=web run test:e2e:server
all-ci-passed:
# This allows us to have a branch protection rule for tests and deploys with matrix
runs-on: ubuntu-latest
needs:
[
lint,
tests-web-sync,
tests-worker,
e2e-tests,
test-docker-build,
e2e-server-tests,
tests-web-async,
]
if: always()
steps:
- name: Successful deploy
if: ${{ !(contains(needs.*.result, 'failure')) }}
run: exit 0
working-directory: .
- name: Failing deploy
if: ${{ contains(needs.*.result, 'failure') }}
run: exit 1
working-directory: .
push-docker-image:
needs: all-ci-passed
if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/'))
environment: "protected branches"
runs-on: ubuntu-latest
permissions:
packages: write
contents: read
steps:
- uses: pnpm/action-setup@v3
with:
version: 9.5.0
- name: Setup node
uses: actions/setup-node@v4
with:
node-version: 20
cache-dependency-path: "pnpm-lock.yaml"
- name: Checkout
uses: actions/checkout@v4
- name: Set NEXT_PUBLIC_BUILD_ID
run: echo "NEXT_PUBLIC_BUILD_ID=$(git rev-parse --short HEAD)" >> $GITHUB_ENV
- name: Log in to the GitHub Container registry
uses: docker/login-action@v2
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Log in to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
with:
driver-opts: network=host
- name: Extract metadata (tags, labels) for Docker
id: meta-web
uses: docker/metadata-action@v4
with:
images: |
ghcr.io/langfuse/langfuse # GitHub
langfuse/langfuse # Docker Hub
flavor: |
latest=false
tags: |
type=ref,event=branch
type=ref,event=pr
type=sha
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=semver,pattern={{major}}
type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/tags/v3') }}
- name: Build and push Docker image (web)
uses: docker/build-push-action@v4
with:
context: .
file: ./web/Dockerfile
push: true
tags: ${{ steps.meta-web.outputs.tags }}
labels: ${{ steps.meta-web.outputs.labels }}
platforms: |
linux/amd64
${{ startsWith(github.ref, 'refs/tags/') && 'linux/arm64' || '' }}
- name: Extract metadata (tags, labels) for Docker
id: meta-worker
uses: docker/metadata-action@v4
with:
images: |
ghcr.io/langfuse/langfuse-worker # GitHub
langfuse/langfuse-worker # Docker Hub
tags: |
type=ref,event=branch
type=ref,event=pr
type=sha
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=semver,pattern={{major}}
- name: Build and push Docker image (worker)
uses: docker/build-push-action@v4
with:
context: .
file: ./worker/Dockerfile
push: true
tags: ${{ steps.meta-worker.outputs.tags }}
labels: ${{ steps.meta-worker.outputs.labels }}
platforms: |
linux/amd64
${{ startsWith(github.ref, 'refs/tags/') && 'linux/arm64' || '' }}
-19
View File
@@ -1,19 +0,0 @@
on:
workflow_dispatch:
push:
# Pattern matched against refs/tags
tags:
- "v3.[0-9]+.[0-9]+" # Semantic version tags
jobs:
release:
runs-on: ubuntu-latest
environment: "protected branches"
steps:
- uses: actions/checkout@v4
with:
ref: main # Always checkout main even for tagged releases
fetch-depth: 0
token: ${{ secrets.GH_ACCESS_TOKEN }}
- name: Push to production
run: git push origin +main:production
-46
View File
@@ -1,46 +0,0 @@
name: Snyk Container
on:
pull_request:
branches:
- "**"
push:
branches:
- main
jobs:
snyk:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Build a Docker image
run: docker compose -f docker-compose.build.yml up -d
- name: Run Snyk to check Docker image for vulnerabilities (langfuse-server)
continue-on-error: true
uses: snyk/actions/docker@master
env:
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
with:
image: langfuse-server
args: --file=web/Dockerfile
- name: Upload result to GitHub Code Scanning
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: snyk.sarif
category: web
- name: Run Snyk to check Docker image for vulnerabilities (langfuse-worker)
continue-on-error: true
uses: snyk/actions/docker@master
env:
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
with:
image: langfuse-worker
args: --file=worker/Dockerfile
- name: Upload result to GitHub Code Scanning
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: snyk.sarif
category: worker
+17 -61
View File
@@ -1,66 +1,22 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
node_modules/
.next/
out/
dist/
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# database
/prisma/db.sqlite
/prisma/db.sqlite-journal
# next.js
/.next/
/out/
# build artifacts
*.tsbuildinfo
next-env.d.ts
# production
/build
# env
.env*.local
# idea
.idea
# misc
# editor / os
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# local env files
# do not commit any .env files to git, except for the .env.example file. https://create.t3.gg/en/usage/env-variables#using-environment-variables
.env*
!.env.dev.example
!.env.dev-azure.example
!.env.local.example
!.env.prod.example
!.env.dev.legacy.example
# vercel
.vercel
# typescript
*.tsbuildinfo
/generated/typescript-server
# openapi spec that is copied during build
/public/openapi*.yml
# vscode
.devcontainer
node_modules
**/node_modules
**/dist
**/.next/*
**/.turbo/*
.yarn
.turbo
.vscode/
.idea/
*.log
e2e/screenshots/
e2e-shots/
test-results/
playwright-report/
.claude/
-22
View File
@@ -1,22 +0,0 @@
#!/bin/sh
# Get the current branch
current_branch=$(git rev-parse --abbrev-ref HEAD)
# Define the protected branch
protected_branch="main"
# Check if the current branch is the protected branch
if [ "$current_branch" = "$protected_branch" ]; then
echo "🚨 You are about to commit to the $protected_branch branch. Are you sure? (y/n)"
read -r answer < /dev/tty
if [ "$answer" != "${answer#[Yy]}" ]; then
exit 0 # Commit will proceed
else
echo "Commit to $protected_branch branch has been canceled."
exit 1 # Commit will be blocked
fi
fi
# If not the protected branch, proceed with the commit
exit 0
-22
View File
@@ -1,22 +0,0 @@
#!/bin/sh
# Get the current branch
current_branch=$(git rev-parse --abbrev-ref HEAD)
# Define the protected branch
protected_branch="main"
# Check if the current branch is the protected branch
if [ "$current_branch" = "$protected_branch" ]; then
echo "🚨 You are about to push to the $protected_branch branch. Are you sure? (y/n)"
read -r answer < /dev/tty
if [ "$answer" != "${answer#[Yy]}" ]; then
exit 0 # Push will proceed
else
echo "Push to $protected_branch branch has been canceled."
exit 1 # Push will be blocked
fi
fi
# If not the protected branch, proceed with the push
exit 0
-1
View File
@@ -1 +0,0 @@
public-hoist-pattern[]=*prisma*
-1
View File
@@ -1 +0,0 @@
v20
-10
View File
@@ -1,10 +0,0 @@
{
"recommendations": [
"esbenp.prettier-vscode",
"dbaeumer.vscode-eslint",
"bradlc.vscode-tailwindcss",
"unifiedjs.vscode-mdx",
"yoavbls.pretty-ts-errors",
"Prisma.prisma"
]
}
-28
View File
@@ -1,28 +0,0 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Web and Worker: server side",
"type": "node-terminal",
"request": "launch",
"command": "pnpm run dev"
},
{
"name": "Next.js: debug client-side",
"type": "chrome",
"request": "launch",
"url": "http://localhost:3000"
},
{
"name": "Next.js: debug full stack",
"type": "node-terminal",
"request": "launch",
"command": "npm run dev",
"serverReadyAction": {
"pattern": "- Local:.+(https?://.+)",
"uriFormat": "%s",
"action": "debugWithChrome"
}
}
]
}
-32
View File
@@ -1,32 +0,0 @@
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.rulers": [100],
"editor.tabSize": 2,
"eslint.validate": [
"javascript",
"javascriptreact",
"astro",
"typescript",
"typescriptreact"
],
"eslint.rules.customizations": [{ "rule": "*", "severity": "warn" }],
"typescript.tsdk": "node_modules/typescript/lib",
"prettier.documentSelectors": [
"**/*.{cjs,mjs,ts,tsx,astro,md,mdx,json,yaml,yml}"
],
"prettier.trailingComma": "all",
"mdx.experimentalLanguageServer": true,
"typescript.preferences.importModuleSpecifier": "non-relative",
"docwriter.style": "JSDoc",
"[prisma]": {
"editor.defaultFormatter": "Prisma.prisma"
},
"eslint.lintTask.enable": true,
"eslint.workingDirectories": ["./web", "./worker"]
}
Symlink
+1
View File
@@ -0,0 +1 @@
LLM.md
Symlink
+1
View File
@@ -0,0 +1 @@
LLM.md
-453
View File
@@ -1,453 +0,0 @@
![Langfuse GitHub Banner](https://github.com/langfuse/langfuse/assets/121163007/6035f0f3-d691-4963-b5d0-10cf506e9d42)
# Contributing to Langfuse
First off, thanks for taking the time to contribute! ❤️
The best ways to contribute to Langfuse:
- Submit and vote on [Ideas](https://github.com/orgs/langfuse/discussions/categories/ideas)
- Create and comment on [Issues](https://github.com/langfuse/langfuse/issues)
- Open a PR.
We welcome contributions through GitHub pull requests. This document outlines our conventions regarding development workflow, commit message formatting, contact points, and other resources. Our goal is to simplify the process and ensure that your contributions are easily accepted.
We gratefully welcome improvements to documentation ([docs repo](https://github.com/langfuse/langfuse-docs)), the core application (this repo) and the SDKs ([Python](https://github.com/langfuse/langfuse-python), [JS](https://github.com/langfuse/langfuse-js)).
The maintainers are available on [Discord](https://langfuse.com/discord) in case you have any questions.
> And if you like the project, but just don't have time to contribute code, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about:
>
> - Star the project;
> - Tweet about it;
> - Refer to this project in your project's readme;
> - Submit and vote on [Ideas](https://github.com/orgs/langfuse/discussions/categories/ideas);
> - Create and comment on [Issues](https://github.com/langfuse/langfuse/issues);
> - Mention the project at local meetups and tell your friends/colleagues.
## Making a change
_Before making any significant changes, please [open an issue](https://github.com/langfuse/langfuse/issues)._ Discussing your proposed changes ahead of time will make the contribution process smooth for everyone. Large changes that were not discussed in an issue may be rejected.
Once we've discussed your changes and you've got your code ready, make sure that tests are passing and open your pull request.
A good first step is to search for open [issues](https://github.com/langfuse/langfuse/issues). Issues are labeled, and some good issues to start with are labeled: [good first issue](https://github.com/langfuse/langfuse/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22).
## Project Overview
### Technologies we use
- Application (this repository)
- NextJS 14, pages router
- NextAuth.js / Auth.js
- tRPC: Frontend APIs
- Prisma ORM
- Zod
- Tailwind CSS
- shadcn/ui tailwind components (using Radix and tanstack)
- Fern: generate OpenAPI spec and Pydantic models
- JS SDK ([langfuse/langfuse-js](https://github.com/langfuse/langfuse-js))
- openapi-typescript to generated types based on OpenAPI spec
- Python SDK ([langfuse/langfuse-python](https://github.com/langfuse/langfuse-python))
- Pydantic for input validation, models generated by fern
### Architecture Overview
**Langfuse v2**
```mermaid
flowchart TB
subgraph s4["Clients"]
subgraph s2["langfuse/langfuse-python"]
Python["Python low-level SDK"]
Decorator["observe() decorator"] -->|extends| Python
OAI["OpenAI drop-in replacement"] -->|extends| Python
Llamaindex["LlamaIndex Integration"] -->|extends| Python
LCPYTHON["Langchain Python Integration"] -->|extends| Python
Langflow -->|uses| LCPYTHON
LiteLLM -->|uses| Python
end
subgraph s3["langfuse/langfuse-js"]
JS["JS SDK"]
LCJS["Langchain JS Integration"] -->|extends| JS
Flowise -->|uses| LCJS
end
end
DB[Postgres Database]
Redis[Redis]
subgraph s1["Application (langfuse/langfuse/web)"]
API[Public HTTP API]
G[TRPC API]
I[NextAuth]
H[React Frontend]
Prisma[Prisma ORM]
H --> G
H --> I
G --> I
G --- Prisma
API --- Prisma
I --- Prisma
end
Prisma --- DB
JS --- API
Python --- API
```
**Langfuse v3 (work in progress, not released yet)**
> [!NOTE]
> Infrastructure will change in Langfuse version 3.0. More in the [GitHub Discussions](https://github.com/orgs/langfuse/discussions/1902).
> `langfuse/langfuse/worker` is under active development and not recommended for production use in Langfuse 2.x.
```mermaid
flowchart TB
subgraph s4["Clients"]
subgraph s2["langfuse/langfuse-python"]
Python["Python low-level SDK"]
Decorator["observe() decorator"] -->|extends| Python
OAI["OpenAI drop-in replacement"] -->|extends| Python
Llamaindex["LlamaIndex Integration"] -->|extends| Python
LCPYTHON["Langchain Python Integration"] -->|extends| Python
Langflow -->|uses| LCPYTHON
LiteLLM -->|uses| Python
end
subgraph s3["langfuse/langfuse-js"]
JS["JS SDK"]
LCJS["Langchain JS Integration"] -->|extends| JS
Flowise -->|uses| LCJS
end
end
DB[Postgres Database]
Redis[Redis Cache/Queue]
Clickhouse[Clickhouse Database]
subgraph s1["Application (langfuse/langfuse/web)"]
API[Public HTTP API]
G[TRPC API]
I[NextAuth]
H[React Frontend]
ORM
H --> G
H --> I
G --> I
G --- ORM
API --- ORM
I --- ORM
end
subgraph s5["Application (langfuse/langfuse/worker)"]
Worker
end
Worker --- DB
Worker --- Redis
Worker --- Clickhouse
ORM --- DB
ORM --- Redis
ORM --- Clickhouse
JS --- API
Python --- API
```
### Network Overview
> [!NOTE]
> This will change in Langfuse version 3.0. More in the [GitHub Discussions](https://github.com/orgs/langfuse/discussions/1902).
```mermaid
flowchart LR
Browser ---|Web UI & TRPC API| App
Integrations/SDKs ---|Public HTTP API| App
subgraph i1["Application Network"]
App["Langfuse Application"]
end
subgraph i2["Database Network"]
DB["Postgres Database"]
end
App --- DB
```
### Database Overview
The diagram below may not show all relationships if the foreign key is not defined in the database schema. For instance, `trace_id` in the `observation` table is not defined as a foreign key to the `trace` table to allow unordered ingestion of these objects, but it is still a foreign key in the application code.
Full database schema: [packages/shared/prisma/schema.prisma](packages/shared/prisma/schema.prisma)
<img src="./packages/shared/prisma/database.svg">
## Repository Structure
We built a monorepo using [pnpm](https://pnpm.io/motivation) and [turbo](https://turbo.build/repo/docs) to manage the dependencies and build process. The monorepo contains the following packages:
- `web`: is the main application package providing Frontend and Backend APIs for Langfuse.
- `worker` (no production yet): contains an application for asynchronous processing of tasks. This package is not yet used in production.
- `packages`:
- `shared`: contains shared code between the above packages.
- `config-eslint`: contains eslint configurations which are shared between the above packages.
- `config-typescript`: contains typescript configurations which are shared between the above packages.
- `ee`: contains all enterprise features. See [EE README](ee/README.md) for more details.
## Development Setup
Requirements
- Node.js 20 as specified in the [.nvmrc](.nvmrc)
- Pnpm v.9.5.0
- Docker to run the database locally
**Note:** You can also simply run Langfuse in a **GitHub Codespace** via the provided devcontainer. To do this, click on the green "Code" button in the top right corner of the repository and select "Open with Codespaces".
**Steps**
1. Fork the repository and clone it locally
2. Run the development database
```bash
pnpm run infra:dev:up
```
3. Create an env file
```bash
cp .env.dev.example .env
```
4. Install dependencies
```bash
pnpm install
```
5. Run the migrations
All database migrations and configs are in the `shared` package.
```bash
pnpm --filter=shared run db:migrate
# Optional: seed the database
# pnpm run db:seed
# pnpm run db:seed:examples
# pnpm --filter=shared run db:seed:load
```
6. Start the development server
```bash
pnpm run dev
```
7. Open the web app in the browser:
http://localhost:3000
8. Log in as a test user (after you ran `db:seed` command):
Username: demo@langfuse.com
Password: password
## Monorepo quickstart
- Available packages and their dependencies
Packages are included in the monorepo according to the `pnpm-workspace.yaml` file. Each package maintains its own dependencies defined in the `package.json`. Internal dependencies can be added as well by adding them to the package dependencies: `"@langfuse/shared": "workspace:*"`.
- Executing commands
You can run commands in all packages at once. For example, to install all dependencies in all packages, you can execute:
```bash
pnpm install
pnpm run dev
pnpm --filter=web run dev # execute command only in one package
```
In the root `package.json`, you can find scripts which are executed with turbo e.g. `turbo run dev`. These scripts are executed with the help of Turbo. Turbo executes the commands in all packages taking care of the correct order of execution. Task definitions can be found in the `turbo.config.js` file.
- Run migrations
To run migrations, you can execute the following command.
```bash
pnpm run db:migrate -- --name <name of the migration>
```
> [!NOTE]
> If you frequently switch branches, use `pnpm run dx` instead of `pnpm run dev`. This command will install dependencies, reset the database (wipe and apply all migrations), and run the database seeder with example data before starting the development server.
> [!NOTE]
> If you find yourself stuck and want to clean the repo, execute `pnpm run nuke`. It will remove all node_modules and build files.
## System behavior
### Ingestion API `(/public/api/ingestion)`
- the ingestion API takes different event types (creation and updates of traces, generations, spans, events)
- The API loops through each event and:
- validates the event
- stores the event raw in the events table
- calculates tokens for `generations`
- matches models from the `models` table to model for `generations` events
- upserts the event in the `traces` or `observations` table
- returns a `207` HTTP status code with a list of errors if any event failed to be ingested
## Commit messages
On the main branch, we adhere to the best practices of [conventional commits](https://www.conventionalcommits.org/en/v1.0.0/). All pull requests and branches are squash-merged to maintain a clean and readable history. This approach ensures the addition of a conventional commit message when merging contributions.
## Test the public API
The API is tested using Jest. With the development server running, you can run the tests with:
Run all
```bash
npm run test
```
Run interactively in watch mode
```bash
npm run test:watch
```
These tests are also run in CI.
## CI/CD
We use GitHub Actions for CI/CD, the configuration is in [`.github/workflows/pipeline.yml`](.github/workflows/pipeline.yml)
CI on `main` and `pull_request`
- Check Linting
- E2E test of API using Jest
- E2E tests of UI using Playwright
CD on `main`
- Publish Docker image to GitHub Packages if CI passes. Done on every push to `main` branch. Only released versions are tagged with `latest`.
## Staging environment
We run a staging environment at [https://staging.langfuse.com](https://staging.langfuse.com) that is automatically deployed on every push to `main` branch.
The same environment is also used for preview deployments of pull requests. Limitations:
- SSO is not available as dynamic domains are not supported by most SSO providers.
- When making changes to the database, migrations to the staging database need to be applied manually by a maintainer. If you want to interactively test database changes in the staging environment, please reach out.
You can use the staging environment end-to-end with the Langfuse integrations or SDKs (host: `https://staging.langfuse.com`). However, please note that the staging environment is not intended for production use and may be reset at any time.
## Production environment
When a new release is tagged on the `main` branch (excluding prereleases), it triggers a production deployment. The deployment process consists of two steps:
1. The Docker image is published to GitHub Packages with the version number and `latest` tag.
2. The deployment is carried out on Langfuse Cloud. This is done by force pushing the `main` branch to the `production` branch during every release, using the [`release.yml`](.github/workflows/release.yml) GitHub Action.
## Theming
At Langfuse, we utilize CSS variables to manage our theme settings across the platform.
Our approach leverages separate CSS variables for backgrounds (--background) and foregrounds (--foreground), fully adhering to the [shadcn/ui](https://ui.shadcn.com/docs/theming) color conventions. The background suffix can be omitted if the variable is used for the background color of the component. We recommend using HSL values for these colors to enhance consistency and customization. There is no need to manually handle dark mode styling with "dark:" prefixes, as next-themes automatically manages the theme switching.
Given the following CSS variables:
```
--primary: 222.2 47.4% 11.2%; // e.g. background-color
--primary-foreground: 210 40% 98%; // e.g. text-color
```
The background color of the following component will be `hsl(var(--primary))` and the foreground color will be `hsl(var(--primary-foreground))`.
```
<div class="bg-primary text-primary-foreground">Hello</div>
```
### Color Variables
| Variable | Description | Examples |
| ------------------------ | ------------------------------------------------------------------ | -------------------------------- |
| --background | Background color | Default background color of body |
| --foreground | Foreground color | Default text color of body |
| --muted | Muted background color | TabsList, Skeleton and Switch |
| --muted-foreground | Muted foreground color | |
| --popover | Popover background color | DropdownMenu, HoverCard, Popover |
| --popover-foreground | Popover foreground color | |
| --card | Card background color | Card |
| --card-foreground | Card foreground color | |
| --border | Border color | Default border color |
| --input | Input field border color | Input, Select, Textarea |
| --primary | Primary button background colors | Button variant="primary" |
| --primary-foreground | Primary button foreground color | |
| --secondary | Secondary button background color | Button variant="secondary" |
| --secondary-foreground | Secondary button foreground color | |
| --accent | Used for accents such as hover effects | DropdownMenuItem, SelectItem |
| --accent-foreground | Used for texts on hover effects | DropdownMenuItem, SelectItem |
| --destructive | Destructive action color for background | Button variant="destructive" |
| --destructive-foreground | Destructive action color for text | |
| --ring | Focus ring color | MultiSelect |
| --primary-accent | Primary accent color used for branding | Layout |
| --hover-primary-accent | Primary accent color used for hover effects for links | SignIn and AuthCloudRegionSwitch |
| --muted-green | Muted green for Event label | ObservationTree |
| --muted-orange | Muted orange for Generation label | ObservationTree |
| --muted-blue | Muted blue for Span label | ObservationTree |
| --muted-gray | Muted gray for disabled status badges | StatusBadge |
| --accent-light-green | Light green accent for background of output and assistant messages | IOPreview, Generations, Traces |
| --accent-dark-green | Dark green accent for border of output and assistant messages | CodeJsonViewer and IOPReview |
| --light-red | Light red for error background | level-color and StatusBadge |
| --dark-red | Dark red for error text and error badge dot color | level-color and ErrorPage |
| --light-yellow | Light yellow for warning background | LevelColor |
| --dark-yellow | Dark yellow for warning text | LevelColor |
| --light-green | Light green for success status badge background | StatusBadge |
| --dark-green | Dark green for success status badge text and dot | StatusBadge |
| --light-blue | Light blue for background of Staging label | LangfuseLogo |
| --dark-blue | Dark blue for text and border of Staging label | LangfuseLogo |
| --accent-light-blue | Light blue accent for table link hover effect | TableLink |
| --accent-dark-blue | Dark blue accent for table link text | TableLink |
### Adding New Colors
1. Global Definitions: Add new CSS variable definitions in the global.css file.
2. Tailwind Configuration: Reflect these new colors in the tailwind.config.js to maintain alignment with Tailwind's utility classes.
By following these guidelines, you can ensure that any contributions to our theme are consistent, maintainable, and aligned with our design system.
## Maintainers
### Using secrets stored in 1Password
When applying changes to non-local environments, you may need to use secrets stored in 1Password. We use the 1Password CLI for this purpose.
Example:
```bash
op run --env-file="./.env" -- pnpm --filter=shared run db:deploy
```
### Editing default models and prices
You can update the default AI models and prices by adding or updating an entry in `worker/src/constants/default-model-prices.json`.
Please note that
- prices are in USD
- the list is ordered by ID, so make sure to keep this order
- the `updated_at` field must be updated with the current date in ISO 8601 format. Otherwise, the change will be ignored.
### Transition period until V3 release
Until the V3 release, both the JSON record must be updated **and** a migration must be created to continue supporting self-hosted users. Note that the migration must updated both the `models` as well as the `prices` table accordingly.
## License
Langfuse is MIT licensed, except for `ee/` folder. See [LICENSE](LICENSE) and [docs](https://langfuse.com/docs/open-source) for more details.
When contributing to the Langfuse codebase, you need to agree to the [Contributor License Agreement](https://cla-assistant.io/langfuse/langfuse). You only need to do this once and the CLA bot will remind you if you haven't signed it yet.
+38
View File
@@ -0,0 +1,38 @@
# console2 — Hanzo Cloud Console (Next.js 15 + @hanzo/gui). BSD-3-Clause.
# NEXT_PUBLIC_* are inlined at build time (browser config), so they are build args.
FROM public.ecr.aws/docker/library/node:24-alpine AS build
WORKDIR /app
# Copy ALL source FIRST, then install — order matters under Kaniko --single-snapshot:
# a `COPY` that FOLLOWS `RUN npm install` in the same stage drops the RUN's freshly
# created node_modules (the 'next not found' cause — the install's own `test -f next`
# passed, then `COPY . .` wiped node_modules before the build RUN). Putting COPY
# before install means node_modules is created by the LAST RUNs and nothing clobbers
# it. (Layer-cache for deps is moot here — the on-cluster build runs --cache=false.)
COPY . .
# public/ may be empty (git doesn't track empty dirs) — ensure it exists for the runner COPY.
RUN mkdir -p public
# npm install (not ci): @hanzo/gui pulls a react-native dep tree whose platform/
# optional packages resolve differently across npm versions, so a lockfile generated
# by one npm fails `npm ci` under another. install reconciles the tree for the
# build platform; retry-hardened against registry throttling.
RUN npm install --no-audit --no-fund --fetch-retries=5 --fetch-retry-mintimeout=20000 --fetch-timeout=120000
# ONE brand-agnostic image: brand (IAM org/issuer/app + wordmark) is resolved at
# RUNTIME from the request hostname (src/config/index.ts), and /v1 is same-origin
# per host. Baking NEXT_PUBLIC_* here would inline a single brand and break that.
# Next 15 + @hanzo/gui (large RN dep tree) overflows Node's default heap → OOMKill
# (exit 137); cap the heap generously (chat uses 4096).
ENV NEXT_TELEMETRY_DISABLED=1 NODE_OPTIONS=--max-old-space-size=6144
RUN npm run build
FROM public.ecr.aws/docker/library/node:24-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production NEXT_TELEMETRY_DISABLED=1 PORT=4000
RUN addgroup -S app && adduser -S app -G app
COPY --from=build /app/.next ./.next
COPY --from=build /app/public ./public
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/package.json ./package.json
COPY --from=build /app/next.config.mjs ./next.config.mjs
USER app
EXPOSE 4000
CMD ["node", "node_modules/next/dist/bin/next", "start", "-p", "4000"]
+37 -20
View File
@@ -1,25 +1,42 @@
Copyright (c) 2023--2024 Langfuse GmbH
BSD 3-Clause License
Portions of this software are licensed as follows:
Copyright (c) 2026-present, Hanzo AI, Inc.
- All content that resides under the "ee/" and/or "web/src/ee" directories of this repository, if these directories exist, is licensed under the license defined in "ee/LICENSE".
- All third party components incorporated into the Finto Technologies Software are licensed under the original license provided by the owner of the applicable component.
- Content outside of the above mentioned directories or restrictions above is available under the "MIT Expat" license as defined below.
Portions of this software are derived from upstream code originally licensed under
the MIT License, with the following copyright notices retained per its terms:
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
Copyright (c) 2020 Nate Wienert
Copyright (c) 2015-present, Nicolas Gallagher.
Copyright (c) 2015-present, Facebook, Inc.
Copyright (c) 2021 Radix
Copyright (c) 2017 Carmelo Pullara
Copyright (c) 2018 Framer B.V.
Copyright (c) 2022 WorkOS
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
All rights reserved.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
+2021
View File
File diff suppressed because it is too large Load Diff
+41
View File
@@ -0,0 +1,41 @@
Hanzo Cloud Console (console2)
Copyright (c) Hanzo AI, Inc. Licensed BSD-3-Clause (see LICENSE).
------------------------------------------------------------------------
Third-party attribution
------------------------------------------------------------------------
Observe surface — Langfuse (MIT License)
The console's Observe screens (Traces, Trace detail with the span-tree /
latency-waterfall, Observations, Sessions, Scores, Score Configs, Datasets,
Dataset Items, Dataset Runs / Experiments, and the observability Dashboards /
Metrics) reproduce the SCREEN LAYOUT AND USER FLOWS of Langfuse's observability
product.
This is a clean-room reimplementation in our own code (React + @hanzo/gui),
wired to the native Hanzo Cloud /v1/evals contract. No Langfuse source code is
copied. Only the MIT-licensed layout/flow concepts inform the design; the
Langfuse EE / commercial ("ee") code is neither used nor referenced.
Langfuse — https://github.com/langfuse/langfuse
Copyright (c) Langfuse GmbH
Licensed under the MIT License.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+34 -176
View File
@@ -1,193 +1,51 @@
![Langfuse GitHub Banner](https://github.com/langfuse/langfuse/assets/121163007/6035f0f3-d691-4963-b5d0-10cf506e9d42)
<p align="center"><img src=".github/hero.svg" alt="console2" width="880"></p>
<div align="center"><h1>Langfuse: Open Source LLM Engineering Platform</h1></div>
<div align="center"><h4>LLM Observability, Prompt Management, LLM Evaluations,<br/>Datasets, LLM Metrics, and Prompt Playground</h4></div>
# Hanzo Cloud Console
<div align="center">
<div>
<h3>
<a href="https://cloud.langfuse.com">
<strong>Sign up</strong>
</a> ·
<a href="https://langfuse.com/docs/deployment/self-host">
<strong>Self Host</strong>
</a> ·
<a href="https://langfuse.com/demo">
<strong>Demo (live data)</strong>
</a>
</h3>
</div>
<div>
<a href="https://langfuse.com/docs"><strong>Docs</strong></a> ·
<a href="https://langfuse.com/issues"><strong>Report Bug</strong></a> ·
<a href="https://langfuse.com/ideas"><strong>Feature Request</strong></a> ·
<a href="https://langfuse.com/changelog"><strong>Changelog</strong></a> ·
<a href="https://langfuse.com/roadmap"><strong>Roadmap</strong></a> ·
<a href="https://langfuse.com/discord"><strong>Discord</strong></a>
</div>
<span>Langfuse uses <a href="https://github.com/orgs/langfuse/discussions"><strong>Github Discussions</strong></a> for Support and Feature Requests.</span>
<br/>
<span>We're hiring. <a href="https://langfuse.com/careers"><strong>Join us</strong></a> in Product Engineering and Developer Relations.</span>
<br/>
<br/>
<div>
<a href="https://github.com/langfuse/langfuse/blob/main/LICENSE"><img src="https://img.shields.io/badge/License-MIT-red.svg?style=flat-square" alt="MIT License"></a>
<a href="https://www.ycombinator.com/companies/langfuse"><img src="https://img.shields.io/badge/Y%20Combinator-W23-orange?style=flat-square" alt="Y Combinator W23"></a>
<a href="https://github.com/langfuse/langfuse/pkgs/container/langfuse"><img alt="Docker Image" src="https://img.shields.io/badge/docker-langfuse-blue?logo=Docker&logoColor=white&style=flat-square"></a>
<a href="https://pypi.python.org/pypi/langfuse"><img src="https://img.shields.io/pypi/dm/langfuse?style=flat-square&logo=python&logoColor=white&label=pypi%20langfuse&color=blue" alt="langfuse Python package on PyPi"></a>
<a href="https://www.npmjs.com/package/langfuse"><img src="https://img.shields.io/npm/dm/langfuse?style=flat-square&logo=npm&logoColor=white&label=npm%20langfuse&color=blue" alt="langfuse npm package"></a>
</div>
</div>
</br>
Unified admin console for **Hanzo Cloud** and all Hanzo cloud products. Built on
[@hanzo/gui](https://gui.hanzo.ai) (cross-platform UI) over the unified `/v1`
backend (`hanzoai/cloud`). Dark theme, OIDC sign-in via Hanzo IAM.
## Langfuse Overview
Manages: **Providers · Models · Applications · Stores · Chat** — with an
extensible product-module registry so every cloud product can be added as a
module.
_Unmute video for voice-over_
https://github.com/langfuse/langfuse/assets/2834609/a94062e9-c782-4ee9-af59-dee6370149a8
### Develop
- **LLM Observability:** Instrument your app and start ingesting traces to Langfuse ([Quickstart](https://langfuse.com/docs/get-started), [Integrations](https://langfuse.com/docs/integrations) [Tracing](https://langfuse.com/docs/tracing))
- **Langfuse UI:** Inspect and debug complex logs ([Demo](https://langfuse.com/docs/demo), [Tracing](https://langfuse.com/docs/tracing))
- **Prompt Management:** Manage, version and deploy prompts from within Langfuse ([Prompt Management](https://langfuse.com/docs/prompts/get-started))
- **Prompt Engineering:** Test and iterate on your prompts with the [LLM Playground](https://langfuse.com/docs/playground)
### Monitor
- **LLM Analytics:** Track metrics (cost, latency, quality) and gain insights from dashboards & data exports ([Analytics](https://langfuse.com/docs/analytics))
- **LLM Evaluations:** Collect and calculate scores for your LLM completions ([Scores & Evaluations](https://langfuse.com/docs/scores))
- Run ([Model-based evaluations](https://langfuse.com/docs/scores/model-based-evals)) and LLM-as-a-Judge within Langfuse
- Collect user feedback ([User Feedback](https://langfuse.com/docs/scores/user-feedback))
- Manually score LLM outputs in Langfuse ([Manual Scores](https://langfuse.com/docs/scores/manually))
### Test
- **Experiments:** Track and test app behaviour before deploying a new version
- Datasets let you test expected in and output pairs and benchmark performance before deploying ([Datasets](https://langfuse.com/docs/datasets))
- Track versions and releases in your application ([Experimentation](https://langfuse.com/docs/experimentation), [Prompt Management](https://langfuse.com/docs/prompts))
## Get started
### Langfuse Cloud
Managed deployment by the Langfuse team, generous free-tier (hobby plan), no credit card required.
**[» Langfuse Cloud](https://cloud.langfuse.com)**
## Self-Hosting Open Source LLM Observability with Langfuse
### Localhost (docker)
## Quick start
```bash
# Clone repository
git clone https://github.com/langfuse/langfuse.git
cd langfuse
# Run server and database
docker compose up -d
npm install
cp .env.example .env.local
# set NEXT_PUBLIC_IAM_CLIENT_ID for live sign-in; defaults point at production.
npm run dev # http://localhost:4000
```
[→ Learn more about deploying locally](https://langfuse.com/docs/deployment/local)
## Scripts
### Self-host (docker)
| Script | What |
| --- | --- |
| `npm run dev` | Dev server on :4000 |
| `npm run build` | Production build (type-checks; Gui CSS injected at runtime) |
| `npm run start` | Serve the production build |
| `npm run typecheck` | `tsc --noEmit` (strict) |
Langfuse is simple to self-host and keep updated. It currently requires only a single docker container and a postgres database.
[→ Self Hosting Instructions](https://langfuse.com/docs/deployment/self-host)
## Configuration
Templated deployments: [Railway, GCP, AWS, Azure, Kubernetes and others](https://langfuse.com/docs/deployment/self-host#platform-specific-information)
All config is `NEXT_PUBLIC_*` (browser app, cookie auth). See `.env.example`.
## Get Started
| Var | Default | Meaning |
| --- | --- | --- |
| `NEXT_PUBLIC_CLOUD_URL` | `https://cloud.hanzo.ai` | Unified `/v1` backend base URL |
| `NEXT_PUBLIC_IAM_URL` | `https://iam.hanzo.ai` | Hanzo IAM OIDC authority |
| `NEXT_PUBLIC_IAM_APP_NAME` | `hanzo-console` | IAM application (`<org>-<app>`) |
| `NEXT_PUBLIC_IAM_ORG_NAME` | `hanzo` | IAM organization |
| `NEXT_PUBLIC_IAM_CLIENT_ID` | — | OAuth client id |
### API Keys
## Architecture
You need a Langfuse public and secret key to get started. Sign up [here](https://cloud.langfuse.com) and find them in your project settings.
### Ingesting Data · Instrumenting Your Application · LLM Observability with Langfuse
Note: We recommend using our fully async, typed [SDKs](https://langfuse.com/docs/sdk) that allow you to instrument any LLM application with any underlying model. They are available in [Python (Decorators)](https://langfuse.com/docs/sdk/python) & [JS/TS](https://langfuse.com/docs/sdk/typescript). The SDKs will always be the most fully featured and stable way to ingest data into Langfuse.
See the [→ Quickstart](https://langfuse.com/docs/get-started) to integrate Langfuse.
### LLM Observability Integrations
| Integration | Supports | Description |
| ---------------------------------------------------------------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| [SDK](https://langfuse.com/docs/sdk) | Python, JS/TS | Manual instrumentation using the SDKs for full flexibility. |
| [OpenAI](https://langfuse.com/docs/integrations/openai) | Python, JS/TS | Automated instrumentation using drop-in replacement of OpenAI SDK. |
| [Langchain](https://langfuse.com/docs/integrations/langchain) | Python, JS/TS | Automated instrumentation by passing callback handler to Langchain application. |
| [LlamaIndex](https://langfuse.com/docs/integrations/llama-index/get-started) | Python | Automated instrumentation via LlamaIndex callback system. |
| [Haystack](https://langfuse.com/docs/integrations/haystack) | Python | Automated instrumentation via Haystack content tracing system. |
| [LiteLLM](https://langfuse.com/docs/integrations/litellm) | Python, JS/TS (proxy only) | Use any LLM as a drop in replacement for GPT. Use Azure, OpenAI, Cohere, Anthropic, Ollama, VLLM, Sagemaker, HuggingFace, Replicate (100+ LLMs). |
| [Vercel AI SDK](https://langfuse.com/docs/integrations/vercel-ai-sdk) | JS/TS | TypeScript toolkit designed to help developers build AI-powered applications with React, Next.js, Vue, Svelte, Node.js. |
| [API](https://langfuse.com/docs/api) | | Directly call the public API. OpenAPI spec available. |
Packages integrated with Langfuse:
| Name | Description |
| --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| [Instructor](https://langfuse.com/docs/integrations/instructor) | Library to get structured LLM outputs (JSON, Pydantic) |
| [Dify](https://langfuse.com/docs/integrations/dify) | Open source LLM app development platform with no-code builder. |
| [Ollama](https://langfuse.com/docs/integrations/ollama) | Easily run open source LLMs on your own machine. |
| [Mirascope](https://langfuse.com/docs/integrations/mirascope) | Python toolkit for building LLM applications. |
| [Flowise](https://langfuse.com/docs/integrations/flowise) | JS/TS no-code builder for customized LLM flows. |
| [Langflow](https://langfuse.com/docs/integrations/langflow) | Python-based UI for LangChain, designed with react-flow to provide an effortless way to experiment and prototype flows. |
## Questions and feedback
### Ideas and roadmap
- [Roadmap](https://langfuse.com/roadmap)
- [GitHub Discussions](https://github.com/orgs/langfuse/discussions)
- [Feature Requests](https://langfuse.com/ideas)
### Support and feedback
In order of preference the best way to communicate with us:
- [GitHub Discussions](https://github.com/orgs/langfuse/discussions) (preferred): Contribute [ideas](https://langfuse.com/ideas), [support requests](https://langfuse.com/gh-support) and [report bugs](https://langfuse.com/issues)
- [Discord](https://langfuse.com/discord): community support
- Privately: contact at langfuse dot com
## Contributing to Langfuse
- Vote on [Ideas](https://github.com/orgs/langfuse/discussions/categories/ideas)
- Raise and comment on [Issues](https://github.com/langfuse/langfuse/issues)
- Open a PR - see [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to setup a development environment.
See [LLM.md](./LLM.md) for the full design (base choice, /v1 client, auth flow,
the product-module registry, and the Providers surface). Endpoint reference in
[docs/endpoints.md](./docs/endpoints.md).
## License
This repository is MIT licensed, except for the `ee` folders. See [LICENSE](LICENSE) and [docs](https://langfuse.com/docs/open-source) for more details.
## Misc
### GET API to export your data
[**GET routes**](https://langfuse.com/docs/integrations/api) to use data in downstream applications (e.g. embedded analytics). You can also access them conveniently via the SDKs ([docs](https://langfuse.com/docs/query-traces)).
### Security & Privacy
We take data security and privacy seriously. Please refer to our [Security and Privacy](https://langfuse.com/security) page for more information.
### Telemetry
By default, Langfuse automatically reports basic usage statistics of self-hosted instances to a centralized server (PostHog).
This helps us to:
1. Understand how Langfuse is used and improve the most relevant features.
2. Track overall usage for internal and external (e.g. fundraising) reporting.
None of the data is shared with third parties and does not include any sensitive information. We want to be super transparent about this and you can find the exact data we collect [here](/web/src/features/telemetry/index.ts).
You can opt-out by setting `TELEMETRY_ENABLED=false`.
### Star History
<a href="https://star-history.com/#langfuse/langfuse&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=langfuse/langfuse&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=langfuse/langfuse&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=langfuse/langfuse&type=Date" />
</picture>
</a>
BSD-3-Clause. Copyright (c) 2026-present, Hanzo AI, Inc.
-4
View File
@@ -1,4 +0,0 @@
## Security Policy
We strongly recommend using the latest version of Langfuse to receive all security updates.
For more information, please refer to the [Data Security & Privacy](https://langfuse.com/docs/data-security-privacy) page in the documentation or contact security@langfuse.com.
+69
View File
@@ -0,0 +1,69 @@
'use client'
import { use } from 'react'
import { notFound } from 'next/navigation'
import { resolveView, isAdminRoute } from '~/lib/products/match'
import { findEntry } from '~/lib/products/registry'
import { useIsGlobalAdmin } from '~/lib/auth/admin'
import { ProductSubpageStub } from '~/components/products/ProductSubpageStub'
import { ProductSubpageModule } from '~/components/products/subpage/ProductSubpageModule'
import { AdminManagedNotice } from '~/components/products/AdminManagedNotice'
import { ProductErrorBoundary } from '~/components/errors/ProductErrorBoundary'
/**
* Catch-all product route. Resolves the module + route from the registry and
* renders its component. Adding a product anywhere in the registry makes its
* routes live here — no per-product page files.
*
* Two honest gates on top of the resolver:
* - A known product SUB-PAGE (a declared specific or a uniform base sub-page:
* Overview · Settings · Status · Logs · Metrics) with no backend route yet
* renders a placeholder stub — never a 404, never a fabricated surface.
* - A CUSTOMER (non-global-admin) reaching an admin-only surface (cross-tenant
* IAM/KMS, provider + routing config) gets a graceful "managed by Hanzo" notice
* instead of the module's hostile 403 red error. Access is enforced
* server-side regardless.
*
* The resolved module renders inside `ProductErrorBoundary`: modules mount
* client-only (the authed shell renders a loader during SSR), so a throw in one
* module's first render had no boundary and white-screened the whole console
* ("Application error: a client-side exception") on a direct load / refresh. The
* boundary keeps the shell + nav and shows an honest, retryable card instead —
* one place, every product route (DRY).
*/
export default function ProductPage({ params }: { params: Promise<{ slug: string[] }> }) {
const { slug } = use(params)
const showAdmin = useIsGlobalAdmin()
const view = resolveView(slug)
if (view.kind === 'notfound') notFound()
if (!showAdmin && isAdminRoute(slug)) {
const entry = findEntry(slug[0])
if (entry && entry.kind === 'module') {
const seg = slug[1]
const subpage = seg ? (entry.subpages ?? []).find((s) => s.slug === seg && s.admin) : undefined
return <AdminManagedNotice entry={entry} subpage={subpage} />
}
}
if (view.kind === 'stub') return <ProductSubpageStub entry={view.entry} subpage={view.subpage} />
// A uniform base sub-page (Status/Logs/Metrics/Settings) → the shared per-product
// sub-page system (real feed or honest state), inside the same error boundary so
// a data fetch that throws shows the retryable card, never a white screen.
if (view.kind === 'subpage')
return (
<ProductErrorBoundary resetKey={slug.join('/')}>
<ProductSubpageModule entry={view.entry} subpage={view.subpage} />
</ProductErrorBoundary>
)
const Component = view.matched.route.component
return (
<ProductErrorBoundary resetKey={slug.join('/')}>
<Component params={view.matched.params} />
</ProductErrorBoundary>
)
}
+15
View File
@@ -0,0 +1,15 @@
'use client'
import { use } from 'react'
import { ProductInterstitial } from '~/components/products/ProductInterstitial'
/**
* Product discover screen — `/discover/<id>` renders the interstitial for one
* catalog entry (docs, OSS source, revenue share, open/get-started). A dedicated
* route (more specific than the `[...slug]` product catch-all) so it's shareable.
*/
export default function DiscoverPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = use(params)
return <ProductInterstitial id={id} />
}
+75
View File
@@ -0,0 +1,75 @@
'use client'
/**
* Dashboard route error backstop (Next App Router).
*
* `ProductErrorBoundary` catches throws inside a resolved product module; this
* catches anything above it in the dashboard page tree (the resolver itself, a
* non-catch-all dashboard page). It renders in the layout's content slot, so the
* shell + nav stay mounted — never a white-screened "Application error". Next's
* `reset()` re-renders the segment; `notFound()`/`redirect()` are control flow and
* do not reach here.
*/
import { useEffect } from 'react'
import { Button, Card, Text, XStack, YStack } from '@hanzo/gui'
import { RefreshCw, TriangleAlert } from '@hanzogui/lucide-icons-2'
import { isChunkLoadError, shouldReloadForChunk } from '~/components/errors/boundary-logic'
/** Shared once-per-window guard key (same as ProductErrorBoundary — never double-reload). */
const RELOAD_AT_KEY = 'hz.console.chunkReloadAt'
export default function DashboardError({ error, reset }: { error: Error & { digest?: string }; reset: () => void }) {
const chunk = isChunkLoadError(error)
useEffect(() => {
console.error('[console] dashboard route error:', error)
// A chunk skew self-heals: reload ONCE per window to pull the fresh HTML +
// current chunks (same recovery the product boundary does), so a stale-deploy
// crash at the segment level auto-recovers instead of stranding a manual card.
if (!chunk || typeof window === 'undefined') return
try {
const raw = window.sessionStorage.getItem(RELOAD_AT_KEY)
const last = raw ? Number(raw) : null
if (shouldReloadForChunk(Date.now(), last)) {
window.sessionStorage.setItem(RELOAD_AT_KEY, String(Date.now()))
window.location.reload()
}
} catch {
/* sessionStorage blocked (private mode) — fall through to the manual card */
}
}, [error, chunk])
return (
<YStack p="$4">
<Card borderWidth={1} borderColor="$borderColor" p="$4" gap="$3" maxWidth={640} bg="$color1">
<XStack gap="$2" items="center">
<TriangleAlert size={16} />
<Text fontSize="$4" fontWeight="700">
{chunk ? 'Updating to the latest version' : 'This page hit an unexpected error'}
</Text>
</XStack>
<Text fontSize="$3" color="$color11">
{chunk
? 'A newer version of the console just shipped. Reload to load the latest.'
: 'The rest of the console still works. Try again, or reload the page.'}
</Text>
<XStack gap="$2">
{!chunk ? (
<Button size="$2" icon={<RefreshCw size={14} />} onPress={() => reset()}>
Try again
</Button>
) : null}
<Button
size="$2"
chromeless={!chunk}
icon={<RefreshCw size={14} />}
onPress={() => { if (typeof window !== 'undefined') window.location.reload() }}
>
Reload
</Button>
</XStack>
</Card>
</YStack>
)
}
+39
View File
@@ -0,0 +1,39 @@
import type { ReactNode } from 'react'
import { AuthGate } from '~/components/AuthGate'
import { OrgGate } from '~/components/OrgGate'
import { DashboardShell } from '~/components/DashboardShell'
import { PreferencesProvider } from '~/lib/products/preferences'
import { ScopeProvider } from '~/lib/scope-context'
import { ToastProvider } from '~/components/ui/Toast'
import { CommandPaletteProvider } from '~/components/CommandPalette'
import { AppLauncherProvider } from '~/components/AppLauncher'
import { DetailPaneProvider } from '~/components/DetailPane'
import { FloatingChatProvider } from '~/components/FloatingChat'
export default function DashboardLayout({ children }: { children: ReactNode }) {
return (
<AuthGate>
<OrgGate>
<ScopeProvider>
<PreferencesProvider>
<ToastProvider>
{/* AppLauncher wraps the palette so the palette can open the launcher. */}
<AppLauncherProvider>
<CommandPaletteProvider>
{/* FloatingChat floats the assistant bubble over every page. */}
<FloatingChatProvider>
{/* DetailPane hosts the ONE right-side item detail/edit pane. */}
<DetailPaneProvider>
<DashboardShell>{children}</DashboardShell>
</DetailPaneProvider>
</FloatingChatProvider>
</CommandPaletteProvider>
</AppLauncherProvider>
</ToastProvider>
</PreferencesProvider>
</ScopeProvider>
</OrgGate>
</AuthGate>
)
}
+198
View File
@@ -0,0 +1,198 @@
'use client'
/**
* Product catalog — the unified console home. Every Hanzo product, grouped by the
* ten canonical categories, with its Google Cloud equivalent. Every product is
* open-for-all: each card opens straight into its native in-console surface and
* carries a "Learn more" affordance to its docs — there is no enablement gate and
* no external bounce. Each card can be pinned to the sidebar (persisted to the
* account). Rendered entirely from the catalog registry.
*/
import { useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { Button, Card, Spinner, Text, XStack, YStack } from '@hanzo/gui'
import { Star, Lock, ArrowRight, BookOpen, KeyRound } from '@hanzogui/lucide-icons-2'
import { config } from '~/config'
import { visibleCatalogByCategory, categorySlug, type CatalogEntry } from '~/lib/products/registry'
import { openProduct } from '~/lib/products/open'
import { useFavorites } from '~/lib/products/favorites'
import { useIsGlobalAdmin } from '~/lib/auth/admin'
import { PageHeader } from '~/components/ui/PageHeader'
import { PrimaryButton } from '~/components/ui/PrimaryButton'
import { FadeIn } from '~/components/ui/FadeIn'
import { livingOverviewModule } from '~/components/products/overview/living/LivingOverviewModule'
// The home centerpiece is the reusable LivingOverview (count-up KPIs, live
// sparklines, streaming activity) — the SAME component every product overview uses.
const OverviewDashboard = livingOverviewModule('overview')
function ProductCard({
entry,
pinned,
onOpen,
onToggle,
onLearnMore,
}: {
entry: CatalogEntry
pinned: boolean
onOpen: () => void
onToggle: () => void
onLearnMore: () => void
}) {
const Icon = entry.icon
return (
<Card borderWidth={1} borderColor="$borderColor" p="$4" gap="$3" width={272}>
<XStack justify="space-between" items="flex-start">
<XStack gap="$2" items="center" flex={1}>
<Icon size={20} />
<YStack flex={1}>
<Text fontSize="$5" fontWeight="700">
{entry.label}
</Text>
{entry.gcp ? (
<Text fontSize="$1" color="$color10">
{entry.gcp}
</Text>
) : null}
</YStack>
</XStack>
<XStack gap="$1" items="center">
{entry.admin ? <Lock size={13} opacity={0.45} /> : null}
<Button
size="$2"
chromeless
opacity={pinned ? 1 : 0.3}
icon={<Star size={15} />}
onPress={onToggle}
aria-label={pinned ? `Unpin ${entry.label}` : `Pin ${entry.label}`}
/>
</XStack>
</XStack>
<Text fontSize="$3" color="$color11" minH={40}>
{entry.description}
</Text>
<XStack justify="space-between" items="center">
<Button
size="$2"
chromeless
icon={<BookOpen size={14} />}
onPress={onLearnMore}
aria-label={`Learn more about ${entry.label}`}
>
Learn more
</Button>
<Button
size="$2"
bg="$color5"
borderWidth={1}
borderColor="$borderColor"
onPress={onOpen}
iconAfter={<ArrowRight size={14} />}
>
Open
</Button>
</XStack>
</Card>
)
}
/**
* Prominent, always-visible "Get API key" call-to-action at the top of the home.
* A cold customer must reach "New key" in one obvious click from landing — the
* api-keys page is otherwise buried in the collapsed Dev nav group. Routes to the
* real ApiKeysModule (`/api-keys`), where the `hk-` key is created/copied/rotated.
*/
function GetApiKeyCta({ onOpen }: { onOpen: () => void }) {
return (
<Card borderWidth={1} borderColor="$borderColor" bg="$color2" p="$4">
<XStack items="center" justify="space-between" gap="$4" flexWrap="wrap">
<XStack items="center" gap="$3" flex={1} minW={240}>
<YStack bg="$color5" rounded="$4" p="$2.5" items="center" justify="center">
<KeyRound size={20} />
</YStack>
<YStack flex={1} minW={180}>
<Text fontSize="$5" fontWeight="800">
Get your API key
</Text>
<Text fontSize="$3" color="$color11">
Call {config.brandName} models from your apps, SDKs, and CLI with a personal key.
</Text>
</YStack>
</XStack>
<PrimaryButton size="$4" iconAfter={<ArrowRight size={16} />} onPress={onOpen}>
Get API key
</PrimaryButton>
</XStack>
</Card>
)
}
export default function DashboardHome() {
const router = useRouter()
const { toggle, isPinned } = useFavorites()
const showAdmin = useIsGlobalAdmin()
const push = (path: string) => router.push(path)
const groups = visibleCatalogByCategory(showAdmin)
// Billing-only shell (billing.<brand> / NEXT_PUBLIC_BILLING_ONLY): the default
// route IS the Billing Center — redirect the catalog home to the billing overview
// so people who only ever see billing.hanzo.ai land straight on billing.
useEffect(() => {
if (config.billingOnly) router.replace('/billing')
}, [router])
if (config.billingOnly) {
return (
<XStack flex={1} justify="center" items="center" p="$8">
<Spinner size="large" color="$color11" />
</XStack>
)
}
return (
<YStack gap="$7">
<GetApiKeyCta onOpen={() => push('/api-keys')} />
<OverviewDashboard params={{}} />
<YStack gap="$4">
<PageHeader
title="Explore products"
subtitle={`Open and manage every ${config.brandName} product from one place.`}
/>
{groups.map((group, i) => (
<FadeIn key={group.category} index={i} style={{ width: '100%' }}>
<YStack gap="$3">
<XStack
self="flex-start"
items="center"
gap="$2"
cursor="pointer"
hoverStyle={{ opacity: 0.75 }}
onPress={() => push(`/category/${categorySlug(group.category)}`)}
aria-label={`${group.category} overview`}
>
<Text fontSize="$5" fontWeight="800" color="$color12">
{group.category}
</Text>
<ArrowRight size={16} opacity={0.5} />
</XStack>
<XStack flexWrap="wrap" gap="$3">
{group.entries.map((entry) => (
<ProductCard
key={entry.id}
entry={entry}
pinned={isPinned(entry.id)}
onOpen={() => openProduct(entry, push)}
onToggle={() => toggle(entry.id)}
onLearnMore={() => push(`/discover/${entry.id}`)}
/>
))}
</XStack>
</YStack>
</FadeIn>
))}
</YStack>
</YStack>
)
}
+106
View File
@@ -0,0 +1,106 @@
/**
* Server-gated GLOBAL admin aggregate proxy — the cross-tenant business/platform
* reads (`/v1/admin/{overview,usage,orgs,audit,products,finance,compute,providers}`)
* AND the few GLOBAL-admin mutations that ride the same god-view gate
* (`POST /v1/admin/providers/{toggle,primary}` — flip shared-gateway provider
* routing that affects every org).
*
* The admin business board is an ALL-ORGS god view (`?org=all`) over IAM + commerce
* + o11y. So — unlike the per-tenant `/cloud` proxy, which authorizes on the bearer
* `owner` claim and is safe for any authenticated user — this MUST be gated to a
* GLOBAL admin BEFORE anything is forwarded: a tenant customer (even one who is
* `isAdmin` of their own org) must NOT read another org's revenue/spend/customers,
* must NOT trigger the `org=all` aggregate at all, and must NOT flip a shared
* provider's enabled/primary state.
*
* Defense in depth (RED H1 — the cloud-side gate for `/v1/admin/*` is a separate
* backend contract we cannot see or test from this repo): `getAdminGate` enforces the
* SAME policy the IAM/KMS admin proxies use — a VERIFIED `@<brand.adminDomain>` email
* AND an IAM global-admin flag, fail-closed (→ 403) on any miss. Only then does the
* shared `forwardWithUserBearer` mint a short-lived user bearer and forward to
* cloud-api, applying the usual path-traversal + same-origin-CSRF hardening. On a
* mutating method (POST), that CSRF gate (Sec-Fetch-Site ≠ cross-site AND Origin/
* Referer host == Host, fail-closed 403 BEFORE resolving the user) means a
* cross-site page can never flip a provider on the victim admin's behalf. The
* browser holds no cloud credential and cannot reach this endpoint without passing
* the gate; the client-side `admin: true` nav gate + `AdminManagedNotice` is UI-only
* defense-in-depth, never the boundary.
*
* Least privilege: only the admin aggregate heads are reachable, NOT `iam`/`kms`
* (those keep their own gated proxies with their own tenant-scoping semantics) — this
* is not a general cloud-api tunnel. `allowAdminSurface` admits `v1/admin/<head>[/...]`
* (the exact forwarded upstream shape), so `providers` covers the GET list and the
* `providers/{toggle,primary}` POSTs and nothing else. `next.config.mjs` rewrites
* `/v1/admin/<head>[/...]` here for BOTH GET and POST (dropping the `/v1/` into the
* internal Next route path); this handler re-adds `v1/` for the upstream cloud call,
* and the client calls the clean same-origin `/v1/admin/*` form (unchanged).
*/
import { type NextRequest, NextResponse } from 'next/server'
import { getAdminGate } from '~/lib/server/identity'
import { forwardWithUserBearer } from '~/lib/server/bearer-proxy'
import { allowAdminSurface } from '~/lib/server/admin-aggregate'
export const runtime = 'nodejs'
const trim = (s: string) => s.replace(/\/+$/, '')
/** The unified cloud backend (hanzoai/cloud). In-cluster ClusterIP — public egress is CF-403'd.
* `|| default` (not `??`) so an env reconciled to an EMPTY string still resolves the service. */
const CLOUD_API_URL = trim(process.env.CLOUD_API_URL?.trim() || 'http://cloud-api.hanzo.svc.cluster.local:8000')
const forbidden = () => NextResponse.json({ status: 'error', msg: 'forbidden' }, { status: 403 })
type Ctx = { params: Promise<{ path: string[] }> }
async function handle(req: NextRequest, ctx: Ctx): Promise<NextResponse> {
// AUTHORIZE FIRST — global-admin only, fail-closed. A non-global-admin (tenant
// customer, org-level isAdmin) gets a 403 and never triggers the org=all aggregate.
const gate = await getAdminGate(req)
if (!gate) return forbidden()
// The rewrite feeds the tail after `/v1/admin/` (e.g. `overview`, `audit`); rebuild
// the FULL cloud path, which is `/v1/admin/<head>` — cloud serves every admin route
// under `/v1/admin/*` (the beego `/v1/*` glob in hanzoai/ai + cloud's own
// `clients/admin` `app.Get("/v1/admin/…")`), and `forwardWithUserBearer` forwards to
// `target/path` VERBATIM (no `/v1` prepend), so the `v1/` MUST be part of the path
// here or the request lands on a non-existent bare `/admin/*` and 404s. The rewrite
// destination (`app/admin/aggregate/<head>`) is the internal Next route, not the
// upstream — it deliberately carries no `v1/`; this handler adds it.
// `forwardWithUserBearer` re-validates the exact forwarded path via `allow`
// (`allowAdminSurface`, keyed on the `v1/admin/<head>` shape) + `pathIsClean`.
const path = `v1/admin/${(await ctx.params).path.join('/')}`.replace(/\/+$/, '')
return forwardWithUserBearer(req, {
target: CLOUD_API_URL,
path,
allow: allowAdminSurface,
// The AdminApi client unwraps the casibase `{status,msg,data}` envelope, so this
// proxy's own 401/404 must speak the same shape (an honest state, never a throw).
errorShape: 'casibase',
unauthorizedMessage: 'Sign in as an administrator.',
})
}
export async function GET(req: NextRequest, ctx: Ctx) {
return handle(req, ctx)
}
/**
* POST — the GLOBAL-admin mutations that ride the same god-view gate
* (`/v1/admin/providers/{toggle,primary}`). Identical path through `getAdminGate`
* (fail-closed 403) → `forwardWithUserBearer`, which applies the same-origin CSRF
* check to this mutating method BEFORE resolving the user, streams the JSON body
* through, and re-validates the path against `allowAdminSurface` (so a POST can only
* ever reach an allowed head — never `iam`/`kms`, never a traversal).
*/
export async function POST(req: NextRequest, ctx: Ctx) {
return handle(req, ctx)
}
/**
* PUT — the GLOBAL-admin enablement set (`PUT /v1/admin/enablement`, flip an item
* off|beta|ga + grant orgs). Same gate + same CSRF/traversal hardening as POST;
* `allowAdminSurface` admits only `v1/admin/enablement`, nothing else.
*/
export async function PUT(req: NextRequest, ctx: Ctx) {
return handle(req, ctx)
}
+85
View File
@@ -0,0 +1,85 @@
/**
* Server-gated GLOBAL IAM admin proxy — cross-tenant IAM ops (any org).
*
* The browser holds no IAM credential. It calls this SAME-ORIGIN route with just
* its session cookie; the handler enforces the GLOBAL admin gate (`getAdminGate`:
* verified @<adminDomain> email AND a global-admin flag), then the shared
* `forwardIam` applies the allow-list + tenant scoping (a global admin may act on
* any org) and forwards to IAM as the user. A CUSTOMER managing their OWN org uses
* `/org/iam` instead — this route is global-only.
*
* Least privilege: only an explicit allow-list of admin segments is reachable
* (GET reads / POST mutations); every owner the request references — including
* the mutation BODY owner — is validated by `forwardIam`.
*/
import { type NextRequest, NextResponse } from 'next/server'
import { getAdminGate } from '~/lib/server/identity'
import { forwardIam } from '~/lib/server/iam-proxy'
export const runtime = 'nodejs'
/** Read segments — reachable via GET only. */
const GET_SEGMENTS = new Set([
'get-organizations',
'get-organization',
'get-users',
'get-user',
'get-applications',
'get-application',
'get-providers',
'get-provider',
'get-roles',
'get-records',
])
/** Mutation segments — reachable via POST only (JSON body forwarded). */
const POST_SEGMENTS = new Set([
'add-user',
'update-user',
'delete-user',
'add-application',
'update-application',
'delete-application',
'add-provider',
'update-provider',
'delete-provider',
'add-role',
'update-role',
'delete-role',
])
/**
* Organization objects are owned by IAM's built-in `admin`, and the org
* list/get endpoints scope results to the caller's org server-side — so `admin`
* is an acceptable owner THERE (never for tenant data like users/roles).
*/
const ORG_ENDPOINTS = new Set(['get-organizations', 'get-organization'])
const forbidden = () => NextResponse.json({ error: 'forbidden' }, { status: 403 })
async function handle(req: NextRequest, path: string[], method: 'GET' | 'POST'): Promise<NextResponse> {
const gate = await getAdminGate(req)
if (!gate) return forbidden()
return forwardIam(
req,
{ user: gate.user, isGlobalAdmin: gate.user.isGlobalAdmin, orgScope: gate.orgScope },
{
segment: path.join('/'),
method,
allowed: method === 'GET' ? GET_SEGMENTS : POST_SEGMENTS,
orgMetaSegments: ORG_ENDPOINTS,
// The gate is already global-only; global admins may write to any org.
requireAdminForWrite: false,
},
)
}
type Ctx = { params: Promise<{ path: string[] }> }
export async function GET(req: NextRequest, ctx: Ctx) {
return handle(req, (await ctx.params).path, 'GET')
}
export async function POST(req: NextRequest, ctx: Ctx) {
return handle(req, (await ctx.params).path, 'POST')
}
+144
View File
@@ -0,0 +1,144 @@
/**
* Server-gated KMS admin proxy — the ONLY way the browser reaches Hanzo KMS.
*
* Same trust boundary as the IAM proxy: the browser sends only its session
* cookie, this handler enforces the brand-admin gate, then forwards to kmsd as
* the user (short-lived user-bound bearer) so KMS enforces org isolation from the
* verified `owner` claim (`canActOnOrg`). Secrets are scoped to the brand org by
* default; a global admin may target another org with `?org=`.
*
* Zero-knowledge discipline: this route NEVER logs a secret value or any request
* body, and never derives or stores key material — it is a faithful pass-through
* of kmsd's JSON + status code. One resource path (`/admin/kms/secrets`); the
* verb + query select the operation:
* GET ?path=&name=&env= → reveal one value → GET .../secrets/<path>/<name>?env=
* GET ?prefix=&env= → list metadata → GET .../secrets?prefix=&env=
* POST {path,name,env,value} → create/upsert → POST .../secrets
* PATCH ?path=&name= {value,version,env} → rotate → PATCH .../secrets/<path>/<name>
* DELETE ?path=&name=&env= → delete → DELETE .../secrets/<path>/<name>?env=
*
* kmsd has no list endpoint yet — the list GET returns 404, which the KMS module
* renders as an honest "listing requires kmsd ≥ next release" state.
*/
import { type NextRequest, NextResponse } from 'next/server'
import { getAdminGate, adminBearer, kmsBaseUrl, type AdminGate } from '~/lib/server/identity'
import { orgFor as policyOrgFor } from '~/lib/server/admin-policy'
import { csrfRefusal } from '~/lib/server/bearer-proxy'
import { fetchWithTimeout } from '~/lib/server/fetch-timeout'
export const runtime = 'nodejs'
const forbidden = () => NextResponse.json({ error: 'forbidden' }, { status: 403 })
const notFound = () => NextResponse.json({ error: 'not found' }, { status: 404 })
/** `<path>/<name>` for the kmsd route, each segment encoded, slashes preserved. */
function secretRest(path: string, name: string): string {
return [...path.split('/').filter(Boolean), name].map(encodeURIComponent).join('/')
}
/** Org the operator acts on — the brand org, unless a global admin passes ?org=
* (the pure `admin-policy` predicate, tested in admin-policy.test.ts). */
function orgFor(gate: AdminGate, req: NextRequest): string {
return policyOrgFor(
{ isGlobalAdmin: gate.user.isGlobalAdmin, orgScope: gate.orgScope },
req.nextUrl.searchParams.get('org'),
)
}
async function handle(req: NextRequest, segments: string[]): Promise<NextResponse> {
// CSRF: a cross-site page carrying the admin's auto-sent cookie must never be able
// to create / rotate / delete a KMS secret. Refuse a cross-origin MUTATION before
// the admin gate or any body read (safe GET reveals pass). Defense in depth on top
// of the session cookie's own SameSite attribute.
const csrf = csrfRefusal(req)
if (csrf) return csrf
const gate = await getAdminGate(req)
if (!gate) return forbidden()
if (segments.length !== 1 || segments[0] !== 'secrets') return notFound()
const org = orgFor(gate, req)
const base = `${kmsBaseUrl()}/v1/kms/orgs/${encodeURIComponent(org)}/secrets`
const q = req.nextUrl.searchParams
const name = q.get('name') ?? ''
const path = q.get('path') ?? ''
const env = q.get('env') ?? ''
let target: string
let body: string | undefined
if (req.method === 'GET') {
if (name) {
const params = new URLSearchParams()
if (env) params.set('env', env)
target = `${base}/${secretRest(path, name)}${params.toString() ? `?${params}` : ''}`
} else {
const params = new URLSearchParams()
const prefix = q.get('prefix')
if (prefix) params.set('prefix', prefix)
if (env) params.set('env', env)
target = `${base}${params.toString() ? `?${params}` : ''}`
}
} else if (req.method === 'POST') {
target = base
body = await req.text() // {path,name,env,value} — forwarded verbatim, never logged
} else if (req.method === 'PATCH') {
if (!name) return notFound()
target = `${base}/${secretRest(path, name)}`
body = await req.text() // {value,version,env} — forwarded verbatim, never logged
} else if (req.method === 'DELETE') {
if (!name) return notFound()
const params = new URLSearchParams()
if (env) params.set('env', env)
target = `${base}/${secretRest(path, name)}${params.toString() ? `?${params}` : ''}`
} else {
return notFound()
}
let bearer: string
try {
bearer = await adminBearer(gate.user)
} catch (e) {
return NextResponse.json(
{ message: `Could not authorize the request: ${e instanceof Error ? e.message : String(e)}` },
{ status: 502 },
)
}
const headers: Record<string, string> = { Authorization: `Bearer ${bearer}`, Accept: 'application/json' }
const init: RequestInit = { method: req.method, headers, cache: 'no-store' }
if (body !== undefined) {
headers['Content-Type'] = 'application/json'
init.body = body
}
try {
const res = await fetchWithTimeout(target, init)
const text = await res.text()
return new NextResponse(text, {
status: res.status,
headers: { 'Content-Type': res.headers.get('content-type') ?? 'application/json' },
})
} catch (e) {
// Surface only the transport failure — never the request body/value.
return NextResponse.json(
{ message: `KMS unreachable: ${e instanceof Error ? e.message : String(e)}` },
{ status: 502 },
)
}
}
type Ctx = { params: Promise<{ path: string[] }> }
export async function GET(req: NextRequest, ctx: Ctx) {
return handle(req, (await ctx.params).path)
}
export async function POST(req: NextRequest, ctx: Ctx) {
return handle(req, (await ctx.params).path)
}
export async function PATCH(req: NextRequest, ctx: Ctx) {
return handle(req, (await ctx.params).path)
}
export async function DELETE(req: NextRequest, ctx: Ctx) {
return handle(req, (await ctx.params).path)
}
+66
View File
@@ -0,0 +1,66 @@
/**
* Keyless AI proxy — the ONE path the console uses to reach the model gateway.
*
* `/v1/chat/completions` (and friends) REQUIRE an `Authorization: Bearer` token; a
* browser session cookie alone is rejected. Rather than ship the user's durable
* `hk-` key to the browser, the console calls its OWN origin (`/ai/v1/...`) with just
* the session cookie; `forwardWithUserBearer` resolves the user, mints a SHORT-LIVED,
* user-bound IAM token (shared per-user cache in identity.ts), and forwards to the
* gateway with that token. No key in the browser, no rotation on a chat turn, and
* every call is billed to the user's own org. The response STREAMS through, so
* `chat/completions` SSE (and the multi-model TTFT measurement) is preserved.
*
* Least privilege: only the read/inference AI endpoints are proxied (the ALLOWED
* allow-list); anything else 404s, so this is not a general gateway tunnel. The RAG
* retrieval switch (`X-Retrieval`/`X-Retrieval-Store`) is the ONE client-header
* passthrough (allow-listed in `ai-proxy`).
*/
import { type NextRequest } from 'next/server'
import { forwardWithUserBearer } from '~/lib/server/bearer-proxy'
import { retrievalHeaders } from '~/lib/server/ai-proxy'
export const runtime = 'nodejs'
const trim = (s: string) => s.replace(/\/+$/, '')
/** Gateway the proxied AI calls are forwarded to (gated/priced api.hanzo.ai). */
const AI_GATEWAY_URL = trim(process.env.AI_GATEWAY_URL ?? 'https://api.hanzo.ai')
/** The exact `/v1/<...>` endpoints the console is allowed to reach. */
const ALLOWED = new Set([
'v1/models',
'v1/pricing/models', // the rich model+provider catalog (context, pricing, specs, tier) for Models/Providers pages
'v1/plans', // the subscription tiers + entitlements (rpm/tpm/quota) for the catalog plan badges
'v1/chat',
'v1/chat/completions',
'v1/embeddings',
'v1/rerank',
'v1/audio/speech', // text-to-speech (JSON in → audio bytes out) for the Playground Audio tab
'v1/images/generations', // text-to-image (JSON in → image url/b64 out) for the Playground Image tab
'v1/videos/generations', // text-to-video (JSON in → base64 MP4 out) for the Playground Video tab
])
type Ctx = { params: Promise<{ path: string[] }> }
function handle(req: NextRequest, ctx: Ctx) {
return (async () => {
const path = (await ctx.params).path.join('/')
return forwardWithUserBearer(req, {
target: AI_GATEWAY_URL,
path,
allow: (p) => ALLOWED.has(p),
// Forward the RAG retrieval switch when present; the store's org owner is still
// resolved server-side from the session (the bearer), never the browser.
extraHeaders: retrievalHeaders((h) => req.headers.get(h)),
errorShape: 'openai',
unauthorizedMessage: 'Sign in to use AI.',
})
})()
}
export async function GET(req: NextRequest, ctx: Ctx) {
return handle(req, ctx)
}
export async function POST(req: NextRequest, ctx: Ctx) {
return handle(req, ctx)
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

+55
View File
@@ -0,0 +1,55 @@
'use client'
/**
* IAM OAuth callback. IAM redirects here with `?code&state`; we exchange them
* for a backend session (`/v1/iam/signin`) and land on the dashboard. On failure we
* surface the error and offer a retry.
*/
import { Suspense, useEffect, useState } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { Button, Text, YStack } from '@hanzo/gui'
import { ApiError } from '~/lib/api'
import { Loader } from '~/components/ui/Loader'
import { useSession } from '~/lib/auth/session'
import { takeReturnTo } from '~/lib/auth/iam'
function Callback() {
const params = useSearchParams()
const router = useRouter()
const { completeSignIn } = useSession()
const [error, setError] = useState<string | null>(null)
useEffect(() => {
const code = params.get('code')
const state = params.get('state')
if (!code || !state) {
setError('Missing authorization code.')
return
}
completeSignIn(code, state)
// Land the user back where a mid-task expiry interrupted them (default home).
.then(() => router.replace(takeReturnTo()))
.catch((e: unknown) => setError(e instanceof ApiError ? e.message : 'Sign-in failed.'))
}, [params, completeSignIn, router])
if (error) {
return (
<YStack flex={1} minH="100vh" items="center" justify="center" gap="$3">
<Text color="$color12" fontWeight="600">
{error}
</Text>
<Button onPress={() => router.replace('/signin')}>Back to sign in</Button>
</YStack>
)
}
return <Loader label="Completing sign-in…" />
}
export default function CallbackPage() {
return (
<Suspense fallback={null}>
<Callback />
</Suspense>
)
}
+69
View File
@@ -0,0 +1,69 @@
/**
* /auth/refresh — silently renew the console session (server-side, BFF).
*
* The browser calls this with just its httpOnly cookies (no token in the body, none
* in the URL). The route reassembles + reads the sealed refresh token, calls IAM with
* `grant_type=refresh_token`, and re-seals the ROTATED token set (IAM issues a new
* one-time-use refresh token every refresh — we always persist the NEW one). It
* returns only the new lifetime, never a token.
*
* Called two ways, both single-flight on the client (`lib/auth/refresh`): proactively
* on a timer at ~80% of the access lifetime, and reactively on a 401 from any cloud/BFF
* call. On failure (the refresh token is truly expired/revoked, or a replay of a
* rotated one) it 401s WITHOUT clearing the cookies (multi-tab rotating-token race
* safety — a lost-race 401 must not nuke another tab's freshly-rotated cookie); the
* client then re-reads the session (seeing a winner's fresh cookie if any) or falls
* through to graceful re-auth. Only explicit sign-out clears the cookies.
*/
import { type NextRequest, NextResponse } from 'next/server'
import { readRefreshToken, refreshGrant, sealSession, setCookies, SessionError, type CookieDirective } from '~/lib/server/session'
import { csrfRefusal } from '~/lib/server/bearer-proxy'
export const runtime = 'nodejs'
function withCookies(res: NextResponse, dirs: CookieDirective[]): NextResponse {
for (const d of dirs) {
res.cookies.set(d.name, d.value, {
httpOnly: d.httpOnly,
secure: d.secure,
sameSite: d.sameSite,
path: d.path,
maxAge: d.maxAge,
})
}
return res
}
/** 401 WITHOUT clearing the cookies (see the multi-tab note above). */
const fail = () => NextResponse.json({ error: 'refresh failed' }, { status: 401 })
export async function POST(req: NextRequest): Promise<NextResponse> {
// CSRF: uniform same-origin gate on every mutating BFF route (the hz_rt cookie is
// already SameSite=lax + Path=/auth, so this is belt-and-suspenders).
const csrf = csrfRefusal(req)
if (csrf) return csrf
const rt = readRefreshToken(req)
if (!rt) return fail()
let tokens
try {
tokens = await refreshGrant(rt)
} catch (e) {
// A 502 (endpoint unreachable) is transient — surface it distinctly so the client
// can retry, and never touch the cookies.
if (e instanceof SessionError && e.status === 502) {
return NextResponse.json({ error: 'refresh unavailable' }, { status: 502 })
}
return fail()
}
// A rotated set with no new refresh token would strand us next cycle — require it
// (fail-closed: never persist a session we cannot refresh again).
if (!tokens.refreshToken) return fail()
const sealed = sealSession(tokens)
if (!sealed) return fail()
const res = NextResponse.json({ expiresIn: Math.floor(sealed.expiresInMs / 1000) })
return withCookies(res, setCookies(sealed.identity, sealed.refresh))
}
+149
View File
@@ -0,0 +1,149 @@
/**
* /auth/session — the console's OWN durable, refreshable OAuth session (BFF).
*
* POST establish the console session for the SIGNED-IN user (first-party
* confidential-client password grant WITH offline_access → access +
* rotating refresh token, sealed into the httpOnly cookies).
* GET the current account resolved from that session (what the AuthGate reads
* FIRST — durable + silently refreshed, so it survives the casibase
* session's own lifetime and never bounces the user mid-task).
* DELETE sign out — best-effort revoke the refresh token + clear the cookies.
*
* SECURITY. POST is GATED: it mints a console session ONLY for a caller who is
* ALREADY authenticated (a valid casibase/console session — the full login incl. any
* MFA), AND only when the password grant resolves to the SAME principal — so it can
* never be driven standalone with a stolen password, and never bypasses MFA (an MFA
* account never reaches this call). Tokens live only inside the sealed httpOnly
* cookies — never returned to the browser, never logged, never in a URL.
*/
import { type NextRequest, NextResponse } from 'next/server'
import { type Account } from '~/lib/api/types'
import { csrfRefusal } from '~/lib/server/bearer-proxy'
import { resolveUser } from '~/lib/server/identity'
import {
clearCookies,
consoleSession,
passwordGrant,
readRefreshToken,
revokeRefreshToken,
sameSubject,
sealSession,
sessionConfigured,
setCookies,
SessionError,
type ConsoleClaims,
type CookieDirective,
} from '~/lib/server/session'
export const runtime = 'nodejs'
/** Build the client-facing Account from console claims (display + admin fields only;
* never the secret material Casdoor also packs into the token). `isGlobalAdmin` is
* carried so the client nav/org gates (`isGlobalAdminAccount`) match the casibase
* path; `owner === 'admin'` also implies it. */
function accountOf(c: ConsoleClaims): Account {
return {
owner: c.owner ?? '',
name: c.name ?? '',
type: c.type,
displayName: c.displayName,
email: c.email,
avatar: c.avatar,
isAdmin: c.isAdmin,
isGlobalAdmin: c.isGlobalAdmin || c.owner === 'admin',
properties: c.properties,
}
}
/** Apply cookie directives to a NextResponse. */
function withCookies(res: NextResponse, dirs: CookieDirective[]): NextResponse {
for (const d of dirs) {
res.cookies.set(d.name, d.value, {
httpOnly: d.httpOnly,
secure: d.secure,
sameSite: d.sameSite,
path: d.path,
maxAge: d.maxAge,
})
}
return res
}
/** GET — the account + remaining access lifetime from the live console session, or
* 401 when there is none (the client then falls back to the casibase session). */
export async function GET(req: NextRequest): Promise<NextResponse> {
const sess = consoleSession(req)
if (!sess || !sess.claims.name) {
return NextResponse.json({ error: 'no session' }, { status: 401 })
}
return NextResponse.json({ account: accountOf(sess.claims), expiresIn: sess.expiresInSec })
}
/** POST { username, password } — establish the console session for the signed-in user. */
export async function POST(req: NextRequest): Promise<NextResponse> {
// CSRF: refuse a cross-origin login (login-CSRF fixes the victim into an attacker's
// session) before touching credentials.
const csrf = csrfRefusal(req)
if (csrf) return csrf
if (!sessionConfigured()) {
// No confidential client wired: the console still runs on the casibase session;
// report "not configured" so the client silently skips the console session.
return NextResponse.json({ error: 'session not configured' }, { status: 501 })
}
let body: { username?: unknown; password?: unknown }
try {
body = (await req.json()) as typeof body
} catch {
return NextResponse.json({ error: 'bad request' }, { status: 400 })
}
const username = typeof body.username === 'string' ? body.username.trim() : ''
const password = typeof body.password === 'string' ? body.password : ''
if (!username || !password) {
return NextResponse.json({ error: 'missing credentials' }, { status: 400 })
}
// GATE: the caller must already be authenticated (they just completed the casibase
// login incl. any MFA). This binds the console session to a real, MFA-cleared
// session and blocks standalone password abuse.
const authed = await resolveUser(req)
if (!authed) {
return NextResponse.json({ error: 'not authenticated' }, { status: 401 })
}
let tokens
try {
tokens = await passwordGrant(username, password)
} catch (e) {
const status = e instanceof SessionError ? e.status : 502
return NextResponse.json({ error: 'grant failed' }, { status })
}
const sealed = sealSession(tokens)
// The grant MUST resolve to the same principal as the established session — the
// console session is for the already-authenticated user, never a third party.
const grantId =
sealed && sealed.claims.owner && sealed.claims.name ? `${sealed.claims.owner}/${sealed.claims.name}` : ''
if (!sealed || !grantId || !sameSubject(grantId, authed.id)) {
return NextResponse.json({ error: 'identity mismatch' }, { status: 401 })
}
const res = NextResponse.json({
account: accountOf(sealed.claims),
expiresIn: Math.floor(sealed.expiresInMs / 1000),
})
return withCookies(res, setCookies(sealed.identity, sealed.refresh))
}
/** DELETE — sign out: best-effort revoke the refresh token, then clear the cookies. */
export async function DELETE(req: NextRequest): Promise<NextResponse> {
// CSRF: refuse a cross-origin forced sign-out.
const csrf = csrfRefusal(req)
if (csrf) return csrf
const rt = readRefreshToken(req)
if (rt) await revokeRefreshToken(rt)
return withCookies(NextResponse.json({ ok: true }), clearCookies())
}
+93
View File
@@ -0,0 +1,93 @@
/**
* Email self-serve signup (HIP-0111) — create a brand-new account + its own org.
*
* This is the ONE unauthenticated BFF route (the caller has no account yet). It
* acts as the confidential `hanzo-console` client to mint, in one shot:
* 1. a personal organization (owner=`admin`, password/locale cloned from the
* brand org so the account hashes with the brand's argon2id policy), and
* 2. the user as that org's ADMIN (IAM hashes the password server-side).
* The client then signs in with the same credentials and lands as admin — no
* separate onboarding step (IAM users always belong to an org, so "create then
* onboard" is not possible against casibase; the org is minted here).
*
* Email uniqueness without a global user-lookup endpoint: the org slug is a
* DETERMINISTIC, injective function of the email (`personalOrgFromEmail`), so a
* repeat signup with the same email resolves to the same slug and is caught by
* `getOrganization` (409) — two different emails never false-collide.
*
* Honest states: 501 when the IAM client is unwired, 400 on bad input, 409 when
* the account already exists, 502 on an IAM failure.
*
* NOTE (hardening, flagged not done here): this endpoint creates accounts from the
* open internet. It validates input but has NO captcha / rate-limit / email-
* verification gate yet — those are follow-ups (email verification especially
* would add friction the go-live conversion goal explicitly avoids).
*/
import { createHash } from 'node:crypto'
import { type NextRequest, NextResponse } from 'next/server'
import { brandFromHost } from '~/config'
import { BRANDS } from '~/lib/branding/brands'
import { createOrganization, createUser, getOrganization, mintConfigured } from '~/lib/server/identity'
import {
deriveUsername,
displayNameFromEmail,
personalOrgFromEmail,
validateSignup,
} from '~/lib/server/onboarding'
import { csrfRefusal } from '~/lib/server/bearer-proxy'
export const runtime = 'nodejs'
export async function POST(req: NextRequest): Promise<NextResponse> {
// Same-origin gate: this route creates accounts from the open internet with no
// captcha/rate-limit yet, so refuse cross-origin scripted signups (a mild anti-abuse
// measure; the console's own signup form is same-origin).
const csrf = csrfRefusal(req)
if (csrf) return csrf
if (!mintConfigured()) {
return NextResponse.json(
{ error: 'Account creation is not configured on this deployment (IAM client unset).' },
{ status: 501 },
)
}
const body = (await req.json().catch(() => ({}))) as { email?: string; password?: string }
const v = validateSignup(body.email ?? '', body.password ?? '')
if (!v.ok) return NextResponse.json({ error: v.error }, { status: 400 })
const brand = BRANDS[brandFromHost(req.headers.get('host'))]
const brandOrg = brand.id // hanzo/lux/zoo/pars — cloned for password/locale policy
const signupApplication = `${brand.id}-cloud` // hanzo-cloud, lux-cloud, …
const digest = createHash('sha256').update(v.email).digest('hex')
const orgSlug = personalOrgFromEmail(v.email, digest)
if (await getOrganization(orgSlug)) {
return NextResponse.json(
{ error: 'An account with this email already exists. Sign in instead.' },
{ status: 409 },
)
}
const displayName = displayNameFromEmail(v.email)
try {
await createOrganization({ name: orgSlug, displayName, personal: true, sourceOwner: brandOrg })
await createUser({
org: orgSlug,
username: deriveUsername(v.email),
email: v.email,
password: v.password,
displayName,
signupApplication,
})
} catch (e) {
return NextResponse.json(
{ error: `Could not create your account: ${e instanceof Error ? e.message : String(e)}` },
{ status: 502 },
)
}
return NextResponse.json({ ok: true, org: orgSlug })
}
+139
View File
@@ -0,0 +1,139 @@
/**
* Per-tenant billing DATA proxy → commerce. The browser calls console2's OWN origin
* (`/billing/v1/...`); this server handler forwards to commerce's `/v1/billing/...`,
* injecting the commerce SERVICE token from server-only env (never `NEXT_PUBLIC_`,
* never in the browser bundle) AND scoping every request to the caller's OWN org.
*
* Namespaced under `/billing/v1/` (NOT bare `/billing/`) so the data plane never
* shadows the billing UI tab URLs (`/billing/reports`, `/billing/invoices`, …): a
* route handler always wins over the catch-all page for a matching path segment, so
* the tab slugs and the data endpoints must live in disjoint path space. The tab
* URLs now fall through to the SPA (`app/(dashboard)/[...slug]`).
*
* Same trust boundary as the `/admin/iam` + `/admin/kms` proxies, but the authz is
* PER-TENANT, not admin: any authenticated session may read/act on ITS OWN billing
* (balance / usage / invoices / credit-grants / subscriptions / payment-methods).
* The org is resolved server-side from the validated session (`resolveUser`) and
* stamped as `X-Org-Id` (the header commerce's service-token path actually reads —
* `commerce/middleware/accesstoken.go`), and the server-resolved billing subject is
* pinned onto the FULL commerce subject-key set (`user`/`userId`/`customerId`, via
* `scopedBillingSearch`) while `?org=` is dropped. The client CANNOT widen scope: a
* forged `?userId=`/`?customerId=`/`?org=` is overwritten, and because EVERY subject
* param is pinned, no billing endpoint is left unfiltered regardless of which one it
* reads (subscriptions filter `userId`, payment-methods `customerId`). So commerce's
* per-tenant isolation can never be crossed from the browser. No session → 401.
*
* Billing-subject mirrors `object.BillingSubject` (hanzoai/ai) + chat's
* `billingSubject`: a member of a PERSONAL-billing org (default the shared `hanzo`
* catch-all) bills per-user as `<org>/<name>`; a dedicated org (maxpower, …) bills
* per-org as `<org>`. The SAME subject the gateway debits — so the console shows
* the exact balance/usage that gets charged.
*
* `COMMERCE_TOKEN` unset → honest 501 (the UI shows a truthful "not configured"
* state; it never fabricates a balance).
*/
import { type NextRequest, NextResponse } from 'next/server'
import { resolveUser } from '~/lib/server/identity'
import { billingSubject, scopedBillingSearch, scopedBillingBody } from '~/lib/server/billing-scope'
import { csrfRefusal } from '~/lib/server/bearer-proxy'
import { fetchWithTimeout } from '~/lib/server/fetch-timeout'
export const runtime = 'nodejs'
const isSafeSegment = (s: string): boolean =>
s.length > 0 && s !== '.' && s !== '..' && !s.includes('/') && !s.includes('\\') && !s.includes('\0')
function commerceBaseUrl(): string {
return (process.env.COMMERCE_URL ?? 'http://commerce.hanzo.svc:8001').replace(/\/+$/, '')
}
async function forward(req: NextRequest, path: string[]): Promise<NextResponse> {
// CSRF: a mutating billing write (spend-alert/budget) authenticates from the
// auto-sent cookie, so refuse a cross-origin one before any work (safe reads pass).
const csrf = csrfRefusal(req)
if (csrf) return csrf
// Per-tenant authz: any valid session may see ITS OWN billing (no admin gate).
const user = await resolveUser(req)
if (!user) {
return NextResponse.json({ error: 'Sign in to view billing.' }, { status: 401 })
}
if (!path.every(isSafeSegment)) {
return NextResponse.json({ error: 'Invalid billing path.' }, { status: 400 })
}
const token = process.env.COMMERCE_TOKEN ?? process.env.COMMERCE_SERVICE_TOKEN ?? ''
if (!token) {
return NextResponse.json(
{ error: 'Billing is not configured (COMMERCE_TOKEN missing).' },
{ status: 501 },
)
}
// Scope to the caller's OWN org — server-resolved, never client-supplied.
const org = user.owner.trim()
const subject = billingSubject(org, user.name)
// Pin the FULL billing-subject key set to the server-resolved subject, and
// strip `org`, so the browser can never read another tenant's ledger. Commerce
// filters each endpoint on a DIFFERENT param — subscriptions on `userId`,
// payment-methods on `customerId` (or `user`), usage on `user` — so pinning
// only ONE param leaves the others unfiltered (a cross-tenant read). This
// mirrors commerce's own edge-auth `billingSubjectKeys`
// (commerce/middleware/edgeauth.go: {"user","userId","customerId"}) exactly, so
// every billing endpoint is scoped no matter which param it reads.
const qs = scopedBillingSearch(req.nextUrl.search, subject)
const url = `${commerceBaseUrl()}/v1/billing/${path.join('/')}${qs ? `?${qs}` : ''}`
const init: RequestInit = {
method: req.method,
headers: {
Authorization: `Bearer ${token}`,
// Commerce resolves the tenant namespace from `X-Org-Id` on the service-token
// path (commerce/middleware/accesstoken.go). It does NOT read `X-Hanzo-Org`,
// so sending that alone silently falls back to the service org — every tenant
// sharing one namespace. Send `X-Org-Id`, matching the `/ai` proxy.
'X-Org-Id': org,
'Content-Type': 'application/json',
Accept: 'application/json',
},
cache: 'no-store',
}
if (req.method !== 'GET' && req.method !== 'HEAD') {
// Scope the WRITE body to the caller's OWN subject too (not just the query):
// commerce reads the subject from the JSON body on writes like create-spend-alert
// (`userId`), so pin it server-side — the browser needn't know its subject and a
// forged body subject cannot widen scope. Mirrors `scopedBillingSearch`.
init.body = scopedBillingBody(await req.text(), subject)
}
try {
const res = await fetchWithTimeout(url, init)
const text = await res.text()
return new NextResponse(text, {
status: res.status,
headers: {
'Content-Type': res.headers.get('content-type') ?? 'application/json',
// A per-tenant money response (balance/usage/invoices) must NEVER be cached
// by the browser or any intermediary — otherwise the wallet shows a stale
// number after a completion or a top-up. The live-balance store still polls,
// but this guarantees each fetch hits commerce, not a cache.
'Cache-Control': 'no-store, must-revalidate',
},
})
} catch (e) {
return NextResponse.json(
{ error: `Billing upstream unreachable: ${e instanceof Error ? e.message : String(e)}` },
{ status: 502 },
)
}
}
type Ctx = { params: Promise<{ path: string[] }> }
export async function GET(req: NextRequest, ctx: Ctx) {
return forward(req, (await ctx.params).path)
}
export async function POST(req: NextRequest, ctx: Ctx) {
return forward(req, (await ctx.params).path)
}
+62
View File
@@ -0,0 +1,62 @@
/**
* Same-origin user-bearer proxy to the unified cloud-api `/v1/*` — the ONE path the
* browser uses to reach the cloud surfaces that authorize on a Bearer JWT.
*
* The managed data resources (vector/sql/kv/s3/docdb/datastore/search) and the
* serverless / prompt / agent surfaces resolve the org from the token's `owner`
* claim and 403 a cookie-only call ("X-Org-Id required"). So — exactly like the
* `/ai` proxy — the browser calls this OWN-origin route with just its session
* cookie; `forwardWithUserBearer` resolves the user, mints a short-lived user-bound
* IAM token (shared per-user cache), and forwards to cloud-api with that Bearer. No
* credential reaches the browser, org is server-authoritative (never the browser's
* claim), and every read/write is billed + scoped to the user's own org.
*
* Least privilege: only the data + serverless HEADS are reachable (`allowCloudSurface`);
* `v1/iam/*`, `v1/admin/*`, etc. 404 here — this is not a general cloud-api tunnel.
*/
import { type NextRequest } from 'next/server'
import { forwardWithUserBearer } from '~/lib/server/bearer-proxy'
import { allowCloudSurface } from '~/lib/server/proxy-allow'
export const runtime = 'nodejs'
const trim = (s: string) => s.replace(/\/+$/, '')
/** The unified cloud backend (hanzoai/cloud). In-cluster ClusterIP — public egress is CF-403'd.
* `|| default` (not `??`) so an env accidentally reconciled to an EMPTY string still falls
* back to the in-cluster service (a blank CLOUD_API_URL would otherwise break every cloud page). */
const CLOUD_API_URL = trim(process.env.CLOUD_API_URL?.trim() || 'http://cloud-api.hanzo.svc.cluster.local:8000')
type Ctx = { params: Promise<{ path: string[] }> }
function handle(req: NextRequest, ctx: Ctx) {
return (async () => {
const path = (await ctx.params).path.join('/')
return forwardWithUserBearer(req, {
target: CLOUD_API_URL,
path,
allow: allowCloudSurface,
// Org is authoritative (Bearer owner). Do NOT forward the browser-controlled
// X-Project-Id/X-Environment sub-scopes — the data/serverless resources are
// org-keyed, and forwarding an unvalidated project id is an attack surface
// (RED MEDIUM). A project-scoped feature must validate membership first.
unauthorizedMessage: 'Sign in to use Hanzo Cloud.',
})
})()
}
export async function GET(req: NextRequest, ctx: Ctx) {
return handle(req, ctx)
}
export async function POST(req: NextRequest, ctx: Ctx) {
return handle(req, ctx)
}
export async function PUT(req: NextRequest, ctx: Ctx) {
return handle(req, ctx)
}
export async function PATCH(req: NextRequest, ctx: Ctx) {
return handle(req, ctx)
}
export async function DELETE(req: NextRequest, ctx: Ctx) {
return handle(req, ctx)
}
+62
View File
@@ -0,0 +1,62 @@
/**
* Same-origin user-bearer proxy to commerce (`commerce.hanzo.svc`) — the store /
* merchant admin surface (products / orders / customers / collections / variants /
* discounts / store settings). The browser calls this OWN-origin route
* (`/commerce/v1/...`) with just its session cookie; `forwardWithUserBearer` resolves
* the user, mints a short-lived user-bound IAM token, and forwards to commerce with
* that Bearer. Commerce's EdgeAuth validates the JWT and resolves the org from its
* `owner` claim (`middleware.TokenRequired` fast-paths IAM auth), so the store is
* org-scoped SERVER-SIDE — a merchant only ever sees their OWN org's catalog/orders/
* customers. No token reaches the browser, and the org is never browser-supplied.
*
* This is the TENANT store surface (any signed-in org member acts on their own org's
* store), so it is user-scoped (`resolveUser`), NOT the `/paas` god-mode service-token
* path. It is also DISTINCT from the `/billing` proxy: money (balance/usage/invoices/
* Square) stays on `/billing` with its own per-tenant subject scoping — this proxy
* carries only the store catalog/orders/customers. Least privilege on the path:
* `allowCommerceSurface` admits only the merchant REST heads (product/order/user/…),
* so `/v1/billing`, `/v1/checkout`, `/_/commerce/tenants` are NOT reachable here.
*/
import { type NextRequest } from 'next/server'
import { forwardWithUserBearer } from '~/lib/server/bearer-proxy'
import { allowCommerceSurface } from '~/lib/server/proxy-allow'
export const runtime = 'nodejs'
const trim = (s: string) => s.replace(/\/+$/, '')
/** Commerce API (commerce.hanzo.ai). In-cluster ClusterIP on :8001; the CR already
* wires `COMMERCE_URL` (public egress is CF-gated). Override per-deploy with COMMERCE_URL. */
const COMMERCE_URL = trim(process.env.COMMERCE_URL ?? 'http://commerce.hanzo.svc:8001')
type Ctx = { params: Promise<{ path: string[] }> }
function handle(req: NextRequest, ctx: Ctx) {
return (async () => {
const path = (await ctx.params).path.join('/')
return forwardWithUserBearer(req, {
target: COMMERCE_URL,
path,
allow: allowCommerceSurface,
// Org is authoritative (Bearer owner). Do NOT forward browser X-Project-Id/
// X-Environment — the store is org-keyed and commerce re-scopes on the token.
unauthorizedMessage: 'Sign in to manage your store.',
})
})()
}
export async function GET(req: NextRequest, ctx: Ctx) {
return handle(req, ctx)
}
export async function POST(req: NextRequest, ctx: Ctx) {
return handle(req, ctx)
}
export async function PUT(req: NextRequest, ctx: Ctx) {
return handle(req, ctx)
}
export async function PATCH(req: NextRequest, ctx: Ctx) {
return handle(req, ctx)
}
export async function DELETE(req: NextRequest, ctx: Ctx) {
return handle(req, ctx)
}
+35
View File
@@ -0,0 +1,35 @@
'use client'
/**
* `/docs` → the brand documentation site (docs.hanzo.ai / docs.lux.network / …),
* resolved CLIENT-side (task #41, "True 1-binary FE").
*
* Docs are an EXTERNAL product on their own domain, never an in-app route — so a
* typed or bookmarked `<console-host>/docs` must land on the real docs, not the
* catch-all not-found. The old app/docs/route.ts issued a server 308; in the
* one-binary there is no Next runtime (the static export has no server, and a static
* export cannot rewrite), so the redirect is resolved from the per-host brand
* (`config.docsUrl`) in the browser — exactly what the sidebar "Docs" link and the
* header "?" already open. One way, both topologies (embed + standalone).
*
* The target is set in an effect (not during render) so there is no SSR/CSR
* hydration mismatch on the per-brand host between the build-time default and the
* real browser host.
*/
import { useEffect, useState } from 'react'
import { config } from '~/config'
export default function DocsRedirect() {
const [url, setUrl] = useState('')
useEffect(() => {
const target = config.docsUrl
setUrl(target)
window.location.replace(target)
}, [])
return (
<main style={{ padding: 24, fontFamily: 'system-ui, sans-serif' }}>
Opening documentation {url ? <a href={url}>Continue</a> : null}
</main>
)
}
+175
View File
@@ -0,0 +1,175 @@
/**
* Per-user proxy to the Lux DEX indexer's `dex` subgraph — the Lux Economy /
* Markets board's ONE transport. The browser calls console2's OWN origin
* (`/economy/v1/overview`) with just the session cookie; this handler resolves the
* caller, resolves the BRAND from the request host, and POSTs a FIXED, allowlisted
* GraphQL query to the in-cluster graphd per brand-scoped network, returning the
* NORMALIZED markets + fills + day-data. No graph host or GraphQL query ever reaches
* the browser, and the browser can never compose one.
*
* Security (mirrors app/nodes/[...path]/route.ts):
* - Session-gated: an unauthenticated caller gets 401.
* - Org/brand-aware: the network set is scoped by `nodeNetworksForBrand(brand)`,
* brand resolved from the host — cloud.lux.cloud sees only Lux networks.
* - Least privilege: the ONLY path is `v1/overview`, and the ONLY GraphQL query is
* the fixed markets+fills+dayData read below — this is not a general GraphQL
* tunnel (no client-supplied query, no mutations, no arbitrary entity).
*
* Honest by construction: an unset/unreachable graph host yields a `not-reporting`
* snapshot with the real error — never fabricated markets. The native DEX is a CLOB,
* so the query asks only for the fields the `dex` subgraph really exposes.
*/
import { type NextRequest, NextResponse } from 'next/server'
import { brandFromHost } from '~/config'
import { resolveUser } from '~/lib/server/identity'
import { nodeNetworksForBrand, type NodeNetworkId } from '~/lib/products/brand-scope'
import { fetchWithTimeout } from '~/lib/server/fetch-timeout'
import {
normalizeMarkets,
normalizeTrades,
normalizeDayData,
type EconomySnapshot,
type RawMarket,
type RawFill,
type RawMarketDayData,
} from '~/lib/api/economy'
export const runtime = 'nodejs'
const trim = (s: string) => s.replace(/\/+$/, '')
/**
* The `dex` subgraph GraphQL endpoint per network — the ONLY endpoint this proxy
* will query. graphd serves the DEX subgraph at `<prefix>/graphql` (default prefix
* `/v1/graph/cchain/dex`); each is overridable per-deploy. An unset/unreachable host
* yields an honest `not-reporting` snapshot — never fake markets. (Cross-cluster
* reach depends on network policy; when unreachable the board shows honest empty.)
*/
const GRAPH_HOSTS: Partial<Record<NodeNetworkId, string>> = {
'lux-mainnet': trim(process.env.DEX_GRAPHQL_MAINNET ?? 'http://graph.lux-mainnet.svc:8080/v1/graph/cchain/dex/graphql'),
'lux-testnet': trim(process.env.DEX_GRAPHQL_TESTNET ?? 'http://graph.lux-testnet.svc:8080/v1/graph/cchain/dex/graphql'),
'lux-devnet': trim(process.env.DEX_GRAPHQL_DEVNET ?? 'http://graph.lux-devnet.svc:8080/v1/graph/cchain/dex/graphql'),
}
/** Per-query timeout (ms). */
const TIMEOUT_MS = Number(process.env.ECONOMY_TIMEOUT_MS ?? 8000)
/**
* The ONE fixed GraphQL query — markets (book summary + accrued 24h aggregates),
* recent fills (the trade feed), and day-data (the historical series, empty until a
* MarketDayData producer emits). Only fields the `dex` subgraph really exposes.
*/
const QUERY = `query LuxEconomy {
markets(first: 100) {
id
symbol
baseToken
quoteToken
assetsBound
openOrders
remaining
bestBid
bestAsk
volume24h
tradeCount
lastPrice
feeTier
}
fills(first: 40) {
id
symbol
price
size
side
timestamp
}
marketDayDatas(first: 90) {
id
date
symbol
volumeUSD
feesUSD
tvlUSD
}
}`
interface GraphResp {
data?: { markets?: RawMarket[]; fills?: RawFill[]; marketDayDatas?: RawMarketDayData[] }
errors?: { message?: string }[]
}
/** Query ONE network's `dex` subgraph → normalized snapshot. Honest not-reporting on failure. */
async function probe(net: NodeNetworkId): Promise<EconomySnapshot> {
const base: EconomySnapshot = { network: net, status: 'not-reporting', markets: [], trades: [], dayData: [] }
const host = GRAPH_HOSTS[net]
if (!host) {
base.error = 'no DEX GraphQL host configured for this network'
return base
}
try {
const res = await fetchWithTimeout(
host,
{
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify({ query: QUERY }),
cache: 'no-store',
},
{ timeoutMs: TIMEOUT_MS },
)
if (!res.ok) {
base.error = `graphql ${res.status}`
return base
}
const json = (await res.json()) as GraphResp
if (json?.errors?.length) {
base.error = json.errors[0]?.message ?? 'graphql error'
return base
}
const d = json?.data ?? {}
return {
network: net,
status: 'reporting',
markets: normalizeMarkets(d.markets),
trades: normalizeTrades(d.fills),
dayData: normalizeDayData(d.marketDayDatas),
}
} catch (e) {
base.error = e instanceof Error ? e.message : String(e)
return base
}
}
async function forward(req: NextRequest, path: string[]): Promise<NextResponse> {
if (path.join('/') !== 'v1/overview') {
return NextResponse.json({ error: 'not found' }, { status: 404 })
}
const user = await resolveUser(req)
if (!user) {
return NextResponse.json({ error: 'Sign in to view the market economy.' }, { status: 401 })
}
const brand = brandFromHost(req.headers.get('host'))
let networks = nodeNetworksForBrand(brand)
const only = req.nextUrl.searchParams.get('network') as NodeNetworkId | null
if (only) networks = networks.filter((n) => n === only)
// Query the brand's networks and return the FIRST that reports markets (the live
// economy), else the first reporting network, else the first (honest not-reporting).
const snaps = await Promise.all(networks.map(probe))
const withMarkets = snaps.find((s) => s.status === 'reporting' && s.markets.length > 0)
const reporting = snaps.find((s) => s.status === 'reporting')
const chosen = withMarkets ?? reporting ?? snaps[0]
if (!chosen) {
return NextResponse.json({ network: null, status: 'not-reporting', markets: [], trades: [], dayData: [], error: 'no network in scope' })
}
return NextResponse.json(chosen)
}
type Ctx = { params: Promise<{ path: string[] }> }
export async function GET(req: NextRequest, ctx: Ctx) {
return forward(req, (await ctx.params).path)
}
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

+68
View File
@@ -0,0 +1,68 @@
/**
* /git/* — the console's Git-import BFF (connected accounts + repositories).
*
* A `[...path]` catch-all route handler (the PROVEN top-level BFF shape used by
* `/cloud`, `/ai`, `/paas`, `/cms`): a catch-all route handler wins over the
* `(dashboard)/[...slug]` SPA page, whereas a STATIC route handler at the same depth
* is shadowed by it. Served at TOP-LEVEL `/git/*` (NOT `/v1/*`) because
* console.hanzo.ai's ingress routes `/v1/*` to hanzoai/gateway (bypassing Next), so
* a `/v1/git/*` handler would 404 at the cloud binary.
*
* Two heads, one handler:
* - GET /git/accounts → { connected, accounts }
* - GET /git/repos?account&q → { repos } (401 when not connected)
*
* The GitHub token is resolved from IAM server-side (the user's own session) and
* used only here — it never reaches the browser. Per-user data ⇒ no-store.
*/
import { type NextRequest, NextResponse } from 'next/server'
import { resolveGithubConnection, listAccounts, listRepos } from '~/lib/server/git'
export const runtime = 'nodejs'
const NO_STORE = { 'Cache-Control': 'no-store' } as const
type Ctx = { params: Promise<{ path: string[] }> }
export async function GET(req: NextRequest, ctx: Ctx) {
const head = (await ctx.params).path?.[0] ?? ''
const conn = await resolveGithubConnection(req)
// /git/accounts — the signed-in user's connected Git accounts. Not connected ⇒
// honest `{ connected: false, accounts: [] }` (drives the "Connect GitHub" CTA).
if (head === 'accounts') {
if (!conn) return NextResponse.json({ connected: false, accounts: [] }, { headers: NO_STORE })
let accounts
try {
accounts = await listAccounts(conn)
} catch {
return NextResponse.json(
{ connected: true, accounts: [], error: 'github unreachable' },
{ status: 502, headers: NO_STORE },
)
}
// A 401 from GitHub (token revoked/expired) ⇒ treat as not connected.
if (accounts === null) return NextResponse.json({ connected: false, accounts: [] }, { headers: NO_STORE })
return NextResponse.json({ connected: true, accounts }, { headers: NO_STORE })
}
// /git/repos?account=<login>&q=<search> — repositories for one account, newest-push
// first, server-side filtered. No linked token ⇒ 401 (the client falls back to the
// "Connect GitHub" CTA) — never a service-token leak.
if (head === 'repos') {
if (!conn) return NextResponse.json({ repos: [], connected: false }, { status: 401, headers: NO_STORE })
const account = req.nextUrl.searchParams.get('account')?.trim() || ''
const q = req.nextUrl.searchParams.get('q')?.trim() || ''
let repos
try {
repos = await listRepos(conn, account, q)
} catch {
return NextResponse.json({ repos: [], error: 'github unreachable' }, { status: 502, headers: NO_STORE })
}
if (repos === null) return NextResponse.json({ repos: [], connected: false }, { status: 401, headers: NO_STORE })
return NextResponse.json({ repos, connected: true }, { headers: NO_STORE })
}
return NextResponse.json({ error: 'not found' }, { status: 404, headers: NO_STORE })
}
+356
View File
@@ -0,0 +1,356 @@
/* Geist Mono — canonical Hanzo mono face (code/data). */
@import url('https://cdn.jsdelivr.net/npm/geist@1.3.1/dist/fonts/geist-mono/style.css');
/* Basel Grotesk — canonical Hanzo UI/body/display/heading face (self-hosted). */
@font-face {
font-family: 'Basel';
font-style: normal;
font-weight: 400;
font-display: swap;
src:
url('/fonts/Basel-Grotesk-Book.woff2') format('woff2'),
url('/fonts/Basel-Grotesk-Book.woff') format('woff');
}
@font-face {
font-family: 'Basel';
font-style: normal;
font-weight: 500;
font-display: swap;
src:
url('/fonts/Basel-Grotesk-Medium.woff2') format('woff2'),
url('/fonts/Basel-Grotesk-Medium.woff') format('woff');
}
html,
body,
#__next {
height: 100%;
}
body {
margin: 0;
background-color: var(--background, #000000);
color: var(--color, #ededf1);
font-family:
'Basel', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
/* Calm type rendering — crisp, low-glare, comfortable rhythm for a full workday. */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-rendering: optimizeLegibility;
line-height: 1.5;
}
code,
pre,
kbd,
samp {
font-family: 'Geist Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
/* Tabular numerals — metrics, prices, contexts and IDs align on a fixed advance
width so columns of numbers read cleanly (the dashboard-grade detail). */
.hz-tnum {
font-variant-numeric: tabular-nums;
font-feature-settings: 'tnum' 1;
}
* {
box-sizing: border-box;
}
/* ── Console dark theme — TRUE-BLACK canvas + calm text/borders. The ONE place the
console's dark/light palette is set. Overrides the generated @hanzo/gui (Tamagui)
theme variables; the `html:root.t_*` selector is one step more specific than the
library's runtime `:root.t_*` block so it wins regardless of stylesheet insertion
order. DRY: every surface, border and text color in the app reads from these
tokens, so this one block sets the whole product.
Design intent (dark): a TRUE-BLACK #000 canvas (matches hanzo.ai marketing +
hanzo.chat OLED) with a Linear/Vercel-caliber surface-depth ladder above it —
resting panels #050505, the next surface #0a0a0a, interactive/elevated #171717 →
#1f1f1f — so cards read with real depth, never flat voids. Above the surface
ladder the CALM neutral scale (color512) gives premium, low-glare off-white text
and quiet hairline borders (never harsh pure #fff on pure #000). Neutral grey,
monochrome-first; text contrast stays WCAG-AA+ on every surface. */
html:root.t_dark {
--background: #000000;
--backgroundStrong: #000000;
--backgroundHover: #171717;
--backgroundPress: #050505;
--backgroundFocus: #171717;
/* Surface depth ladder over the true-black canvas — panels/cards step up from
#050505 so they separate cleanly without heavy borders (Linear-grade depth). */
--color1: #050505;
--color2: #0a0a0a;
--color3: #171717;
--color4: #1f1f1f;
--color5: hsl(220 6% 16%);
--color6: hsl(220 6% 22%);
--color7: hsl(220 6% 30%);
--color8: hsl(219 6% 42%);
--color9: hsl(220 6% 55%);
--color10: hsl(219 7% 68%);
--color11: hsl(214 9% 83%);
--color12: hsl(210 12% 95%);
--color: hsl(210 12% 95%);
/* Gentle hairlines — present enough to define, quiet enough to disappear on black. */
--borderColor: hsl(220 8% 15%);
--borderColorHover: hsl(220 7% 23%);
--borderColorPress: hsl(220 8% 13%);
--borderColorFocus: hsl(220 7% 23%);
}
/* Light theme — the calm parallel: a warm off-white base (not stark #fff), soft
ink text (not pure black), and quiet hairlines. Lighter touch than dark, since
the console defaults to dark, but kept consistent for the theme toggle. */
html:root.t_light {
--background: hsl(220 20% 99%);
--color1: hsl(220 24% 100%);
--color2: hsl(220 20% 98%);
--color3: hsl(220 18% 95.5%);
--color4: hsl(220 16% 92.5%);
--color5: hsl(220 15% 89%);
--color9: hsl(220 9% 46%);
--color10: hsl(220 10% 38%);
--color11: hsl(220 14% 22%);
--color12: hsl(220 22% 12%);
--color: hsl(220 22% 12%);
--borderColor: hsl(220 16% 90%);
--borderColorHover: hsl(220 14% 82%);
}
/* Motion — a single fade-up entrance (matches the hanzo.ai marketing feel:
~0.4s ease-out, small upward travel, staggered by the consumer). One place
defines it; <FadeIn> applies the class + per-item delay. */
@keyframes hz-fade-up {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.hz-fade-up {
animation: hz-fade-up 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
will-change: transform, opacity;
}
/* Honor the user's reduced-motion preference — no entrance animation. */
@media (prefers-reduced-motion: reduce) {
.hz-fade-up {
animation: none;
}
}
/* Shell chrome motion — the sidebar collapse (width) and the Linear-style
two-level nav slide (transform). One place defines the easing; the shell
applies the class. `className` forwards to the underlying DOM node on web, so
the browser transitions the Gui-driven inline width/transform. */
.hz-collapse {
transition: width 220ms cubic-bezier(0.16, 1, 0.3, 1);
will-change: width;
}
.hz-slide {
transition: transform 260ms cubic-bezier(0.16, 1, 0.3, 1);
will-change: transform;
}
/* Backdrop cross-fade behind a SlideOver / dialog. */
.hz-fade {
transition: opacity 240ms cubic-bezier(0.16, 1, 0.3, 1);
will-change: opacity;
}
/* Drag-to-reorder — a pinned row while it is being dragged (pointer DnD). The
lifted row gets a subtle lift; siblings ease into place via `.hz-slide`. */
.hz-drag-item {
touch-action: none;
transition: transform 180ms cubic-bezier(0.16, 1, 0.3, 1);
}
.hz-drag-item[data-dragging='true'] {
transition: none;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.28);
opacity: 0.96;
cursor: grabbing;
}
@media (prefers-reduced-motion: reduce) {
.hz-collapse,
.hz-slide,
.hz-fade,
.hz-drag-item {
transition: none;
}
}
/* Sidebar category accordion — a collapsible level-1 section. The body animates
its HEIGHT via grid-template-rows 0fr↔1fr (no magic max-height — the row
resolves to the real content height) plus a short opacity fade; the header
chevron rotates ▸→▾. Collapsed content stays in the DOM (so both directions
animate) but is `inert` (out of tab order + a11y tree). One place defines the
easing; the shell toggles `data-open`. */
.hz-acc {
display: grid;
grid-template-rows: 0fr;
transition: grid-template-rows 220ms cubic-bezier(0.16, 1, 0.3, 1);
}
.hz-acc[data-open='true'] {
grid-template-rows: 1fr;
}
.hz-acc-inner {
overflow: hidden;
min-height: 0;
opacity: 0;
transition: opacity 180ms ease;
}
.hz-acc[data-open='true'] .hz-acc-inner {
opacity: 1;
}
.hz-chevron {
transition: transform 200ms cubic-bezier(0.16, 1, 0.3, 1);
will-change: transform;
}
@media (prefers-reduced-motion: reduce) {
.hz-acc,
.hz-acc-inner,
.hz-chevron {
transition: none;
}
}
/* LivingOverview motion — the "videogame-like" living dashboard. The count-up +
live sparkline are driven in JS (rAF, gated by prefers-reduced-motion in the
hooks); these are the pure-CSS bits: a loading shimmer, a live-feed pulse, and
a brief highlight when a tile's number changes. One place defines the easing. */
/* Skeleton shimmer — an honest "loading", never fabricated content. */
@keyframes hz-shimmer {
0% {
background-position: -160px 0;
}
100% {
background-position: 160px 0;
}
}
.hz-skeleton {
background-color: var(--color3, rgba(148, 163, 184, 0.14));
background-image: linear-gradient(
90deg,
transparent 0%,
var(--color4, rgba(148, 163, 184, 0.22)) 50%,
transparent 100%
);
background-size: 160px 100%;
background-repeat: no-repeat;
animation: hz-shimmer 1.2s ease-in-out infinite;
}
/* Live-feed pulse — the "Live" dot on a streaming panel. */
@keyframes hz-pulse {
0%,
100% {
opacity: 1;
transform: scale(1);
}
50% {
opacity: 0.45;
transform: scale(0.82);
}
}
/* Entrance for a freshly-arrived activity row (staggerless — one row at a time). */
@keyframes hz-row-in {
from {
opacity: 0;
transform: translateY(-6px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.hz-row-in {
animation: hz-row-in 0.35s cubic-bezier(0.16, 1, 0.3, 1) both;
}
@media (prefers-reduced-motion: reduce) {
.hz-skeleton {
animation: none;
}
.hz-row-in {
animation: none;
}
}
/* RailwayDeploy — the deployment pipeline. A smooth flowing gradient marches along the
active leg of the track (stroke-dashoffset), a soft halo pulses out from the current
station, and the status dot breathes. All reduced-motion-guarded (→ static). One place
defines the easing; RailwayDeploy applies the classes. */
@keyframes hz-rail-flow {
to {
stroke-dashoffset: -28;
}
}
.hz-rail-flow {
stroke-dasharray: 5 9;
animation: hz-rail-flow 0.85s linear infinite;
}
@keyframes hz-rail-pulse {
0% {
transform: scale(1);
opacity: 0.34;
}
70% {
transform: scale(2.1);
opacity: 0;
}
100% {
transform: scale(2.1);
opacity: 0;
}
}
.hz-rail-pulse {
transform-box: fill-box;
transform-origin: center;
animation: hz-rail-pulse 1.7s ease-out infinite;
}
.hz-rail-dot {
animation: hz-pulse 1.5s ease-in-out infinite;
}
@media (prefers-reduced-motion: reduce) {
.hz-rail-flow,
.hz-rail-pulse,
.hz-rail-dot {
animation: none;
}
}
/* Hover lift — a subtle rise + border/background brighten on interactive cards and
rows (the deploy-hub aesthetic: true-black ground, hairline borders, hover lift).
Reduced-motion keeps the color transition but drops the transform. */
.hz-lift {
transition: transform 0.16s cubic-bezier(0.16, 1, 0.3, 1), border-color 0.16s ease, background-color 0.16s ease;
}
.hz-lift:hover {
transform: translateY(-1px);
}
@media (prefers-reduced-motion: reduce) {
.hz-lift {
transition: border-color 0.16s ease, background-color 0.16s ease;
}
.hz-lift:hover {
transform: none;
}
}
+8
View File
@@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 67 67" role="img" aria-label="Hanzo">
<style>path{fill:#000}@media (prefers-color-scheme:dark){path{fill:#fff}}</style>
<path d="M22.21 67V44.6369H0V67H22.21Z"/>
<path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/>
<path d="M22.21 0H0V22.3184H22.21V0Z"/>
<path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/>
<path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/>
</svg>

After

Width:  |  Height:  |  Size: 443 B

+39
View File
@@ -0,0 +1,39 @@
import '@hanzogui/core/reset.css'
import './globals.css'
import type { Metadata, Viewport } from 'next'
import type { ReactNode } from 'react'
import { headers } from 'next/headers'
import { Provider } from '~/components/Provider'
import { ChunkGuard } from '~/components/ChunkGuard'
import { resolveConfig } from '~/config'
// The document <title> is SSR metadata, so it must reflect the REQUEST host's
// brand (console.lux.cloud -> "Lux Cloud Console"), not the build-time default.
// The visible shell resolves the brand client-side from window.location, but the
// tab title is server-rendered — without reading the Host header here the browser
// tab leaks "Hanzo Cloud Console" on Lux/Zoo hosts, a white-label violation.
export async function generateMetadata(): Promise<Metadata> {
const host = (await headers()).get('host') ?? undefined
const { brandName } = resolveConfig(host)
return {
title: `${brandName} Console`,
description: 'Unified admin console for Hanzo Cloud and all cloud products.',
}
}
export const viewport: Viewport = {
themeColor: '#000000',
}
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en" className="t_dark" style={{ backgroundColor: '#000000', colorScheme: 'dark' }} suppressHydrationWarning>
<body style={{ margin: 0 }}>
<ChunkGuard />
<Provider>{children}</Provider>
</body>
</html>
)
}
+167
View File
@@ -0,0 +1,167 @@
/**
* Per-user proxy to the REAL luxd node RPC — the Nodes module's ONE transport.
* The browser calls console2's OWN origin (`/nodes/v1/inventory`) with just the
* session cookie; this handler resolves the caller, resolves the BRAND from the
* request host, and fetches the allowlisted luxd RPC methods server-side for each
* network that brand may see, returning NORMALIZED per-node rows. No RPC host or
* method ever reaches the browser, and the browser can never choose either.
*
* Security (mirrors app/bootnode/[...path]/route.ts):
* - Session-gated: an unauthenticated caller gets 401 (the RPC data is public,
* but the console surface is authenticated, same as every other module).
* - Org/brand-aware: the network set is scoped by `nodeNetworksForBrand(brand)`,
* brand resolved from the host — so cloud.lux.cloud sees only Lux networks,
* console.hanzo.ai (hanzo) sees all.
* - Least privilege: the ONLY path is `v1/inventory`, and the ONLY luxd methods
* called are the four read methods below — this is not a general RPC tunnel.
*/
import { type NextRequest, NextResponse } from 'next/server'
import { brandFromHost } from '~/config'
import { resolveUser } from '~/lib/server/identity'
import { nodeNetworksForBrand, type NodeNetworkId } from '~/lib/products/brand-scope'
import {
NODE_NETWORK_META,
combineInventory,
normalizeChains,
parseHeight,
type NetworkInventory,
type RawBlockchain,
type RawPeer,
type RawValidator,
} from '~/lib/api/nodes'
export const runtime = 'nodejs'
const trim = (s: string) => s.replace(/\/+$/, '')
/**
* Public luxd RPC host per network — the ONLY endpoints this proxy will call.
* These are PUBLIC RPC hosts (not secrets); each is overridable per-deploy so a
* network can be repointed or disabled without a code change. A host that is
* unset/unreachable yields an honest `not-reporting` network — never fake rows.
*/
const HOSTS: Record<NodeNetworkId, string> = {
'lux-mainnet': trim(process.env.LUX_MAINNET_RPC ?? 'https://api.lux.network'),
'lux-testnet': trim(process.env.LUX_TESTNET_RPC ?? 'https://api.lux-test.network'),
'lux-devnet': trim(process.env.LUX_DEVNET_RPC ?? 'https://api.lux-dev.network'),
'pars-mainnet': trim(process.env.PARS_MAINNET_RPC ?? 'https://api.pars.network'),
// Zoo has no confirmed public primary-network host yet; the default is the
// conventional host (api.<brand>.network) and reports honestly when unreachable.
'zoo-mainnet': trim(process.env.ZOO_MAINNET_RPC ?? 'https://api.zoo.network'),
}
/** Per-network probe timeout (ms). */
const TIMEOUT_MS = Number(process.env.NODES_RPC_TIMEOUT_MS ?? 8000)
/** A single allowlisted luxd JSON-RPC call. `path` and `method` are fixed here. */
async function rpc<T>(
host: string,
path: '/ext/bc/P' | '/ext/info',
method: string,
signal: AbortSignal,
): Promise<T> {
const res = await fetch(`${host}${path}`, {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method }),
cache: 'no-store',
signal,
})
if (!res.ok) throw new Error(`${method} ${res.status}`)
const json = (await res.json()) as { result?: T; error?: { message?: string } }
if (json?.error) throw new Error(json.error.message ?? `${method} error`)
return json.result as T
}
/** Probe ONE network: validators + peers + version + height, normalized. */
async function probe(net: NodeNetworkId): Promise<NetworkInventory> {
const meta = NODE_NETWORK_META[net]
const host = HOSTS[net]
const base: NetworkInventory = {
id: net,
chain: meta.chain,
env: meta.env,
label: meta.label,
status: 'not-reporting',
validators: 0,
peers: 0,
nodes: [],
chains: [],
}
const ctrl = new AbortController()
const timer = setTimeout(() => ctrl.abort(), TIMEOUT_MS)
try {
const [valR, peerR, verR, hgtR, chainR] = await Promise.allSettled([
rpc<{ validators?: RawValidator[] }>(host, '/ext/bc/P', 'platform.getCurrentValidators', ctrl.signal),
rpc<{ numPeers?: string; peers?: RawPeer[] }>(host, '/ext/info', 'info.peers', ctrl.signal),
rpc<{ version?: string }>(host, '/ext/info', 'info.getNodeVersion', ctrl.signal),
rpc<{ height?: string }>(host, '/ext/bc/P', 'platform.getHeight', ctrl.signal),
rpc<{ blockchains?: RawBlockchain[] }>(host, '/ext/bc/P', 'platform.getBlockchains', ctrl.signal),
])
const reachable =
valR.status === 'fulfilled' || peerR.status === 'fulfilled' || chainR.status === 'fulfilled'
if (!reachable) {
const reason =
valR.status === 'rejected'
? valR.reason
: peerR.status === 'rejected'
? peerR.reason
: chainR.status === 'rejected'
? chainR.reason
: null
base.error = reason instanceof Error ? reason.message : 'unreachable'
return base
}
const validators = valR.status === 'fulfilled' ? valR.value?.validators : undefined
const peers = peerR.status === 'fulfilled' ? peerR.value?.peers : undefined
const nodes = combineInventory(validators, peers, net)
base.status = 'reporting'
base.nodes = nodes
base.validators = nodes.filter((n) => n.role === 'validator').length
base.peers = nodes.filter((n) => n.role === 'peer').length
if (verR.status === 'fulfilled') base.version = verR.value?.version
if (hgtR.status === 'fulfilled') base.height = parseHeight(hgtR.value?.height)
// Chains are best-effort: a network can report validators/peers yet not answer
// getBlockchains — then the chains list is honestly empty (no fabricated chains).
if (chainR.status === 'fulfilled') base.chains = normalizeChains(chainR.value?.blockchains)
return base
} catch (e) {
base.error = e instanceof Error ? e.message : String(e)
return base
} finally {
clearTimeout(timer)
}
}
async function forward(req: NextRequest, path: string[]): Promise<NextResponse> {
// ONE endpoint — the inventory. No arbitrary RPC pass-through.
if (path.join('/') !== 'v1/inventory') {
return NextResponse.json({ error: 'not found' }, { status: 404 })
}
const user = await resolveUser(req)
if (!user) {
return NextResponse.json({ error: 'Sign in to view node infrastructure.' }, { status: 401 })
}
const brand = brandFromHost(req.headers.get('host'))
let networks = nodeNetworksForBrand(brand)
// Optional single-network scope, still gated by the brand's allowed set.
const only = req.nextUrl.searchParams.get('network') as NodeNetworkId | null
if (only) networks = networks.filter((n) => n === only)
const inventory = await Promise.all(networks.map(probe))
return NextResponse.json({ brand, networks: inventory })
}
type Ctx = { params: Promise<{ path: string[] }> }
export async function GET(req: NextRequest, ctx: Ctx) {
return forward(req, (await ctx.params).path)
}
+78
View File
@@ -0,0 +1,78 @@
/**
* Server-gated SELF-SERVICE org member proxy — a CUSTOMER managing their OWN org.
*
* The `/admin/iam` proxy is GLOBAL-admin only, so a tenant org owner (e.g.
* Dave/maxpower) could never manage their own members through it. This proxy
* closes that: it admits ANY authenticated user with an org (`getOrgGate`), then
* the shared `forwardIam`:
* - scopes every reference (query `owner`, `id` owner, and the mutation BODY
* owner) to the caller's OWN org — a global admin may cross, a customer never;
* - guards get-organization by org NAME (no reading another org's settings);
* - requires an ORG ADMIN for writes (invite / change-role / remove), while any
* member may READ the roster.
* IAM enforces its own checks on the user-bound bearer too — this is the matching,
* fail-closed server gate, not the only one.
*/
import { type NextRequest, NextResponse } from 'next/server'
import { getOrgGate } from '~/lib/server/identity'
import { forwardIam } from '~/lib/server/iam-proxy'
export const runtime = 'nodejs'
/** Reads — any member of the org (own org only, unless global). */
const GET_SEGMENTS = new Set([
'get-users',
'get-user',
'get-roles',
'get-organization',
// Projects live under the org (IAM-served); the console host's /v1 sends /v1/iam/*
// to the cloud binary → 404, so the Projects page routes here (Bearer → IAM).
'get-organization-projects',
])
/** Writes — org admin only, own org only (unless global). */
const POST_SEGMENTS = new Set([
'add-user',
'update-user',
'delete-user',
// Org branding/settings — org-admin only, pinned to the caller's OWN org by both
// the `?id` name AND the body name (below), so a brand admin can't retarget another.
'update-organization',
// Project CRUD — org-admin only (requireAdminForWrite), pinned to the caller's org.
'add-project',
'delete-project',
])
/** Org objects are owned by the `admin` metadata org (name guarded separately). */
const ORG_META = new Set(['get-organization', 'update-organization'])
/** Segments carrying an org NAME to pin to the caller's scope (read id + write body). */
const ORG_NAME = new Set(['get-organization', 'update-organization'])
/** Segments keyed by `organization` (projects) — pin it to the caller's own org so an
* omitted/empty organization can't enumerate/pollute across tenants. */
const ORG_PARAM = new Set(['get-organization-projects', 'add-project', 'delete-project'])
const forbidden = () => NextResponse.json({ error: 'forbidden' }, { status: 403 })
async function handle(req: NextRequest, path: string[], method: 'GET' | 'POST'): Promise<NextResponse> {
const gate = await getOrgGate(req)
if (!gate) return forbidden()
return forwardIam(req, gate, {
segment: path.join('/'),
method,
allowed: method === 'GET' ? GET_SEGMENTS : POST_SEGMENTS,
orgMetaSegments: ORG_META,
orgNameSegments: ORG_NAME,
orgParamSegments: ORG_PARAM,
requireAdminForWrite: true,
})
}
type Ctx = { params: Promise<{ path: string[] }> }
export async function GET(req: NextRequest, ctx: Ctx) {
return handle(req, (await ctx.params).path, 'GET')
}
export async function POST(req: NextRequest, ctx: Ctx) {
return handle(req, (await ctx.params).path, 'POST')
}
+115
View File
@@ -0,0 +1,115 @@
/**
* Same-origin proxy to the platform.hanzo.ai control plane (Job 3 — embedded
* PaaS). The browser calls console2's OWN origin (`/paas/...`); this server-side
* handler forwards to `platform.hanzo.ai/v1/...`, injecting the service token
* from server-only env (sourced via KMS — never `NEXT_PUBLIC_`, never in the
* browser bundle). This is the real control-plane API, not an iframe stub.
*
* SECURITY: the forwarded token is a PLATFORM SERVICE token — full control-plane
* authority, NOT tenant-scoped. So this route is gated to brand admins exactly
* like the IAM/KMS admin proxies: `getAdminGate` resolves the caller from their
* own session and requires a verified brand-admin (no gate → 403). Without this,
* any authenticated browser could drive the whole control plane through the
* service token. The gate is the control, NOT a deploy-time env toggle.
*
* When `PAAS_SERVICE_TOKEN` is unset the proxy returns an honest 501 so the UI
* can show a truthful "not configured" state — it never fabricates apps/deploys.
*
* SCOPE: the browser stamps the active tenant path (X-Org-Id / X-Project-Id /
* X-Environment) on every call. We forward it to the control plane so PaaS
* resources scope by org → project → environment like the rest of the console —
* but the ORG is re-resolved server-side through the admin policy (`orgFor`): a
* global admin's switched org is honored, a brand admin is PINNED to their own,
* so the forwarded X-Org-Id is authoritative and never the spoofable claim.
* Project + environment are sub-scopes the admin picks WITHIN that org, passed
* through verbatim.
*/
import { type NextRequest, NextResponse } from 'next/server'
import { getAdminGate } from '~/lib/server/identity'
import { orgFor as policyOrgFor } from '~/lib/server/admin-policy'
import { csrfRefusal } from '~/lib/server/bearer-proxy'
import { fetchWithTimeout } from '~/lib/server/fetch-timeout'
export const runtime = 'nodejs'
const PLATFORM_URL = (process.env.PLATFORM_URL ?? 'https://platform.hanzo.ai').replace(/\/+$/, '')
const TOKEN = process.env.PAAS_SERVICE_TOKEN ?? ''
async function forward(req: NextRequest, path: string[]): Promise<NextResponse> {
// CSRF FIRST — the service token below is control-plane god-mode, so a cross-site
// page carrying the admin's auto-sent cookie must never drive a deploy/scale/delete.
// Refuse a cross-origin MUTATION before the admin gate or any body read (safe reads
// pass). Defense in depth on top of the session cookie's own SameSite attribute.
const csrf = csrfRefusal(req)
if (csrf) return csrf
// Brand-admin gate — the service token below is control-plane god-mode.
const gate = await getAdminGate(req)
if (!gate) {
return NextResponse.json({ error: 'forbidden' }, { status: 403 })
}
if (!TOKEN) {
return NextResponse.json(
{ error: 'PaaS control plane is not configured (PAAS_SERVICE_TOKEN missing).' },
{ status: 501 },
)
}
// Resolve the authoritative tenant path. Org: the admin policy honors a global
// admin's switched org (the X-Org-Id the browser sends = currentOrg()) and pins
// a brand admin to their own — so we forward the resolved org, never the raw
// claim. Project + environment are sub-scopes within that org, forwarded as-is.
const org = policyOrgFor(
{ isGlobalAdmin: gate.user.isGlobalAdmin, orgScope: gate.orgScope },
req.headers.get('X-Org-Id'),
)
const projectId = req.headers.get('X-Project-Id')
const environment = req.headers.get('X-Environment')
const search = req.nextUrl.search
const url = `${PLATFORM_URL}/v1/${path.join('/')}${search}`
const init: RequestInit = {
method: req.method,
headers: {
Authorization: `Bearer ${TOKEN}`,
'Content-Type': 'application/json',
Accept: 'application/json',
'X-Org-Id': org,
...(projectId ? { 'X-Project-Id': projectId } : {}),
...(environment ? { 'X-Environment': environment } : {}),
},
// Never cache control-plane reads.
cache: 'no-store',
}
if (req.method !== 'GET' && req.method !== 'HEAD') {
init.body = await req.text()
}
try {
const res = await fetchWithTimeout(url, init)
const text = await res.text()
return new NextResponse(text, {
status: res.status,
headers: { 'Content-Type': res.headers.get('content-type') ?? 'application/json' },
})
} catch (e) {
return NextResponse.json(
{ error: `PaaS upstream unreachable: ${e instanceof Error ? e.message : String(e)}` },
{ status: 502 },
)
}
}
type Ctx = { params: Promise<{ path: string[] }> }
export async function GET(req: NextRequest, ctx: Ctx) {
return forward(req, (await ctx.params).path)
}
export async function POST(req: NextRequest, ctx: Ctx) {
return forward(req, (await ctx.params).path)
}
export async function PATCH(req: NextRequest, ctx: Ctx) {
return forward(req, (await ctx.params).path)
}
export async function DELETE(req: NextRequest, ctx: Ctx) {
return forward(req, (await ctx.params).path)
}
+69
View File
@@ -0,0 +1,69 @@
'use client'
/**
* Design-reference route — renders the ProductLanding kit + the RailwayDeploy pipeline
* in its lifecycle states OFFLINE (static status props, no backend, no auth), so the
* landing/pipeline design can be reviewed and screenshotted from `next dev` without a
* live session. Data-free by construction; not linked from the product nav.
*/
import { Boxes, DollarSign, FileText, Gauge, Layers, Plus, Search, Sparkles } from '@hanzogui/lucide-icons-2'
import { Card, Text, XStack, YStack } from '@hanzo/gui'
import { ProductLanding, apiBaseFromDocs, type LandingMetric, type ProductLandingConfig } from '~/components/products/landing'
import { RailwayDeploy } from '~/components/products/paas/RailwayDeploy'
import { embeddingsCodeSamples } from '~/components/products/embeddings/logic'
const metrics: LandingMetric[] = [
{ key: 'collections', label: 'Collections', value: 12, format: (n) => Math.round(n).toLocaleString(), icon: <Boxes size={14} opacity={0.6} /> },
{ key: 'documents', label: 'Documents indexed', value: 3420, format: (n) => Math.round(n).toLocaleString(), icon: <FileText size={14} opacity={0.6} /> },
{ key: 'vectors', label: 'Total vectors', value: 184213, format: (n) => Math.round(n).toLocaleString(), series: [120, 138, 150, 171, 184], deltaPct: 12, icon: <Layers size={14} opacity={0.6} /> },
{ key: 'queries', label: 'Queries (7D)', value: 8241, format: (n) => Math.round(n).toLocaleString(), series: [900, 1100, 1050, 1300, 1450], deltaPct: 8, icon: <Search size={14} opacity={0.6} /> },
{ key: 'latency', label: 'Avg latency', value: 42, format: (n) => `${Math.round(n)} ms`, series: [55, 50, 47, 44, 42], deltaPct: -6, icon: <Gauge size={14} opacity={0.6} /> },
{ key: 'cost', label: 'Cost (7D)', value: null, format: (n) => `$${(n / 100).toFixed(2)}`, icon: <DollarSign size={14} opacity={0.6} />, hint: 'Awaiting metering' },
]
const landingConfig: ProductLandingConfig = {
productId: 'embeddings',
title: 'Vector embeddings & semantic search',
tagline: 'Generate, store, and search embeddings at scale — one API for semantic search and RAG, powered by Zen embedding models.',
icon: Boxes,
docsProduct: 'embeddings',
primary: { label: 'Create collection', icon: <Plus size={16} />, onPress: () => {} },
secondary: { label: 'Try search', icon: <Search size={15} />, onPress: () => {} },
metrics,
samples: embeddingsCodeSamples(apiBaseFromDocs('https://docs.hanzo.ai'), 'zen-embedding'),
run: { label: 'Generate in console', icon: <Sparkles size={14} />, onPress: () => {} },
actions: [
{ label: 'Create collection', icon: <Plus size={15} />, onPress: () => {} },
{ label: 'Explore search', icon: <Search size={15} />, onPress: () => {} },
{ label: 'Generate embeddings', icon: <Sparkles size={15} />, onPress: () => {} },
],
}
function RailCard({ title, status }: { title: string; status: string }) {
return (
<Card p="$4" gap="$3" borderWidth={1} borderColor="$borderColor" bg="$color2" flex={1} minW={320}>
<Text fontSize="$3" fontWeight="700" color="$color12">
{title}
</Text>
<RailwayDeploy status={status} />
</Card>
)
}
export default function RailwayDemoPage() {
return (
<YStack gap="$6" p="$5" maxW={1180} self="center" width="100%">
<Text fontSize="$9" fontWeight="900">RailwayDeploy pipeline</Text>
<XStack gap="$4" flexWrap="wrap">
<RailCard title="Building (in progress)" status="building" />
<RailCard title="Deploying (in progress)" status="deploying" />
<RailCard title="Live" status="live" />
<RailCard title="Failed" status="error" />
</XStack>
<Text fontSize="$9" fontWeight="900">Embeddings landing (ProductLanding kit)</Text>
<ProductLanding config={landingConfig} />
</YStack>
)
}
+18
View File
@@ -0,0 +1,18 @@
'use client'
import { useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { SignInForm } from '~/components/SignInForm'
import { useSession } from '~/lib/auth/session'
export default function SignInPage() {
const { account, loading } = useSession()
const router = useRouter()
useEffect(() => {
if (!loading && account) router.replace('/')
}, [loading, account, router])
return <SignInForm />
}
+61
View File
@@ -0,0 +1,61 @@
/**
* Per-user proxy to the Hanzo Base control plane (base.hanzo.ai) — the embedded
* Base module's ONE transport. The browser calls console2's OWN origin
* (`/superbase/v1/...`) with just the session cookie; `forwardWithUserBearer`
* resolves the user, mints a short-lived user-bound IAM token (shared per-user
* cache), and forwards to base.hanzo.ai with that token. No token ever reaches the
* browser, and the SAME @hanzo/superbase-dashboard screens render here and standalone.
*
* NOT the PaaS pattern: PaaS forwards a god-mode SERVICE token and is gated to brand
* admins. Base authorizes PER USER itself — the `tenants` collection's
* `ListRule = "owner_iam_user = @request.auth.id"` and admin-only mutations are
* enforced by Base against the forwarded user identity. So here we forward the
* USER's own minted bearer (least privilege, tenant-scoped by Base), and the only
* gate is "must be signed in" (resolveUser → 401). A non-admin simply sees their own
* tenants and gets Base's 403 on a mutation — honest, not faked.
*
* Least privilege on the path too: only the Base DATA PLANE is proxied — the
* collection schemas (read) and any collection's records (list/get/create/update/
* delete), via `allowBaseSurface`. Base's admin/settings/backup/log surfaces 404,
* so this stays a data-plane proxy, not a general Base tunnel. Base still authorizes
* every read/write per-user and per-collection itself, so a non-admin sees only what
* a collection's rules permit and gets Base's own honest 403 on a denied mutation.
* (The tenants manager rides this same proxy — records/tenants is one such path.)
*/
import { type NextRequest } from 'next/server'
import { forwardWithUserBearer } from '~/lib/server/bearer-proxy'
import { allowBaseSurface } from '~/lib/server/proxy-allow'
export const runtime = 'nodejs'
const trim = (s: string) => s.replace(/\/+$/, '')
/** The Base control plane the proxied calls are forwarded to. */
const BASE_URL = trim(process.env.BASE_DASHBOARD_URL ?? 'https://base.hanzo.ai')
type Ctx = { params: Promise<{ path: string[] }> }
function handle(req: NextRequest, ctx: Ctx) {
return (async () => {
const path = (await ctx.params).path.join('/')
return forwardWithUserBearer(req, {
target: BASE_URL,
path,
allow: allowBaseSurface,
unauthorizedMessage: 'Sign in to manage Base records.',
})
})()
}
export async function GET(req: NextRequest, ctx: Ctx) {
return handle(req, ctx)
}
export async function POST(req: NextRequest, ctx: Ctx) {
return handle(req, ctx)
}
export async function PATCH(req: NextRequest, ctx: Ctx) {
return handle(req, ctx)
}
export async function DELETE(req: NextRequest, ctx: Ctx) {
return handle(req, ctx)
}
+38
View File
@@ -0,0 +1,38 @@
/**
* Same-origin proxy to the durable task engine (hanzoai/tasks `tasksd`, the native
* Temporal-style HTTP surface at `/v1/tasks/*`).
*
* `tasksd` runs `TASKSD_REQUIRE_IDENTITY=true`: it validates an IAM **Bearer JWT**
* against the IAM JWKS, unconditionally STRIPS inbound `X-Org-Id`, and mints org +
* user from the JWT claims (`owner`→org). So — like the `/ai` proxy — the console
* calls its OWN origin (`/tasksd/...`) with just the session cookie;
* `forwardWithUserBearer` resolves the signed-in user, mints a short-lived
* user-bound IAM token (shared per-user cache), and forwards it as the Bearer. No
* key in the browser, and every read is org-scoped by the JWT server-side.
*
* READ-ONLY: only GET is proxied (the console never mutates workflows here), scoped
* to the `v1/tasks/*` subtree. When the engine is unreachable the UI shows an honest
* BackendStateCard — never fabricated workflows.
*/
import { type NextRequest } from 'next/server'
import { forwardWithUserBearer } from '~/lib/server/bearer-proxy'
export const runtime = 'nodejs'
const trim = (s: string) => s.replace(/\/+$/, '')
/** The durable task engine. Public TLS is not live yet → default to the in-cluster
* service. The tasks Service exposes REST on :7243 (http port); there is NO :80,
* so target :7243 explicitly. Override with TASKS_URL. `|| default` (not `??`) so a
* blank env still falls back to the in-cluster service. */
const TASKS_URL = trim(process.env.TASKS_URL?.trim() || 'http://tasks.hanzo.svc.cluster.local:7243')
export async function GET(req: NextRequest, ctx: { params: Promise<{ path: string[] }> }) {
const rel = (await ctx.params).path.join('/')
return forwardWithUserBearer(req, {
target: TASKS_URL,
path: `v1/tasks/${rel}`,
allow: (p) => p === 'v1/tasks' || p.startsWith('v1/tasks/'),
unauthorizedMessage: 'Sign in to view tasks.',
})
}
+106
View File
@@ -0,0 +1,106 @@
/**
* Same-origin READ-ONLY proxy to VictoriaMetrics — the live platform telemetry
* store (Prometheus-compatible TSDB, `vmsingle-victoria-metrics-single-server`).
*
* The browser calls this OWN-origin route (`/telemetry/api/v1/query?query=up`) with
* just its first-party session cookie; this handler resolves the caller
* (`resolveUser`) and — only for a signed-in user — forwards the READ query to
* VictoriaMetrics. It powers Status (real `up{}` service health) and Metrics (real
* infra time-series), replacing the empty `/paas/apps` board and the unwired
* Metrics overview. VictoriaMetrics has no per-request auth of its own (it is an
* internal ClusterIP service), so this route IS the access boundary — hence three
* hard limits, all fail-closed:
*
* 1. Authenticated only — `resolveUser` (401 otherwise). Platform status/metrics
* is not tenant-customer data; it is the health of the Hanzo Cloud platform the
* user is signed into (a status-page concern), appropriate for any signed-in
* console user and strictly READ-ONLY — no service token, far weaker than the
* admin `/paas` control plane.
* 2. READ-only — GET only, and only the allow-listed VictoriaMetrics query
* endpoints (`allowTelemetrySurface`): `/api/v1/query`, `/query_range`,
* `/series`, `/labels`, `/label/<name>/values`, `/status/tsdb`, `/metadata`.
* Never `/api/v1/write`, `/import`, `/-/reload`, or any admin/mutating path.
* 3. Traversal-hardened — `pathIsClean` rejects `.`/`..`/`%XX`/`;` segments and the
* forward re-validates the WHATWG-normalized path, exactly like the bearer
* proxies.
*
* Honest 501 when `VM_URL` is unset, so the UI shows a truthful "telemetry not
* configured" state — never fabricated metrics.
*/
import { type NextRequest, NextResponse } from 'next/server'
import { resolveUser } from '~/lib/server/identity'
import { pathIsClean } from '~/lib/server/bearer-proxy'
import { allowTelemetrySurface } from '~/lib/server/proxy-allow'
import { fetchWithTimeout } from '~/lib/server/fetch-timeout'
export const runtime = 'nodejs'
const trimR = (s: string) => s.replace(/\/+$/, '')
const trimL = (s: string) => s.replace(/^\/+/, '')
const msgOf = (e: unknown) => (e instanceof Error ? e.message : String(e))
/** VictoriaMetrics single-node read API. In-cluster ClusterIP :8428 (headless).
* Override with VM_URL. `|| default` (not `??`) so a blank/whitespace env still
* resolves the in-cluster service (the same env-drift guard the /vm proxy uses). */
const VM_URL = trimR(
process.env.VM_URL?.trim() || 'http://vmsingle-victoria-metrics-single-server.hanzo.svc:8428',
)
const json = (body: unknown, status: number) => NextResponse.json(body, { status })
type Ctx = { params: Promise<{ path: string[] }> }
export async function GET(req: NextRequest, ctx: Ctx): Promise<NextResponse> {
const rawPath = trimL((await ctx.params).path.join('/')).replace(/\/+$/, '')
// Traversal + least-privilege on the RAW path (literal `.`/`..`/`%XX`/`;` rejected).
if (!pathIsClean(rawPath) || !allowTelemetrySurface(rawPath)) {
return json({ status: 'error', errorType: 'not_allowed', error: 'Not a telemetry read endpoint.' }, 404)
}
if (!process.env.VM_URL?.trim() && !VM_URL) {
return json(
{ status: 'error', errorType: 'not_configured', error: 'Telemetry store is not configured (VM_URL missing).' },
501,
)
}
// Authenticated only — the query surface is the access boundary (VM has no auth).
const user = await resolveUser(req)
if (!user) {
return json({ status: 'error', errorType: 'unauthenticated', error: 'Sign in to view platform telemetry.' }, 401)
}
// Re-validate the WHATWG-normalized destination (undici resolves %2e/double-encoded
// dot-segments a raw check can't see) — validate AND fetch the exact same URL.
let dest: URL
try {
dest = new URL(`${VM_URL}/${rawPath}${req.nextUrl.search}`)
} catch {
return json({ status: 'error', errorType: 'not_allowed', error: 'Bad telemetry path.' }, 404)
}
const normPath = trimL(dest.pathname).replace(/\/+$/, '')
if (!pathIsClean(normPath) || !allowTelemetrySurface(normPath)) {
return json({ status: 'error', errorType: 'not_allowed', error: 'Not a telemetry read endpoint.' }, 404)
}
try {
const res = await fetchWithTimeout(dest, {
method: 'GET',
headers: { Accept: 'application/json' },
cache: 'no-store',
signal: req.signal,
})
return new NextResponse(res.body, {
status: res.status,
headers: {
'Content-Type': res.headers.get('content-type') ?? 'application/json',
'Cache-Control': 'no-cache, no-transform',
},
})
} catch (e) {
console.error('telemetry-proxy: VictoriaMetrics unreachable:', msgOf(e))
return json({ status: 'error', errorType: 'upstream_error', error: 'Telemetry store is unavailable.' }, 502)
}
}
+185
View File
@@ -0,0 +1,185 @@
/**
* Per-user proxy to the LIVE trading-bot state — the Trading module's ONE
* live-data transport (the DEPLOYED FLEET is read separately via the `/cloud`
* PaaS proxy). The browser calls console2's OWN origin (`/trading/v1/*`) with just
* the session cookie; this handler resolves the caller, resolves the BRAND from the
* request host, and reads the allowlisted upstreams server-side, per network that
* brand may see. No cluster host or RPC method ever reaches the browser, and the
* browser can never choose either.
*
* Security (mirrors app/nodes/[...path]/route.ts):
* - Session-gated: an unauthenticated caller gets 401.
* - Org/brand-aware: the network set is scoped by `nodeNetworksForBrand(brand)`,
* brand resolved from the host — cloud.lux.cloud sees only Lux networks.
* - Least privilege: the ONLY paths are `v1/metrics` and `v1/orderbook`; the ONLY
* upstreams are the maker's :2112 /metrics scrape and the DEX read endpoint —
* this is not a general RPC/HTTP tunnel.
*
* Two upstreams, one concern each:
* 1. METRICS — GETs the in-cluster maker's Prometheus `:2112/metrics` for a
* network and parses it to `MakerStatus`. The maker Service host per network is
* env-configurable; unset/unreachable → an honest `not-reporting` status.
* 2. ORDERBOOK — reads the DEX CLOB `dex_get_orders?market=<poolHex>` for a market
* on a network. The DEX read host is env-configurable; the private D-Chain is
* not publicly exposed, so an unreachable venue → an honest `not-reporting` book
* (never fabricated bids/asks).
*/
import { type NextRequest, NextResponse } from 'next/server'
import { brandFromHost } from '~/config'
import { resolveUser } from '~/lib/server/identity'
import { nodeNetworksForBrand, type NodeNetworkId } from '~/lib/products/brand-scope'
import { fetchWithTimeout } from '~/lib/server/fetch-timeout'
import {
parseMakerMetrics,
normalizeBook,
type MakerStatus,
type OrderBook,
type RawBookOrder,
} from '~/lib/api/trading'
export const runtime = 'nodejs'
const trim = (s: string) => s.replace(/\/+$/, '')
/**
* The maker's Prometheus metrics host per network — the ONLY metrics endpoint this
* proxy will scrape. These point at the in-cluster maker Service (`maker-coherence`,
* port 2112) per luxd network namespace. Each is overridable per-deploy; an
* unset/unreachable host yields an honest `not-reporting` status — never fake rows.
* (Cross-cluster reach depends on network policy; when unreachable the console shows
* the honest not-reporting state, exactly like the Nodes surface.)
*/
const MAKER_METRICS_HOSTS: Partial<Record<NodeNetworkId, string>> = {
'lux-mainnet': trim(process.env.MAKER_METRICS_MAINNET ?? 'http://maker-coherence.lux-mainnet.svc:2112'),
'lux-testnet': trim(process.env.MAKER_METRICS_TESTNET ?? 'http://maker-coherence.lux-testnet.svc:2112'),
'lux-devnet': trim(process.env.MAKER_METRICS_DEVNET ?? 'http://maker-coherence.lux-devnet.svc:2112'),
}
/**
* The DEX read host per network — the ONLY DEX endpoint this proxy will query for
* the order book (`<host>/dex/dex_get_orders?market=<poolHex>`). The native D-Chain
* CLOB is not publicly exposed, so these default to the in-cluster luxd router;
* unreachable → an honest `not-reporting` book.
*/
const DEX_READ_HOSTS: Partial<Record<NodeNetworkId, string>> = {
'lux-mainnet': trim(process.env.DEX_READ_MAINNET ?? 'http://luxd-0.luxd-headless.lux-mainnet.svc:9630/v1/bc/D'),
'lux-testnet': trim(process.env.DEX_READ_TESTNET ?? 'http://luxd-0.luxd-headless.lux-testnet.svc:9640/v1/bc/D'),
'lux-devnet': trim(process.env.DEX_READ_DEVNET ?? 'http://luxd-0.luxd-headless.lux-devnet.svc:9650/v1/bc/D'),
}
/** Per-upstream probe timeout (ms). */
const TIMEOUT_MS = Number(process.env.TRADING_TIMEOUT_MS ?? 8000)
/** Scrape ONE network's maker metrics → MakerStatus. Honest not-reporting on failure. */
async function makerStatus(net: NodeNetworkId): Promise<MakerStatus> {
const host = MAKER_METRICS_HOSTS[net]
const base: MakerStatus = { status: 'not-reporting', symbols: [] }
if (!host) {
base.error = 'no metrics host configured for this network'
return base
}
try {
const res = await fetchWithTimeout(
`${host}/metrics`,
{ headers: { accept: 'text/plain' }, cache: 'no-store' },
{ timeoutMs: TIMEOUT_MS },
)
if (!res.ok) {
base.error = `metrics ${res.status}`
return base
}
const text = await res.text()
const parsed = parseMakerMetrics(text)
return { status: 'reporting', ...parsed }
} catch (e) {
base.error = e instanceof Error ? e.message : String(e)
return base
}
}
/** A single allowlisted DEX read call. `method` is fixed here (dex_get_orders). */
async function dexGetOrders(host: string, poolHex: string): Promise<RawBookOrder[]> {
const url = `${host}/dex/dex_get_orders?market=${encodeURIComponent(poolHex)}`
const res = await fetchWithTimeout(url, { headers: { accept: 'application/json' }, cache: 'no-store' }, { timeoutMs: TIMEOUT_MS })
if (!res.ok) throw new Error(`dex_get_orders ${res.status}`)
const json = (await res.json()) as { orders?: RawBookOrder[] }
return Array.isArray(json?.orders) ? json.orders : []
}
/**
* Read ONE market's order book. A `poolId` (32-byte hex) addresses the book
* directly; a `symbol`/`base`/`quote` are echoed for display but the book is only
* readable by poolId (the console does not compute keccak client- or server-side to
* avoid an eth-crypto dep — the caller supplies the poolId, or the book is honestly
* not-reporting). Honest not-reporting when the DEX is unreachable.
*/
async function orderbook(net: NodeNetworkId, params: URLSearchParams): Promise<OrderBook> {
const symbol = params.get('symbol') ?? undefined
const poolId = params.get('poolId') ?? undefined
const base: OrderBook = { network: net, symbol, poolId, status: 'not-reporting', orders: [] }
const host = DEX_READ_HOSTS[net]
if (!host) {
base.error = 'no DEX read host configured for this network'
return base
}
if (!poolId) {
// No poolId → the book can't be addressed. Honest, never fabricated.
base.error = 'order book is read by poolId; none supplied for this market'
return base
}
try {
const raw = await dexGetOrders(host, poolId)
return { ...base, status: 'reporting', orders: normalizeBook(raw), error: undefined }
} catch (e) {
base.error = e instanceof Error ? e.message : String(e)
return base
}
}
/** Resolve the brand's networks, optionally narrowed to `?network=` (still gated). */
function scopedNetworks(req: NextRequest): NodeNetworkId[] {
const brand = brandFromHost(req.headers.get('host'))
let networks = nodeNetworksForBrand(brand)
const only = req.nextUrl.searchParams.get('network') as NodeNetworkId | null
if (only) networks = networks.filter((n) => n === only)
return networks
}
async function forward(req: NextRequest, path: string[]): Promise<NextResponse> {
const route = path.join('/')
const user = await resolveUser(req)
if (!user) {
return NextResponse.json({ error: 'Sign in to view trading bots.' }, { status: 401 })
}
if (route === 'v1/metrics') {
const networks = scopedNetworks(req)
// A single-network scope is the common case (per-bot status); return the first
// (the network the caller asked for), or the brand's first if none specified.
const net = networks[0]
if (!net) return NextResponse.json({ status: 'not-reporting', symbols: [], error: 'no network in scope' })
const status = await makerStatus(net)
return NextResponse.json(status)
}
if (route === 'v1/orderbook') {
const networks = scopedNetworks(req)
const net = networks[0]
if (!net) {
return NextResponse.json({ network: null, status: 'not-reporting', orders: [], error: 'no network in scope' })
}
const book = await orderbook(net, req.nextUrl.searchParams)
return NextResponse.json(book)
}
return NextResponse.json({ error: 'not found' }, { status: 404 })
}
type Ctx = { params: Promise<{ path: string[] }> }
export async function GET(req: NextRequest, ctx: Ctx) {
return forward(req, (await ctx.params).path)
}
+118
View File
@@ -0,0 +1,118 @@
/**
* Same-origin proxy to the cloud ML/training surface on hanzoai/ai (`/v1/train/*`,
* `/v1/ml/models`, and the fine-tuning broker `/v1/finetune/*`).
*
* The console's Training page calls its OWN origin (`/training/...`) with just the
* first-party session cookie; this server handler resolves the signed-in user from
* that cookie and forwards to the cloud backend's `/v1/...` surface, passing the
* cookie through (the proven `get-account` server-to-server pattern in
* lib/server/identity.ts) plus the active `X-Org-Id`. Training is a TENANT action —
* any signed-in org user may run it — so this is user-scoped (resolveUser), NOT the
* control-plane admin gate the `/paas` proxy uses. The cloud backend scopes by org
* (GetEffectiveOrg / the X-Org-Id the plain-REST train sub-service requires), so a
* caller can only ever touch their own org's jobs. `POST /v1/train/jobs` is
* billing-gated by the live ResourceMeter and returns 402 on an unfunded org — that
* status flows straight back so the UI can surface it honestly.
*
* Least privilege: only the explicit ML/training sub-paths are forwarded; anything
* else 404s, so this is not a general backend tunnel. No secret ever reaches the
* browser — the HuggingFace token (for private repos) is resolved from KMS
* server-side inside the broker, never here.
*/
import { type NextRequest, NextResponse } from 'next/server'
import { resolveUser } from '~/lib/server/identity'
import { orgFor } from '~/lib/server/admin-policy'
import { csrfRefusal } from '~/lib/server/bearer-proxy'
import { fetchWithTimeout } from '~/lib/server/fetch-timeout'
export const runtime = 'nodejs'
const trim = (s: string) => s.replace(/\/+$/, '')
/** Cloud `/v1` backend (hanzoai/ai) — same target lib/server/identity.ts resolves. */
const CLOUD_API_URL = trim(process.env.CLOUD_API_URL ?? 'http://cloud.hanzo.svc.cluster.local:8000')
/** The exact `/v1/<...>` ML/training sub-paths the console is allowed to reach. */
const ALLOWED = new Set([
// mlsvc — the canonical training surface (task #40 ResourceMeter gates POST jobs).
'train/jobs',
'train/experiments',
'ml/models',
// Real Kubeflow control-plane probe (which operators/CRDs are actually served).
// Read-only; 503 + body flows through so the UI can report a degraded plane.
'train/health',
// fine-tuning broker (custom-data runs, HF search) — sibling surface.
'finetune/jobs',
'finetune/job',
'finetune/cancel',
'finetune/deploy',
'finetune/presets',
'finetune/hf/models',
'finetune/hf/datasets',
'finetune/hf/repo',
])
async function forward(req: NextRequest, path: string[]): Promise<NextResponse> {
const rel = path.join('/')
if (!ALLOWED.has(rel)) {
return NextResponse.json({ status: 'error', msg: 'Not found' }, { status: 404 })
}
// CSRF: `POST /train/jobs` mutates (and bills) from the auto-sent cookie — refuse a
// cross-origin one before any work (safe reads pass).
const csrf = csrfRefusal(req, 'casibase')
if (csrf) return csrf
const user = await resolveUser(req)
if (!user) {
return NextResponse.json(
{ status: 'error', msg: 'Sign in to manage training.' },
{ status: 401 },
)
}
const cookie = req.headers.get('cookie') ?? ''
const url = `${CLOUD_API_URL}/v1/${rel}${req.nextUrl.search}`
const headers: Record<string, string> = {
cookie,
Accept: 'application/json',
'Content-Type': 'application/json',
// Org is SERVER-RESOLVED, not the raw browser header: a global admin's switched
// org (?/X-Org-Id) is honored, a non-global caller is PINNED to their own — so a
// brand admin can't drive another tenant's training jobs even if the backend
// trusted the forwarded header. Matches the /paas + /admin/kms orgFor pin.
'X-Org-Id': orgFor({ isGlobalAdmin: user.isGlobalAdmin, orgScope: user.owner }, req.headers.get('X-Org-Id')),
}
const projectId = req.headers.get('X-Project-Id')
const environment = req.headers.get('X-Environment')
if (projectId) headers['X-Project-Id'] = projectId
if (environment) headers['X-Environment'] = environment
const init: RequestInit = { method: req.method, headers, cache: 'no-store' }
if (req.method !== 'GET' && req.method !== 'HEAD') {
init.body = await req.text()
}
try {
const res = await fetchWithTimeout(url, init)
const text = await res.text()
return new NextResponse(text, {
status: res.status,
headers: { 'Content-Type': res.headers.get('content-type') ?? 'application/json' },
})
} catch (e) {
return NextResponse.json(
{ status: 'error', msg: `Fine-tuning backend unreachable: ${e instanceof Error ? e.message : String(e)}` },
{ status: 502 },
)
}
}
type Ctx = { params: Promise<{ path: string[] }> }
export async function GET(req: NextRequest, ctx: Ctx) {
return forward(req, (await ctx.params).path)
}
export async function POST(req: NextRequest, ctx: Ctx) {
return forward(req, (await ctx.params).path)
}
+63
View File
@@ -0,0 +1,63 @@
/**
* Same-origin user-bearer proxy to Visor (vm.hanzo.ai) — the compute control plane
* (regions / gpus / machines / instances). The browser calls this OWN-origin route
* (`/vm/v1/...`) with just its session cookie; `forwardWithUserBearer` resolves the
* user, mints a short-lived user-bound IAM token, and forwards to visor with that
* Bearer. Visor mints org + user from the JWT claims, so compute is org-scoped
* server-side — a caller only ever sees their own org's machines. No token reaches
* the browser.
*
* NOT the `/paas` pattern: `/paas` forwards a god-mode control-plane SERVICE token
* and is gated to brand admins. Compute is a TENANT action (any signed-in org user
* may list/manage their own machines), so this is user-scoped (resolveUser), and
* visor itself authorizes the forwarded user bearer.
*
* Least privilege on the path: only the visor `v1/*` surface is reachable
* (`allowVisorSurface`); anything else 404s.
*/
import { type NextRequest } from 'next/server'
import { forwardWithUserBearer } from '~/lib/server/bearer-proxy'
import { allowVisorSurface } from '~/lib/server/proxy-allow'
export const runtime = 'nodejs'
const trim = (s: string) => s.replace(/\/+$/, '')
/** Visor (vm.hanzo.ai). In-cluster ClusterIP on :19000 (its Service has NO :80) — public
* egress is CF-403'd. Override with VISOR_URL (the CR sets visor.hanzo.svc:19000).
* `|| default` (not `??`): if the env is reconciled to an EMPTY string (observed drift on
* the live pod), `??` would keep the blank and every machines/GPUs call would fail —
* `|| default` treats blank/whitespace as unset so visor ALWAYS resolves. */
const VISOR_URL = trim(process.env.VISOR_URL?.trim() || 'http://visor.hanzo.svc:19000')
type Ctx = { params: Promise<{ path: string[] }> }
function handle(req: NextRequest, ctx: Ctx) {
return (async () => {
const path = (await ctx.params).path.join('/')
return forwardWithUserBearer(req, {
target: VISOR_URL,
path,
allow: allowVisorSurface,
// Org is authoritative (Bearer owner). Don't forward browser X-Project-Id/
// X-Environment (unvalidated sub-scopes) — RED MEDIUM.
unauthorizedMessage: 'Sign in to manage compute.',
})
})()
}
export async function GET(req: NextRequest, ctx: Ctx) {
return handle(req, ctx)
}
export async function POST(req: NextRequest, ctx: Ctx) {
return handle(req, ctx)
}
export async function PUT(req: NextRequest, ctx: Ctx) {
return handle(req, ctx)
}
export async function PATCH(req: NextRequest, ctx: Ctx) {
return handle(req, ctx)
}
export async function DELETE(req: NextRequest, ctx: Ctx) {
return handle(req, ctx)
}
-13
View File
@@ -1,13 +0,0 @@
_We are Hiring_
Join us in scaling Langfuse in Berlin, Germany. We are an open source company, we hire in person, we are only hiring technical talent.
_Open Roles_
- Product Engineer, 70-130k EUR, 0.25-0.75% Equity, https://www.ycombinator.com/companies/langfuse/jobs/aAvmoFB-product-engineer
- Developer Advocate, 60-110k EUR, 0.25-0.5% Equity, https://www.ycombinator.com/companies/langfuse/jobs/uHysbKH-developer-advocate-devrel
_More Info_
- https://langfuse.com/careers
- https://langfuse.com/docs
- https://langfuse.com/changelog
Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

-88
View File
@@ -1,88 +0,0 @@
version: "3.5"
services:
server:
build:
dockerfile: ./web/Dockerfile
context: .
args:
- NEXT_PUBLIC_LANGFUSE_CLOUD_REGION=${NEXT_PUBLIC_LANGFUSE_CLOUD_REGION}
depends_on:
- db
- redis
ports:
- "3000:3000"
environment:
- DATABASE_URL=postgresql://postgres:postgres@db:5432/postgres
- NEXTAUTH_SECRET=mysecret
- SALT=mysalt
- ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000 # generate via `openssl rand -hex 32`
- NEXTAUTH_URL=http://localhost:3000
- TELEMETRY_ENABLED=${TELEMETRY_ENABLED:-true}
- LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES=${LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES:-false}
- LANGFUSE_INIT_ORG_ID=${LANGFUSE_INIT_ORG_ID:-}
- LANGFUSE_INIT_ORG_NAME=${LANGFUSE_INIT_ORG_NAME:-}
- LANGFUSE_INIT_PROJECT_ID=${LANGFUSE_INIT_PROJECT_ID:-}
- LANGFUSE_INIT_PROJECT_NAME=${LANGFUSE_INIT_PROJECT_NAME:-}
- LANGFUSE_INIT_PROJECT_PUBLIC_KEY=${LANGFUSE_INIT_PROJECT_PUBLIC_KEY:-}
- LANGFUSE_INIT_PROJECT_SECRET_KEY=${LANGFUSE_INIT_PROJECT_SECRET_KEY:-}
- LANGFUSE_INIT_USER_EMAIL=${LANGFUSE_INIT_USER_EMAIL:-}
- LANGFUSE_INIT_USER_NAME=${LANGFUSE_INIT_USER_NAME:-}
- LANGFUSE_INIT_USER_PASSWORD=${LANGFUSE_INIT_USER_PASSWORD:-}
restart: always
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/api/public/health"]
interval: 30s
timeout: 10s
retries: 3
worker:
build:
dockerfile: ./worker/Dockerfile
context: .
args:
- NEXT_PUBLIC_LANGFUSE_CLOUD_REGION=${NEXT_PUBLIC_LANGFUSE_CLOUD_REGION}
depends_on:
- db
- redis
ports:
- "3030:3030"
environment:
- DATABASE_URL=postgresql://postgres:postgres@db:5432/postgres
- NEXTAUTH_SECRET=mysecret
- TELEMETRY_ENABLED=${TELEMETRY_ENABLED:-true}
- LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES=${LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES:-false}
- PORT=${PORT:-3030}
- REDIS_HOST=${REDIS_HOST:-redis}
- REDIS_PORT=${REDIS_PORT:-6379}
- REDIS_AUTH=${REDIS_AUTH:-myredissecret}
restart: always
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3030/api/health"]
interval: 30s
timeout: 10s
retries: 3
redis:
image: redis:7.2.4
command: >
--requirepass ${REDIS_AUTH:-myredissecret}
restart: always
ports:
- 6379:6379
db:
image: postgres
restart: always
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
- POSTGRES_DB=postgres
ports:
- 5432:5432
volumes:
- database_data:/var/lib/postgresql/data
volumes:
database_data:
driver: local
-63
View File
@@ -1,63 +0,0 @@
services:
clickhouse:
image: clickhouse/clickhouse-server
user: "101:101"
container_name: clickhouse
hostname: clickhouse
environment:
CLICKHOUSE_DB: default
CLICKHOUSE_USER: clickhouse
CLICKHOUSE_PASSWORD: clickhouse
volumes:
- langfuse_clickhouse_data:/var/lib/clickhouse
- langfuse_clickhouse_logs:/var/log/clickhouse-server
ports:
- "8123:8123"
- "9000:9000"
depends_on:
- postgres
azurite:
image: mcr.microsoft.com/azure-storage/azurite
container_name: azurite
command: azurite-blob --blobHost 0.0.0.0
ports:
- "10000:10000"
volumes:
- langfuse_azurite_data:/data
redis:
image: redis:7.2.4
restart: always
command: >
--requirepass ${REDIS_AUTH:-myredissecret}
ports:
- 6379:6379
postgres:
image: postgres:${POSTGRES_VERSION:-latest}
restart: always
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 3s
timeout: 3s
retries: 10
command: ["postgres", "-c", "log_statement=all"]
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
- POSTGRES_DB=postgres
ports:
- 5432:5432
volumes:
- langfuse_postgres_data:/var/lib/postgresql/data
volumes:
langfuse_postgres_data:
driver: local
langfuse_clickhouse_data:
driver: local
langfuse_clickhouse_logs:
driver: local
langfuse_azurite_data:
driver: local
-75
View File
@@ -1,75 +0,0 @@
services:
clickhouse:
image: clickhouse/clickhouse-server
user: "101:101"
container_name: clickhouse
hostname: clickhouse
environment:
CLICKHOUSE_DB: default
CLICKHOUSE_USER: clickhouse
CLICKHOUSE_PASSWORD: clickhouse
volumes:
- langfuse_clickhouse_data:/var/lib/clickhouse
- langfuse_clickhouse_logs:/var/log/clickhouse-server
ports:
- "8123:8123"
- "9000:9000"
depends_on:
- postgres
minio:
image: minio/minio
container_name: minio
entrypoint: sh
# create the 'langfuse' bucket before starting the service
command: -c 'mkdir -p /data/langfuse && minio server --address ":9000" --console-address ":9001" /data'
environment:
MINIO_ACCESS_KEY: minio
MINIO_SECRET_KEY: miniosecret
ports:
- "9090:9000"
- "9091:9001"
volumes:
- langfuse_minio_data:/data
healthcheck:
test: ["CMD", "mc", "ready", "local"]
interval: 1s
timeout: 5s
retries: 5
start_period: 1s
redis:
image: redis:7.2.4
restart: always
command: >
--requirepass ${REDIS_AUTH:-myredissecret}
ports:
- 6379:6379
postgres:
image: postgres:${POSTGRES_VERSION:-latest}
restart: always
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 3s
timeout: 3s
retries: 10
command: ["postgres", "-c", "log_statement=all"]
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
- POSTGRES_DB=postgres
ports:
- 5432:5432
volumes:
- langfuse_postgres_data:/var/lib/postgresql/data
volumes:
langfuse_postgres_data:
driver: local
langfuse_clickhouse_data:
driver: local
langfuse_clickhouse_logs:
driver: local
langfuse_minio_data:
driver: local
-145
View File
@@ -1,145 +0,0 @@
services:
langfuse-worker:
image: langfuse/langfuse-worker:latest
depends_on: &langfuse-depends-on
postgres:
condition: service_healthy
minio:
condition: service_healthy
redis:
condition: service_healthy
ports:
- "3030:3030"
environment: &langfuse-worker-env
DATABASE_URL: postgresql://postgres:postgres@postgres:5432/postgres
SALT: "mysalt"
ENCRYPTION_KEY: "0000000000000000000000000000000000000000000000000000000000000000" # generate via `openssl rand -hex 32`
TELEMETRY_ENABLED: ${TELEMETRY_ENABLED:-true}
LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES: ${LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES:-true}
LANGFUSE_ASYNC_INGESTION_PROCESSING: ${LANGFUSE_ASYNC_INGESTION_PROCESSING:-true}
LANGFUSE_ASYNC_CLICKHOUSE_INGESTION_PROCESSING: ${LANGFUSE_ASYNC_CLICKHOUSE_INGESTION_PROCESSING:-true}
LANGFUSE_READ_DASHBOARDS_FROM_CLICKHOUSE: ${LANGFUSE_READ_DASHBOARDS_FROM_CLICKHOUSE:-true}
LANGFUSE_READ_FROM_POSTGRES_ONLY: ${LANGFUSE_READ_FROM_POSTGRES_ONLY:-false}
LANGFUSE_RETURN_FROM_CLICKHOUSE: ${LANGFUSE_RETURN_FROM_CLICKHOUSE:-true}
CLICKHOUSE_MIGRATION_URL: ${CLICKHOUSE_MIGRATION_URL:-clickhouse://clickhouse:9000}
CLICKHOUSE_URL: ${CLICKHOUSE_URL:-http://clickhouse:8123}
CLICKHOUSE_USER: ${CLICKHOUSE_USER:-clickhouse}
CLICKHOUSE_PASSWORD: ${CLICKHOUSE_PASSWORD:-clickhouse}
CLICKHOUSE_CLUSTER_ENABLED: ${CLICKHOUSE_CLUSTER_ENABLED:-false}
LANGFUSE_S3_EVENT_UPLOAD_ENABLED: ${LANGFUSE_S3_EVENT_UPLOAD_ENABLED:-true}
LANGFUSE_S3_EVENT_UPLOAD_BUCKET: ${LANGFUSE_S3_EVENT_UPLOAD_BUCKET:-langfuse}
LANGFUSE_S3_EVENT_UPLOAD_REGION: ${LANGFUSE_S3_EVENT_UPLOAD_REGION:-us-east-1}
LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID: ${LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID:-minio}
LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY: ${LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY:-miniosecret}
LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT: ${LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT:-http://minio:9000}
LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE: ${LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE:-true}
LANGFUSE_S3_EVENT_UPLOAD_PREFIX: ${LANGFUSE_S3_EVENT_UPLOAD_PREFIX:-events/}
LANGFUSE_S3_MEDIA_UPLOAD_ENABLED: ${LANGFUSE_S3_MEDIA_UPLOAD_ENABLED:-true}
LANGFUSE_S3_MEDIA_UPLOAD_BUCKET: ${LANGFUSE_S3_MEDIA_UPLOAD_BUCKET:-langfuse}
LANGFUSE_S3_MEDIA_UPLOAD_REGION: ${LANGFUSE_S3_MEDIA_UPLOAD_REGION:-us-east-1}
LANGFUSE_S3_MEDIA_UPLOAD_ACCESS_KEY_ID: ${LANGFUSE_S3_MEDIA_UPLOAD_ACCESS_KEY_ID:-minio}
LANGFUSE_S3_MEDIA_UPLOAD_SECRET_ACCESS_KEY: ${LANGFUSE_S3_MEDIA_UPLOAD_SECRET_ACCESS_KEY:-miniosecret}
LANGFUSE_S3_MEDIA_UPLOAD_ENDPOINT: ${LANGFUSE_S3_MEDIA_UPLOAD_ENDPOINT:-http://minio:9000}
LANGFUSE_S3_MEDIA_UPLOAD_FORCE_PATH_STYLE: ${LANGFUSE_S3_MEDIA_UPLOAD_FORCE_PATH_STYLE:-true}
LANGFUSE_S3_MEDIA_UPLOAD_PREFIX: ${LANGFUSE_S3_MEDIA_UPLOAD_PREFIX:-media/}
REDIS_HOST: ${REDIS_HOST:-redis}
REDIS_PORT: ${REDIS_PORT:-6379}
REDIS_AUTH: ${REDIS_AUTH:-myredissecret}
langfuse-web:
image: langfuse/langfuse:latest
depends_on: *langfuse-depends-on
ports:
- "3000:3000"
environment:
<<: *langfuse-worker-env
NEXTAUTH_URL: http://localhost:3000
NEXTAUTH_SECRET: mysecret
LANGFUSE_INIT_ORG_ID: ${LANGFUSE_INIT_ORG_ID:-}
LANGFUSE_INIT_ORG_NAME: ${LANGFUSE_INIT_ORG_NAME:-}
LANGFUSE_INIT_PROJECT_ID: ${LANGFUSE_INIT_PROJECT_ID:-}
LANGFUSE_INIT_PROJECT_NAME: ${LANGFUSE_INIT_PROJECT_NAME:-}
LANGFUSE_INIT_PROJECT_PUBLIC_KEY: ${LANGFUSE_INIT_PROJECT_PUBLIC_KEY:-}
LANGFUSE_INIT_PROJECT_SECRET_KEY: ${LANGFUSE_INIT_PROJECT_SECRET_KEY:-}
LANGFUSE_INIT_USER_EMAIL: ${LANGFUSE_INIT_USER_EMAIL:-}
LANGFUSE_INIT_USER_NAME: ${LANGFUSE_INIT_USER_NAME:-}
LANGFUSE_INIT_USER_PASSWORD: ${LANGFUSE_INIT_USER_PASSWORD:-}
clickhouse:
image: clickhouse/clickhouse-server
user: "101:101"
container_name: clickhouse
hostname: clickhouse
environment:
CLICKHOUSE_DB: default
CLICKHOUSE_USER: clickhouse
CLICKHOUSE_PASSWORD: clickhouse
volumes:
- langfuse_clickhouse_data:/var/lib/clickhouse
- langfuse_clickhouse_logs:/var/log/clickhouse-server
ports:
- "8123:8123"
- "9000:9000"
depends_on:
- postgres
minio:
image: minio/minio
container_name: minio
entrypoint: sh
# create the 'langfuse' bucket before starting the service
command: -c 'mkdir -p /data/langfuse && minio server --address ":9000" --console-address ":9001" /data'
environment:
MINIO_ROOT_USER: minio
MINIO_ROOT_PASSWORD: miniosecret
ports:
- "9090:9000"
- "9091:9001"
volumes:
- langfuse_minio_data:/data
healthcheck:
test: ["CMD", "mc", "ready", "local"]
interval: 1s
timeout: 5s
retries: 5
start_period: 1s
redis:
image: redis:7
restart: always
command: >
--requirepass ${REDIS_AUTH:-myredissecret}
ports:
- 6379:6379
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 3s
timeout: 10s
retries: 10
postgres:
image: postgres:${POSTGRES_VERSION:-latest}
restart: always
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 3s
timeout: 3s
retries: 10
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: postgres
ports:
- 5432:5432
volumes:
- langfuse_postgres_data:/var/lib/postgresql/data
volumes:
langfuse_postgres_data:
driver: local
langfuse_clickhouse_data:
driver: local
langfuse_clickhouse_logs:
driver: local
langfuse_minio_data:
driver: local
-46
View File
@@ -1,46 +0,0 @@
services:
langfuse-server:
image: langfuse/langfuse:2
depends_on:
db:
condition: service_healthy
ports:
- "3000:3000"
environment:
- DATABASE_URL=postgresql://postgres:postgres@db:5432/postgres
- NEXTAUTH_SECRET=mysecret
- SALT=mysalt
- ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000 # generate via `openssl rand -hex 32`
- NEXTAUTH_URL=http://localhost:3000
- TELEMETRY_ENABLED=${TELEMETRY_ENABLED:-true}
- LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES=${LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES:-false}
- LANGFUSE_INIT_ORG_ID=${LANGFUSE_INIT_ORG_ID:-}
- LANGFUSE_INIT_ORG_NAME=${LANGFUSE_INIT_ORG_NAME:-}
- LANGFUSE_INIT_PROJECT_ID=${LANGFUSE_INIT_PROJECT_ID:-}
- LANGFUSE_INIT_PROJECT_NAME=${LANGFUSE_INIT_PROJECT_NAME:-}
- LANGFUSE_INIT_PROJECT_PUBLIC_KEY=${LANGFUSE_INIT_PROJECT_PUBLIC_KEY:-}
- LANGFUSE_INIT_PROJECT_SECRET_KEY=${LANGFUSE_INIT_PROJECT_SECRET_KEY:-}
- LANGFUSE_INIT_USER_EMAIL=${LANGFUSE_INIT_USER_EMAIL:-}
- LANGFUSE_INIT_USER_NAME=${LANGFUSE_INIT_USER_NAME:-}
- LANGFUSE_INIT_USER_PASSWORD=${LANGFUSE_INIT_USER_PASSWORD:-}
db:
image: postgres
restart: always
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 3s
timeout: 3s
retries: 10
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
- POSTGRES_DB=postgres
ports:
- 5432:5432
volumes:
- database_data:/var/lib/postgresql/data
volumes:
database_data:
driver: local
+74
View File
@@ -0,0 +1,74 @@
# Unified `/v1` backend endpoints
The console talks to the unified Hanzo Cloud backend (`hanzoai/cloud`, the
casibase API). Base URL: `${NEXT_PUBLIC_CLOUD_URL}/v1`. All requests send cookie
credentials; responses are the envelope `{ status, msg, data, data2 }` (`data2`
is the total row count on list endpoints).
Client modules live in `src/lib/api/`.
## Account / session — `AccountApi`
| Method | Endpoint |
| --- | --- |
| `current()` | `GET /get-account` |
| `signin(code, state)` | `POST /signin?code&state` |
| `signout()` | `POST /signout` |
## Providers — `ProviderApi`
| Method | Endpoint |
| --- | --- |
| `listGlobal()` | `GET /get-global-providers` |
| `list({ owner, store, p, pageSize, … })` | `GET /get-providers` |
| `get(owner, name)` | `GET /get-provider?id=owner/name` |
| `add(p)` | `POST /add-provider` |
| `update(owner, name, p)` | `POST /update-provider?id=owner/name` |
| `remove(p)` | `POST /delete-provider` |
| `refreshMcpTools(p)` | `POST /refresh-mcp-tools` |
## Model routes — `ModelRouteApi`
| Method | Endpoint |
| --- | --- |
| `list({ owner, … })` | `GET /get-model-routes` |
| `get(owner, modelName)` | `GET /get-model-route?owner&modelName` |
| `add(r)` | `POST /add-model-route` |
| `update(owner, modelName, r)` | `POST /update-model-route?owner&modelName` |
| `remove(r)` | `POST /delete-model-route` |
## Applications — `ApplicationApi`
| Method | Endpoint |
| --- | --- |
| `list({ owner, … })` | `GET /get-applications` |
| `get(owner, name)` | `GET /get-application?id=owner/name` |
| `add(a)` | `POST /add-application` |
| `update(owner, name, a)` | `POST /update-application?id=owner/name` |
| `remove(a)` | `POST /delete-application` |
| `deploy(a)` | `POST /deploy-application?id=owner/name` |
| `undeploy(owner, name)` | `POST /undeploy-application?id=owner/name` |
## Stores — `StoreApi`
| Method | Endpoint |
| --- | --- |
| `listGlobal()` | `GET /get-global-stores` |
| `list(owner)` | `GET /get-stores?owner` |
| `get(owner, name)` | `GET /get-store?id=owner/name` |
| `names(owner)` | `GET /get-store-names?owner` |
| `add(s)` | `POST /add-store` |
| `update(owner, name, s)` | `POST /update-store?id=owner/name` |
| `remove(s)` | `POST /delete-store` |
| `refreshVectors(s)` | `POST /refresh-store-vectors` |
## Chat — `ChatApi`
| Method | Endpoint |
| --- | --- |
| `listGlobal({ … })` | `GET /get-global-chats` |
| `list({ user, store, selectedUser, … })` | `GET /get-chats` |
| `get(owner, name)` | `GET /get-chat?id=owner/name` |
| `add(c)` | `POST /add-chat` |
| `update(owner, name, c)` | `POST /update-chat?id=owner/name` |
| `remove(c)` | `POST /delete-chat` |
+94
View File
@@ -0,0 +1,94 @@
/**
* e2e: two-tenant BILLING ISOLATION through the `/billing/*` proxy.
*
* The proxy (app/billing/v1/[...path]/route.ts) resolves the billing subject from the
* session server-side and pins the full subject-key set (user/userId/customerId) +
* the X-Org-Id header, so a tenant can only ever read its OWN commerce ledger. This
* spec proves that end-to-end against the LIVE proxy: two accounts in DIFFERENT orgs
* each fetch `/billing/subscriptions` (and `/payment-methods`), and we assert the
* two result sets are disjoint — neither tenant can see the other's rows.
*
* This is the regression guard for the IDOR RED found (the proxy previously pinned
* only `?user=` while commerce filters subscriptions on `?userId=`, so subscriptions
* were returned across the whole namespace).
*
* Credentials (env, never in repo). Skips unless BOTH tenants are provided:
* TENANT_A_EMAIL / TENANT_A_PASSWORD (org A)
* TENANT_B_EMAIL / TENANT_B_PASSWORD (org B, a DIFFERENT org)
* BASE_URL default https://console.hanzo.ai
*
* Run: TENANT_A_EMAIL=.. TENANT_A_PASSWORD=.. TENANT_B_EMAIL=.. TENANT_B_PASSWORD=.. pnpm e2e billing-isolation.spec.ts
*/
import { test, expect, type Page } from '@playwright/test'
const BASE_URL = process.env.BASE_URL ?? 'https://console.hanzo.ai'
const A = { email: process.env.TENANT_A_EMAIL ?? '', password: process.env.TENANT_A_PASSWORD ?? '' }
const B = { email: process.env.TENANT_B_EMAIL ?? '', password: process.env.TENANT_B_PASSWORD ?? '' }
async function signIn(page: Page, email: string, password: string) {
await page.goto(`${BASE_URL}/signin`)
await page.waitForSelector('input[placeholder="Email"]', { timeout: 20_000 })
await page.fill('input[placeholder="Email"]', email)
await page.fill('input[placeholder="Password"]', password)
await page.click('button:has-text("Sign in")')
const base = new URL(BASE_URL).origin
await page.waitForURL((url) => url.origin === base && url.pathname === '/', { timeout: 30_000 })
await page.waitForLoadState('domcontentloaded')
}
/** Fetch a billing path through the same-origin DATA proxy (`/billing/v1/*`), as the
* signed-in browser. (`/billing/<slug>` without `v1/` is a UI tab, served by the SPA.) */
async function billing(page: Page, path: string): Promise<{ status: number; ids: string[] }> {
return page.evaluate(async (p) => {
const res = await fetch(`/billing/v1/${p}`, { credentials: 'include', headers: { Accept: 'application/json' } })
let ids: string[] = []
try {
const body = await res.json()
const rows = Array.isArray(body)
? body
: (body?.subscriptions ?? body?.paymentMethods ?? body?.payment_methods ?? body?.data ?? [])
ids = (Array.isArray(rows) ? rows : [])
.map((r: { id?: unknown }) => (typeof r?.id === 'string' ? r.id : ''))
.filter(Boolean)
} catch {
/* non-JSON (e.g. 501 not-configured) — ids stays empty */
}
return { status: res.status, ids }
}, path)
}
test.describe('billing is isolated per tenant through the proxy', () => {
test.skip(
!A.email || !A.password || !B.email || !B.password,
'TENANT_A_* / TENANT_B_* not set — skipping two-tenant billing isolation',
)
test('two distinct-org tenants never see each others subscriptions or payment methods', async ({ browser }) => {
const ctxA = await browser.newContext()
const ctxB = await browser.newContext()
const pageA = await ctxA.newPage()
const pageB = await ctxB.newPage()
await signIn(pageA, A.email, A.password)
await signIn(pageB, B.email, B.password)
for (const path of ['subscriptions', 'payment-methods']) {
const a = await billing(pageA, path)
const b = await billing(pageB, path)
// A 401 would mean the session broke; a 501 means commerce isn't configured
// on this deployment (isolation is vacuously safe — nothing is returned).
expect(a.status, `tenant A /${path} not authorized`).not.toBe(401)
expect(b.status, `tenant B /${path} not authorized`).not.toBe(401)
if (a.status === 501 || b.status === 501) continue
// The core isolation assertion: the two tenants' row-id sets are disjoint.
const overlap = a.ids.filter((id) => b.ids.includes(id))
expect(overlap, `/${path} leaked ${overlap.length} shared rows across tenants`).toEqual([])
}
await ctxA.close()
await ctxB.close()
})
})
+295
View File
@@ -0,0 +1,295 @@
/**
* e2e: Hanzo Cloud Console — login → API key → AI inference
*
* z@hanzo.ai is in the `hanzo` org (isGlobalAdmin), so the OrgGate now shows
* a dismissible admin banner and renders the full console on console.hanzo.ai.
* Admin ops still live at admin.hanzo.ai.
*
* Credentials (env, never in repo):
* HANZO_EMAIL default z@hanzo.ai
* HANZO_PASSWORD required
* HANZO_API_KEY optional; skip UI flow, go straight to inference
* HANZO_API_BASE default https://api.hanzo.ai
* BASE_URL default https://console.hanzo.ai
*
* Run:
* HANZO_PASSWORD=xxx pnpm e2e
* HANZO_PASSWORD=xxx HANZO_API_KEY=hk-xxx pnpm e2e
*/
import { test, expect, type Page } from '@playwright/test'
const EMAIL = process.env.HANZO_EMAIL ?? 'z@hanzo.ai'
const PASSWORD = process.env.HANZO_PASSWORD ?? ''
const API_KEY = process.env.HANZO_API_KEY ?? ''
const API_BASE = process.env.HANZO_API_BASE ?? 'https://api.hanzo.ai'
const BASE_URL = process.env.BASE_URL ?? 'https://console.hanzo.ai'
// ─── helpers ────────────────────────────────────────────────────────────────
async function signIn(page: Page) {
await page.goto(`${BASE_URL}/signin`)
await page.waitForSelector('input[placeholder="Email"]', { timeout: 20_000 })
await page.fill('input[placeholder="Email"]', EMAIL)
await page.fill('input[placeholder="Password"]', PASSWORD)
await page.click('button:has-text("Sign in")')
}
/** Wait until we're on the dashboard (route replaced to '/'). */
async function waitForDashboard(page: Page) {
const base = new URL(BASE_URL).origin
await page.waitForURL(url => url.origin === base && url.pathname === '/', { timeout: 30_000 })
// The dashboard renders product grid cards — wait for at least one visible card/link
await page.waitForLoadState('domcontentloaded')
}
// ─── tests ──────────────────────────────────────────────────────────────────
// Public smoke — needs no credentials, so it always runs (in CI, for Dave, etc.)
// and catches a dead/blank sign-in gate. The authenticated flows below gate on
// HANZO_PASSWORD.
test.describe('Hanzo Cloud Console — public', () => {
test('sign-in page renders (email/password + OAuth + passkey)', async ({ page }) => {
await page.goto(`${BASE_URL}/signin`)
await expect(page.locator('input[placeholder="Email"]')).toBeVisible({ timeout: 20_000 })
await expect(page.locator('input[placeholder="Password"]')).toBeVisible()
await expect(page.locator('button:has-text("Sign in")')).toBeVisible()
await expect(page.locator('button:has-text("Continue with GitHub")')).toBeVisible()
await expect(page.locator('button:has-text("Continue with Google")')).toBeVisible()
await expect(page.locator('text=/passkey/i')).toBeVisible()
})
test('root serves the app (200, dark #0a0a0a) + /base resolves', async ({ page, request }) => {
const res = await page.goto(BASE_URL)
expect(res?.status()).toBe(200)
await expect(page).toHaveTitle(/Hanzo Cloud Console/)
await expect(page.locator('meta[name="theme-color"][content="#0a0a0a"]')).toHaveCount(1)
expect((await request.get(`${BASE_URL}/base`)).status()).toBe(200)
})
// Security gates — the server proxies must reject unauthenticated calls and
// stay inside their allow-list. No credentials (plain request context) so this
// proves the production posture in CI. A regression is a real security bug.
test('server proxies reject unauthenticated calls (401)', async ({ request }) => {
for (const path of [
'/superbase/v1/collections/tenants/records',
'/keys',
]) {
const res = await request.get(`${BASE_URL}${path}`)
expect(res.status(), `${path} must gate`).toBe(401)
}
})
test('proxy allow-lists reject off-list paths (no tunnel)', async ({ request }) => {
const res = await request.get(`${BASE_URL}/superbase/v1/collections/secrets/records`)
// The point is "no tunnel to the backend": the off-list path must be blocked,
// not proxied. The proxy may reject with 404 (off allow-list) or 401 (auth
// gate hit first) — both are blocked; a 2xx would be the real bug.
expect([401, 404], `off-list path must be blocked, got ${res.status()}`).toContain(res.status())
})
test('unknown route never 5xxs', async ({ request }) => {
const res = await request.get(`${BASE_URL}/no-such-surface-xyz`)
expect(res.status()).toBeLessThan(500)
})
})
test.describe('Hanzo Cloud Console e2e', () => {
test.skip(!PASSWORD, 'HANZO_PASSWORD not set — skipping live authenticated tests')
test('login as z@hanzo.ai — dashboard renders', async ({ page }) => {
await signIn(page)
await waitForDashboard(page)
// Dashboard renders — sign-in form must be gone
await expect(page.locator('input[placeholder="Password"]')).not.toBeVisible({ timeout: 10_000 })
// At least one product category or card is visible (Overview / AI / Compute etc.)
await expect(
page.locator('a, button, [role="link"]').filter({ hasText: /models|providers|overview|AI/i }).first()
).toBeVisible({ timeout: 15_000 })
console.log('✓ Signed in; dashboard is rendering')
})
test('admin banner visible (z is isAdmin on console.hanzo.ai)', async ({ page }) => {
await signIn(page)
await waitForDashboard(page)
// OrgGate shows the admin banner for admins on the non-admin console host.
// The banner may have been dismissed in a prior run (localStorage). Skip softly.
const banner = page.locator('text=/Admin ops|admin\\.hanzo\\.ai/i').first()
const visible = await banner.isVisible({ timeout: 5_000 }).catch(() => false)
if (visible) {
console.log('✓ Admin banner visible')
await expect(page.locator('button:has-text("Open admin")')).toBeVisible()
} else {
console.log(' Admin banner was dismissed (localStorage) — OK')
}
})
test('create or confirm API key', async ({ page }) => {
await signIn(page)
await waitForDashboard(page)
// API Keys module is at /api-keys (catch-all route, id='api-keys')
await page.goto(`${BASE_URL}/api-keys`, { waitUntil: 'domcontentloaded' })
// Wait for the module to hydrate — look for the page header or key cards
await expect(
page.locator('text=/API Keys/i, text=/Cloud API key/i, text=/Create.*API key/i').first()
).toBeVisible({ timeout: 25_000 })
const hasKey = page.locator('text=/Cloud API key/i')
const noKey = page.locator('text=/Create your Cloud API key/i')
const createBtn = page.locator('button:has-text("Create API key")')
const needsCreate = await noKey.isVisible({ timeout: 3_000 }).catch(() => false)
|| await createBtn.isVisible({ timeout: 1_000 }).catch(() => false)
if (needsCreate) {
await createBtn.click()
// One-time reveal card with the hk- key
await expect(page.locator('text=/hk-/')).toBeVisible({ timeout: 25_000 })
await expect(page.locator('text=/shown only once/i')).toBeVisible()
await expect(page.locator('button:has-text("Copy")')).toBeVisible()
console.log('✓ API key created (hk- one-time reveal shown)')
} else {
// Key already exists
await expect(hasKey).toBeVisible({ timeout: 10_000 })
await expect(page.locator('text=/hk-…|hk-[A-Za-z0-9]{3,}/i')).toBeVisible({ timeout: 5_000 })
console.log('✓ API key already exists (prefix shown)')
}
})
test('API key works — GET /v1/models', async ({ page }) => {
let apiKey = API_KEY
if (!apiKey) {
await signIn(page)
await waitForDashboard(page)
await page.goto(`${BASE_URL}/api-keys`, { waitUntil: 'domcontentloaded' })
await expect(
page.locator('text=/API Keys/i').first()
).toBeVisible({ timeout: 25_000 })
// Rotate (or create) to show the full key on-screen
const rotateBtn = page.locator('button:has-text("Rotate")')
const createBtn = page.locator('button:has-text("Create API key")')
if (await rotateBtn.isVisible({ timeout: 3_000 }).catch(() => false)) {
await rotateBtn.click()
} else if (await createBtn.isVisible({ timeout: 1_000 }).catch(() => false)) {
await createBtn.click()
}
await expect(page.locator('text=/hk-/')).toBeVisible({ timeout: 25_000 })
// Grab the FULL key from the one-time reveal — never the masked display
// (the account card shows `hk-2f18…` with an ellipsis, which is not a
// usable credential). Match only a full hk- token (no `…`/`...`).
const fullKey = /hk-[A-Za-z0-9._-]{16,}/
const keyEl = page.locator('[style*="monospace"]').filter({ hasText: fullKey }).first()
apiKey = (((await keyEl.textContent().catch(() => '')) ?? '').match(fullKey) ?? [''])[0]
if (!apiKey) {
const m = ((await page.textContent('body')) ?? '').match(fullKey)
apiKey = m ? m[0] : ''
}
expect(apiKey, 'Could not extract hk- key from page').toMatch(/^hk-/)
console.log(`✓ Extracted key prefix: ${apiKey.slice(0, 11)}`)
}
// Verify the key works against api.hanzo.ai
const resp = await page.request.get(`${API_BASE}/v1/models`, {
headers: { Authorization: `Bearer ${apiKey}`, Accept: 'application/json' },
timeout: 30_000,
})
expect(resp.ok(), `GET /v1/models → ${resp.status()}`).toBe(true)
const json = await resp.json()
expect(json).toMatchObject({ data: expect.any(Array) })
const models: Array<{ id: string }> = json.data
expect(models.length).toBeGreaterThan(0)
const ids = models.map(m => m.id)
console.log(`✓ /v1/models: ${models.length} models`)
console.log(` GLM present: ${ids.some(id => id.includes('glm'))}`)
console.log(` Claude present: ${ids.some(id => id.includes('claude'))}`)
console.log(` DeepSeek present: ${ids.some(id => id.includes('deepseek'))}`)
console.log(` First 5: ${ids.slice(0, 5).join(', ')}`)
})
test('OpenAI inference — glm-5.2', async ({ page }) => {
test.skip(!API_KEY, 'Set HANZO_API_KEY to run inference tests')
const resp = await page.request.post(`${API_BASE}/v1/chat/completions`, {
headers: {
Authorization: `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
Accept: 'application/json',
},
data: {
model: 'glm-5.2',
messages: [{ role: 'user', content: 'Reply with only: PONG' }],
max_tokens: 16,
stream: false,
},
timeout: 30_000,
})
expect(resp.ok(), `glm-5.2 → ${resp.status()}`).toBe(true)
const json = await resp.json()
const text: string = json.choices?.[0]?.message?.content ?? ''
expect(text).toBeTruthy()
console.log(`✓ glm-5.2: "${text.trim()}"`)
})
test('OpenAI inference — deepseek-v4-pro', async ({ page }) => {
test.skip(!API_KEY, 'Set HANZO_API_KEY to run inference tests')
const resp = await page.request.post(`${API_BASE}/v1/chat/completions`, {
headers: {
Authorization: `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
Accept: 'application/json',
},
data: {
model: 'deepseek-v4-pro',
messages: [{ role: 'user', content: 'Reply with only: PONG' }],
max_tokens: 16,
stream: false,
},
timeout: 30_000,
})
expect(resp.ok(), `deepseek-v4-pro → ${resp.status()}`).toBe(true)
const json = await resp.json()
const text: string = json.choices?.[0]?.message?.content ?? ''
expect(text).toBeTruthy()
console.log(`✓ deepseek-v4-pro: "${text.trim()}"`)
})
test('Anthropic-compat /v1/messages — live catalog model', async ({ page }) => {
test.skip(!API_KEY, 'Set HANZO_API_KEY to run inference tests')
// Pick a model that is ACTUALLY available right now (the catalog changes;
// a hardcoded id like claude-sonnet-4-6 fails when it isn't provisioned).
// The /v1/messages Anthropic surface accepts any catalog model.
const listed = await page.request.get(`${API_BASE}/v1/models`, {
headers: { Authorization: `Bearer ${API_KEY}`, Accept: 'application/json' },
timeout: 30_000,
})
const ids: string[] = (await listed.json()).data?.map((m: { id: string }) => m.id) ?? []
const model = ids.find((id) => id.includes('claude')) ?? ids.find((id) => id === 'glm-5.2') ?? ids[0]
expect(model, 'no model available in catalog').toBeTruthy()
const resp = await page.request.post(`${API_BASE}/v1/messages`, {
headers: {
Authorization: `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
Accept: 'application/json',
'anthropic-version': '2023-06-01',
},
data: {
model,
messages: [{ role: 'user', content: 'Reply with only: PONG' }],
max_tokens: 16,
},
timeout: 30_000,
})
expect(resp.ok(), `/v1/messages (${model}) → ${resp.status()}`).toBe(true)
const json = await resp.json()
const text: string = json.content?.[0]?.text ?? ''
expect(text).toBeTruthy()
console.log(`✓ Anthropic-compat /v1/messages (${model}): "${text.trim()}"`)
})
})
+80
View File
@@ -0,0 +1,80 @@
/**
* e2e regression: the reported launch bug — product routes must render on a
* DIRECT URL load and a browser REFRESH, not only via in-app navigation.
*
* Product modules mount client-only under the catch-all route, so a throw in one
* module's first render used to bubble to Next's root fallback and white-screen
* the whole console with "Application error: a client-side exception has
* occurred" — but ONLY on a direct load / refresh (in-app nav renders fresh and
* hid it). `ProductErrorBoundary` + the dashboard `error.tsx` close that class:
* even a module throw now keeps the shell and shows a retryable card, never a
* white screen. This spec proves each target route:
* 1. direct-loads without a client-exception white-screen,
* 2. refreshes (F5) without one,
* 3. still deep-links its own real content (shell + main region present).
*
* Credentials (env, never in repo): HANZO_EMAIL / HANZO_PASSWORD, BASE_URL.
* Run: HANZO_PASSWORD=xxx BASE_URL=https://console.hanzo.ai pnpm e2e deeplink-refresh.spec.ts
*/
import { test, expect, type Page } from '@playwright/test'
const EMAIL = process.env.HANZO_EMAIL ?? 'z@hanzo.ai'
const PASSWORD = process.env.HANZO_PASSWORD ?? ''
const BASE_URL = process.env.BASE_URL ?? 'https://console.hanzo.ai'
// The three routes from the report, plus controls known to deep-link fine.
const TARGETS = ['/playground', '/prompts', '/gpus']
const CONTROLS = ['/models', '/providers']
async function signIn(page: Page) {
await page.goto(`${BASE_URL}/signin`)
await page.waitForSelector('input[placeholder="Email"]', { timeout: 20_000 })
// @hanzo/gui Input binds onChangeText — real keystrokes, not fill().
await page.locator('input[placeholder="Email"]').pressSequentially(EMAIL, { delay: 12 })
await page.locator('input[placeholder="Password"]').pressSequentially(PASSWORD, { delay: 12 })
await page.click('button:has-text("Sign in")')
const origin = new URL(BASE_URL).origin
await page.waitForURL((u) => u.origin === origin && u.pathname === '/', { timeout: 30_000 })
await page.waitForLoadState('domcontentloaded')
}
/** Assert the page rendered the console (shell + main) and did NOT white-screen. */
async function assertRendered(page: Page, route: string, phase: string) {
await page.waitForLoadState('networkidle', { timeout: 20_000 }).catch(() => {})
// No client-exception white-screen.
await expect(
page.locator('text=/Application error|client-side exception|Unhandled Runtime Error/i'),
`${route} (${phase}) must not white-screen`,
).toHaveCount(0)
// Shell survived: the persistent nav ("Overview"/"Apps") is present.
const body = (await page.locator('body').innerText().catch(() => '')) || ''
expect(body.length, `${route} (${phase}) has content`).toBeGreaterThan(200)
expect(body, `${route} (${phase}) kept the shell`).toMatch(/Overview|Apps|Sign out/i)
}
test.describe('deep-link + refresh must not crash', () => {
test.skip(!PASSWORD, 'HANZO_PASSWORD not set — skipping authenticated deep-link pass')
test.beforeEach(async ({ page }) => {
await signIn(page)
})
for (const route of [...TARGETS, ...CONTROLS]) {
test(`direct load + refresh: ${route}`, async ({ page }) => {
const errors: string[] = []
page.on('pageerror', (e) => errors.push(String(e)))
// 1) DIRECT URL load (full navigation, fresh document).
const res = await page.goto(`${BASE_URL}${route}`, { waitUntil: 'domcontentloaded' })
expect(res?.status() ?? 0, `${route} HTTP`).toBeLessThan(500)
await assertRendered(page, route, 'direct')
// 2) REFRESH (F5) — the reported failing action.
await page.reload({ waitUntil: 'domcontentloaded' })
await assertRendered(page, route, 'refresh')
// An uncaught pageerror on these routes is the regression we are locking out.
expect(errors, `${route} uncaught pageerror(s): ${errors.join(' | ').slice(0, 300)}`).toEqual([])
})
}
})
+148
View File
@@ -0,0 +1,148 @@
/**
* LIVE confirmation for feat/billing-usage-admin (v8.4.15) on the deployed cluster.
*
* Topology (verified live):
* - console.hanzo.ai: the console app is directly reachable at `/`; `/v1/*` is
* routed by the ingress to cloud-api (hanzoai/gateway), which enforces its OWN
* `global admin required` gate. The console's own H1 gate is reachable directly
* at `/admin/aggregate/*`. z@hanzo.ai is a global admin on this host.
* - admin.hanzo.ai: an EDGE forward-auth (`admin-guard@file`, org=admin, cookie
* on `.hanzo.ai`) sits in front of the SAME console image. A browser must carry
* a valid `.hanzo.ai` guard/session cookie to pass; a cold hit is 401.
*
* Three required checks (task bar):
* (a) admin business board (LivingOverview: MRR/usage/orgs/top-agents/fleet)
* renders for the GLOBAL admin z@hanzo.ai.
* (b) an unprivileged caller gets 403 on /v1/admin/* — no cross-org leak
* (fail-closed gate); iam/kms are not tunneled.
* (c) billing Reports shows the product/agent cost DIMENSION (honest-empty ok).
*/
import { test, expect, type Page, type APIRequestContext } from '@playwright/test'
const EMAIL = process.env.HANZO_EMAIL ?? 'z@hanzo.ai'
const PASSWORD = process.env.HANZO_PASSWORD ?? ''
const CONSOLE = process.env.CONSOLE_URL ?? 'https://console.hanzo.ai'
const ADMIN = process.env.ADMIN_URL ?? 'https://admin.hanzo.ai'
const SHOTS = process.env.SHOT_DIR ?? 'e2e-shots'
/** Sign in via the console app sign-in form (email/password → cloud /v1/signin). */
async function signIn(page: Page, base: string) {
await page.goto(`${base}/signin`)
await page.waitForSelector('input[placeholder="Email"]', { timeout: 25_000 })
await page.fill('input[placeholder="Email"]', EMAIL)
await page.fill('input[placeholder="Password"]', PASSWORD)
await page.click('button:has-text("Sign in")')
await page.waitForFunction(() => !location.pathname.startsWith('/signin'), { timeout: 30_000 })
await page.waitForLoadState('domcontentloaded')
}
// ─── (b) fail-closed gate — needs no credentials, always runs ─────────────────
test.describe('LIVE v8.4.15 — (b) admin gate fail-closed', () => {
test('/v1/admin/* → 403 unauthenticated on console.hanzo.ai; iam/kms not tunneled', async ({ request }) => {
for (const head of ['overview', 'usage', 'orgs', 'audit', 'products']) {
const res = await request.get(`${CONSOLE}/v1/admin/${head}`)
expect(res.status(), `${CONSOLE}/v1/admin/${head} must be 403`).toBe(403)
}
// The console's OWN H1 route is also fail-closed.
const own = await request.get(`${CONSOLE}/admin/aggregate/overview`)
expect(own.status(), 'console app /admin/aggregate gate must be 403').toBe(403)
// Least privilege: iam/kms are NOT reachable through the aggregate rewrite.
for (const head of ['iam', 'kms']) {
const res = await request.get(`${CONSOLE}/admin/aggregate/${head}`)
expect([403, 404], `${head} must not tunnel via aggregate`).toContain(res.status())
}
// Edge-guarded admin host: cold hit is refused (401 forward-auth) — never open.
const edge = await request.get(`${ADMIN}/v1/admin/overview`)
expect(edge.status(), 'admin.hanzo.ai must be edge-gated (401/403)').toBeGreaterThanOrEqual(401)
expect(edge.status()).toBeLessThan(404)
console.log('✓ (b) console /v1/admin/* → 403 unauth; /admin/aggregate/{iam,kms} not tunneled; admin.hanzo.ai edge-gated')
})
})
// ─── (a) + (c) authenticated as the global admin z@hanzo.ai ───────────────────
test.describe('LIVE v8.4.15 — (a) business board + (c) billing dimension', () => {
test.skip(!PASSWORD, 'HANZO_PASSWORD not set')
test('(a) admin business board renders for global admin z@hanzo.ai', async ({ page }) => {
await signIn(page, CONSOLE)
// The business board (catalog id `business`, admin:true) renders the ONE
// LivingOverview for `admin-business`: MRR / revenue / active orgs / customers,
// revenue+usage trend, top-agents-by-cost donut, fleet health.
await page.goto(`${CONSOLE}/business`, { waitUntil: 'domcontentloaded' })
await expect(page).not.toHaveURL(/\/signin/, { timeout: 15_000 })
// Global admin sees the board (not the admin-only "not authorized" gate).
const board = page.locator(
'text=/MRR|Revenue|Active orgs|Customers|Usage cost|Top agents|Fleet|Business/i'
).first()
await expect(board, 'admin business board did not render for the global admin').toBeVisible({ timeout: 30_000 })
// The client admin gate did NOT block z (would show a forbidden/hidden state).
await expect(page.locator('text=/not authorized|access denied|admin only|forbidden/i')).toHaveCount(0)
await page.screenshot({ path: `${SHOTS}/a-business-board.png`, fullPage: true })
console.log('✓ (a) admin business board rendered for global admin z@hanzo.ai')
})
// (a2) The god-view gate is consistent with the account's ACTUAL grant. z@hanzo.ai
// lives in org `hanzo` (a brand/org admin), NOT the global `admin` org, so the
// all-orgs god view is correctly refused (403) and the board shows the honest
// "managed by Hanzo" fallback — no fabricated cross-org KPIs, no leak. A member of
// the `admin` org would instead get 200 and the KPI board. Either way the gate is
// fail-closed and matches what the board renders.
test('(a2) god-view gate matches the account grant (hanzo org-admin → honest 403)', async ({ page }) => {
await signIn(page, CONSOLE)
const acct = await (await page.request.get(`${CONSOLE}/v1/get-account`)).json().catch(() => ({}))
const owner = acct?.data?.owner
const res = await page.request.get(`${CONSOLE}/v1/admin/overview`)
if (owner === 'admin') {
expect(res.status(), 'global admin must pass the gate').not.toBe(403)
console.log(`✓ (a2) global-admin (org=admin) /v1/admin/overview → ${res.status()} (gate passed)`)
} else {
expect(res.status(), 'non-global-admin must be refused the god view').toBe(403)
console.log(`✓ (a2) org-admin (org=${owner}) → 403 on the god view; board shows honest managed fallback (no cross-org leak)`)
}
})
// (a3) admin.hanzo.ai: after establishing the shared `.hanzo.ai` session, the
// edge guard should admit the global admin and render the same board. If the
// guard still refuses (its own OIDC bootstrap), record the honest state — the
// board is proven on console.hanzo.ai (same image) and the edge gate is proven
// fail-closed above.
test('(a3) admin.hanzo.ai admits the global admin (or is honestly edge-gated)', async ({ page }) => {
await signIn(page, CONSOLE) // sets the `.hanzo.ai`-scoped session
const res = await page.request.get(`${ADMIN}/`)
if (res.status() === 200) {
await page.goto(`${ADMIN}/business`, { waitUntil: 'domcontentloaded' })
const board = page.locator('text=/MRR|Revenue|Active orgs|Customers|Top agents|Business/i').first()
await expect(board).toBeVisible({ timeout: 30_000 })
await page.screenshot({ path: `${SHOTS}/a3-admin-host-board.png`, fullPage: true })
console.log('✓ (a3) admin.hanzo.ai admitted the global admin; board rendered')
} else {
console.log(` (a3) admin.hanzo.ai edge-guard returned ${res.status()} for the shared session — board verified on console.hanzo.ai (same image)`)
}
})
test('(c) billing Reports renders the cost-dimension surface', async ({ page }) => {
await signIn(page, CONSOLE)
// v8.4.16: the data proxy moved to /billing/v1/*, so /billing/reports now falls
// through to the SPA (was shadowed by the /billing/[...path] proxy → raw JSON).
// A hard deep-link must render the Reports UI, not a proxy "not found".
await page.goto(`${CONSOLE}/billing/reports`, { waitUntil: 'domcontentloaded' })
await expect(page).not.toHaveURL(/\/signin/, { timeout: 15_000 })
// The route no longer resolves to the commerce proxy JSON.
await expect(page.locator('text=/^\\{"error":"not found"\\}$|could not be found/i'),
'reports still shadowed by the /billing proxy').toHaveCount(0, { timeout: 20_000 })
// The Cost-table Reports surface: the "spend by <dimension>" control. model +
// provider are always offered; product + agent appear the moment the commerce
// ledger tags a row (honest — never a fabricated column). Assert a dimension
// affordance renders (BillingReports mounted).
const dim = page.getByText(/by model|by provider|by product|by agent|group by|dimension|spend by|Cost by/i).first()
await expect(dim, 'cost dimension control did not render').toBeVisible({ timeout: 30_000 })
await expect(page.locator('text=/something went wrong|application error/i')).toHaveCount(0)
await page.screenshot({ path: `${SHOTS}/c-billing-reports.png`, fullPage: true })
console.log('✓ (c) /billing/reports rendered the BillingReports cost-dimension control (unshadowed)')
})
})
+103
View File
@@ -0,0 +1,103 @@
/**
* e2e: the Open Edition (run-for-pay) overview renders its real, product-specific
* content — not just "a page mounted".
*
* `pages.spec.ts` proves /open-edition is reachable + doesn't crash (the generic
* sweep). THIS spec proves the run-for-pay board actually rendered the things that
* make it the Open Edition board: the "Open Edition" heading, the run-for-pay
* framing, the "cost + 25%" margin caption on the Spend KPI, and the spend/tokens
* KPI labels — all sourced from the config in
* src/components/products/overview/living/registry.ts (id `open-edition`), which
* reads the REAL commerce usage ledger scoped to the open-edition product tag.
*
* These are content assertions on the live surface, not a stub: if the config is
* unwired, the route unrouted, or the board silently swapped for another usage
* view, a specific assertion fails.
*
* Credentials (env, never in repo):
* HANZO_EMAIL default z@hanzo.ai (global admin — sees every product)
* HANZO_PASSWORD required (skips when unset)
* BASE_URL default https://console.hanzo.ai
*
* Run: HANZO_PASSWORD=xxx pnpm e2e open-edition.spec.ts
*/
import { test, expect, type Page } from '@playwright/test'
const EMAIL = process.env.HANZO_EMAIL ?? 'z@hanzo.ai'
const PASSWORD = process.env.HANZO_PASSWORD ?? ''
const BASE_URL = process.env.BASE_URL ?? 'https://console.hanzo.ai'
async function signIn(page: Page) {
await page.goto(`${BASE_URL}/signin`)
await page.waitForSelector('input[placeholder="Email"]', { timeout: 20_000 })
await page.fill('input[placeholder="Email"]', EMAIL)
await page.fill('input[placeholder="Password"]', PASSWORD)
await page.click('button:has-text("Sign in")')
const base = new URL(BASE_URL).origin
await page.waitForURL((url) => url.origin === base && url.pathname === '/', { timeout: 30_000 })
await page.waitForLoadState('domcontentloaded')
}
test.describe('Open Edition — run-for-pay overview renders real content', () => {
test.skip(!PASSWORD, 'HANZO_PASSWORD not set — skipping authenticated Open Edition visual gate')
let ctx: import('@playwright/test').BrowserContext
let page: Page
test.beforeAll(async ({ browser }) => {
ctx = await browser.newContext()
page = await ctx.newPage()
await signIn(page)
})
test.afterAll(async () => {
await ctx?.close()
})
test('the /open-edition board mounts, is reachable, and does not crash', async () => {
const errors: string[] = []
const onErr = (e: Error) => errors.push(String(e))
page.on('pageerror', onErr)
const res = await page.goto(`${BASE_URL}/open-edition`, { waitUntil: 'domcontentloaded' })
expect(res?.status() ?? 0, '/open-edition HTTP').toBeLessThan(500)
await page.waitForLoadState('networkidle', { timeout: 20_000 }).catch(() => {})
await expect(page.locator('text=/Application error|Unhandled Runtime Error/i')).toHaveCount(0)
const bodyText = (await page.locator('body').innerText().catch(() => '')) || ''
expect(bodyText.trim().length, '/open-edition rendered content').toBeGreaterThan(0)
page.off('pageerror', onErr)
if (errors.length) console.log(`⚠ /open-edition pageerror: ${errors.join(' | ').slice(0, 200)}`)
})
test('renders the Open Edition run-for-pay header + the cost+25% Spend KPI', async () => {
await page.goto(`${BASE_URL}/open-edition`, { waitUntil: 'domcontentloaded' })
await page.waitForLoadState('networkidle', { timeout: 20_000 }).catch(() => {})
// The product heading — this is the Open Edition board, not a generic usage view.
await expect(page.getByText('Open Edition', { exact: false }).first()).toBeVisible({ timeout: 20_000 })
// The run-for-pay framing from the config subtitle (`Run open-source workloads
// for pay …`). Matches on the distinctive phrase so it can't pass on another board.
await expect(page.getByText(/run open-source workloads for pay/i).first()).toBeVisible()
// The load-bearing pricing detail: the Spend KPI carries the "cost + 25% margin"
// caption (the served revenue R = cost + resell margin). This is the visible
// proof the 25% run-for-pay model is surfaced, not just tokens.
await expect(page.getByText(/cost \+ 25% margin/i).first()).toBeVisible()
// The run-for-pay KPI labels the config declares (spend billed, tokens run).
await expect(page.getByText(/spend billed/i).first()).toBeVisible()
await expect(page.getByText(/tokens run/i).first()).toBeVisible()
})
test('captures a full-page screenshot of the Open Edition board', async () => {
await page.goto(`${BASE_URL}/open-edition`, { waitUntil: 'domcontentloaded' })
await page.waitForLoadState('networkidle', { timeout: 20_000 }).catch(() => {})
// Wait for the heading so the shot is of the rendered board, not a spinner frame.
await expect(page.getByText('Open Edition', { exact: false }).first()).toBeVisible({ timeout: 20_000 })
await page.screenshot({ path: 'e2e/screenshots/open-edition.png', fullPage: true })
})
})
+121
View File
@@ -0,0 +1,121 @@
/**
* e2e: screenshot every console page + assert each renders (FE↔BE wired).
*
* Signs in as z@hanzo.ai (global admin, sees every product), then visits all 89
* registered product routes. For each page it:
* - navigates to /<id>,
* - waits for hydration,
* - asserts the app shell is present and the page did NOT hit a hard crash
* (Next error overlay / "Application error" / a blank body),
* - captures a full-page screenshot into e2e/screenshots/<id>.png.
*
* This is the "screenshot it all, make sure every page is wired" pass. It does
* NOT click destructive buttons — it proves each surface mounts, renders real
* state (or an honest empty/loading/403), and is reachable end to end. Deeper
* per-button flows live in console.spec.ts (API key create/rotate, inference).
*
* Credentials (env, never in repo):
* HANZO_EMAIL default z@hanzo.ai
* HANZO_PASSWORD required (skips when unset)
* BASE_URL default https://console.hanzo.ai
*
* Run: HANZO_PASSWORD=xxx pnpm e2e pages.spec.ts
*/
import { test, expect, type Page } from '@playwright/test'
const EMAIL = process.env.HANZO_EMAIL ?? 'z@hanzo.ai'
const PASSWORD = process.env.HANZO_PASSWORD ?? ''
const BASE_URL = process.env.BASE_URL ?? 'https://console.hanzo.ai'
/**
* Every product route id in the registry (src/lib/products/registry.tsx).
* Kept as a literal list so the spec has zero import coupling to the app bundle;
* a page added to the registry gets a screenshot by adding its id here.
*/
const PAGES: string[] = [
'overview', 'dashboards', 'status',
// AI
'models', 'model-catalog' /* alias */, 'providers', 'playground', 'chat', 'inference',
'agents', 'prompts', 'finetuning', 'embeddings', 'evals', 'datasets', 'experiments',
'annotation-queues', 'scores', 'score-configs', 'observations', 'traces', 'sessions',
// Compute / hypervisor
'machines', 'gpus', 'clusters', 'kubernetes', 'containers', 'networks', 'vpc',
'load-balancer', 'service-mesh', 'edge', 'zero-trust', 'dns', 'cdn',
// Data / storage
's3', 'sql', 'vector', 'datastore', 'kv', 'search', 'docdb', 'base', 'memory', 'indexer',
// Platform
'functions', 'pipelines', 'builds', 'releases', 'environments', 'projects', 'oracles',
// Identity / security
'iam', 'users', 'team', 'authz', 'kms', 'secrets', 'mpc', 'hsm', 'attestations',
'api-keys', 'tokens', 'applications',
// Business / analytics — the unified Billing Center + its sub-pages (Cost /
// Subscriptions / Payment-methods are now tabs of /billing, not top-level routes).
'billing', 'billing/reports', 'billing/budgets', 'billing/invoices',
'billing/subscriptions', 'billing/payment-methods', 'billing/credits',
'ai-metrics', 'open-edition', 'metrics', 'settlement', 'wallet', 'plans', 'referrals', 'marketplace',
// Ops / tooling
'logs', 'alerts', 'o11y', 'gateway', 'tasks', 'integrations', 'registry', 'audit',
'sdks', 'cli', 'ide', 'studio', 'desktop', 'bot', 'profile', 'settings',
]
async function signIn(page: Page) {
await page.goto(`${BASE_URL}/signin`)
await page.waitForSelector('input[placeholder="Email"]', { timeout: 20_000 })
await page.fill('input[placeholder="Email"]', EMAIL)
await page.fill('input[placeholder="Password"]', PASSWORD)
await page.click('button:has-text("Sign in")')
const base = new URL(BASE_URL).origin
await page.waitForURL((url) => url.origin === base && url.pathname === '/', { timeout: 30_000 })
await page.waitForLoadState('domcontentloaded')
}
// Sign in ONCE and reuse the session for all 94 pages. A per-test login (94×)
// trips IAM's "too many login attempts" rate-limit around page 35, which is a
// SECURITY FEATURE working correctly — not a page failure. One shared context
// signs in once, then every page reuses the cookie. Serial so they share it.
test.describe.configure({ mode: 'serial' })
test.describe('Hanzo Cloud Console — every page renders + screenshot', () => {
test.skip(!PASSWORD, 'HANZO_PASSWORD not set — skipping authenticated screenshot pass')
let ctx: import('@playwright/test').BrowserContext
let page: Page
test.beforeAll(async ({ browser }) => {
ctx = await browser.newContext()
page = await ctx.newPage()
await signIn(page)
})
test.afterAll(async () => {
await ctx?.close()
})
for (const id of PAGES) {
test(`page: /${id}`, async () => {
const errors: string[] = []
const onErr = (e: Error) => errors.push(String(e))
page.on('pageerror', onErr)
const res = await page.goto(`${BASE_URL}/${id}`, { waitUntil: 'domcontentloaded' })
// Route must not 5xx.
expect(res?.status() ?? 0, `/${id} HTTP`).toBeLessThan(500)
// App shell mounted (the console renders a nav + main region on every page).
await page.waitForLoadState('networkidle', { timeout: 20_000 }).catch(() => {})
// Hard-crash guards: no Next error overlay, no generic crash banner.
await expect(page.locator('text=/Application error|Unhandled Runtime Error/i')).toHaveCount(0)
// The body must have real content (not a blank white page).
const bodyText = (await page.locator('body').innerText().catch(() => '')) || ''
expect(bodyText.trim().length, `/${id} rendered content`).toBeGreaterThan(0)
await page.screenshot({ path: `e2e/screenshots/${id}.png`, fullPage: true })
page.off('pageerror', onErr)
// Surface (don't fail on) any console page errors for triage.
if (errors.length) console.log(`⚠ /${id} pageerror: ${errors.join(' | ').slice(0, 200)}`)
})
}
})
+153
View File
@@ -0,0 +1,153 @@
/**
* LIVE probe of the o11y (SigNoz) backend through the console's own /cloud bearer
* proxy. Logs in as z@hanzo.ai and, from the AUTHENTICATED page context, fetches
* each candidate endpoint exactly as the new Observe modules will — same-origin
* `<origin>/v1/o11y/*` (rewritten to `/cloud/v1/o11y/*`, cloud rewrites to the o11y
* runtime's `/api/*`). Prints the HTTP status + a body snippet per endpoint so we
* know what returns real data vs 404 (which must be flagged) before we build.
*
* Not a pass/fail test — a discovery harness. Run:
* BASE_URL=https://console.hanzo.ai HANZO_PASSWORD='…' npx playwright test probe-o11y --reporter=line
*/
import { test, type Page } from '@playwright/test'
const EMAIL = process.env.HANZO_EMAIL ?? 'z@hanzo.ai'
const PASSWORD = process.env.HANZO_PASSWORD ?? ''
const BASE_URL = process.env.BASE_URL ?? 'https://console.hanzo.ai'
async function signIn(page: Page) {
await page.goto(`${BASE_URL}/signin`)
await page.waitForSelector('input[placeholder="Email"]', { timeout: 20_000 })
await page.fill('input[placeholder="Email"]', EMAIL)
await page.fill('input[placeholder="Password"]', PASSWORD)
await page.click('button:has-text("Sign in")')
const base = new URL(BASE_URL).origin
// Resilient: the post-login target may be '/' (dashboard) OR '/onboard' (org gate)
// OR it may just set the session cookie while staying put briefly. Wait for the
// sign-in form to DISAPPEAR (we left the /signin gate), whatever the destination.
await page
.waitForFunction(() => !document.querySelector('input[placeholder="Password"]'), { timeout: 90_000 })
.catch(() => {})
// Give the session cookie + any redirect a moment to settle, then land on '/'.
await page.goto(base, { waitUntil: 'domcontentloaded' }).catch(() => {})
await page.waitForTimeout(2500)
}
/** now() epoch — SigNoz wants ns for services/errors, ms for infra. */
const nowMs = Date.now()
const endNs = String(nowMs * 1_000_000)
const startNs = String((nowMs - 60 * 60 * 1000) * 1_000_000) // 1h window
const endMs = nowMs
const startMs = nowMs - 60 * 60 * 1000
type Probe = { name: string; path: string; method: 'GET' | 'POST'; body?: unknown }
const PROBES: Probe[] = [
// ── Dashboards (SigNoz) ──
{ name: 'dashboards.list', path: 'o11y/v1/dashboards', method: 'GET' },
{ name: 'dashboards.v2', path: 'o11y/v2/dashboards', method: 'GET' },
// ── Service map / APM ──
{ name: 'services.list', path: 'o11y/v1/services/list', method: 'GET' },
{
name: 'services',
path: 'o11y/v1/services',
method: 'POST',
body: { start: startNs, end: endNs, tags: [] },
},
{
name: 'dependency_graph',
path: 'o11y/v1/dependency_graph',
method: 'POST',
body: { start: startNs, end: endNs, tags: [] },
},
{
name: 'service.top_operations',
path: 'o11y/v1/service/top_operations',
method: 'POST',
body: { start: startNs, end: endNs, service: '' },
},
// ── Infra ──
{
name: 'hosts.list',
path: 'o11y/v1/hosts/list',
method: 'POST',
body: { start: startMs, end: endMs, filters: { op: 'AND', items: [] } },
},
{
name: 'pods.list',
path: 'o11y/v1/pods/list',
method: 'POST',
body: { start: startMs, end: endMs, filters: { op: 'AND', items: [] } },
},
{
name: 'nodes.list',
path: 'o11y/v1/nodes/list',
method: 'POST',
body: { start: startMs, end: endMs, filters: { op: 'AND', items: [] } },
},
{
name: 'namespaces.list',
path: 'o11y/v1/namespaces/list',
method: 'POST',
body: { start: startMs, end: endMs, filters: { op: 'AND', items: [] } },
},
{
name: 'clusters.list',
path: 'o11y/v1/clusters/list',
method: 'POST',
body: { start: startMs, end: endMs, filters: { op: 'AND', items: [] } },
},
// ── Exceptions ──
{
name: 'listErrors',
path: 'o11y/v1/listErrors',
method: 'POST',
body: { start: startNs, end: endNs, limit: 50, order: 'descending', orderParam: 'exceptionCount' },
},
{
name: 'countErrors',
path: 'o11y/v1/countErrors',
method: 'POST',
body: { start: startNs, end: endNs },
},
// ── Health (sanity: proves the runtime is reachable) ──
{ name: 'health', path: 'o11y/v1/health', method: 'GET' },
{ name: 'version', path: 'o11y/v1/version', method: 'GET' },
// ── Alerts (known-good baseline — AlertsModule already uses this) ──
{ name: 'rules', path: 'o11y/v1/rules', method: 'GET' },
]
test('probe o11y endpoints (live, authenticated)', async ({ page }) => {
test.setTimeout(180_000)
if (!PASSWORD) throw new Error('HANZO_PASSWORD required for the live probe')
await signIn(page)
const results = await page.evaluate(
async ({ probes }: { probes: Probe[] }) => {
const out: { name: string; status: number; ok: boolean; snippet: string }[] = []
for (const p of probes) {
try {
const res = await fetch(`${window.location.origin}/v1/${p.path}`, {
method: p.method,
credentials: 'include',
headers: p.body !== undefined ? { 'Content-Type': 'application/json' } : {},
body: p.body !== undefined ? JSON.stringify(p.body) : undefined,
})
const text = await res.text()
out.push({ name: p.name, status: res.status, ok: res.ok, snippet: text.slice(0, 240) })
} catch (e) {
out.push({ name: p.name, status: -1, ok: false, snippet: String(e).slice(0, 240) })
}
}
return out
},
{ probes: PROBES },
)
console.log('\n================ O11Y LIVE PROBE ================')
for (const r of results) {
console.log(`\n[${r.status}] ${r.name}`)
console.log(` ${r.snippet.replace(/\n/g, ' ')}`)
}
console.log('\n================ END PROBE ================\n')
})
-8
View File
@@ -1,8 +0,0 @@
/** @type {import("eslint").Linter.Config} */
module.exports = {
extends: ["@repo/eslint-config/library.js"],
parser: "@typescript-eslint/parser",
parserOptions: {
project: true,
},
};
-37
View File
@@ -1,37 +0,0 @@
Langfuse Enterprise License (the “Enterprise License”)
Copyright (c) 2024 Langfuse GmbH ('Langfuse')
With regard to the Langfuse Software:
This software and associated documentation files (the "Software") may only be
used in production, if you (and any entity that you represent) have agreed to,
and are in compliance with, the Langfuse Terms of Service, available
at https://langfuse.com/terms (the “Enterprise Terms”), or other
agreement governing the use of the Software, as agreed by you and Langfuse,
and otherwise have a valid Langfuse Enterprise license.
Subject to the foregoing sentence, you are free to
modify this Software and publish patches to the Software. You agree that Langfuse
and/or its licensors (as applicable) retain all right, title and interest in and
to all such modifications and/or patches, and all such modifications and/or
patches may only be used, copied, modified, displayed, distributed, or otherwise
exploited with a valid Langfuse Enterprise license.
Notwithstanding the foregoing, you may copy and modify
the Software for development and testing purposes, without requiring a
subscription. You agree that Langfuse and/or its licensors (as applicable) retain
all right, title and interest in and to all such modifications. You are not
granted any other rights beyond what is expressly stated herein. Subject to the
foregoing, it is forbidden to copy, merge, publish, distribute, sublicense,
and/or sell the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
For all third party components incorporated into the Langfuse Software, those
components are licensed under the original license provided by the owner of the
applicable component.
-5
View File
@@ -1,5 +0,0 @@
# Enterprise Edition
This folder includes features that are only available in the Enterprise Edition of Langfuse and on Langfuse Cloud.
See [LICENSE](../LICENSE) and [docs](https://langfuse.com/docs/open-source) for more details.
-54
View File
@@ -1,54 +0,0 @@
{
"name": "@langfuse/ee",
"version": "1.0.0",
"private": true,
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"exports": {
".": {
"import": "./dist/src/index.js",
"require": "./dist/src/index.js"
},
"./sso": {
"import": "./dist/src/sso/index.js",
"require": "./dist/src/sso/index.js"
}
},
"engines": {
"node": "20"
},
"scripts": {
"build": "tsc",
"dev": "tsc --watch",
"lint": "eslint . --ext .js,.jsx,.ts,.tsx --max-warnings 0",
"lint:fix": "eslint . --ext .js,.jsx,.ts,.tsx --fix"
},
"dependencies": {
"@langfuse/shared": "workspace:*",
"@opentelemetry/api": ">=1.0.0 <1.10.0",
"axios": "^1.7.7",
"https-proxy-agent": "^7.0.6",
"next": "^14.2.21",
"next-auth": "^4.24.11",
"zod": "^3.23.8"
},
"devDependencies": {
"@repo/eslint-config": "workspace:*",
"@repo/typescript-config": "workspace:*",
"@types/node": "^20.11.29",
"@typescript-eslint/parser": "^7.12.0",
"eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0",
"eslint-config-standard": "^17.1.0",
"eslint-plugin-prettier": "^5.1.3",
"prettier": "^3.3.3",
"ts-node": "^10.9.2",
"tsc-watch": "^6.2.0",
"typescript": "^5.4.5"
},
"pnpm": {
"overrides": {
"jsonpath-plus": "10.2.0"
}
}
}
-5
View File
@@ -1,5 +0,0 @@
import { env } from "../env";
export const isEeAvailable: boolean =
env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== undefined ||
env.LANGFUSE_EE_LICENSE_KEY !== undefined;
-12
View File
@@ -1,12 +0,0 @@
import { z } from "zod";
import { env as sharedEnv, removeEmptyEnvVariables } from "@langfuse/shared";
const EnvSchema = z.object({
NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: z.string().optional(),
LANGFUSE_EE_LICENSE_KEY: z.string().optional(),
});
export const env = {
...sharedEnv,
...EnvSchema.parse(removeEmptyEnvVariables(process.env)),
};

Some files were not shown because too many files have changed in this diff Show More