Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(runtimes): self-host daemon setup URLs (MUL-2804) (#3474)

Ivan Vinokurov9aa8ba01910b
diff --git a/.env.example b/.env.example
index 6d49d89cb3..ec178830f6 100644
--- a/.env.example
+++ b/.env.example
@@ -40,11 +40,12 @@ JWT_SECRET=change-me-in-production
# MULTICA_APP_URL=http://localhost:3000
# Public URL the API is reachable at from the open internet (no trailing
# slash). Used to mint absolute webhook URLs for autopilot webhook
-# triggers. Leave unset behind a same-origin reverse proxy or for plain
-# localhost dev — the frontend will compose the URL from
-# window.origin + webhook_path in that case. Headers are intentionally
-# not used to derive this value, to avoid Host / X-Forwarded-Host
-# spoofing when a self-hosted reverse proxy is not hardened.
+# triggers and to show correct daemon setup commands in the web UI. Leave
+# unset behind a same-origin reverse proxy or for plain localhost dev —
+# the frontend will compose the URL from window.origin + webhook_path in
+# that case. Headers are intentionally not used to derive this value, to
+# avoid Host / X-Forwarded-Host spoofing when a self-hosted reverse proxy
+# is not hardened.
MULTICA_PUBLIC_URL=
# Comma-separated CIDR list of reverse proxies whose X-Forwarded-For /
# X-Real-IP headers the per-IP webhook rate limiter is allowed to trust.
diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdx
index 93e03918ac..882df9c9b2 100644
--- a/apps/docs/content/docs/environment-variables.mdx
+++ b/apps/docs/content/docs/environment-variables.mdx
@@ -183,6 +183,8 @@ For a full explanation of how each parameter affects daemon behavior, see [Daemo
| Variable | Default | Description |
|---|---|---|
| `FRONTEND_ORIGIN` | empty | Frontend address. Invite email links, the CORS allowlist, and the cookie domain are all derived from this. When unset, invite email links fall back to the hosted domain `https://app.multica.ai` — self-host must set this explicitly |
+| `MULTICA_APP_URL` | empty | Frontend URL for CLI login flow. Also used by the web UI to show self-host daemon setup commands with your app domain; for same-origin deployments this is also used as daemon `server_url` when `MULTICA_PUBLIC_URL` is unset |
+| `MULTICA_PUBLIC_URL` | empty | Public API URL, without trailing slash. Used for autopilot webhook URLs and by the web UI as the daemon `server_url` |
| `CORS_ALLOWED_ORIGINS` | empty | Additional allowed CORS origins (comma-separated) |
| `ALLOWED_ORIGINS` | empty | WebSocket-specific origin allowlist (comma-separated); when unset, fallback order is `CORS_ALLOWED_ORIGINS` → `FRONTEND_ORIGIN` → `localhost:3000/5173/5174` |
diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdx
index 42e37e6d6c..6bebec89a0 100644
--- a/apps/docs/content/docs/environment-variables.zh.mdx
+++ b/apps/docs/content/docs/environment-variables.zh.mdx
@@ -183,6 +183,8 @@ Multica 存储用户上传的附件(评论里的图片、文件等)。**优
| 环境变量 | 默认值 | 说明 |
|---|---|---|
| `FRONTEND_ORIGIN` | 空 | 前端地址。邀请邮件里的链接、CORS 白名单、cookie domain 都从这里推导。邮件链接在不设时会 fallback 到托管版域名 `https://app.multica.ai`——self-host 必须显式填 |
+| `MULTICA_APP_URL` | 空 | CLI 登录流程使用的前端 URL。Web UI 也会用它显示带你自己 app domain 的 self-host 守护进程 setup 命令;同源部署中,如果 `MULTICA_PUBLIC_URL` 未设置,它也会作为守护进程的 `server_url` |
+| `MULTICA_PUBLIC_URL` | 空 | 公开 API URL,不带结尾 slash。用于 autopilot webhook URL,也会被 Web UI 用作守护进程的 `server_url` |
| `CORS_ALLOWED_ORIGINS` | 空 | 额外的 CORS 允许来源(逗号分隔)|
| `ALLOWED_ORIGINS` | 空 | WebSocket 专用的 origin 白名单(逗号分隔);不设就按 `CORS_ALLOWED_ORIGINS` → `FRONTEND_ORIGIN` → `localhost:3000/5173/5174` 顺序回落 |
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index f02daeb128..8769b803e2 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -137,6 +137,7 @@ import {
DashboardUsageDailyListSchema,
EMPTY_AGENT_TEMPLATE_DETAIL,
EMPTY_AGENT_TEMPLATE_SUMMARY_LIST,
+ EMPTY_APP_CONFIG,
EMPTY_ATTACHMENT,
EMPTY_CLOUD_RUNTIME_NODE,
EMPTY_CLOUD_RUNTIME_NODE_LIST,
@@ -150,6 +151,8 @@ import {
EMPTY_USER,
EMPTY_LIST_WEBHOOK_DELIVERIES_RESPONSE,
EMPTY_WEBHOOK_DELIVERY,
+ AppConfigSchema,
+ type AppConfigResponse,
GroupedIssuesResponseSchema,
ListIssuesResponseSchema,
ListWebhookDeliveriesResponseSchema,
@@ -1359,18 +1362,11 @@ export class ApiClient {
}
// App Config
- async getConfig(): Promise<{
- cdn_domain: string;
- allow_signup: boolean;
- google_client_id?: string;
- posthog_key?: string;
- posthog_host?: string;
- analytics_environment?: string;
- // Self-host gate (#3433). Optional because older servers omit the field
- // entirely; consumers must default to false.
- workspace_creation_disabled?: boolean;
- }> {
- return this.fetch("/api/config");
+ async getConfig(): Promise<AppConfigResponse> {
+ const raw = await this.fetch<unknown>("/api/config");
+ return parseWithFallback<AppConfigResponse>(raw, AppConfigSchema, EMPTY_APP_CONFIG, {
+ endpoint: "GET /api/config",
+ });
}
// Workspaces
diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.ts
index b09d5c15ec..4bc8398863 100644
--- a/packages/core/api/schema.test.ts
+++ b/packages/core/api/schema.test.ts
@@ -91,6 +91,24 @@ describe("ApiClient schema fallback", () => {
});
});
+ describe("getConfig", () => {
+ it("drops malformed daemon setup URLs instead of throwing", async () => {
+ stubFetchJson({
+ cdn_domain: "cdn.example.com",
+ allow_signup: true,
+ daemon_server_url: { wrong: "shape" },
+ daemon_app_url: 123,
+ workspace_creation_disabled: false,
+ });
+ const client = new ApiClient("https://api.example.test");
+ const config = await client.getConfig();
+ expect(config.cdn_domain).toBe("cdn.example.com");
+ expect(config.allow_signup).toBe(true);
+ expect(config.daemon_server_url).toBeUndefined();
+ expect(config.daemon_app_url).toBeUndefined();
+ });
+ });
+
describe("listGroupedIssues", () => {
it("falls back to empty groups when the response is malformed", async () => {
stubFetchJson({ groups: "not-an-array" });
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index de430753b4..ea3c7dda97 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -23,6 +23,18 @@ import type {
} from "../types";
import type { CloudRuntimeNode } from "../runtimes/cloud-runtime";
+export interface AppConfigResponse {
+ cdn_domain: string;
+ allow_signup: boolean;
+ google_client_id?: string;
+ posthog_key?: string;
+ posthog_host?: string;
+ analytics_environment?: string;
+ daemon_server_url?: string;
+ daemon_app_url?: string;
+ workspace_creation_disabled?: boolean;
+}
+
// ---------------------------------------------------------------------------
// Schemas for the highest-risk API endpoints — those whose responses drive
// the issue detail page (timeline, comments, subscribers) and the issues
@@ -129,6 +141,38 @@ export const TimelineEntriesSchema = z.array(TimelineEntrySchema);
export const EMPTY_TIMELINE_ENTRIES: TimelineEntry[] = [];
+const OptionalStringSchema = z.preprocess(
+ (value) => (typeof value === "string" ? value : undefined),
+ z.string().optional(),
+);
+
+const BooleanWithDefaultSchema = (fallback: boolean) =>
+ z.preprocess(
+ (value) => (typeof value === "boolean" ? value : undefined),
+ z.boolean().default(fallback),
+ );
+
+export const AppConfigSchema = z.object({
+ cdn_domain: z.string().default(""),
+ allow_signup: BooleanWithDefaultSchema(true),
+ google_client_id: OptionalStringSchema,
+ posthog_key: OptionalStringSchema,
+ posthog_host: OptionalStringSchema,
+ analytics_environment: OptionalStringSchema,
+ daemon_server_url: OptionalStringSchema,
+ daemon_app_url: OptionalStringSchema,
+ workspace_creation_disabled: BooleanWithDefaultSchema(false).optional(),
+}).loose();
+
+export const EMPTY_APP_CONFIG: AppConfigResponse = {
+ cdn_domain: "",
+ allow_signup: true,
+ google_client_id: "",
+ daemon_server_url: "",
+ daemon_app_url: "",
+ workspace_creation_disabled: false,
+};
+
export const CommentSchema = z.object({
id: z.string(),
issue_id: z.string(),
diff --git a/packages/core/config/index.ts b/packages/core/config/index.ts
index ee1cfd1c4c..f24336471a 100644
--- a/packages/core/config/index.ts
+++ b/packages/core/config/index.ts
@@ -5,6 +5,8 @@ interface ConfigState {
cdnDomain: string;
allowSignup: boolean;
googleClientId: string;
+ daemonServerUrl: string;
+ daemonAppUrl: string;
// Self-host gate (#3433): when true, every "Create workspace" affordance
// must be hidden. Defaults to false so unknown / older servers behave like
// the managed-cloud case.
@@ -15,16 +17,24 @@ interface ConfigState {
googleClientId?: string;
workspaceCreationDisabled?: boolean;
}) => void;
+ setDaemonConfig: (config: {
+ daemonServerUrl?: string;
+ daemonAppUrl?: string;
+ }) => void;
}
export const configStore = createStore<ConfigState>((set) => ({
cdnDomain: "",
allowSignup: true,
googleClientId: "",
+ daemonServerUrl: "",
+ daemonAppUrl: "",
workspaceCreationDisabled: false,
setCdnDomain: (domain) => set({ cdnDomain: domain }),
setAuthConfig: ({ allowSignup, googleClientId = "", workspaceCreationDisabled = false }) =>
set({ allowSignup, googleClientId, workspaceCreationDisabled }),
+ setDaemonConfig: ({ daemonServerUrl = "", daemonAppUrl = "" }) =>
+ set({ daemonServerUrl, daemonAppUrl }),
}));
export function useConfigStore(): ConfigState;
diff --git a/packages/core/platform/auth-initializer.tsx b/packages/core/platform/auth-initializer.tsx
index 40dcb3d8be..c085178796 100644
--- a/packages/core/platform/auth-initializer.tsx
+++ b/packages/core/platform/auth-initializer.tsx
@@ -57,6 +57,10 @@ export function AuthInitializer({
// (the managed-cloud default) rather than blocking the UI.
workspaceCreationDisabled: cfg.workspace_creation_disabled === true,
});
+ configStore.getState().setDaemonConfig({
+ daemonServerUrl: cfg.daemon_server_url,
+ daemonAppUrl: cfg.daemon_app_url,
+ });
if (cfg.posthog_key) {
initAnalytics({
key: cfg.posthog_key,
diff --git a/packages/views/runtimes/components/connect-remote-dialog.test.tsx b/packages/views/runtimes/components/connect-remote-dialog.test.tsx
index c99cbd2025..e3fb74a636 100644
--- a/packages/views/runtimes/components/connect-remote-dialog.test.tsx
+++ b/packages/views/runtimes/components/connect-remote-dialog.test.tsx
@@ -2,6 +2,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { render } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { I18nProvider } from "@multica/core/i18n/react";
+import { configStore } from "@multica/core/config";
import enCommon from "../../locales/en/common.json";
import enRuntimes from "../../locales/en/runtimes.json";
import { ConnectRemoteDialog } from "./connect-remote-dialog";
@@ -30,7 +31,25 @@ vi.mock("../../navigation", () => ({
useNavigation: () => ({ push: vi.fn() }),
}));
-function renderDialog() {
+function resetConfigStore() {
+ configStore.setState({
+ cdnDomain: "",
+ allowSignup: true,
+ googleClientId: "",
+ daemonServerUrl: "",
+ daemonAppUrl: "",
+ workspaceCreationDisabled: false,
+ });
+}
+
+function renderDialog(config?: {
+ daemonServerUrl?: string;
+ daemonAppUrl?: string;
+}) {
+ resetConfigStore();
+ if (config) {
+ configStore.getState().setDaemonConfig(config);
+ }
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<QueryClientProvider client={qc}>
@@ -47,6 +66,36 @@ const ligatureClasses = [
];
describe("ConnectRemoteDialog", () => {
+ it("uses cloud setup commands by default", () => {
+ const { baseElement } = renderDialog();
+
+ expect(baseElement).toHaveTextContent("multica setup");
+ expect(baseElement).not.toHaveTextContent("multica setup self-host");
+ expect(baseElement).toHaveTextContent(
+ "multica config set server_url https://api.multica.ai",
+ );
+ expect(baseElement).toHaveTextContent(
+ "multica config set app_url https://multica.ai",
+ );
+ });
+
+ it("uses self-host daemon URLs from runtime config", () => {
+ const { baseElement } = renderDialog({
+ daemonServerUrl: "https://api.example.com/",
+ daemonAppUrl: "https://app.example.com/",
+ });
+
+ expect(baseElement).toHaveTextContent(
+ "multica setup self-host --server-url https://api.example.com --app-url https://app.example.com",
+ );
+ expect(baseElement).toHaveTextContent(
+ "multica config set server_url https://api.example.com",
+ );
+ expect(baseElement).toHaveTextContent(
+ "multica config set app_url https://app.example.com",
+ );
+ });
+
it("disables font ligatures in setup command code", () => {
const { baseElement } = renderDialog();
diff --git a/packages/views/runtimes/components/connect-remote-dialog.tsx b/packages/views/runtimes/components/connect-remote-dialog.tsx
index 9cbd1729e3..0317558be0 100644
--- a/packages/views/runtimes/components/connect-remote-dialog.tsx
+++ b/packages/views/runtimes/components/connect-remote-dialog.tsx
@@ -7,6 +7,7 @@ import { useWorkspaceId } from "@multica/core/hooks";
import { runtimeKeys } from "@multica/core/runtimes/queries";
import { useWSEvent } from "@multica/core/realtime";
import { paths, useWorkspaceSlug } from "@multica/core/paths";
+import { useConfigStore } from "@multica/core/config";
import {
Dialog,
DialogContent,
@@ -25,11 +26,34 @@ type Step = "instructions" | "success";
const INSTALL_CMD =
"curl -fsSL https://raw.githubusercontent.com/multica-ai/multica/main/scripts/install.sh | bash";
-const SETUP_CMD = "multica setup";
-const TOKEN_CMD = `multica config set server_url https://api.multica.ai
-multica config set app_url https://multica.ai
+const CLOUD_SERVER_URL = "https://api.multica.ai";
+const CLOUD_APP_URL = "https://multica.ai";
+
+function normalizeCommandURL(url: string | undefined) {
+ return url?.trim().replace(/\/+$/, "") ?? "";
+}
+
+function daemonCommands(serverUrl: string | undefined, appUrl: string | undefined) {
+ const normalizedServerUrl = normalizeCommandURL(serverUrl);
+ const normalizedAppUrl = normalizeCommandURL(appUrl);
+ if (normalizedServerUrl && normalizedAppUrl) {
+ return {
+ setupCmd: `multica setup self-host --server-url ${normalizedServerUrl} --app-url ${normalizedAppUrl}`,
+ tokenCmd: `multica config set server_url ${normalizedServerUrl}
+multica config set app_url ${normalizedAppUrl}
multica login --token <YOUR_TOKEN>
-multica daemon start`;
+multica daemon start`,
+ };
+ }
+
+ return {
+ setupCmd: "multica setup",
+ tokenCmd: `multica config set server_url ${CLOUD_SERVER_URL}
+multica config set app_url ${CLOUD_APP_URL}
+multica login --token <YOUR_TOKEN>
+multica daemon start`,
+ };
+}
export function ConnectRemoteDialog({ onClose }: { onClose: () => void }) {
const [step, setStep] = useState<Step>("instructions");
@@ -164,6 +188,9 @@ function CommandStep({
function InstructionsStep({ onClose }: { onClose: () => void }) {
const { t } = useT("runtimes");
+ const daemonServerUrl = useConfigStore((s) => s.daemonServerUrl);
+ const daemonAppUrl = useConfigStore((s) => s.daemonAppUrl);
+ const { setupCmd, tokenCmd } = daemonCommands(daemonServerUrl, daemonAppUrl);
return (
<>
<DialogHeader className="px-6 pt-6 pb-2">
@@ -188,7 +215,7 @@ function InstructionsStep({ onClose }: { onClose: () => void }) {
<CommandStep
n={2}
label={t(($) => $.connect.step2_label)}
- cmd={SETUP_CMD}
+ cmd={setupCmd}
copyAria={t(($) => $.connect.copy_aria)}
/>
<p className="mt-1.5 text-[11px] leading-[1.55] text-muted-foreground">
@@ -198,7 +225,7 @@ function InstructionsStep({ onClose }: { onClose: () => void }) {
<LiveListening />
- <TroubleshootingDetails />
+ <TroubleshootingDetails tokenCmd={tokenCmd} />
</div>
</div>
@@ -211,7 +238,7 @@ function InstructionsStep({ onClose }: { onClose: () => void }) {
);
}
-function TroubleshootingDetails() {
+function TroubleshootingDetails({ tokenCmd }: { tokenCmd: string }) {
const { t } = useT("runtimes");
return (
<details className="group rounded-lg border border-dashed">
@@ -227,7 +254,7 @@ function TroubleshootingDetails() {
<CommandStep
n={2}
label={t(($) => $.connect.step2_label)}
- cmd={TOKEN_CMD}
+ cmd={tokenCmd}
copyAria={t(($) => $.connect.copy_aria)}
/>
<p>
diff --git a/server/internal/handler/config.go b/server/internal/handler/config.go
index cbeccc504c..720d4b6358 100644
--- a/server/internal/handler/config.go
+++ b/server/internal/handler/config.go
@@ -2,7 +2,9 @@ package handler
import (
"net/http"
+ "net/url"
"os"
+ "strings"
"github.com/multica-ai/multica/server/internal/analytics"
)
@@ -20,6 +22,11 @@ type AppConfig struct {
// from the JSON when false to keep responses identical to the
// previous shape for the common managed-cloud case (#3433).
WorkspaceCreationDisabled bool `json:"workspace_creation_disabled,omitempty"`
+ // Public daemon setup config consumed by the web app at runtime so
+ // self-hosted instances can show `multica setup self-host` commands
+ // with the operator's own domains instead of Multica Cloud defaults.
+ DaemonServerURL string `json:"daemon_server_url,omitempty"`
+ DaemonAppURL string `json:"daemon_app_url,omitempty"`
// PostHog public config for the frontend. The key is the same Project
// API Key the backend uses; returning it here (instead of baking it
@@ -44,6 +51,7 @@ func (h *Handler) GetConfig(w http.ResponseWriter, r *http.Request) {
if h.Storage != nil {
config.CdnDomain = h.Storage.CdnDomain()
}
+ config.DaemonServerURL, config.DaemonAppURL = daemonSetupURLsFromEnv()
// Re-read from env on every request so operators can rotate keys via
// secret refresh without a server restart.
@@ -58,3 +66,59 @@ func (h *Handler) GetConfig(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, config)
}
+
+func daemonSetupURLsFromEnv() (string, string) {
+ serverURL := normalizePublicURL(os.Getenv("MULTICA_PUBLIC_URL"))
+ appURL := normalizePublicURL(os.Getenv("MULTICA_APP_URL"))
+ if appURL == "" {
+ appURL = normalizePublicURL(os.Getenv("FRONTEND_ORIGIN"))
+ }
+ if appURL == "" {
+ return "", ""
+ }
+
+ if serverURL == "" {
+ serverURL = appURL
+ }
+ if isOfficialCloudDaemonConfig(serverURL, appURL) {
+ return "", ""
+ }
+ return serverURL, appURL
+}
+
+func normalizePublicURL(raw string) string {
+ return strings.TrimRight(strings.TrimSpace(raw), "/")
+}
+
+func isOfficialCloudDaemonConfig(serverURL, appURL string) bool {
+ if !urlHostEquals(serverURL, "api.multica.ai") {
+ return false
+ }
+ return urlHostEquals(appURL, "multica.ai") || urlHostEquals(appURL, "app.multica.ai")
+}
+
+func urlHostEquals(raw, want string) bool {
+ host := canonicalURLHost(raw)
+ if host == "" {
+ return false
+ }
+ want = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(want)), ".")
+ return host == want
+}
+
+func canonicalURLHost(raw string) string {
+ raw = strings.TrimSpace(raw)
+ u, err := url.Parse(raw)
+ if err != nil {
+ return ""
+ }
+ host := u.Hostname()
+ if host == "" && !strings.Contains(raw, "://") {
+ u, err = url.Parse("https://" + raw)
+ if err != nil {
+ return ""
+ }
+ host = u.Hostname()
+ }
+ return strings.TrimSuffix(strings.ToLower(host), ".")
+}
diff --git a/server/internal/handler/config_test.go b/server/internal/handler/config_test.go
index d1c930849a..9a9a29e63d 100644
--- a/server/internal/handler/config_test.go
+++ b/server/internal/handler/config_test.go
@@ -16,6 +16,8 @@ func TestGetConfigIncludesRuntimeAuthConfig(t *testing.T) {
t.Setenv("GOOGLE_CLIENT_ID", "google-client-id")
t.Setenv("POSTHOG_API_KEY", "phc_test")
t.Setenv("POSTHOG_HOST", "https://eu.i.posthog.com")
+ t.Setenv("MULTICA_PUBLIC_URL", "https://api.example.com/")
+ t.Setenv("MULTICA_APP_URL", "https://app.example.com/")
req := httptest.NewRequest(http.MethodGet, "/api/config", nil)
w := httptest.NewRecorder()
@@ -51,6 +53,105 @@ func TestGetConfigIncludesRuntimeAuthConfig(t *testing.T) {
if cfg.WorkspaceCreationDisabled {
t.Fatalf("workspace_creation_disabled: want false by default, got true")
}
+ if cfg.DaemonServerURL != "https://api.example.com" {
+ t.Fatalf("daemon_server_url: want https://api.example.com, got %q", cfg.DaemonServerURL)
+ }
+ if cfg.DaemonAppURL != "https://app.example.com" {
+ t.Fatalf("daemon_app_url: want https://app.example.com, got %q", cfg.DaemonAppURL)
+ }
+}
+
+func TestGetConfigUsesAppURLForSameOriginDaemonSetup(t *testing.T) {
+ t.Setenv("MULTICA_APP_URL", "https://multica.internal.example/")
+
+ req := httptest.NewRequest(http.MethodGet, "/api/config", nil)
+ w := httptest.NewRecorder()
+
+ testHandler.GetConfig(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("GetConfig: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var cfg AppConfig
+ if err := json.Unmarshal(w.Body.Bytes(), &cfg); err != nil {
+ t.Fatalf("decode config: %v", err)
+ }
+ if cfg.DaemonServerURL != "https://multica.internal.example" {
+ t.Fatalf("daemon_server_url: want same-origin URL, got %q", cfg.DaemonServerURL)
+ }
+ if cfg.DaemonAppURL != "https://multica.internal.example" {
+ t.Fatalf("daemon_app_url: want app URL, got %q", cfg.DaemonAppURL)
+ }
+}
+
+func TestGetConfigUsesFrontendOriginForSameOriginDaemonSetup(t *testing.T) {
+ t.Setenv("FRONTEND_ORIGIN", "https://multica.internal.example/")
+
+ req := httptest.NewRequest(http.MethodGet, "/api/config", nil)
+ w := httptest.NewRecorder()
+
+ testHandler.GetConfig(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("GetConfig: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var cfg AppConfig
+ if err := json.Unmarshal(w.Body.Bytes(), &cfg); err != nil {
+ t.Fatalf("decode config: %v", err)
+ }
+ if cfg.DaemonServerURL != "https://multica.internal.example" {
+ t.Fatalf("daemon_server_url: want same-origin URL, got %q", cfg.DaemonServerURL)
+ }
+ if cfg.DaemonAppURL != "https://multica.internal.example" {
+ t.Fatalf("daemon_app_url: want frontend origin, got %q", cfg.DaemonAppURL)
+ }
+}
+
+func TestGetConfigOmitsOfficialCloudDaemonSetup(t *testing.T) {
+ t.Setenv("MULTICA_PUBLIC_URL", "https://api.multica.ai")
+ t.Setenv("FRONTEND_ORIGIN", "https://multica.ai")
+
+ req := httptest.NewRequest(http.MethodGet, "/api/config", nil)
+ w := httptest.NewRecorder()
+
+ testHandler.GetConfig(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("GetConfig: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var cfg AppConfig
+ if err := json.Unmarshal(w.Body.Bytes(), &cfg); err != nil {
+ t.Fatalf("decode config: %v", err)
+ }
+ if cfg.DaemonServerURL != "" {
+ t.Fatalf("daemon_server_url: want omitted for cloud, got %q", cfg.DaemonServerURL)
+ }
+ if cfg.DaemonAppURL != "" {
+ t.Fatalf("daemon_app_url: want omitted for cloud, got %q", cfg.DaemonAppURL)
+ }
+}
+
+func TestURLHostEqualsCanonicalizesCommonHostForms(t *testing.T) {
+ tests := []struct {
+ name string
+ raw string
+ want bool
+ }{
+ {name: "full URL", raw: "https://api.multica.ai", want: true},
+ {name: "bare host", raw: "api.multica.ai", want: true},
+ {name: "host port", raw: "api.multica.ai:8080", want: true},
+ {name: "trailing dot", raw: "https://api.multica.ai.", want: true},
+ {name: "different host", raw: "https://evil.example", want: false},
+ {name: "empty", raw: "", want: false},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := urlHostEquals(tt.raw, "api.multica.ai"); got != tt.want {
+ t.Fatalf("urlHostEquals(%q): want %v, got %v", tt.raw, tt.want, got)
+ }
+ })
+ }
}
// TestGetConfigExposesWorkspaceCreationDisabled verifies that the self-host