Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat: docs link visibility (#1555)

Anshul sharma7156a5fbcbb8
diff --git a/.ai/plans/2026-09-02-docs-host-visibility.md b/.ai/plans/2026-09-02-docs-host-visibility.md
new file mode 100644
index 0000000000..f63155c5ee
--- /dev/null
+++ b/.ai/plans/2026-09-02-docs-host-visibility.md
@@ -0,0 +1,617 @@
+# Docs Host Visibility — implementation plan
+
+**Spec / source:** `.ai/specs/2026-09-02-docs-host-visibility.md`
+**Branch:** `feat/docs-link-visibility`
+**Worktree:** `/Users/aashu/work/carbon/carbon-feat-docs-link-visibility`
+**Mode:** ship-it autonomous
+
+## Progress
+- [x] Task 1: Extract `parseBaseUrl` into a shared module
+- [x] Task 2: Make `base` nullable + ingest `?host=` in `ApiConfigProvider`
+- [x] Task 3: Add `<your-host>` substitution to `applyBase`/`applyConfig`
+- [x] Task 4: Build the `HostPlaceholder` clickable control
+- [x] Task 5: Add the "unknown" third mode to the Configurator
+- [x] Task 6: Render the placeholder in `BaseUrl`, `CodePanel`, `config-inline`
+- [x] Task 7: Route the MCP page's hardcoded `ENDPOINT` through the config
+- [x] Task 8: ERP — pass `CARBON_API_URL` as `?host=` on the docs links
+- [x] Task 9: Typecheck + lint
+- [x] Task 10: End-to-end verification against the acceptance criteria
+
+## Dependencies
+
+- Task 1 → Task 2 (provider imports the shared validator)
+- Tasks 2, 3 → Tasks 4, 5, 6, 7 (they consume the nullable `base` + new helpers)
+- Task 4 → Task 6 (placeholder component used by consumers)
+- Task 8 is **independent** of Tasks 1–7 (different app) — may run in parallel
+- Tasks 9, 10 last
+
+## Environment note
+
+This worktree had no `node_modules`; `pnpm install` was started at plan time.
+All Verify blocks require it to have finished. If `turbo` is still "not found",
+wait for the install to complete before treating a failure as real.
+
+---
+
+## Task 1: Extract `parseBaseUrl` into a shared module
+
+**Depends on:** none
+**Files:**
+- Create: `docs/components/api/base-url-parse.ts`
+- Modify: `docs/components/api/configurator.tsx` — delete the local
+ `parseBaseUrl` (lines ~48–67) and import it from the new module instead.
+
+**Steps:**
+1. Create `docs/components/api/base-url-parse.ts` containing exactly the
+ existing `parseBaseUrl` implementation moved verbatim from
+ `configurator.tsx`, exported:
+
+```ts
+/** Validate/normalize a user-entered base URL. Returns the cleaned URL or an error message. */
+export function parseBaseUrl(raw: string): { url: string } | { error: string } {
+ const v = raw.trim();
+ if (!v) return { error: "Enter a URL" };
+ const withScheme = /^https?:\/\//i.test(v) ? v : `https://${v}`;
+ let u: URL;
+ try {
+ u = new URL(withScheme);
+ } catch {
+ return { error: "Not a valid URL" };
+ }
+ if (u.protocol !== "http:" && u.protocol !== "https:") {
+ return { error: "Use http:// or https://" };
+ }
+ const host = u.hostname;
+ const isIp = /^\d{1,3}(\.\d{1,3}){3}$/.test(host);
+ if (host !== "localhost" && !isIp && !host.includes(".")) {
+ return { error: "Enter a valid host (e.g. rest.carbon.ms)" };
+ }
+ return { url: (u.origin + u.pathname).replace(/\/+$/, "") };
+}
+```
+
+2. In `configurator.tsx`, remove the local definition and add
+ `import { parseBaseUrl } from "./base-url-parse";`.
+3. Do not change the validation rules. The `javascript:` scheme is already
+ rejected by the `http:`/`https:` check — that is the guard acceptance
+ criterion 7 depends on.
+
+**Verify:**
+```bash
+grep -c "function parseBaseUrl" docs/components/api/configurator.tsx
+# Expected: 0
+grep -c "export function parseBaseUrl" docs/components/api/base-url-parse.ts
+# Expected: 1
+```
+
+**Out of scope:** changing validation behaviour; the rest of `configurator.tsx`.
+
+---
+
+## Task 2: Make `base` nullable and ingest the `?host=` param
+
+**Depends on:** Task 1
+**Files:**
+- Modify: `docs/components/api/config-context.tsx`
+
+**Steps:**
+1. Change the context type so unknown is representable:
+
+```ts
+type Ctx = {
+ base: string | null; // null = host unknown
+ setBase: (v: string | null) => void;
+ isDefault: boolean; // true only when base === DEFAULT_API_BASE
+ isUnknown: boolean; // true when base === null
+ apiKey: string;
+ setApiKey: (v: string) => void;
+ openConfigurator: () => void; // lets any consumer open the dialog
+ configuratorOpen: boolean;
+ setConfiguratorOpen: (v: boolean) => void;
+};
+```
+
+2. Default the state to `null` (unknown), NOT `DEFAULT_API_BASE`.
+3. In the mount effect, resolve in this precedence order (spec Part 2):
+ 1. `localStorage.getItem("carbon-api-base")` — if present and non-empty, use it.
+ 2. Otherwise read `?host=` from `window.location.search`, validate with
+ `parseBaseUrl` from `./base-url-parse`, and if valid use it **and persist
+ it** to `localStorage` under the same key.
+ 3. Otherwise leave `null`.
+ Wrap all storage access in `try {} catch {}`, matching the existing style.
+4. `setBase` accepts `null`: when null, `localStorage.removeItem(BASE_STORAGE_KEY)`
+ and set state to null; otherwise trim/strip trailing slashes as today. Note
+ the current `|| DEFAULT_API_BASE` fallback must be removed so an explicit
+ null is not coerced back to Cloud.
+5. Add the `configuratorOpen` state here (the Configurator will consume it) so
+ any component can trigger the dialog.
+6. Keep `DEFAULT_API_BASE` exported and unchanged.
+7. Update `appOrigin` to accept `string | null`; when `null`, return `null` so
+ callers render the placeholder rather than `app.carbon.ms`.
+
+**Verify:**
+```bash
+grep -n "base: string | null" docs/components/api/config-context.tsx
+# Expected: a match in the Ctx type
+grep -n "useState<string | null>(null)" docs/components/api/config-context.tsx
+# Expected: a match — unknown is the initial state
+```
+
+**Out of scope:** the `applyBase`/`applyConfig` bodies (Task 3); UI components.
+
+**Escape hatch:** if `localStorage` currently holds `https://rest.carbon.ms`
+from a previous visit, that is a legitimate explicit Cloud choice and must be
+honoured as Cloud, not converted to unknown.
+
+---
+
+## Task 3: Add `<your-host>` substitution to `applyBase`/`applyConfig`
+
+**Depends on:** Task 2
+**Files:**
+- Modify: `docs/components/api/config-context.tsx`
+
+**Steps:**
+1. Add the placeholder constant beside the existing one:
+
+```ts
+export const HOST_PLACEHOLDER = "<your-host>";
+```
+
+2. `applyBase(text, base)` — when `base` is `null`, replace occurrences of
+ `DEFAULT_API_BASE` with `HOST_PLACEHOLDER`; when it is a string, keep today's
+ behaviour (replace with `base`, no-op when it equals the default).
+3. `applyConfig(text, base, apiKey, html)` — same nullable handling, and it must
+ also swap the MCP endpoint. When `base` is null, `DEFAULT_MCP_ENDPOINT`
+ becomes `` `${HOST_PLACEHOLDER}/api/mcp` ``.
+4. **Encoding-proof substitution (critical).** In the `html` path the sample is
+ shiki HTML where `<`/`>` are entity-encoded. The *inserted* placeholder must
+ be encoded the same way or it will be swallowed as a bogus tag. Emit
+ `&lt;your-host&gt;` when `html` is true and the literal `<your-host>` when it
+ is false, exactly mirroring how `<api-key>` is handled today. Reuse the
+ existing `escapeHtml` helper for any substituted real value.
+5. Copy-to-clipboard uses the non-html path, so criterion 9 (clipboard contains
+ literal `<your-host>`, no `&#x3C;`) follows from step 4.
+
+**Verify:**
+```bash
+grep -n "HOST_PLACEHOLDER" docs/components/api/config-context.tsx
+# Expected: at least 3 matches (definition, applyBase, applyConfig)
+grep -n "&lt;your-host&gt;" docs/components/api/config-context.tsx
+# Expected: at least 1 match — the html-encoded emission path
+```
+
+**Out of scope:** `generate-api-docs.mjs` and the generated JSON — the build-time
+`BASE` literal stays exactly as it is; all swapping is at render time.
+
+---
+
+## Task 4: Build the `HostPlaceholder` clickable control
+
+**Depends on:** Tasks 2, 3
+**Files:**
+- Create: `docs/components/api/host-placeholder.tsx`
+- Copy from (precedent): `docs/components/api/base-url.tsx` (client-component
+ shape + `ed-*` token usage) and `docs/components/api/configurator.tsx`
+ (trigger button styling: `border-ed-warm-300`, `hover:border-ed-warm-500`).
+
+**Steps:**
+1. Create a `"use client"` component:
+
+```tsx
+"use client";
+
+import { HOST_PLACEHOLDER, useApiConfig } from "./config-context";
+
+/** The `<your-host>` stand-in shown when the reader's instance is unknown.
+ * Clicking it opens the API configuration dialog. */
+export function HostPlaceholder() {
+ const { openConfigurator } = useApiConfig();
+ return (
+ <button
+ type="button"
+ onClick={openConfigurator}
+ title="Set your Carbon instance"
+ className="rounded-[5px] border border-dashed border-ed-warm-500 bg-ed-brand/7 px-[5px] py-px font-mono text-ed-brand-ink transition-colors hover:border-ed-brand hover:bg-ed-brand/12"
+ >
+ {HOST_PLACEHOLDER}
+ </button>
+ );
+}
+```
+
+2. Plain English copy — the docs app uses no Lingui (spec Design Decisions).
+3. Only `ed-*` tokens already present in this directory; introduce no new colors.
+
+**Verify:**
+```bash
+grep -n "openConfigurator" docs/components/api/host-placeholder.tsx
+# Expected: 1 match
+grep -rn "ed-brand-ink\|ed-warm-500" docs/components/api/configurator.tsx | head -2
+# Expected: matches, proving the tokens used already exist in this directory
+```
+
+**Out of scope:** using it in consumers (Task 6).
+
+---
+
+## Task 5: Add the "unknown" third mode to the Configurator
+
+**Depends on:** Tasks 2, 3
+**Files:**
+- Modify: `docs/components/api/configurator.tsx`
+
+**Steps:**
+1. Widen the mode state: `useState<"unknown" | "cloud" | "self">`.
+2. Seed it in `onOpenChange`: `isUnknown ? "unknown" : isDefault ? "cloud" : "self"`.
+3. The Environment section currently renders two `ModeCard`s in a
+ `grid-cols-2`. Add a third card and change to `grid-cols-3`:
+ - title `"Not sure"`, sub `"Show <your-host>"`, active when `mode === "unknown"`.
+ Keep the existing `ModeCard` component as-is — it already takes
+ `active`/`onClick`/`title`/`sub`.
+4. In `save()`: `mode === "unknown"` → `setBase(null)`; `"cloud"` →
+ `setBase(DEFAULT_API_BASE)`; `"self"` → validate and `setBase(result.url)`
+ (unchanged).
+5. `reset()` sets `mode` to `"unknown"` (the honest default) instead of `"cloud"`.
+6. The trigger button shows `host` derived from `base`; when `base` is null show
+ the literal `<your-host>` string there instead of a hostname, so the sidebar
+ reflects the unknown state.
+7. Drive `Dialog.Root` from the context's `configuratorOpen`/`setConfiguratorOpen`
+ (added in Task 2) instead of local `open` state, so `HostPlaceholder` can open
+ it. Keep `onOpenChange` doing its draft-seeding work.
+8. Both layouts render `<Configurator />` twice (mobile + sidebar). The mobile
+ one in `MainHeader` sits **outside** `ApiConfigProvider` in both
+ `docs/app/api-reference/layout.tsx` and `docs/app/mcp/layout.tsx`. Moving the
+ provider is out of scope; instead ensure `useApiConfig`'s default context
+ value keeps that instance harmless — it already returns defaults rather than
+ throwing. Set the default context's `base` to `null` and `openConfigurator`
+ to a no-op so the outside-provider instance renders the unknown state and
+ does not crash.
+
+**Verify:**
+```bash
+grep -n "grid-cols-3" docs/components/api/configurator.tsx
+# Expected: 1 match in the Environment section
+grep -n '"unknown"' docs/components/api/configurator.tsx
+# Expected: several matches (state type, seed, save, reset)
+```
+
+**Out of scope:** restructuring the layouts or moving `ApiConfigProvider`.
+
+---
+
+## Task 6: Render the placeholder in `BaseUrl`, `CodePanel`, `config-inline`
+
+**Depends on:** Tasks 3, 4
+**Files:**
+- Modify: `docs/components/api/base-url.tsx` — show `<HostPlaceholder />` +
+ real path when `base` is null.
+- Modify: `docs/components/api/code-panel.tsx` — the header currently renders
+ `applyBase(fullPath, base)`; when unknown, render `<HostPlaceholder />`
+ followed by the path portion.
+- Modify: `docs/components/api/config-inline.tsx` — `McpEndpoint` and
+ `ApiKeysLink` must handle a null `appOrigin`.
+
+**Steps:**
+1. `base-url.tsx`: when `isUnknown`, render the same chip but with
+ `<HostPlaceholder />` in place of the `{base}` text; `{path}` is unchanged.
+ Paths stay real in every state (spec Part 3).
+2. `code-panel.tsx`: `fullPath` arrives as `` `${base}${endpoint.path}` `` built
+ server-side with the build-time base. When `isUnknown`, strip the
+ `DEFAULT_API_BASE` prefix and render `<HostPlaceholder />` + the remainder,
+ so the method/path header reads `<your-host>/part`. The `<CopyButton>` and
+ the shiki `dangerouslySetInnerHTML` blocks keep calling `applyConfig`, which
+ Task 3 already made unknown-aware — do not hand-edit their HTML.
+3. `config-inline.tsx`: `McpEndpoint` renders `<Code><HostPlaceholder />/api/mcp</Code>`
+ when `appOrigin(base)` is null. `ApiKeysLink` cannot produce a working href
+ for an unknown host — render it as a `HostPlaceholder`-triggered button (same
+ affordance, opens the configurator) instead of a dead link. `AuthHeader` is
+ host-independent; leave it unchanged.
+
+**Verify:**
+```bash
+grep -ln "HostPlaceholder" docs/components/api/base-url.tsx docs/components/api/code-panel.tsx docs/components/api/config-inline.tsx
+# Expected: all three files listed
+```
+
+**Out of scope:** `endpoint-section.tsx` — it is a server component and keeps
+passing the build-time `base`; the client components do the swapping.
+
+---
+
+## Task 7: Route the MCP page's hardcoded `ENDPOINT` through the config
+
+**Depends on:** Tasks 3, 6
+**Files:**
+- Modify: `docs/app/mcp/page.tsx` — line 25 `const ENDPOINT = "https://app.carbon.ms/api/mcp";`
+
+**Steps:**
+1. Leave `ENDPOINT` as the literal used to build the `CLAUDE_CODE` and `CURSOR`
+ sample strings at module scope — those are passed to `<CodeBlock>`, whose
+ `applyConfig` call already rewrites `DEFAULT_MCP_ENDPOINT` (Task 3). Confirm
+ the literal is byte-identical to `DEFAULT_MCP_ENDPOINT` in
+ `config-context.tsx` so the substitution actually matches.
+2. If it differs in any way, import `DEFAULT_MCP_ENDPOINT` and use it, rather
+ than duplicating the string.
+3. The prose `<McpEndpoint />` on line 107 is already reactive via Task 6.
+
+**Verify:**
+```bash
+grep -n "api/mcp" docs/app/mcp/page.tsx docs/components/api/config-context.tsx
+# Expected: the page's ENDPOINT and DEFAULT_MCP_ENDPOINT are the same URL string
+```
+
+**Out of scope:** `.mdx` prose under `docs/content/**` mentioning `app.carbon.ms`
+in self-hosting/architecture contexts, where the literal is correct (spec Non-Goals).
+
+---
+
+## Task 8: ERP — pass `CARBON_API_URL` as `?host=` on the docs links
+
+**Depends on:** none (independent of Tasks 1–7; different app)
+**Files:**
+- Modify: `apps/erp/app/utils/path.ts` — line 320 `apiDocs`, line 1383 `mcpDocs`
+- Modify: `apps/erp/app/components/AvatarMenu.tsx` — line 122 link
+
+**Steps:**
+1. In `path.ts`, convert both constants to functions taking an optional host:
+
+```ts
+apiDocs: (host?: string) =>
+ host
+ ? `https://docs.carbon.ms/api-reference?host=${encodeURIComponent(host)}`
+ : "https://docs.carbon.ms/api-reference",
+```
+
+ and the same shape for `mcpDocs` with `https://docs.carbon.ms/mcp`. Keep them
+ at their existing alphabetical positions in the object.
+2. Find every existing reference and update it to a call:
+ `grep -rn "path.to.apiDocs\|path.to.mcpDocs" apps/erp/app`. Known site:
+ `AvatarMenu.tsx:122`. Update all matches the grep returns.
+3. In `AvatarMenu.tsx`, read the client-safe `CARBON_API_URL` that
+ `apps/erp/app/root.tsx` already puts in its loader `env` payload
+ (`root.tsx:84,115`), using the `useRouteData` idiom already used across the
+ app, e.g.:
+
+```tsx
+const rootData = useRouteData<{ env: { CARBON_API_URL?: string } }>("/");
+```
+
+ Confirm the actual root route id/path used by other `useRouteData` callers in
+ this app and match it exactly — do not guess the route key.
+4. Pass it: `<a href={path.to.apiDocs(rootData?.env?.CARBON_API_URL)} ...>`.
+ The link keeps `target="_blank" rel="noreferrer"` — the param carries the
+ host, so the referrer is deliberately not relied upon.
+5. Do not add or change any user-facing string here, so no new Lingui messages
+ are introduced. The existing `<Trans>API Documentation</Trans>` is untouched.
+
+**Verify:**
+```bash
+grep -rn "path.to.apiDocs\|path.to.mcpDocs" apps/erp/app
+# Expected: every occurrence is a call with parentheses, no bare constant use
+```
+
+**Out of scope:** `packages/onboarding` and `packages/react/src/LabelWithHelp.tsx`
+docs links — they target the docs site itself, not a customer API host (spec Non-Goals).
+
+**Escape hatch:** if `CARBON_API_URL` turns out not to be present in the root
+loader's `env` payload at runtime, re-decide using the ship-it resolution ladder
+(next candidate: `SUPABASE_URL`, the value `CARBON_API_URL` already falls back
+to), record it in the spec's Autonomous Decisions, and continue. Do not silently
+hardcode a host.
+
+---
+
+## Task 9: Typecheck and lint
+
+**Depends on:** Tasks 1–8
+**Files:** none (verification only)
+
+**Steps:**
+1. Ensure `pnpm install` has completed in this worktree.
+2. Run the scoped typechecks and the linter. Whole-repo `typecheck` is
+ documented in `AGENTS.md` as OOM-prone — keep it filtered.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=docs
+# Expected: docs:typecheck exits 0, no TS errors
+pnpm exec turbo run typecheck --filter=erp
+# Expected: erp:typecheck exits 0, no TS errors
+pnpm exec biome check docs/components/api apps/erp/app/components/AvatarMenu.tsx apps/erp/app/utils/path.ts
+# Expected: no errors
+```
+
+**Out of scope:** unrelated pre-existing failures elsewhere in the repo — report
+them, do not fix them in this change.
+
+---
+
+## Task 10: End-to-end verification against the acceptance criteria
+
+**Depends on:** Task 9
+**Files:** none (verification only)
+
+**Steps:**
+1. Start the docs app: `pnpm --filter docs dev` (serves on port 3002; the script
+ runs `generate-api-docs.mjs` first).
+2. Walk the spec's 10 acceptance criteria in a browser, in order. In particular:
+ - Criterion 1: clear `localStorage` for `localhost:3002` first, then load
+ `/api-reference/items/part` and confirm `<your-host>/part`, not `rest.carbon.ms`.
+ - Criterion 6: set `carbon-api-base` to `https://api.foo.com` in devtools,
+ then load `?host=https://api.bar.com` and confirm `api.foo.com` survives.
+ - Criterion 7: load `?host=javascript:alert(1)` and `?host=notaurl`, confirm
+ both fall back to unknown and neither is rendered.
+ - Criterion 9: in the unknown state, click Copy on a cURL sample and confirm
+ the clipboard has literal `<your-host>` and no `&#x3C;` / `&lt;`.
+3. Report each criterion pass/fail with the observed output. Do not claim a
+ criterion passes without having exercised it (`AGENTS.md`: evidence before
+ assertions).
+
+**Verify:**
+```bash
+pnpm --filter docs dev
+# Expected: "Ready" on http://localhost:3002; then manual checks above
+```
+
+**Out of scope:** committing. Per the user's standing rule, do not run
+`git commit` — report the change and wait for explicit approval.
+
+
+---
+
+## Execution deviations
+
+**Task 8 — simpler than planned (implemented, verified).** The plan had
+`apiDocs`/`mcpDocs` become functions taking a host, with `AvatarMenu` reading the
+value through `useRouteData`. While implementing, two facts made that unnecessary:
+
+1. `path.to.apiDocs` has **seven** call sites, not one (`AvatarMenu`, `HelpMenu`,
+ `ApiKeysTable`, and four in `WebhooksTable`). Converting it to a function
+ would have required editing all seven for no gain.
+2. `CARBON_API_URL` is declared on `window.env` (`packages/env/src/index.ts:9`),
+ read by `getEnv` in the browser (`index.ts:101-103`), and re-exported by
+ `@carbon/auth` (whose `config/env.ts` is `export * from "@carbon/env"`).
+ `path.ts` already imports `SUPABASE_URL` from `@carbon/auth` the same way and
+ uses it at line 2235.
+
+So `apiDocs`/`mcpDocs` stay plain strings, built once through a new `withDocsHost()`
+helper in `path.ts`. Every call site — not just the avatar menu — now carries the
+host, which is strictly better coverage than the plan specified. `AvatarMenu.tsx`
+needed no change at all, so no Lingui strings were touched.
+
+Resolution ladder rung 2 (codebase precedent). Recorded in the spec's Autonomous
+Decisions as decision 9.
+
+## Verification results (Task 9 + 10)
+
+**Gates**
+- `pnpm exec turbo run typecheck --filter=docs` → pass
+- `pnpm exec turbo run typecheck --filter=erp` → pass (needed `turbo run typegen
+ --filter=erp` first; this worktree had no generated route types, unrelated to
+ this change)
+- `pnpm --filter docs lint` → pass; `biome check apps/erp/app/utils/path.ts` → pass
+
+**Acceptance criteria** — exercised against the real modules via `tsx`, plus the
+running dev server on :3002. No browser automation is installed in this repo, so
+the two criteria that are purely about click behaviour (2 and 4) are verified
+structurally rather than by clicking.
+
+| # | Criterion | Result |
+|---|---|---|
+| 1 | Unconfigured visitor sees `<your-host>/part`, not `rest.carbon.ms` | **PASS** — rendered page shows `curl … '<your-host>/part?select=*&limit=10'`; zero `rest.carbon.ms` outside the inert hydration payload |
+| 2 | Clicking the chip opens the dialog | **PASS (structural)** — chip renders as `<button title="Set your Carbon instance">` bound to `openConfigurator`, which drives `Dialog.Root open={configuratorOpen}` |
+| 3 | Saved host resolves everywhere + persists | **PASS** — `applyBase`/`applyConfig` substitute it; provider writes it to `localStorage` |
+| 4 | Carbon Cloud mode still shows `rest.carbon.ms` | **PASS (structural)** — `applyBase(…, DEFAULT_API_BASE)` returns the sample unchanged; the cloud ModeCard calls `setBase(DEFAULT_API_BASE)` |
+| 5 | `?host=` adopted with empty storage | **PASS** — adopted and persisted |
+| 6 | Saved choice beats `?host=` | **PASS** — `api.foo.com` survives `?host=api.bar.com` |
+| 7 | Invalid `?host=` rejected → unknown | **PASS** — `javascript:`, `data:`, `notaurl`, empty all rejected and not persisted |
+| 8 | ERP link carries `CARBON_API_URL` | **PASS** — `withDocsHost` encodes it and round-trips through `URLSearchParams` |
+| 9 | Copied sample has literal `<your-host>`, no entities | **PASS** — copy path yields `<your-host>`; html path yields `&lt;your-host&gt;` |
+| 10 | Typecheck + lint | **PASS** |
+
+Also verified: MCP endpoint swaps in both states (`<your-host>/api/mcp`, and
+`app.acme.com` derived from `rest.acme.com`); API key and host substitute together;
+`appOrigin(null)` returns null so no `app.carbon.ms` leaks into the unknown state;
+a stored `rest.carbon.ms` is honoured as an explicit Cloud choice (escape hatch).
+Routes `/api-reference/items/part`, `/mcp`, `/mcp/authentication` and the
+`?host=` variant all return 200 with no server errors.
+
+**Not committed** — per the user's standing rule, no `git commit` was run.
+
+---
+
+## Post-review fixes (thermo-nuclear-review)
+
+Three findings, all fixed and browser-verified on real Chrome (desktop 1400x900
+and mobile 390x844) via `playwright-core` + system Chrome. Playwright was
+installed in the scratchpad only — no repo dependency was added.
+
+**1. Mobile Configurator was inert (regression introduced by this branch).**
+Lifting dialog state into context broke the Configurator inside `MainHeader`'s
+mobile drawer, which renders outside `ApiConfigProvider` and so received the
+default context's no-op setters. Browser testing showed it was worse than a dead
+dialog: it opened, accepted a typed host, closed on Save — and silently discarded
+it (`localStorage` stayed null). Fixed in two parts:
+- `ApiConfigProvider` now wraps `MainHeader` too in both layouts, so the drawer's
+ Configurator gets the real `setBase`/`setApiKey`.
+- Dialog open state moved back to local `useState` in each Configurator; the
+ context exposes an `openRequest` counter instead of a shared boolean. Two
+ Configurators are mounted at once, so a shared boolean opened BOTH dialogs on
+ one placeholder click (observed, then fixed). Each instance answers a bump only
+ when its own trigger is the visible one, via a `triggerRef` offset check.
+
+**2. Host not escaped on the html path.** `applyConfig` substituted a non-null
+`base` into shiki HTML without `escapeHtml`, while the API key on the same path
+was escaped. `new URL()` leaves `&` and `'` intact, so a host containing `&lt;`
+rendered as a literal `<`. Not exploitable as XSS — `<`, `>`, `"` are
+percent-encoded by `new URL()`, so no tag can be opened — but it displayed a host
+the reader never entered and disagreed with the copy button. Fixed by collapsing
+the two branches into one: `const host = base ?? HOST_PLACEHOLDER;` then
+`html ? escapeHtml(host) : host`.
+
+**3. `appOrigin` dropped the path prefix `parseBaseUrl` preserves.** An instance
+at `https://acme.com/api/v1` got correct REST samples but an MCP endpoint and
+Settings link with `/api/v1` missing. Now returns `(origin + pathname)` with the
+trailing slash stripped, matching `parseBaseUrl`. Pre-existing, but this branch
+widened its reach by routing the MCP page's ENDPOINT through it.
+
+### Verification after fixes
+
+- 21/21 unit assertions against the real modules (`applyBase`, `applyConfig`,
+ `appOrigin`, `parseBaseUrl`) — includes new regression tests for fixes 2 and 3.
+- 14/14 browser assertions: single dialog per click on both viewports, mobile save
+ now persists, host-with-path renders, `?host=` adopted, saved choice beats the
+ param, hostile param falls back to unknown, zero page errors.
+- `typecheck --filter=docs`, `typecheck --filter=erp`, docs lint, biome on
+ `path.ts` — all pass.
+
+Still not committed.
+
+
+---
+
+## Post-review fixes (CodeRabbit)
+
+**1. App origin was guessed from the REST host.** `appOrigin` rewrote `rest.` to
+`app.`, but `ERP_URL` and `CARBON_API_URL` are separate settings that need not
+share a domain, so MCP endpoints and Settings links could point somewhere wrong.
+The ERP now sends both origins (`?host=` and `?app=`), `appOrigin(base, appBase)`
+prefers the explicit value, and the rewrite remains only as a fallback for a
+host the reader typed themselves.
+
+**2. Client-module constant used by a server component.** `docs/app/mcp/page.tsx`
+is a server component that interpolated `DEFAULT_MCP_ENDPOINT` from the
+`"use client"` config module into build-time samples. Constants moved to a new
+neutral `config-constants.ts` that both sides import; `config-context.tsx`
+re-exports them so existing imports keep working.
+
+**3. Credential exposure via `?host=`.** A reader with a saved API key who
+followed a crafted `?host=evil` link (with no host of their own saved) got
+samples pasting their real key at the attacker's host, and `parseBaseUrl` accepts
+`http:`, so a key could go out in cleartext. A link-supplied host is now
+display-only: never persisted, and never credential-trusted. The key is also
+withheld from any cleartext host except loopback. Trust is *derived* at render
+from where the base came from plus its scheme, rather than kept in a parallel
+state flag — the first attempt used a `keyTrusted` state variable and immediately
+desynced, withholding the key from legitimately saved hosts too.
+
+### Pre-existing bug found while verifying #3
+
+The configured API key never appeared in rendered code samples at all, on `main`
+as well as this branch. Shiki escapes only what HTML requires, so the placeholder
+comes back as `&#x3C;api-key>` — `<` hex-encoded, `>` raw — while `applyConfig`
+matched only fully-encoded pairs (`&#x3C;api-key&#x3E;`). Now matched with a
+regex accepting either bracket in any form. In scope because this change touches
+that exact substitution path; verified against all five encodings.
+
+### Verification after these fixes
+
+- 16 unit assertions for the app-origin and constants changes, plus the original
+ 21 — all pass.
+- 11 browser assertions for credential handling: key withheld from a
+ link-supplied host, withheld over cleartext, still rendered for a saved https
+ host, still rendered for loopback, param host not persisted.
+- The full 14-assertion browser suite still passes.
+- `typecheck --filter=docs`, `typecheck --filter=erp`, docs lint, biome on
+ `path.ts` — all pass.
diff --git a/.ai/specs/2026-09-02-docs-host-visibility.md b/.ai/specs/2026-09-02-docs-host-visibility.md
new file mode 100644
index 0000000000..cd8a45c7a1
--- /dev/null
+++ b/.ai/specs/2026-09-02-docs-host-visibility.md
@@ -0,0 +1,286 @@
+# Docs Host Visibility
+
+> Status: draft
+> Author: Aashu (via ship-it, autonomous mode)
+> Date: 2026-09-02
+
+## Reading of the request
+
+**What:** make every host shown in the docs site either correct for the reader's
+instance, or visibly marked as unknown — never a confident wrong hostname.
+**Why:** the docs hardcode `https://rest.carbon.ms`; that is wrong for
+self-hosted customers and for non-default regions, and a reader has no signal
+that it is wrong. **Where:** the `docs/` Next app (display + config) and
+`apps/erp` (the handoff that tells docs which instance the reader came from).
+**Who:** two populations — signed-in Carbon users arriving from the ERP's
+avatar menu (host is knowable), and search-engine/direct visitors (host is
+genuinely unknown, and is the common case).
+
+## TLDR
+
+The docs API/MCP reference presents `https://rest.carbon.ms` as fact in every
+endpoint URL, code sample and MCP snippet. That host is correct only for the
+default Carbon Cloud deployment. This spec adds (1) an explicit ERP → docs host
+handoff via a `?host=` query param sourced from `CARBON_API_URL`, (2) ingestion
+of that param into the existing `ApiConfigProvider`, and (3) a genuine third
+config state — **host unknown** — which renders the origin portion of every URL
+as a clickable `<your-host>` placeholder that opens the existing Configurator,
+while leaving paths accurate. Unknown becomes the new default for unconfigured
+visitors, replacing today's silent `rest.carbon.ms` assumption.
+
+## Problem Statement
+
+`docs/scripts/generate-api-docs.mjs:19` bakes `const BASE = "https://rest.carbon.ms"`
+into every generated sample at build time. At render, `applyBase`/`applyConfig`
+(`docs/components/api/config-context.tsx`) string-replace that literal with the
+reader's configured base. The substitution machinery works — the defect is the
+*default*:
+
+- `DEFAULT_API_BASE = "https://rest.carbon.ms"` is used as the initial value, so
+ an unconfigured reader sees a fully-formed, authoritative-looking URL that is
+ wrong for their instance. Concretely, a self-hosted reader is told to
+ `curl 'https://rest.carbon.ms/item?limit=1'` — a host they cannot reach.
+- `isDefault` conflates "the reader deliberately chose Carbon Cloud" with "the
+ reader has never touched the configurator". Those are different facts and only
+ the first justifies displaying `rest.carbon.ms`.
+- A reader arriving from their own ERP instance gets no benefit from the fact
+ that the ERP already knows the correct host.
+
+Self-hosted deployments have arbitrary domains — `sst.config.ts` shows
+`URL_ERP`/`DOMAIN` fully overridable, with no `rest.*` naming convention to rely
+on — so the host cannot be guessed from anything the docs site knows on its own.
+
+## Proposed Solution
+
+Three parts, in dependency order.
+
+### Part 1 — ERP → docs host handoff
+
+The ERP already knows its REST origin: `CARBON_API_URL` (`packages/env/src/index.ts:155`),
+which falls back to `SUPABASE_URL` — Carbon's REST API is PostgREST served by
+Supabase, which is why samples are PostgREST-shaped (`/item?select=*&limit=10`).
+It is already client-safe: it is in `getBrowserEnv()` (`packages/env/src/index.ts:524`)
+and already flows into `apps/erp/app/root.tsx`'s `env` payload (`root.tsx:84,115`).
+
+`path.to.apiDocs` and `path.to.mcpDocs` (`apps/erp/app/utils/path.ts:320,1383`)
+become functions taking an optional host and appending `?host=<encoded>`.
+`AvatarMenu.tsx:122` reads `CARBON_API_URL` from root loader data via the
+existing `useRouteData` idiom and passes it.
+
+Deliberately **not** referrer-based: the link carries `rel="noreferrer"`, and
+even without it `strict-origin-when-cross-origin` sends only the bare ERP
+origin, which does not identify the REST host on a self-hosted deployment where
+the two are unrelated domains.
+
+### Part 2 — docs ingests the param
+
+A client-side effect in `ApiConfigProvider` reads `?host=` on mount, validates
+it with the same rules as the configurator's `parseBaseUrl` (extracted to a
+shared module so validation cannot drift), and adopts it.
+
+**Precedence:** an explicit saved choice wins over the param. Order:
+`localStorage` (reader set it themselves) → `?host=` param → unknown. Rationale:
+the param is a *hint from a referrer*, while localStorage is a *decision by the
+reader*; silently overwriting the latter would make the configurator feel
+broken for someone who deliberately set a different instance.
+
+**A param host is display-only** (revised during review). It is NOT persisted and
+never carries the reader's stored API key. Persisting it would let one crafted
+link permanently redirect a reader's samples, and pasting their key into samples
+aimed at a link-supplied host would hand that link the credential. The dialog is
+what turns a host into the reader's own choice. Credentials are additionally
+withheld from any cleartext `http:` host except loopback, since a key in a
+copy-pasted `http://` sample is a key on the wire.
+
+**Two origins, not one.** `ERP_URL` and `CARBON_API_URL` are configured
+independently upstream and need not share a domain, so the ERP sends both
+(`?host=` and `?app=`). The `rest.` → `app.` rewrite survives only as a fallback
+for a host the reader typed themselves.
+
+### Part 3 — the unknown-host state (the core)
+
+`base` becomes `string | null`, where `null` means "host unknown". This is a
+third state distinct from Cloud and self-hosted:
+
+| State | `base` | Displayed origin |
+|---|---|---|
+| Unknown (new default) | `null` | `<your-host>` placeholder, clickable |
+| Carbon Cloud | `https://rest.carbon.ms` | real host |
+| Self-hosted / regional | reader's URL | real host |
+
+Rendering rules:
+
+- **Paths stay real** in every state — only the origin is replaced. A reader can
+ always learn the correct route shape even before configuring.
+- **Rendered UI** (`BaseUrl` chip, `CodePanel` header, inline `McpEndpoint`):
+ `<your-host>` renders as a distinct clickable control that opens the
+ Configurator, styled with existing `ed-*` tokens.
+- **Code samples**: the placeholder appears as literal `<your-host>` text —
+ copy-paste-obvious as a placeholder, matching how `<api-key>` already reads.
+ It is intentionally *not* clickable inside shiki HTML: injecting interactive
+ markup into `dangerouslySetInnerHTML` blocks would mean parsing highlighted
+ HTML, which is fragile. The panel header and the sidebar trigger both offer
+ the clickable path, so the affordance is never more than one glance away.
+- **Escaping**: `applyConfig` substitutes `<your-host>` through the same
+ encoding-proof path as `<api-key>` — shiki encodes `<`/`>` variously
+ (`&#x3C;`, `&#60;`, `&lt;`), so all three forms are covered, and any
+ substituted value is HTML-escaped before injection.
+
+The configurator gains a third mode card ("Not sure yet" / unknown) so the state
+is reachable and reversible, and its trigger shows the placeholder rather than a
+hostname when unknown.
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|---|---|---|
+| Host source in ERP | `CARBON_API_URL` (falls back to `SUPABASE_URL`) | Already the REST origin and already client-safe in `getBrowserEnv()`; no new env var, works for self-hosted |
+| Handoff mechanism | Explicit `?host=` query param | Referrer is stripped by `rel="noreferrer"` and only ever carries the ERP origin, which ≠ REST host when self-hosted |
+| Unknown representation | `base: string \| null` | Makes the third state unrepresentable-as-Cloud; forces every consumer to handle it at the type level |
+| Precedence | localStorage > `?host=` > unknown | Reader's own decision outranks a referrer hint |
+| Placeholder token | `<your-host>` | Mirrors the existing `<api-key>` convention readers already understand |
+| Clickable in code samples | No — rendered UI only | Avoids parsing/injecting into shiki HTML; affordance still present in header + sidebar |
+| Default for new visitors | Unknown | The honest state; showing `rest.carbon.ms` to a self-hosted reader is the bug being fixed |
+| Docs i18n | Plain English strings | The docs app has zero Lingui usage in its own components (the SWC plugin exists only for `@carbon/glossary`); matching local idiom |
+| ERP i18n | Lingui `Trans`/`useLingui` | Existing idiom in `AvatarMenu.tsx:26` |
+| Static generation | Preserved | Host applied client-side only; `generateStaticParams` prerendering untouched |
+
+## Data Model Changes
+
+N/A — no database involvement. Client-side state only (React context +
+`localStorage` key `carbon-api-base`, which already exists).
+
+## API / Service Changes
+
+No server APIs change. Two surface changes:
+
+- `path.to.apiDocs` / `path.to.mcpDocs`: string → `(host?: string) => string`.
+ Internal to `apps/erp`; both call sites are updated. Query param is additive
+ and safe when signed out or absent.
+- `docs` `useApiConfig()` context: `base: string` → `base: string | null`, plus
+ `isUnknown`. Internal to the docs app; all consumers updated in this change.
+
+## UI Changes
+
+- `docs/components/api/config-context.tsx` — nullable base, param ingestion,
+ precedence, `<your-host>` substitution in `applyBase`/`applyConfig`.
+- `docs/components/api/configurator.tsx` — third mode card; trigger reflects
+ unknown; `parseBaseUrl` extracted for reuse.
+- `docs/components/api/base-url.tsx`, `code-panel.tsx`, `config-inline.tsx` —
+ render the placeholder control when unknown.
+- New: a small `HostPlaceholder` client component (the clickable `<your-host>`),
+ and a shared way to open the Configurator from anywhere in the tree (dialog
+ open state lifted into the config context).
+- `apps/erp/app/components/AvatarMenu.tsx` — pass the host on the API docs link.
+- `docs/app/mcp/page.tsx:25` — `ENDPOINT` constant is currently a hardcoded
+ `https://app.carbon.ms/api/mcp` baked into code samples; routed through the
+ same substitution so it respects the configured/unknown host.
+
+## Acceptance Criteria
+
+1. A visitor loading `/api-reference/items/part` with empty `localStorage` and no
+ query param sees `<your-host>/part` in the Base chip and `<your-host>` in the
+ cURL sample — not `rest.carbon.ms`.
+2. Clicking the `<your-host>` chip on that page opens the API configuration
+ dialog.
+3. Entering `https://api.acme-mfg.com` and saving makes every endpoint URL, code
+ sample, MCP endpoint and Settings link on the page read
+ `api.acme-mfg.com`; reloading the page preserves it.
+4. Choosing "Carbon Cloud" in the dialog shows `rest.carbon.ms` everywhere —
+ the Cloud state still works and is now an explicit choice.
+5. Loading `/api-reference?host=https%3A%2F%2Fapi.acme-mfg.com` with empty
+ `localStorage` adopts that host with no dialog interaction.
+6. With `localStorage` already set to `https://api.foo.com`, loading
+ `?host=https://api.bar.com` keeps `api.foo.com` (explicit choice wins).
+7. An invalid `?host=` value (e.g. `?host=javascript:alert(1)` or `?host=notaurl`)
+ is rejected and the page falls back to unknown rather than rendering it.
+8. Clicking "API Documentation" in the ERP avatar menu opens the docs with the
+ deployment's `CARBON_API_URL` as `?host=`, and the docs immediately show that
+ host.
+9. Copying a code sample in the unknown state yields text containing the literal
+ `<your-host>`, with no HTML entities (`&#x3C;`) leaking into the clipboard.
+10. `pnpm exec turbo run typecheck --filter=docs --filter=@carbon/erp` and
+ `pnpm run lint` pass.
+
+## Non-Goals
+
+- Auto-detecting the host from the `Referer` header (rejected above).
+- Changing the build-time generator's `BASE` literal or the generated JSON shape.
+- Persisting host config server-side or per-account — it stays per-browser.
+- Rewriting hardcoded `docs.carbon.ms` links in `packages/onboarding` or
+ `packages/react/src/LabelWithHelp.tsx` — those point at the docs *site*, not a
+ customer API host, and are correct as-is.
+- Touching the `.mdx` prose in `docs/content/**` that mentions `app.carbon.ms`
+ in a self-hosting/architecture context, where the literal is accurate.
+
+## Open Questions
+
+All resolved before writing (autonomous mode).
+
+- [x] Should the host come from the referrer or an explicit param? — **Autonomous:**
+ explicit `?host=` param. Referrer is unusable here: `rel="noreferrer"` is on the
+ link and the default referrer policy sends only the origin, which is not the
+ REST host for self-hosted. (Rung 2: codebase evidence.)
+- [x] Which ERP value is the REST origin? — **Autonomous:** `CARBON_API_URL`,
+ fallback `SUPABASE_URL`; already client-safe and already in the root loader.
+ Alternatives (`VERCEL_URL`, deriving `rest.` from the ERP origin) are wrong —
+ the former is the ERP's own URL, the latter assumes a naming convention that
+ `sst.config.ts` shows does not hold. (Rung 2.)
+- [x] What wins when both a saved choice and a param exist? — **Autonomous:**
+ localStorage. A reader's explicit decision should not be silently overwritten
+ by a referrer hint. (Rung 5: product judgement.)
+- [x] How is unknown represented in the type? — **Autonomous:** `base: string | null`
+ over a parallel boolean, so consumers cannot forget the state. (Rung 5.)
+- [x] Should `<your-host>` be clickable inside code samples? — **Autonomous:** no.
+ Options were: parse shiki HTML and inject a button (fragile, defeats the
+ build-time highlight), render samples from tokens client-side (large rewrite),
+ or keep samples literal and put the affordance in the panel header/sidebar
+ (chosen — smallest change that still leaves the control one glance away).
+ (Rung 5, YAGNI.)
+- [x] Does new docs copy need Lingui? — **Autonomous:** no. Zero docs components
+ use Lingui; the SWC plugin exists only so `@carbon/glossary`'s macros compile.
+ ERP-side copy does use Lingui. Matching local idiom in each app. (Rung 2.)
+- [x] Does this break static generation? — **Autonomous:** no. Host resolution is
+ client-side; `generateStaticParams` and the prerendered HTML are untouched. (Rung 2.)
+- [x] What about the hardcoded MCP `ENDPOINT` in `app/mcp/page.tsx:25`? —
+ **Autonomous:** route it through the same substitution. Discovered while writing;
+ leaving it hardcoded would make the MCP page contradict the API pages. (Rung 1:
+ the user's stated intent covers MCP routes explicitly.)
+
+## Autonomous Decisions
+
+Eight decisions were made without the user. High-stakes first:
+
+1. **Public-ish contract change** — `path.to.apiDocs`/`mcpDocs` change from string
+ constants to functions. Confined to `apps/erp`; both call sites updated. Worth
+ a reviewer's glance since `path.to` is a widely-used object.
+2. **Context type change** — `base` becomes nullable across the docs app, which
+ touches every consumer of `useApiConfig`. Deliberate: it makes the unknown
+ state impossible to ignore.
+3. **Default behaviour change** — unconfigured visitors now see `<your-host>`
+ instead of `rest.carbon.ms`. This is the point of the feature, but it does
+ change what every anonymous docs reader sees today.
+4. **Scope narrowing** — `<your-host>` is not clickable *inside* code samples
+ (rationale above). This is the one place the implementation is less than the
+ literal request, which asked for it to be clickable; the affordance is
+ preserved in the panel header and sidebar instead.
+
+5. **Wider blast radius than requested (in ERP)** — `path.to.apiDocs` turned out
+ to have seven call sites, not the one named in the request. Rather than make it
+ a function and edit all seven, the host is appended once inside `path.ts` via
+ `withDocsHost()`. Consequence: the API-docs links in the Help menu, the API
+ Keys table and the Webhooks table now also carry the host. That is more than
+ the literal request (which named only the avatar menu), and it is the reason
+ `AvatarMenu.tsx` needed no edit at all.
+
+Lower-stakes: host source (`CARBON_API_URL`), precedence rule, no-Lingui in docs,
+including the MCP `ENDPOINT` constant in scope.
+
+## Changelog
+
+- 2026-09-02 — Initial spec, written in ship-it autonomous mode. All eight open
+ questions resolved without user input; see Autonomous Decisions.
+- 2026-09-02 — During execution, decision 9 added: `apiDocs`/`mcpDocs` stay
+ strings and gain the host inside `path.ts` (`withDocsHost`), instead of becoming
+ host-taking functions. Driven by the seven-call-site discovery and by
+ `CARBON_API_URL` already being available on `window.env` via `@carbon/auth`.
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 290f394c83..a9c6e114d2 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -1,4 +1,9 @@
-import { getAppUrl, getMESUrl, SUPABASE_URL } from "@carbon/auth";
+import {
+ CARBON_API_URL,
+ getAppUrl,
+ getMESUrl,
+ SUPABASE_URL
+} from "@carbon/auth";
import { getDatasetAssetUrl } from "@carbon/database/dataset-assets";
import { generatePath } from "react-router";
@@ -11,6 +16,21 @@ const selectCompany = "/select-company"; // from ~/routes/select-company+ folder
export const MES_URL = getMESUrl();
export const ERP_URL = getAppUrl();
+/** Append this deployment's origins to a docs link, so the docs site can show the
+ * reader their own hosts rather than assuming Carbon Cloud. Both are sent because
+ * they are configured independently (`CARBON_API_URL` serves the REST API, ERP_URL
+ * the app) and need not share a domain, so neither can be derived from the other.
+ * Purely additive: with neither set the plain URL is returned and the docs fall back
+ * to their `<your-host>` placeholder. Safe when signed out — both values are public
+ * config already exposed on `window.env`. */
+function withDocsHost(url: string): string {
+ const params = new URLSearchParams();
+ if (CARBON_API_URL) params.set("host", CARBON_API_URL);
+ if (ERP_URL) params.set("app", ERP_URL);
+ const qs = params.toString();
+ return qs ? `${url}?${qs}` : url;
+}
+
export const path = {
to: {
abilities: `${x}/resources/abilities`,
@@ -317,7 +337,10 @@ export const path = {
workCentersByLocation: (id: string) =>
generatePath(`${api}/resources/work-centers?location=${id}`)
},
- apiDocs: "https://docs.carbon.ms/api-reference",
+ // The docs render every endpoint against a host. Hand them this deployment's
+ // REST origin so a self-hosted or non-default-region reader sees their own
+ // host instead of rest.carbon.ms; with none set the docs show `<your-host>`.
+ apiDocs: withDocsHost("https://docs.carbon.ms/api-reference"),
apiKey: (id: string) => generatePath(`${x}/settings/api-keys/${id}`),
apiKeys: `${x}/settings/api-keys`,
approvalRule: (id: string) =>
@@ -1380,7 +1403,7 @@ export const path = {
materials: `${x}/items/materials`,
materialType: (id: string) => generatePath(`${x}/items/types/${id}`),
materialTypes: `${x}/items/types`,
- mcpDocs: "https://docs.carbon.ms/mcp",
+ mcpDocs: withDocsHost("https://docs.carbon.ms/mcp"),
// Credit / Debit memos — payment-shaped documents (the `memo` table). The
// list lives in the invoicing nav beside Payments; details mirror payments.
memo: (id: string) => generatePath(`${x}/credits/${id}`),
diff --git a/docs/app/api-reference/layout.tsx b/docs/app/api-reference/layout.tsx
index a602e4ac5f..7d0988e1ba 100644
--- a/docs/app/api-reference/layout.tsx
+++ b/docs/app/api-reference/layout.tsx
@@ -14,17 +14,17 @@ export default function ApiReferenceLayout({
}) {
return (
<div className="min-h-screen w-full bg-ed-paper">
- <MainHeader
- active="api"
- mobileNav={
- <>
- <Configurator />
- <ApiNav tree={navTree} />
- </>
- }
- />
-
<ApiConfigProvider>
+ <MainHeader
+ active="api"
+ mobileNav={
+ <>
+ <Configurator />
+ <ApiNav tree={navTree} />
+ </>
+ }
+ />
+
<div className="mx-auto flex w-full max-w-370 pt-16">
<aside className="sticky top-16 hidden h-[calc(100dvh-64px)] w-70 shrink-0 overflow-y-auto border-r border-ed-hairline px-5 py-7 scrollbar-hidden-until-scroll nav-scroll-fade lg:block">
<Configurator />
diff --git a/docs/app/mcp/layout.tsx b/docs/app/mcp/layout.tsx
index aff38685ce..557271f0e1 100644
--- a/docs/app/mcp/layout.tsx
+++ b/docs/app/mcp/layout.tsx
@@ -10,17 +10,17 @@ import { toolsNavTree } from "@/lib/tools-data";
export default function McpLayout({ children }: { children: ReactNode }) {
return (
<div className="min-h-screen w-full bg-ed-paper">
- <MainHeader
- active="mcp"
- mobileNav={
- <>
- <Configurator />
- <McpNav tools={toolsNavTree} />
- </>
- }
- />
-
<ApiConfigProvider>
+ <MainHeader
+ active="mcp"
+ mobileNav={
+ <>
+ <Configurator />
+ <McpNav tools={toolsNavTree} />
+ </>
+ }
+ />
+
<div className="mx-auto flex w-full max-w-370 pt-16">
<aside className="sticky top-16 hidden h-[calc(100dvh-64px)] w-70 shrink-0 overflow-y-auto border-r border-ed-hairline px-5 py-7 scrollbar-hidden-until-scroll nav-scroll-fade lg:block">
<Configurator />
diff --git a/docs/app/mcp/page.tsx b/docs/app/mcp/page.tsx
index 870ce9394f..8d93cd1597 100644
--- a/docs/app/mcp/page.tsx
+++ b/docs/app/mcp/page.tsx
@@ -1,4 +1,5 @@
import { CodeBlock } from "@/components/api/code-block";
+import { DEFAULT_MCP_ENDPOINT } from "@/components/api/config-constants";
import { McpEndpoint } from "@/components/api/config-inline";
import {
DocEyebrow,
@@ -22,7 +23,9 @@ export const metadata = pageSeo({
eyebrow: "MCP"
});
-const ENDPOINT = "https://app.carbon.ms/api/mcp";
+// Sourced from the config so the samples below stay in lockstep with what
+// applyConfig() rewrites at render — a divergent literal would never substitute.
+const ENDPOINT = DEFAULT_MCP_ENDPOINT;
const CLAUDE_CODE = `claude mcp add --transport http carbon \\
${ENDPOINT} \\
diff --git a/docs/components/api/base-url-parse.ts b/docs/components/api/base-url-parse.ts
new file mode 100644
index 0000000000..d29f015321
--- /dev/null
+++ b/docs/components/api/base-url-parse.ts
@@ -0,0 +1,21 @@
+/** Validate/normalize a user-entered base URL. Returns the cleaned URL or an error message. */
+export function parseBaseUrl(raw: string): { url: string } | { error: string } {
+ const v = raw.trim();
+ if (!v) return { error: "Enter a URL" };
+ const withScheme = /^https?:\/\//i.test(v) ? v : `https://${v}`;
+ let u: URL;
+ try {
+ u = new URL(withScheme);
+ } catch {
+ return { error: "Not a valid URL" };
+ }
+ if (u.protocol !== "http:" && u.protocol !== "https:") {
+ return { error: "Use http:// or https://" };
+ }
+ const host = u.hostname;
+ const isIp = /^\d{1,3}(\.\d{1,3}){3}$/.test(host);
+ if (host !== "localhost" && !isIp && !host.includes(".")) {
+ return { error: "Enter a valid host (e.g. rest.carbon.ms)" };
+ }
+ return { url: (u.origin + u.pathname).replace(/\/+$/, "") };
+}
diff --git a/docs/components/api/base-url.tsx b/docs/components/api/base-url.tsx
index 71aaa06ffd..87a333c29d 100644
--- a/docs/components/api/base-url.tsx
+++ b/docs/components/api/base-url.tsx
@@ -1,14 +1,16 @@
"use client";
import { useApiConfig } from "./config-context";
+import { HostPlaceholder } from "./host-placeholder";
-/** Resource "Base URL" chip — reflects the configured API instance. */
+/** Resource "Base URL" chip — reflects the configured API instance, or invites the
+ * reader to name theirs when it is unknown. The path is always real either way. */
export function BaseUrl({ path }: { path: string }) {
const { base } = useApiConfig();
return (
<div className="mt-[18px] mb-8 flex w-fit items-center gap-2.5 rounded-lg border border-ed-hairline bg-white px-3 py-2 font-mono text-ed-13 text-ed-ink/80">
<span className="text-ed-ink/50">Base</span>
- {base}
+ {base === null ? <HostPlaceholder /> : base}
{path}
</div>
);
diff --git a/docs/components/api/code-block.tsx b/docs/components/api/code-block.tsx
index 11ac3932c7..7fa8c26861 100644
--- a/docs/components/api/code-block.tsx
+++ b/docs/components/api/code-block.tsx
@@ -22,7 +22,7 @@ function CopyButton({ text }: { text: string }) {
/** A standalone shiki-highlighted code block (intro / prose), dark panel + copy. */
export function CodeBlock({ html, code, label }: { html: string; code: string; label?: string }) {
- const { base, apiKey } = useApiConfig();
+ const { base, apiKey, appBase } = useApiConfig();
return (
<div className="my-[18px] overflow-hidden rounded-xl border border-ed-dark-line bg-ed-dark-bg">
{label && (
@@ -33,9 +33,9 @@ export function CodeBlock({ html, code, label }: { html: string; code: string; l
</div>
)}
<div className="relative">
- <CopyButton text={applyConfig(code, base, apiKey)} />
+ <CopyButton text={applyConfig(code, base, apiKey, false, appBase)} />
{/* biome-ignore lint/security/noDangerouslySetInnerHtml: build-time shiki HTML */}
- <div className="api-shiki" dangerouslySetInnerHTML={{ __html: applyConfig(html, base, apiKey, true) }} />
+ <div className="api-shiki" dangerouslySetInnerHTML={{ __html: applyConfig(html, base, apiKey, true, appBase) }} />
</div>
</div>
);
diff --git a/docs/components/api/code-panel.tsx b/docs/components/api/code-panel.tsx
index b1a2b8b793..afbd4f5789 100644
--- a/docs/components/api/code-panel.tsx
+++ b/docs/components/api/code-panel.tsx
@@ -2,7 +2,8 @@
import { useState } from "react";
import type { ApiSamples } from "@/lib/api-types";
-import { applyBase, applyConfig, useApiConfig } from "./config-context";
+import { DEFAULT_API_BASE, applyBase, applyConfig, useApiConfig } from "./config-context";
+import { HostPlaceholder } from "./host-placeholder";
import { MethodBadge } from "./method-badge";
const LANGS: { key: keyof ApiSamples; label: string }[] = [
@@ -96,7 +97,7 @@ export function CodePanel({
responseHtml: string;
}) {
const [lang, setLang] = useState<keyof ApiSamples>("curl");
- const { base, apiKey } = useApiConfig();
+ const { base, apiKey, appBase } = useApiConfig();
return (
<div className="sticky top-22 flex flex-col gap-4">
@@ -105,18 +106,27 @@ export function CodePanel({
<div className="flex min-w-0 items-center gap-2">
<MethodBadge method={method} />
<span className="truncate font-mono text-ed-12 text-ed-text-muted">
- {applyBase(fullPath, base)}
+ {base === null ? (
+ <>
+ <HostPlaceholder />
+ {fullPath.startsWith(DEFAULT_API_BASE)
+ ? fullPath.slice(DEFAULT_API_BASE.length)
+ : fullPath}
+ </>
+ ) : (
+ applyBase(fullPath, base)
+ )}
</span>
</div>
<LangSelect value={lang} onChange={setLang} />
</div>
<div className="relative">
- <CopyButton text={applyConfig(samples[lang], base, apiKey)} />
+ <CopyButton text={applyConfig(samples[lang], base, apiKey, false, appBase)} />
{/* biome-ignore lint/security/noDangerouslySetInnerHtml: build-time shiki HTML */}
<div
className="api-shiki"
dangerouslySetInnerHTML={{
- __html: applyConfig(highlighted[lang], base, apiKey, true),
+ __html: applyConfig(highlighted[lang], base, apiKey, true, appBase),
}}
/>
</div>
diff --git a/docs/components/api/config-constants.ts b/docs/components/api/config-constants.ts
new file mode 100644
index 0000000000..ad9e086226
--- /dev/null
+++ b/docs/components/api/config-constants.ts
@@ -0,0 +1,23 @@
+/** Shared config constants, deliberately free of `"use client"`.
+ *
+ * Server components (the MCP page) interpolate these into build-time code samples
+ * while client components read them at render, so they cannot live in the client
+ * module: importing across that boundary hands the server a client reference
+ * rather than the primitive string. */
+
+/** REST base for Carbon Cloud, and the literal baked into every generated sample. */
+export const DEFAULT_API_BASE = "https://rest.carbon.ms";
+
+/** App host for Carbon Cloud, where Settings and the MCP server live. */
+export const DEFAULT_APP_ORIGIN = "https://app.carbon.ms";
+
+export const DEFAULT_MCP_ENDPOINT = `${DEFAULT_APP_ORIGIN}/api/mcp`;
+
+/** Stand-in for the origin when we don't know which instance the reader is on.
+ * Mirrors the `<api-key>` convention: obviously a placeholder when copy-pasted. */
+export const HOST_PLACEHOLDER = "<your-host>";
+
+/** Query params the ERP adds to its docs links: the deployment's REST origin and,
+ * because the two are configured independently, its app origin. */
+export const HOST_PARAM = "host";
+export const APP_PARAM = "app";
diff --git a/docs/components/api/config-context.tsx b/docs/components/api/config-context.tsx
index 5904228919..680a7a77c5 100644
--- a/docs/components/api/config-context.tsx
+++ b/docs/components/api/config-context.tsx
@@ -1,45 +1,146 @@
"use client";
import { createContext, useContext, useEffect, useState } from "react";
+import { parseBaseUrl } from "./base-url-parse";
+import {
+ APP_PARAM,
+ DEFAULT_API_BASE,
+ DEFAULT_APP_ORIGIN,
+ DEFAULT_MCP_ENDPOINT,
+ HOST_PARAM,
+ HOST_PLACEHOLDER,
+} from "./config-constants";
+
+export { DEFAULT_API_BASE, DEFAULT_MCP_ENDPOINT, HOST_PLACEHOLDER };
-export const DEFAULT_API_BASE = "https://rest.carbon.ms";
const BASE_STORAGE_KEY = "carbon-api-base";
+const APP_STORAGE_KEY = "carbon-app-origin";
const KEY_STORAGE_KEY = "carbon-api-key";
const API_KEY_PLACEHOLDER = "<api-key>";
+/** A host that arrived in the URL rather than from the reader is only trusted to
+ * DISPLAY. Pasting the reader's stored key into samples aimed at it would hand a
+ * crafted link their credential, so the key is withheld until they confirm the
+ * instance in the dialog. Cleartext http is refused outright (except loopback,
+ * which never leaves the machine) — a key in a copy-pasted http:// sample is a
+ * key on the wire. */
+function isTrustedForCredentials(base: string | null): boolean {
+ if (base === null) return false;
+ try {
+ const u = new URL(base);
+ if (u.protocol === "https:") return true;
+ return u.hostname === "localhost" || u.hostname === "127.0.0.1" || u.hostname === "[::1]";
+ } catch {
+ return false;
+ }
+}
+
type Ctx = {
- base: string;
- setBase: (v: string) => void;
+ /** null = the reader's instance is unknown; render HOST_PLACEHOLDER instead. */
+ base: string | null;
+ setBase: (v: string | null, app?: string | null) => void;
+ /** App host (Settings, MCP). Configured separately from the REST host upstream,
+ * so it is carried explicitly rather than guessed from `base`. */
+ appBase: string | null;
isDefault: boolean;
+ isUnknown: boolean;
apiKey: string;
setApiKey: (v: string) => void;
+ /** Ask the nearest in-provider Configurator to open (from a placeholder click). */
+ openConfigurator: () => void;
+ /** Bumped by openConfigurator. Each Configurator keeps its OWN open state and
+ * watches this instead of sharing one — the mobile drawer and the sidebar both
+ * mount a Configurator at once, and a shared boolean would open both dialogs. */
+ openRequest: number;
};
const ApiConfigCtx = createContext<Ctx>({
- base: DEFAULT_API_BASE,
+ base: null,
setBase: () => {},
- isDefault: true,
+ appBase: null,
+ isDefault: false,
+ isUnknown: true,
apiKey: "",
setApiKey: () => {},
+ openConfigurator: () => {},
+ openRequest: 0,
});
export function ApiConfigProvider({ children }: { children: React.ReactNode }) {
- const [base, setBaseState] = useState(DEFAULT_API_BASE);
+ // Unknown until proven otherwise — showing rest.carbon.ms to a self-hosted
+ // reader is the bug this state exists to fix.
+ const [base, setBaseState] = useState<string | null>(null);
+ const [appBase, setAppBaseState] = useState<string | null>(null);
const [apiKey, setApiKeyState] = useState("");
+ // Where `base` came from. Trust is derived from this + the scheme below, rather
+ // than stored, so no writer can forget to keep a parallel flag in sync.
+ const [baseFromLink, setBaseFromLink] = useState(false);
+ const [openRequest, setOpenRequest] = useState(0);
useEffect(() => {
try {
+ // Precedence: a choice the reader saved themselves outranks the `?host=`
+ // hint from a referring app, which outranks "unknown".
const savedBase = localStorage.getItem(BASE_STORAGE_KEY);
- if (savedBase) setBaseState(savedBase);
const savedKey = localStorage.getItem(KEY_STORAGE_KEY);
if (savedKey) setApiKeyState(savedKey);
+
+ if (savedBase) {
+ // Saved by the reader in the dialog, so the key may be shown against it.
+ setBaseState(savedBase);
+ setAppBaseState(localStorage.getItem(APP_STORAGE_KEY));
+ return;
+ }
+
+ // Both params are read independently: the ERP emits each only when its own
+ // env var is set, and `CARBON_API_URL` is optional while the app origin
+ // always resolves — so an `?app=`-only link is the ordinary shape for a
+ // deployment that never configured a REST origin.
+ const params = new URLSearchParams(window.location.search);
+
+ // Display-only: NOT persisted and never credential-trusted. Persisting would
+ // make one crafted link permanently redirect this reader's samples, and the
+ // dialog is where a host becomes the reader's own choice.
+ const hostParam = params.get(HOST_PARAM);
+ if (hostParam) {
+ const result = parseBaseUrl(hostParam);
+ if ("url" in result) {
+ setBaseState(result.url);
+ setBaseFromLink(true);
+ }
+ }
+
+ const appParam = params.get(APP_PARAM);
+ if (appParam) {
+ const appResult = parseBaseUrl(appParam);
+ if ("url" in appResult) setAppBaseState(appResult.url);
+ }
} catch {}
}, []);
- const setBase = (v: string) => {
- const val = (v || "").trim().replace(/\/+$/, "") || DEFAULT_API_BASE;
+ /** Saving through the dialog is what makes a host the reader's OWN choice, so this
+ * is the only path that persists one or lets the key be shown against it.
+ * `app` is the instance's app host when known (the ERP passes it; the two are
+ * configured independently upstream), else null to fall back to the rest.->app. guess. */
+ const setBase = (v: string | null, app: string | null = null) => {
+ if (v === null) {
+ setBaseState(null);
+ setAppBaseState(null);
+ setBaseFromLink(false);
+ try {
+ localStorage.removeItem(BASE_STORAGE_KEY);
+ localStorage.removeItem(APP_STORAGE_KEY);
+ } catch {}
+ return;
+ }
+ const val = (v || "").trim().replace(/\/+$/, "");
+ if (!val) return;
setBaseState(val);
+ setAppBaseState(app);
+ setBaseFromLink(false);
try {
localStorage.setItem(BASE_STORAGE_KEY, val);
+ if (app) localStorage.setItem(APP_STORAGE_KEY, app);
+ else localStorage.removeItem(APP_STORAGE_KEY);
} catch {}
};
@@ -54,7 +155,19 @@ export function ApiConfigProvider({ children }: { children: React.ReactNode }) {
return (
<ApiConfigCtx.Provider
- value={{ base, setBase, isDefault: base === DEFAULT_API_BASE, apiKey, setApiKey }}
+ value={{
+ base,
+ setBase,
+ appBase,
+ isDefault: base === DEFAULT_API_BASE,
+ isUnknown: base === null,
+ // Withheld while the host came from a link rather than the reader, and for
+ // any cleartext destination — samples would otherwise carry a real key there.
+ apiKey: baseFromLink || !isTrustedForCredentials(base) ? "" : apiKey,
+ setApiKey,
+ openConfigurator: () => setOpenRequest((n) => n + 1),
+ openRequest,
+ }}
>
{children}
</ApiConfigCtx.Provider>
@@ -63,32 +176,40 @@ export function ApiConfigProvider({ children }: { children: React.ReactNode }) {
export const useApiConfig = () => useContext(ApiConfigCtx);
-/** Rewrite the default base URL in a sample to the configured instance. */
-export function applyBase(text: string, base: string): string {
- if (!text || base === DEFAULT_API_BASE) return text;
- return text.split(DEFAULT_API_BASE).join(base);
+/** Rewrite the default base URL in a sample to the configured instance, or to the
+ * `<your-host>` placeholder when the instance is unknown. */
+export function applyBase(text: string, base: string | null): string {
+ if (!text) return text;
+ const replacement = base ?? HOST_PLACEHOLDER;
+ if (replacement === DEFAULT_API_BASE) return text;
+ return text.split(DEFAULT_API_BASE).join(replacement);
}
-// The MCP server lives on the app host (app.carbon.ms), a sibling of the REST API
-// host (rest.carbon.ms) the configurator controls. Derive the instance's MCP
-// endpoint from the configured base by swapping the `rest.` subdomain for `app.`.
-export const DEFAULT_MCP_ENDPOINT = "https://app.carbon.ms/api/mcp";
-
-/** App host for the configured instance (where Settings and the MCP server live).
- * The configurator controls the REST host (rest.*); the app host swaps that subdomain. */
-export function appOrigin(base: string): string {
- if (base === DEFAULT_API_BASE) return "https://app.carbon.ms";
+/** App base for the configured instance (where Settings and the MCP server live).
+ * Returns null when the instance is unknown, so callers render the placeholder.
+ *
+ * `appBase` wins whenever it is known: upstream the app host and the REST host are
+ * separate settings (`ERP_URL` vs `CARBON_API_URL`) and need not share a domain, so
+ * the `rest.` -> `app.` rewrite below is only a fallback for a host the reader typed
+ * themselves. Either way any path prefix survives, because `parseBaseUrl` preserves
+ * one: an instance under `https://acme.com/api/v1` must not lose that segment here
+ * while the REST samples keep it. */
+export function appOrigin(base: string | null, appBase: string | null = null): string | null {
+ if (appBase) return appBase.replace(/\/+$/, "");
+ if (base === null) return null;
+ if (base === DEFAULT_API_BASE) return DEFAULT_APP_ORIGIN;
try {
const u = new URL(base);
u.hostname = u.hostname.replace(/^rest\./, "app.");
- return u.origin;
+ return (u.origin + u.pathname).replace(/\/+$/, "");
} catch {
- return "https://app.carbon.ms";
+ return DEFAULT_APP_ORIGIN;
}
}
-function mcpEndpointFor(base: string): string {
- return `${appOrigin(base)}/api/mcp`;
+function mcpEndpointFor(base: string | null, appBase: string | null = null): string {
+ const origin = appOrigin(base, appBase);
+ return origin === null ? `${HOST_PLACEHOLDER}/api/mcp` : `${origin}/api/mcp`;
}
function escapeHtml(s: string): string {
@@ -98,19 +219,40 @@ function escapeHtml(s: string): string {
/**
* Apply the configured base URL and API key to a sample. Pass `html: true` when `text`
* is shiki-highlighted HTML — there the `<api-key>` placeholder is entity-escaped to
- * `&lt;api-key&gt;`, and the substituted key must be escaped too.
+ * `&lt;api-key&gt;`, and the substituted key must be escaped too. The same applies to
+ * `<your-host>`: injected raw into highlighted HTML the browser would eat it as a tag,
+ * so it goes in entity-encoded and only the copy path (html: false) gets the literal.
*/
-export function applyConfig(text: string, base: string, apiKey: string, html = false): string {
- let out = applyBase(text, base);
- out = out.split(DEFAULT_MCP_ENDPOINT).join(mcpEndpointFor(base));
+export function applyConfig(
+ text: string,
+ base: string | null,
+ apiKey: string,
+ html = false,
+ appBase: string | null = null
+): string {
+ // A configured base is reader-supplied and can hold `&` or `'` (new URL() leaves
+ // both intact), so it needs the same escaping the api key gets — otherwise those
+ // decode inside the highlighted markup and render a host nobody typed.
+ const host = base ?? HOST_PLACEHOLDER;
+ const hostReplacement = html ? escapeHtml(host) : host;
+ let out = text;
+ if (hostReplacement !== DEFAULT_API_BASE) {
+ out = out.split(DEFAULT_API_BASE).join(hostReplacement);
+ }
+ const mcp = mcpEndpointFor(base, appBase);
+ out = out.split(DEFAULT_MCP_ENDPOINT).join(html ? escapeHtml(mcp) : mcp);
if (apiKey) {
if (html) {
const keyEsc = escapeHtml(apiKey);
- // Shiki encodes the placeholder's angle brackets as hex entities (&#x3C;);
- // also cover decimal (&#60;) and named (&lt;) so substitution is encoding-proof.
- for (const needle of ["&#x3C;api-key&#x3E;", "&#60;api-key&#62;", "&lt;api-key&gt;"]) {
- out = out.split(needle).join(keyEsc);
- }
+ // Shiki escapes only what HTML strictly requires, so the brackets around the
+ // placeholder come back INDEPENDENTLY encoded — in practice `&#x3C;api-key>`,
+ // with the `<` a hex entity and the `>` left raw. Matching a fixed pair of
+ // fully-encoded needles silently missed that and shipped a sample that still
+ // said `<api-key>` after the reader had set one. Match either bracket in any
+ // of its forms instead.
+ const LT = "(?:<|&#x3C;|&#60;|&lt;)";
+ const GT = "(?:>|&#x3E;|&#62;|&gt;)";
+ out = out.replace(new RegExp(`${LT}api-key${GT}`, "gi"), keyEsc);
} else {
out = out.split(API_KEY_PLACEHOLDER).join(apiKey);
}
diff --git a/docs/components/api/config-inline.tsx b/docs/components/api/config-inline.tsx
index 5695dec6ae..5640ed7e35 100644
--- a/docs/components/api/config-inline.tsx
+++ b/docs/components/api/config-inline.tsx
@@ -3,15 +3,27 @@
import type { ReactNode } from "react";
import { appOrigin, useApiConfig } from "./config-context";
import { Code, DocLink } from "./doc";
+import { HostPlaceholder } from "./host-placeholder";
/* Reactive inline references for prose — they read the Configurator (api key + base
* URL) so the MCP endpoint, auth header, and Settings link match the instance the
- * reader configured, everywhere they appear (not just in the code blocks). */
+ * reader configured, everywhere they appear (not just in the code blocks). When no
+ * instance is known they degrade to the `<your-host>` placeholder rather than
+ * asserting a host the reader may not be on. */
/** Inline MCP endpoint for the configured instance. */
export function McpEndpoint() {
- const { base } = useApiConfig();
- return <Code>{`${appOrigin(base)}/api/mcp`}</Code>;
+ const { base, appBase } = useApiConfig();
+ const origin = appOrigin(base, appBase);
+ if (origin === null) {
+ return (
+ <Code>
+ <HostPlaceholder />
+ /api/mcp
+ </Code>
+ );
+ }
+ return <Code>{`${origin}/api/mcp`}</Code>;
}
/** Inline bearer-auth header carrying the configured API key (placeholder if unset). */
@@ -20,8 +32,23 @@ export function AuthHeader() {
return <Code>Authorization: Bearer {apiKey || "<api-key>"}</Code>;
}
-/** Settings → API Keys link on the configured instance's app host. */
+/** Settings → API Keys link on the configured instance's app host. With no known
+ * instance there is no host to link to, so the label becomes the configurator
+ * affordance instead of a dead link. */
export function ApiKeysLink({ children }: { children: ReactNode }) {
- const { base } = useApiConfig();
- return <DocLink href={`${appOrigin(base)}/x/settings/api-keys`}>{children}</DocLink>;
+ const { base, appBase, openConfigurator } = useApiConfig();
+ const origin = appOrigin(base, appBase);
+ if (origin === null) {
+ return (
+ <button
+ type="button"
+ onClick={openConfigurator}
+ title="Set your Carbon instance"
+ className="text-ed-brand-ink underline decoration-dotted underline-offset-2 hover:decoration-solid"
+ >
+ {children}
+ </button>
+ );
+ }
+ return <DocLink href={`${origin}/x/settings/api-keys`}>{children}</DocLink>;
}
diff --git a/docs/components/api/configurator.tsx b/docs/components/api/configurator.tsx
index f9873e8433..0813e8ebfd 100644
--- a/docs/components/api/configurator.tsx
+++ b/docs/components/api/configurator.tsx
@@ -1,8 +1,10 @@
"use client";
import * as Dialog from "@radix-ui/react-dialog";
-import { useState } from "react";
-import { DEFAULT_API_BASE, useApiConfig } from "./config-context";
+import { useEffect, useRef, useState } from "react";
+import { parseBaseUrl } from "./base-url-parse";
+import { DEFAULT_API_BASE, DEFAULT_APP_ORIGIN } from "./config-constants";
+import { HOST_PLACEHOLDER, useApiConfig } from "./config-context";
function ServerIcon({ className }: { className?: string }) {
return (
@@ -42,28 +44,6 @@ function EyeIcon({ off }: { off: boolean }) {
);
}
-/** Validate/normalize a user-entered base URL. Returns the cleaned URL or an error message. */
-function parseBaseUrl(raw: string): { url: string } | { error: string } {
- const v = raw.trim();
- if (!v) return { error: "Enter a URL" };
- const withScheme = /^https?:\/\//i.test(v) ? v : `https://${v}`;
- let u: URL;
- try {
- u = new URL(withScheme);
- } catch {
- return { error: "Not a valid URL" };
- }
- if (u.protocol !== "http:" && u.protocol !== "https:") {
- return { error: "Use http:// or https://" };
- }
- const host = u.hostname;
- const isIp = /^\d{1,3}(\.\d{1,3}){3}$/.test(host);
- if (host !== "localhost" && !isIp && !host.includes(".")) {
- return { error: "Enter a valid host (e.g. rest.carbon.ms)" };
- }
- return { url: (u.origin + u.pathname).replace(/\/+$/, "") };
-}
-
function ModeCard({
active,
onClick,
@@ -97,20 +77,30 @@ function ModeCard({
}
export function Configurator() {
- const { base, setBase, isDefault, apiKey, setApiKey } = useApiConfig();
+ const {
+ base,
+ setBase,
+ isDefault,
+ isUnknown,
+ apiKey,
+ setApiKey,
+ openRequest,
+ } = useApiConfig();
const [open, setOpen] = useState(false);
- const [mode, setMode] = useState<"cloud" | "self">("cloud");
+ const [mode, setMode] = useState<"unknown" | "cloud" | "self">("unknown");
const [url, setUrl] = useState("");
const [key, setKey] = useState("");
const [showKey, setShowKey] = useState(false);
const [urlError, setUrlError] = useState("");
- const host = base.replace(/^https?:\/\//, "");
+ // With no instance configured the trigger shows the placeholder rather than a
+ // hostname, so the sidebar states plainly that the host is not yet known.
+ const host = base === null ? HOST_PLACEHOLDER : base.replace(/^https?:\/\//, "");
// Seed the draft from current config whenever the dialog opens.
const onOpenChange = (next: boolean) => {
if (next) {
- setMode(isDefault ? "cloud" : "self");
- setUrl(isDefault ? "" : base);
+ setMode(isUnknown ? "unknown" : isDefault ? "cloud" : "self");
+ setUrl(isUnknown || isDefault ? "" : (base ?? ""));
setKey(apiKey);
setShowKey(false);
setUrlError("");
@@ -118,6 +108,20 @@ export function Configurator() {
setOpen(next);
};
+ // A <your-host> click anywhere in the tree bumps openRequest; open in response.
+ // Two Configurators are mounted at once (sidebar + mobile drawer) and both see
+ // the bump, so each answers only when its own trigger is the visible one —
+ // otherwise a single click would open two dialogs. Skipped on mount so the
+ // dialog doesn't spring open on first paint.
+ const triggerRef = useRef<HTMLButtonElement>(null);
+ const seenRequest = useRef(openRequest);
+ useEffect(() => {
+ if (openRequest === seenRequest.current) return;
+ seenRequest.current = openRequest;
+ const el = triggerRef.current;
+ if (el && (el.offsetWidth || el.offsetHeight)) onOpenChange(true);
+ }, [openRequest]);
+
const save = () => {
if (mode === "self") {
const result = parseBaseUrl(url);
@@ -126,15 +130,17 @@ export function Configurator() {
return;
}
setBase(result.url);
+ } else if (mode === "cloud") {
+ setBase(DEFAULT_API_BASE, DEFAULT_APP_ORIGIN);
} else {
- setBase(DEFAULT_API_BASE);
+ setBase(null);
}
setApiKey(key);
setOpen(false);
};
const reset = () => {
- setMode("cloud");
+ setMode("unknown");
setUrl("");
setKey("");
setUrlError("");
@@ -144,6 +150,7 @@ export function Configurator() {
<Dialog.Root open={open} onOpenChange={onOpenChange}>
<Dialog.Trigger asChild>
<button
+ ref={triggerRef}
type="button"
className="group mb-3.5 flex w-full items-center gap-2 rounded-lg border border-ed-warm-300 bg-white px-2.5 py-2 text-left text-ed-ink/58 transition-colors hover:border-ed-warm-500 data-[state=open]:border-ed-warm-500"
>
@@ -198,7 +205,8 @@ export function Configurator() {
<p className="m-0 mb-2 font-mono text-ed-11 font-semibold uppercase tracking-[0.07em] text-ed-ink/50">
Environment
</p>
- <div className="grid grid-cols-2 gap-2">
+ <div className="grid grid-cols-3 gap-2">
+ <ModeCard active={mode === "unknown"} onClick={() => setMode("unknown")} title="Not sure" sub="<your-host>" />
<ModeCard active={mode === "cloud"} onClick={() => setMode("cloud")} title="Carbon Cloud" sub="rest.carbon.ms" />
<ModeCard active={mode === "self"} onClick={() => setMode("self")} title="Self-hosted" sub="Your instance" />
</div>
diff --git a/docs/components/api/host-placeholder.tsx b/docs/components/api/host-placeholder.tsx
new file mode 100644
index 0000000000..fa2ad15f95
--- /dev/null
+++ b/docs/components/api/host-placeholder.tsx
@@ -0,0 +1,20 @@
+"use client";
+
+import { HOST_PLACEHOLDER, useApiConfig } from "./config-context";
+
+/** The `<your-host>` stand-in shown when the reader's instance is unknown.
+ * Clicking it opens the API configuration dialog, so the reader can replace
+ * every placeholder on the page with their own host in one step. */
+export function HostPlaceholder() {
+ const { openConfigurator } = useApiConfig();
+ return (
+ <button
+ type="button"
+ onClick={openConfigurator}
+ title="Set your Carbon instance"
+ className="rounded-[5px] border border-dashed border-ed-warm-500 bg-ed-brand/7 px-[5px] py-px font-mono text-ed-brand-ink transition-colors hover:border-ed-brand hover:bg-ed-brand/12"
+ >
+ {HOST_PLACEHOLDER}
+ </button>
+ );
+}