:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(desktop): point the dev region at a custom PostHog Desktop instance (#96361)
Shy Altera9b0f069be7f
diff --git a/.github/workflows/desktop-build-test.yml b/.github/workflows/desktop-build-test.ymlindex a4b233e976e2..3c8a45b8137c 100644--- a/.github/workflows/desktop-build-test.yml+++ b/.github/workflows/desktop-build-test.yml@@ -63,6 +63,7 @@ jobs:VITE_POSTHOG_API_KEY: ${{ vars.VITE_POSTHOG_API_KEY }}VITE_POSTHOG_API_HOST: ${{ vars.VITE_POSTHOG_API_HOST }}VITE_POSTHOG_UI_HOST: ${{ vars.VITE_POSTHOG_UI_HOST }}+ VITE_POSTHOG_BUILD_CHANNEL: test# No sourcemap secrets: without them the posthog vite plugin skips# release creation and sourcemap upload, keeping test builds# hermetic instead of calling the prod API and flaking on it.@@ -251,6 +252,7 @@ jobs:VITE_POSTHOG_API_KEY: ${{ vars.VITE_POSTHOG_API_KEY }}VITE_POSTHOG_API_HOST: ${{ vars.VITE_POSTHOG_API_HOST }}VITE_POSTHOG_UI_HOST: ${{ vars.VITE_POSTHOG_UI_HOST }}+ VITE_POSTHOG_BUILD_CHANNEL: teststeps:- name: Checkoutuses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2@@ -366,6 +368,7 @@ jobs:VITE_POSTHOG_API_KEY: ${{ vars.VITE_POSTHOG_API_KEY }}VITE_POSTHOG_API_HOST: ${{ vars.VITE_POSTHOG_API_HOST }}VITE_POSTHOG_UI_HOST: ${{ vars.VITE_POSTHOG_UI_HOST }}+ VITE_POSTHOG_BUILD_CHANNEL: teststeps:- name: Checkoutuses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2diff --git a/products/desktop/apps/code/electron-builder.ts b/products/desktop/apps/code/electron-builder.tsindex dfbcbd89f47f..90752214e2e1 100644--- a/products/desktop/apps/code/electron-builder.ts+++ b/products/desktop/apps/code/electron-builder.ts@@ -8,6 +8,14 @@ const require = createRequire(import.meta.url);const skipNotarize =process.env.SKIP_NOTARIZE === "1" || !process.env.APPLE_TEAM_ID;+// A test build installs beside a release build, so it must not claim the+// release deep-link scheme: the OS would route one of the two builds'+// callbacks to the wrong app.+const isTestChannelBuild = process.env.VITE_POSTHOG_BUILD_CHANNEL === "test";+const deeplinkSchemes = isTestChannelBuild+ ? ["posthog-code-test"]+ : ["posthog-code"];+const config: Configuration = {// Original release bundle id; changing it breaks existing installs' data dir and Keychain entries.appId: "com.posthog.array",@@ -64,7 +72,7 @@ const config: Configuration = {protocols: [{name: "PostHog",- schemes: ["posthog-code"],+ schemes: deeplinkSchemes,},],diff --git a/products/desktop/apps/code/electron.vite.config.ts b/products/desktop/apps/code/electron.vite.config.tsindex 95dcb3c30d3e..1f451d2013d9 100644--- a/products/desktop/apps/code/electron.vite.config.ts+++ b/products/desktop/apps/code/electron.vite.config.ts@@ -11,6 +11,7 @@ import { loadEnv } from "vite";import tsconfigPaths from "vite-tsconfig-paths";import { buildExternals } from "./runtime-dependencies";import {+ createCustomCloudDefine,createForceDevModeDefine,createPosthogPlugin,mainAliases,@@ -117,6 +118,7 @@ export default defineConfig(({ mode }) => {"process.env.CONTEXT_MILL_ZIP_URL":JSON.stringify(CONTEXT_MILL_ZIP_URL),...createForceDevModeDefine(),+ ...createCustomCloudDefine(isDev),},resolve: {alias: mainAliases,@@ -232,6 +234,7 @@ export default defineConfig(({ mode }) => {envDir: path.resolve(__dirname, "../.."),define: {...createForceDevModeDefine(),+ ...createCustomCloudDefine(isDev),__APP_VERSION__: JSON.stringify(pkg.version),},resolve: {diff --git a/products/desktop/apps/code/src/main/bootstrap.ts b/products/desktop/apps/code/src/main/bootstrap.tsindex 166c1328f773..7075f5775223 100644--- a/products/desktop/apps/code/src/main/bootstrap.ts+++ b/products/desktop/apps/code/src/main/bootstrap.ts@@ -37,8 +37,24 @@ if (shouldRefuseInternalChildBoot(app.isPackaged, process.env)) {const isDev = !app.isPackaged;// Set app name for single-instance lock, crashReporter, etc-const appName = isDev ? "posthog-code-dev" : "posthog-code";-app.setName(isDev ? "PostHog (Development)" : "PostHog");+// A test build shares a machine with a release build. Separate names keep their+// sessions, settings, and databases apart, so a custom target that only a test+// build can edit never reaches a release build.+const isTestChannel =+ (import.meta as unknown as { env?: Record<string, string | undefined> }).env+ ?.VITE_POSTHOG_BUILD_CHANNEL === "test";+const appName = isDev+ ? "posthog-code-dev"+ : isTestChannel+ ? "posthog-code-test"+ : "posthog-code";+app.setName(+ isDev+ ? "PostHog (Development)"+ : isTestChannel+ ? "PostHog (Test build)"+ : "PostHog",+);// Set userData path for @posthog/codeconst appDataPath = app.getPath("appData");@@ -62,7 +78,9 @@ process.env.POSTHOG_CODE_VERSION = app.getVersion();const chromiumLogDir = path.join(os.homedir(),".posthog-code",- isDev ? "logs-dev" : "logs",+ // A test build can run beside a release build, so its logs need their own+ // directory or the two writers would rotate the same file.+ isDev ? "logs-dev" : isTestChannel ? "logs-test" : "logs",);mkdirSync(chromiumLogDir, { recursive: true });const chromiumLogPath = path.join(chromiumLogDir, "chromium.log");diff --git a/products/desktop/apps/code/src/main/di/bindings.ts b/products/desktop/apps/code/src/main/di/bindings.tsindex 37f0f485deff..333a39986eef 100644--- a/products/desktop/apps/code/src/main/di/bindings.ts+++ b/products/desktop/apps/code/src/main/di/bindings.ts@@ -20,6 +20,10 @@ import type {CONTEXT_MENU_EXTERNAL_APPS_SERVICE,IContextMenuExternalApps,} from "@posthog/core/context-menu/identifiers";+import type {+ CUSTOM_CLOUD_STORE,+ CustomCloudStore,+} from "@posthog/core/custom-cloud/identifiers";import type {FOCUS_SESSION_STORE,FOCUS_WORKSPACE_CLIENT,@@ -435,6 +439,7 @@ export interface MainBindings {// Notification / oauth[NOTIFICATION_SERVICE]: NotificationService;[OAUTH_HOST]: OAuthHost;+ [CUSTOM_CLOUD_STORE]: CustomCloudStore;// Process tracking / posthog plugin[MAIN_PROCESS_TRACKING_SERVICE]: ProcessTrackingService;diff --git a/products/desktop/apps/code/src/main/di/container.ts b/products/desktop/apps/code/src/main/di/container.tsindex e9fd74afcbcf..7a6de2dca4d2 100644--- a/products/desktop/apps/code/src/main/di/container.ts+++ b/products/desktop/apps/code/src/main/di/container.ts@@ -31,6 +31,7 @@ import {CONTEXT_MENU_CONTROLLER,CONTEXT_MENU_EXTERNAL_APPS_SERVICE,} from "@posthog/core/context-menu/identifiers";+import { CUSTOM_CLOUD_STORE } from "@posthog/core/custom-cloud/identifiers";import { FocusHostService } from "@posthog/core/focus/focus-service";import { FocusServiceEvent } from "@posthog/core/focus/identifiers";import { gitHostModule } from "@posthog/core/git/git-host.module";@@ -244,6 +245,7 @@ import { ElectronClaudeSubscriptionTokenStore } from "../platform-adapters/electimport { ElectronClipboard } from "../platform-adapters/electron-clipboard";import { ElectronContextMenu } from "../platform-adapters/electron-context-menu";import { ElectronCrypto } from "../platform-adapters/electron-crypto";+import { ElectronCustomCloudStore } from "../platform-adapters/electron-custom-cloud-store";import { ElectronDevHostActions } from "../platform-adapters/electron-dev-host-actions";import { ElectronDialog } from "../platform-adapters/electron-dialog";import { ElectronFileIcon } from "../platform-adapters/electron-file-icon";@@ -368,6 +370,9 @@ container.bind(CONTEXT_MENU_SERVICE).to(ElectronContextMenu);container.bind(BUNDLED_RESOURCES_SERVICE).to(ElectronBundledResources);container.bind(IMAGE_PROCESSOR_SERVICE).to(ElectronImageProcessor);container.bind(WORKSPACE_SETTINGS_SERVICE).to(ElectronWorkspaceSettings);+container+ .bind(CUSTOM_CLOUD_STORE)+ .toConstantValue(new ElectronCustomCloudStore());container.bind(APP_METRICS_SERVICE).to(ElectronAppMetrics);container.bind(DEV_HOST_ACTIONS_SERVICE).to(ElectronDevHostActions);diff --git a/products/desktop/apps/code/src/main/platform-adapters/electron-custom-cloud-store.ts b/products/desktop/apps/code/src/main/platform-adapters/electron-custom-cloud-store.tsnew file mode 100644index 000000000000..6f7ba08bd07f--- /dev/null+++ b/products/desktop/apps/code/src/main/platform-adapters/electron-custom-cloud-store.ts@@ -0,0 +1,36 @@+import type { CustomCloudStore } from "@posthog/core/custom-cloud/identifiers";+import {+ type CustomCloud,+ configureCustomCloud,+ normalizeCustomCloud,+} from "@posthog/shared";+import { settingsStore } from "../services/settingsStore";+import { isCustomCloudBuild } from "../utils/build-channel";++export class ElectronCustomCloudStore implements CustomCloudStore {+ constructor() {+ configureCustomCloud(this.get());+ }++ get(): CustomCloud | null {+ if (!isCustomCloudBuild()) return null;+ return normalizeCustomCloud({+ url: settingsStore.get("customCloudUrl"),+ oauthClientId: settingsStore.get("customCloudOauthClientId"),+ gatewayUrl: settingsStore.get("customCloudGatewayUrl"),+ });+ }++ set(target: CustomCloud | null): CustomCloud | null {+ if (!isCustomCloudBuild()) return null;+ const normalized = normalizeCustomCloud(target);+ settingsStore.set("customCloudUrl", normalized?.url ?? "");+ settingsStore.set(+ "customCloudOauthClientId",+ normalized?.oauthClientId ?? "",+ );+ settingsStore.set("customCloudGatewayUrl", normalized?.gatewayUrl ?? "");+ configureCustomCloud(normalized);+ return normalized;+ }+}diff --git a/products/desktop/apps/code/src/main/quick-ask.ts b/products/desktop/apps/code/src/main/quick-ask.tsindex f813850885df..08365c9f210a 100644--- a/products/desktop/apps/code/src/main/quick-ask.ts+++ b/products/desktop/apps/code/src/main/quick-ask.ts@@ -229,6 +229,7 @@ const QUICK_ASK_TRPC_ROUTES = new Set(["auth.getValidAccessToken","auth.refreshAccessToken","os.openExternal",+ "customCloud.get",]);function createQuickAskWindow(): BrowserWindow {@@ -271,14 +272,18 @@ function createQuickAskWindow(): BrowserWindow {// it gets the same navigation boundary as the main window: links open in// the external browser and the window itself never leaves its own page —// an in-place navigation would carry the bridges into a foreign origin.- const quickAskHome = QUICK_ASK_VITE_DEV_SERVER_URL- ? new URL(`${QUICK_ASK_VITE_DEV_SERVER_URL}/quick-ask.html`)- : pathToFileURL(- path.join(- __dirname,- `../renderer/${QUICK_ASK_VITE_NAME}/quick-ask.html`,- ),- );+ const quickAskUrl = QUICK_ASK_VITE_DEV_SERVER_URL+ ? `${QUICK_ASK_VITE_DEV_SERVER_URL}/quick-ask.html`+ : null;+ const quickAskHome =+ quickAskUrl && URL.canParse(quickAskUrl)+ ? new URL(quickAskUrl)+ : pathToFileURL(+ path.join(+ __dirname,+ `../renderer/${QUICK_ASK_VITE_NAME}/quick-ask.html`,+ ),+ );setupExternalLinkHandlers(window, quickAskHome);window.setAlwaysOnTop(true, "screen-saver");diff --git a/products/desktop/apps/code/src/main/services/settingsStore.ts b/products/desktop/apps/code/src/main/services/settingsStore.tsindex 3c2ed990345a..f1b5eba68224 100644--- a/products/desktop/apps/code/src/main/services/settingsStore.ts+++ b/products/desktop/apps/code/src/main/services/settingsStore.ts@@ -19,6 +19,9 @@ interface SettingsSchema {discordPresenceShowTaskTitle: boolean;discordPresenceShowRepoName: boolean;missionControlOverlayEnabled: boolean;+ customCloudUrl: string;+ customCloudOauthClientId: string;+ customCloudGatewayUrl: string;}function getWorktreePath(dir: string): string {@@ -126,6 +129,18 @@ const schema = {type: "boolean" as const,default: true,},+ customCloudUrl: {+ type: "string" as const,+ default: "",+ },+ customCloudOauthClientId: {+ type: "string" as const,+ default: "",+ },+ customCloudGatewayUrl: {+ type: "string" as const,+ default: "",+ },};export const settingsStore = new Store<SettingsSchema>({@@ -142,6 +157,9 @@ export const settingsStore = new Store<SettingsSchema>({discordPresenceShowTaskTitle: false,discordPresenceShowRepoName: false,missionControlOverlayEnabled: true,+ customCloudUrl: "",+ customCloudOauthClientId: "",+ customCloudGatewayUrl: "",},});diff --git a/products/desktop/apps/code/src/main/trpc/router.ts b/products/desktop/apps/code/src/main/trpc/router.tsindex b960ed54f6c5..012bc5c6fabf 100644--- a/products/desktop/apps/code/src/main/trpc/router.ts+++ b/products/desktop/apps/code/src/main/trpc/router.ts@@ -14,6 +14,7 @@ import { claudeSubscriptionTokenRouter } from "@posthog/host-router/routers/clauimport { cloudTaskRouter } from "@posthog/host-router/routers/cloud-task.router";import { connectivityRouter } from "@posthog/host-router/routers/connectivity.router";import { contextMenuRouter } from "@posthog/host-router/routers/context-menu.router";+import { customCloudRouter } from "@posthog/host-router/routers/custom-cloud.router";import { dashboardsRouter } from "@posthog/host-router/routers/dashboards.router";import { deepLinkRouter } from "@posthog/host-router/routers/deep-link.router";import { diskCacheRouter } from "@posthog/host-router/routers/disk-cache.router";@@ -76,6 +77,7 @@ export const trpcRouter = router({cloudTask: cloudTaskRouter,connectivity: connectivityRouter,contextMenu: contextMenuRouter,+ customCloud: customCloudRouter,dev: devRouter,discordPresence: discordPresenceRouter,enrichment: enrichmentRouter,diff --git a/products/desktop/apps/code/src/main/utils/build-channel.ts b/products/desktop/apps/code/src/main/utils/build-channel.tsnew file mode 100644index 000000000000..f7a49b2cb395--- /dev/null+++ b/products/desktop/apps/code/src/main/utils/build-channel.ts@@ -0,0 +1,17 @@+const TEST_CHANNEL = "test";++function buildChannel(): string | undefined {+ return (+ import.meta as unknown as { env?: Record<string, string | undefined> }+ ).env?.VITE_POSTHOG_BUILD_CHANNEL;+}++export function isTestChannelBuild(): boolean {+ return buildChannel() === TEST_CHANNEL;+}++// A release build has no way to edit a custom target, so it must not read or+// write one either.+export function isCustomCloudBuild(): boolean {+ return process.env.POSTHOG_CODE_IS_DEV === "true" || isTestChannelBuild();+}diff --git a/products/desktop/apps/code/src/main/utils/logger.ts b/products/desktop/apps/code/src/main/utils/logger.tsindex 4bba1aef16c2..b05e6b0f3d20 100644--- a/products/desktop/apps/code/src/main/utils/logger.ts+++ b/products/desktop/apps/code/src/main/utils/logger.ts@@ -13,13 +13,16 @@ import { join } from "node:path";import { initOtelTransport } from "@main/utils/otel-log-transport";import type ElectronLog from "electron-log";import log from "electron-log/main";+import { isTestChannelBuild } from "./build-channel";import { isDevBuild } from "./env";const isDev = process.env.NODE_ENV === "development" || isDevBuild();const LOG_DIR = join(os.homedir(),".posthog-code",- isDev ? "logs-dev" : "logs",+ // A test build can run beside a release build, so its logs need their own+ // directory or the two writers would rotate the same file.+ isDev ? "logs-dev" : isTestChannelBuild() ? "logs-test" : "logs",);const LOG_FILE = "main.log";const NETWORK_LOG_FILE = "network.log";diff --git a/products/desktop/apps/code/src/renderer/custom-cloud.ts b/products/desktop/apps/code/src/renderer/custom-cloud.tsnew file mode 100644index 000000000000..8712fe9b5d7b--- /dev/null+++ b/products/desktop/apps/code/src/renderer/custom-cloud.ts@@ -0,0 +1,21 @@+import { configureCustomCloud } from "@posthog/shared";+import { logger } from "@posthog/ui/shell/logger";+import { trpcClient } from "@renderer/trpc/client";++const log = logger.scope("custom-cloud");++// A renderer window resolves region URLs itself, so it needs the target that+// the main process holds before it renders a link or a region label. Boot+// awaits this, because a memoized read of an unhydrated target would keep the+// empty value for the whole session.+export function hydrateCustomCloud(): Promise<void> {+ return trpcClient.customCloud.get+ .query()+ .then((target) => {+ configureCustomCloud(target);+ })+ .catch((error: unknown) => {+ // Boot continues without a target; only custom sessions need one.+ log.error("Could not read the custom cloud target", error);+ });+}diff --git a/products/desktop/apps/code/src/renderer/desktop-services.ts b/products/desktop/apps/code/src/renderer/desktop-services.tsindex d34b0ccd8513..cec9a612180a 100644--- a/products/desktop/apps/code/src/renderer/desktop-services.ts+++ b/products/desktop/apps/code/src/renderer/desktop-services.ts@@ -454,8 +454,11 @@ containercontainer.bind(SETUP_STORE).toConstantValue(setupStore);-container- .bind(HOST_CAPABILITIES)- .toConstantValue({ localWorkspaces: true } satisfies HostCapabilities);+container.bind(HOST_CAPABILITIES).toConstantValue({+ localWorkspaces: true,+ // Baked from the same rule the main-process store applies to its reads and+ // writes, so the option never appears in a build that cannot serve it.+ customCloud: import.meta.env.VITE_POSTHOG_CUSTOM_CLOUD_BUILD === "true",+} satisfies HostCapabilities);container.bind(DISK_CACHE_IMAGES).toConstantValue(desktopDiskCacheImages);diff --git a/products/desktop/apps/code/src/renderer/main.tsx b/products/desktop/apps/code/src/renderer/main.tsxindex f0a9089987ab..c2b59a76ed94 100644--- a/products/desktop/apps/code/src/renderer/main.tsx+++ b/products/desktop/apps/code/src/renderer/main.tsx@@ -26,6 +26,7 @@ import App from "@posthog/ui/shell/App";import { logger } from "@posthog/ui/shell/logger";import { initializePostHog } from "@posthog/ui/shell/posthogAnalyticsImpl";import { REQUIRED_HOST_CAPABILITIES } from "@posthog/ui/shell/requiredHostCapabilities";+import { hydrateCustomCloud } from "@renderer/custom-cloud";import { registerDesktopContributions } from "@renderer/desktop-contributions";import { container } from "@renderer/di/container";import "@renderer/desktop-services";@@ -94,35 +95,37 @@ if (!rootElement) throw new Error("Root element not found");const root = ReactDOM.createRoot(rootElement);-try {- registerDesktopContributions();- // Fail loudly (into BootErrorScreen) if a capability the shared app resolves- // via service location is unbound, rather than deferring to the first- // navigation that needs it. The renderer container backs every useService, so- // all required tokens must resolve here. Shared with the web host.- assertHostCapabilities(container, REQUIRED_HOST_CAPABILITIES);- boot(container).catch((error: unknown) => {- bootLog.error("Renderer boot sequence failed", error);- // Replaces the mounted tree without running effect cleanup; acceptable- // because a failed boot leaves the app unusable regardless.- root.render(<BootErrorScreen error={error} />);- });+void hydrateCustomCloud().then(() => {+ try {+ registerDesktopContributions();+ // Fail loudly (into BootErrorScreen) if a capability the shared app resolves+ // via service location is unbound, rather than deferring to the first+ // navigation that needs it. The renderer container backs every useService, so+ // all required tokens must resolve here. Shared with the web host.+ assertHostCapabilities(container, REQUIRED_HOST_CAPABILITIES);+ boot(container).catch((error: unknown) => {+ bootLog.error("Renderer boot sequence failed", error);+ // Replaces the mounted tree without running effect cleanup; acceptable+ // because a failed boot leaves the app unusable regardless.+ root.render(<BootErrorScreen error={error} />);+ });- root.render(- <React.StrictMode>- <BootErrorBoundary>- <ServiceProvider container={container}>- <Providers>- <App devToolbar={<DevToolbarHost />} />- {/* Beside the app, not in a route: the overlay must outlive every- gate and shell the router renders. */}- <MissionControlOverlay />- </Providers>- </ServiceProvider>- </BootErrorBoundary>- </React.StrictMode>,- );-} catch (error) {- bootLog.error("Renderer failed to start", error);- root.render(<BootErrorScreen error={error} />);-}+ root.render(+ <React.StrictMode>+ <BootErrorBoundary>+ <ServiceProvider container={container}>+ <Providers>+ <App devToolbar={<DevToolbarHost />} />+ {/* Beside the app, not in a route: the overlay must outlive every+ gate and shell the router renders. */}+ <MissionControlOverlay />+ </Providers>+ </ServiceProvider>+ </BootErrorBoundary>+ </React.StrictMode>,+ );+ } catch (error) {+ bootLog.error("Renderer failed to start", error);+ root.render(<BootErrorScreen error={error} />);+ }+});diff --git a/products/desktop/apps/code/src/renderer/quick-ask/main.tsx b/products/desktop/apps/code/src/renderer/quick-ask/main.tsxindex 0ea75bc3afc2..c755b7f03519 100644--- a/products/desktop/apps/code/src/renderer/quick-ask/main.tsx+++ b/products/desktop/apps/code/src/renderer/quick-ask/main.tsx@@ -11,6 +11,7 @@ import { QuickAsk } from "@posthog/quick-ask/panel/QuickAsk";import { getAuthIdentity, useAuthStore } from "@posthog/ui/features/auth/store";import { ThemeWrapper } from "@posthog/ui/primitives/ThemeWrapper";import { useThemeStore } from "@posthog/ui/shell/themeStore";+import { hydrateCustomCloud } from "@renderer/custom-cloud";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { createTRPCClient } from "@trpc/client";import { Container } from "inversify";@@ -29,69 +30,72 @@ const hostTrpcClient = createTRPCClient<HostRouter>({// through the shared service locator.const container = new Container();container.bind(HOST_TRPC_CLIENT).toConstantValue(hostTrpcClient);-setRootContainer(container);-const queryClient = new QueryClient({- defaultOptions: {- queries: { retry: 1, refetchOnWindowFocus: false },- },-});+void hydrateCustomCloud().then(() => {+ setRootContainer(container);-// The panel has its own react-query cache and never runs the main window's-// project-switch side effects, so it purges auth-scoped queries itself when-// the identity (region + project) changes. Without this, a chart or preview-// cached in project A would serve under project B for its stale period.-let authIdentity: string | null | undefined;-function applyAuthState(state: AuthState): void {- const next = getAuthIdentity(state);- if (authIdentity !== undefined && next !== authIdentity) {- queryClient.removeQueries({- predicate: (query) => query.meta?.authScoped === true,- });+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: 1, refetchOnWindowFocus: false },+ },+ });++ // The panel has its own react-query cache and never runs the main window's+ // project-switch side effects, so it purges auth-scoped queries itself when+ // the identity (region + project) changes. Without this, a chart or preview+ // cached in project A would serve under project B for its stale period.+ let authIdentity: string | null | undefined;+ function applyAuthState(state: AuthState): void {+ const next = getAuthIdentity(state);+ if (authIdentity !== undefined && next !== authIdentity) {+ queryClient.removeQueries({+ predicate: (query) => query.meta?.authScoped === true,+ });+ }+ authIdentity = next;+ useAuthStore.getState().setAuthState(state);}- authIdentity = next;- useAuthStore.getState().setAuthState(state);-}-// Subscription first so no auth state change is missed while the initial-// query is in flight.-hostTrpcClient.auth.onStateChanged.subscribe(undefined, {- onData: (state) => applyAuthState(state),-});-void hostTrpcClient.auth.getState- .query()- .then((state) => applyAuthState(state))- .catch(() => {- // Signed-out rendering is fine; chips fall back to static cards.+ // Subscription first so no auth state change is missed while the initial+ // query is in flight.+ hostTrpcClient.auth.onStateChanged.subscribe(undefined, {+ onData: (state) => applyAuthState(state),});+ void hostTrpcClient.auth.getState+ .query()+ .then((state) => applyAuthState(state))+ .catch(() => {+ // Signed-out rendering is fine; chips fall back to static cards.+ });-// Theme changes made in the main window land in shared localStorage;-// re-reading them keeps this window on the app's theme.-window.addEventListener("storage", (event) => {- if (event.key === "theme-storage") {- void useThemeStore.persist.rehydrate();- }-});+ // Theme changes made in the main window land in shared localStorage;+ // re-reading them keeps this window on the app's theme.+ window.addEventListener("storage", (event) => {+ if (event.key === "theme-storage") {+ void useThemeStore.persist.rehydrate();+ }+ });-const root = document.getElementById("root");-if (root) {- ReactDOM.createRoot(root).render(- <React.StrictMode>- {/* A render crash (rich answer content is live data) otherwise unmounts+ const root = document.getElementById("root");+ if (root) {+ ReactDOM.createRoot(root).render(+ <React.StrictMode>+ {/* A render crash (rich answer content is live data) otherwise unmountsthe whole panel with no way to close, reset, or retry; the boundary'sreload boots the window fresh. */}- <BootErrorBoundary>- <QueryClientProvider client={queryClient}>- <HostTRPCProvider- trpcClient={hostTrpcClient}- queryClient={queryClient}- >- <ThemeWrapper>- <QuickAsk />- </ThemeWrapper>- </HostTRPCProvider>- </QueryClientProvider>- </BootErrorBoundary>- </React.StrictMode>,- );-}+ <BootErrorBoundary>+ <QueryClientProvider client={queryClient}>+ <HostTRPCProvider+ trpcClient={hostTrpcClient}+ queryClient={queryClient}+ >+ <ThemeWrapper>+ <QuickAsk />+ </ThemeWrapper>+ </HostTRPCProvider>+ </QueryClientProvider>+ </BootErrorBoundary>+ </React.StrictMode>,+ );+ }+});diff --git a/products/desktop/apps/code/src/vite-env.d.ts b/products/desktop/apps/code/src/vite-env.d.tsindex 460222bacc8e..322fc943704f 100644--- a/products/desktop/apps/code/src/vite-env.d.ts+++ b/products/desktop/apps/code/src/vite-env.d.ts@@ -6,6 +6,7 @@ interface ImportMetaEnv {readonly DEV: boolean;readonly PROD: boolean;readonly MODE: string;+ readonly VITE_POSTHOG_CUSTOM_CLOUD_BUILD?: string;// PostHog Analyticsreadonly VITE_POSTHOG_API_KEY?: string;diff --git a/products/desktop/apps/code/vite.shared.mts b/products/desktop/apps/code/vite.shared.mtsindex 02f257531e13..0a470c9af5c4 100644--- a/products/desktop/apps/code/vite.shared.mts+++ b/products/desktop/apps/code/vite.shared.mts@@ -34,6 +34,21 @@ export function createForceDevModeDefine(): Record<string, string> | undefined {};}+// The main process decides custom-cloud availability at runtime from+// app.isPackaged and the build channel. The renderer cannot see either, so+// both vite configs bake the same answer here. A packaged build forced into+// dev mode (FORCE_DEV_MODE) must NOT offer Custom, because its store still+// refuses to hold a target.+export function createCustomCloudDefine(+ isDevServer: boolean,+): Record<string, string> {+ return {+ "import.meta.env.VITE_POSTHOG_CUSTOM_CLOUD_BUILD": JSON.stringify(+ String(isDevServer || process.env.VITE_POSTHOG_BUILD_CHANNEL === "test"),+ ),+ };+}+const baseAliases: Alias[] = [{ find: "@main", replacement: path.resolve(__dirname, "./src/main") },{ find: "@renderer", replacement: path.resolve(__dirname, "./src/renderer") },diff --git a/products/desktop/apps/web/src/web-container.ts b/products/desktop/apps/web/src/web-container.tsindex 2b9bfe92dfaf..6e67562d6a68 100644--- a/products/desktop/apps/web/src/web-container.ts+++ b/products/desktop/apps/web/src/web-container.ts@@ -469,9 +469,10 @@ container.bind(POWER_MANAGER_SERVICE).toConstantValue(webPowerManager);// The web host is cloud-only: no local filesystem, so the UI must use remote// (connected-GitHub-org) repositories and cloud workspaces everywhere it would// otherwise reach for local folders/worktrees/terminal.-container- .bind(HOST_CAPABILITIES)- .toConstantValue({ localWorkspaces: false } satisfies HostCapabilities);+container.bind(HOST_CAPABILITIES).toConstantValue({+ localWorkspaces: false,+ customCloud: false,+} satisfies HostCapabilities);container.load(authUiModule);diff --git a/products/desktop/docs/LOCAL-DEVELOPMENT.md b/products/desktop/docs/LOCAL-DEVELOPMENT.mdindex 257fe38d8277..4b4c25b7b22c 100644--- a/products/desktop/docs/LOCAL-DEVELOPMENT.md+++ b/products/desktop/docs/LOCAL-DEVELOPMENT.md@@ -123,6 +123,40 @@ The development build has two separate region values:Keeping both values preserves stored Local development sessions. Dev Cloud agent requests use `https://gateway.dev.posthog.dev`.+## Custom cloud++The **Custom** region points at any PostHog instance, for example a self-hosted deployment. The fields appear when you select it, and each one has an information icon.+The region list holds **Custom** as its last entry in a development build, and in a test build from the **Desktop Build Test** workflow (the `desktop-build-installer` label on a PR).+A release build does not show it, and a release build ignores a stored target.+A packaged test build keeps its own user data, under `posthog-code-test`, so its sessions and settings stay apart from a release build on the same machine.++1. On the instance, make an OAuth application. Open `https://<your-instance>/admin/posthog/oauthapplication/` as a staff user, click **Add OAuth application**, and set:+ - **Name**: anything, for example `PostHog Desktop`.+ - **Client type**: `Public`. The app uses PKCE, so it has no client secret.+ - **Authorization grant type**: `Authorization code`. The form fixes this, with `RS256`.+ - **Redirect URIs**: `posthog-code://callback` for a packaged build. Add `http://localhost:8237/callback` for a local development build, `posthog-code-dev://callback` for a packaged development build, and `posthog-code-test://callback` for a test build from the **Desktop Build Test** workflow.+ - Token signing needs `OIDC_RSA_PRIVATE_KEY` on the instance. A deployment usually has it.+2. Copy the client ID from the list page, then seed the scope ceiling on the instance:++ ```bash+ python manage.py seed_oauth_app_scopes --client-id <id> --scopes @default,llm_gateway:read+ ```++ An empty ceiling resolves to the unprivileged scopes, which exclude `llm_gateway:read`. The gateway refuses a token without it, so agent runs fail.+3. On the sign-in screen, select **Custom** in the region list. It is the last entry, after **Local development**.+4. Enter the URL of the instance and the client ID of the OAuth application. The URL must be an `https` origin, for example `https://posthog.example.com`, with no path, query, or fragment. Plain `http` is only accepted for a loopback host, because OAuth tokens cross this origin.+5. Sign in. The app keeps the values, and applies them to sign-in, API requests, and agent runs.++Agent runs need an LLM gateway that accepts a token from your instance, so give the **LLM gateway URL** field the address of a gateway that reads your instance's database (see `services/llm-gateway`).+A PostHog Cloud gateway cannot serve a custom instance: it resolves a token against the Cloud database, and its `posthog_code` product refuses a personal API key.+With the field empty, the app derives a gateway from the host, and for an unknown host that is the US gateway, which returns 403.++The PostHog MCP server is absent for a custom instance, because `mcp.posthog.com` cannot read a token from your instance either. `POSTHOG_MCP_URL` names one that can.++The `us`, `eu`, `dev`, and `dev-cloud` regions never read these values, and the instance URL field refuses their hosts.++For a standalone headless harness run, the environment variables `POSTHOG_CUSTOM_CLOUD_URL`, `POSTHOG_CUSTOM_CLOUD_OAUTH_CLIENT_ID`, and `POSTHOG_CUSTOM_CLOUD_GATEWAY_URL` hold the target, and `POSTHOG_REGION=custom` selects it. The URL and the client ID are both required. Without the region the harness stays on US, and with the region but an incomplete target it fails with a message that names the missing variables.+## Dev console commandsOpen devtools in the dev build and type:diff --git a/products/desktop/packages/core/src/auth/authIdentity.test.ts b/products/desktop/packages/core/src/auth/authIdentity.test.tsnew file mode 100644index 000000000000..c7b5a8134716--- /dev/null+++ b/products/desktop/packages/core/src/auth/authIdentity.test.ts@@ -0,0 +1,55 @@+import { configureCustomCloud } from "@posthog/shared";+import { afterEach, describe, expect, it } from "vitest";+import { getAuthIdentity } from "./authIdentity";+import type { AuthState } from "./schemas";++function authState(overrides: Partial<AuthState>): AuthState {+ return {+ status: "authenticated",+ bootstrapComplete: true,+ cloudRegion: "us",+ orgProjectsMap: {},+ currentOrgId: null,+ currentProjectId: 1,+ desktopAccess: { projectId: 1, status: "allowed", reason: null },+ needsScopeReauth: false,+ sessionType: "persistent",+ sessionExpiresAt: null,+ sessionEndReason: undefined,+ ...overrides,+ };+}++describe("getAuthIdentity", () => {+ afterEach(() => {+ configureCustomCloud(null);+ });++ it("names the region and the project for a built-in region", () => {+ expect(getAuthIdentity(authState({ cloudRegion: "eu" }))).toBe("eu:1");+ });++ it("returns null when signed out", () => {+ expect(+ getAuthIdentity(authState({ status: "anonymous", cloudRegion: null })),+ ).toBeNull();+ });++ it("names the custom instance, so two instances never share an identity", () => {+ configureCustomCloud({+ url: "https://posthog.example.com",+ oauthClientId: "client-id",+ });+ expect(getAuthIdentity(authState({ cloudRegion: "custom" }))).toBe(+ "custom:posthog.example.com:1",+ );++ configureCustomCloud({+ url: "https://other.example.com",+ oauthClientId: "client-id",+ });+ expect(getAuthIdentity(authState({ cloudRegion: "custom" }))).toBe(+ "custom:other.example.com:1",+ );+ });+});diff --git a/products/desktop/packages/core/src/auth/authIdentity.ts b/products/desktop/packages/core/src/auth/authIdentity.tsindex 554c7eb8712e..50507a1e98e6 100644--- a/products/desktop/packages/core/src/auth/authIdentity.ts+++ b/products/desktop/packages/core/src/auth/authIdentity.ts@@ -1,8 +1,26 @@+import { getCustomCloud } from "@posthog/shared";import type { AuthState } from "./schemas";export function getAuthIdentity(authState: AuthState): string | null {if (authState.status !== "authenticated" || !authState.cloudRegion) {return null;}- return `${authState.cloudRegion}:${authState.currentProjectId ?? "none"}`;+ // Every built-in region maps to one origin, but many instances share the+ // custom region, so the identity needs the instance to keep two custom+ // sessions from reading each other's persisted state.+ const scope =+ authState.cloudRegion === "custom"+ ? `custom:${customCloudHost() ?? "unset"}`+ : authState.cloudRegion;+ return `${scope}:${authState.currentProjectId ?? "none"}`;+}++function customCloudHost(): string | null {+ const url = getCustomCloud()?.url;+ if (!url) return null;+ try {+ return new URL(url).host;+ } catch {+ return null;+ }}diff --git a/products/desktop/packages/core/src/custom-cloud/identifiers.ts b/products/desktop/packages/core/src/custom-cloud/identifiers.tsnew file mode 100644index 000000000000..fa8108377a12--- /dev/null+++ b/products/desktop/packages/core/src/custom-cloud/identifiers.ts@@ -0,0 +1,8 @@+import type { CustomCloud } from "@posthog/shared";++export const CUSTOM_CLOUD_STORE = Symbol.for("posthog.core.customCloudStore");++export interface CustomCloudStore {+ get(): CustomCloud | null;+ set(target: CustomCloud | null): CustomCloud | null;+}diff --git a/products/desktop/packages/core/src/oauth/oauth.ts b/products/desktop/packages/core/src/oauth/oauth.tsindex 215bf4bb02a8..555a72f3a8be 100644--- a/products/desktop/packages/core/src/oauth/oauth.ts+++ b/products/desktop/packages/core/src/oauth/oauth.ts@@ -18,6 +18,8 @@ import {} from "@posthog/platform/url-launcher";import {type BackoffOptions,+ DEV_CALLBACK_PORT,+ DEV_REDIRECT_URI,getCloudUrlFromRegion,getOauthClientIdFromRegion,OAUTH_SCOPES,@@ -35,7 +37,6 @@ import { type OAuthTokenResponse, oAuthTokenResponse } from "./schemas";const OAUTH_TIMEOUT_MS = 180_000; // 3 minutesconst TOKEN_FETCH_TIMEOUT_MS = 30_000;-const DEV_CALLBACK_PORT = 8237;const NETWORK_ERROR_MESSAGE ="Could not connect to PostHog. Please check your internet connection and try again.";@@ -136,7 +137,7 @@ export class OAuthService {*/private getRedirectUri(): string {return this.host.isDev- ? `http://localhost:${DEV_CALLBACK_PORT}/callback`+ ? DEV_REDIRECT_URI: `${this.deepLinkService.getProtocol()}://callback`;}diff --git a/products/desktop/packages/harness/src/extensions/posthog-provider/gateway.test.ts b/products/desktop/packages/harness/src/extensions/posthog-provider/gateway.test.tsindex a7f02f1520ce..307c2e5df391 100644--- a/products/desktop/packages/harness/src/extensions/posthog-provider/gateway.test.ts+++ b/products/desktop/packages/harness/src/extensions/posthog-provider/gateway.test.ts@@ -87,6 +87,8 @@ describe("resolveExplicitRegion", () => {beforeEach(() => {delete process.env.POSTHOG_REGION;+ delete process.env.POSTHOG_CUSTOM_CLOUD_URL;+ delete process.env.POSTHOG_CUSTOM_CLOUD_OAUTH_CLIENT_ID;});afterEach(() => {@@ -119,4 +121,24 @@ describe("resolveExplicitRegion", () => {process.env.POSTHOG_REGION = "dev";expect(resolveExplicitRegion()).toBe("dev");});++ it("accepts custom when the environment holds a target", () => {+ process.env.POSTHOG_REGION = "custom";+ process.env.POSTHOG_CUSTOM_CLOUD_URL = "https://posthog.example.com";+ process.env.POSTHOG_CUSTOM_CLOUD_OAUTH_CLIENT_ID = "client-id";+ expect(resolveExplicitRegion()).toBe("custom");+ });++ it("throws when custom has no target", () => {+ process.env.POSTHOG_REGION = "custom";+ expect(() => resolveExplicitRegion()).toThrow(/POSTHOG_CUSTOM_CLOUD_URL/);+ });++ it("throws when custom holds no OAuth client ID", () => {+ process.env.POSTHOG_REGION = "custom";+ process.env.POSTHOG_CUSTOM_CLOUD_URL = "https://posthog.example.com";+ expect(() => resolveExplicitRegion()).toThrow(+ /POSTHOG_CUSTOM_CLOUD_OAUTH_CLIENT_ID/,+ );+ });});diff --git a/products/desktop/packages/harness/src/extensions/posthog-provider/gateway.ts b/products/desktop/packages/harness/src/extensions/posthog-provider/gateway.tsindex 01ae590c603d..ac846ec8e7c1 100644--- a/products/desktop/packages/harness/src/extensions/posthog-provider/gateway.ts+++ b/products/desktop/packages/harness/src/extensions/posthog-provider/gateway.ts@@ -1,4 +1,4 @@-import type { CloudRegion } from "@posthog/shared";+import { type CloudRegion, getCustomCloud } from "@posthog/shared";export const GATEWAY_PRODUCT = "posthog_code";@@ -7,9 +7,13 @@ const GATEWAY_HOSTS: Record<CloudRegion, string> = {eu: "https://gateway.eu.posthog.com",dev: "http://localhost:3308","dev-cloud": "https://gateway.dev.posthog.dev",+ custom: "https://gateway.us.posthog.com",};export function getGatewayBaseUrl(region: CloudRegion): string {+ if (region === "custom") {+ return getCustomCloud()?.gatewayUrl ?? GATEWAY_HOSTS.custom;+ }return GATEWAY_HOSTS[region];}@@ -34,6 +38,16 @@ export function resolveExplicitRegion() {return candidate;}+ if (candidate === "custom") {+ // A custom region with no target would build every URL from an empty+ // base, so name the missing configuration instead.+ if (!getCustomCloud()) {+ throw new Error(+ "POSTHOG_REGION=custom needs a custom cloud target. Set POSTHOG_CUSTOM_CLOUD_URL (a full https origin) and POSTHOG_CUSTOM_CLOUD_OAUTH_CLIENT_ID.",+ );+ }+ return candidate;+ }return undefined;}diff --git a/products/desktop/packages/harness/src/extensions/posthog-provider/oauth.ts b/products/desktop/packages/harness/src/extensions/posthog-provider/oauth.tsindex 32a22d646fa1..35a8e11bc443 100644--- a/products/desktop/packages/harness/src/extensions/posthog-provider/oauth.ts+++ b/products/desktop/packages/harness/src/extensions/posthog-provider/oauth.ts@@ -8,6 +8,7 @@ import type {import {type CloudRegion,getCloudUrlFromRegion,+ getCustomCloud,getOauthClientIdFromRegion,OAUTH_SCOPES,} from "@posthog/shared";@@ -67,14 +68,39 @@ function toCredentials(response: OAuthTokenResponse,region: CloudRegion,): OAuthCredentials {+ const custom = region === "custom" ? getCustomCloud() : null;return {access: response.access_token,refresh: response.refresh_token,expires: Date.now() + response.expires_in * 1000 - TOKEN_EXPIRY_SKEW_MS,region,+ ...(custom+ ? {+ customCloudUrl: custom.url,+ customOauthClientId: custom.oauthClientId,+ }+ : {}),};}+// A refresh token only works on the instance that issued it, so a stored+// custom credential whose instance changed can never refresh successfully.+function assertCredentialsMatchCustomCloud(+ credentials: OAuthCredentials,+): void {+ if ((credentials.region as CloudRegion | undefined) !== "custom") return;+ const target = getCustomCloud();+ if (+ !target ||+ credentials.customCloudUrl !== target.url ||+ credentials.customOauthClientId !== target.oauthClientId+ ) {+ throw new Error(+ "The custom PostHog instance changed since sign-in. Sign in again to continue.",+ );+ }+}+async function postToken(region: CloudRegion,body: Record<string, string>,@@ -255,12 +281,15 @@ export async function refreshPosthog(): Promise<OAuthCredentials> {const effectiveRegion =(credentials.region as CloudRegion | undefined) ?? region;+ assertCredentialsMatchCustomCloud(credentials);+ // The credential bag is an open record, so the custom fields read as unknown.+ const storedClientId = credentials.customOauthClientId as string | undefined;const tokens = await postToken(effectiveRegion,{grant_type: "refresh_token",refresh_token: credentials.refresh,- client_id: getOauthClientIdFromRegion(effectiveRegion),+ client_id: storedClientId ?? getOauthClientIdFromRegion(effectiveRegion),},signal,);diff --git a/products/desktop/packages/harness/src/extensions/posthog-provider/provider.ts b/products/desktop/packages/harness/src/extensions/posthog-provider/provider.tsindex d487fddb658c..f53ecfbddfc1 100644--- a/products/desktop/packages/harness/src/extensions/posthog-provider/provider.ts+++ b/products/desktop/packages/harness/src/extensions/posthog-provider/provider.ts@@ -31,6 +31,9 @@ export type PosthogOAuthCredentials = Pick<"access" | "refresh" | "expires"> & {region: CloudRegion;+ /** Set for a custom region, so a refresh can verify the issuing instance. */+ customCloudUrl?: string;+ customOauthClientId?: string;};export function parsePosthogOAuthCredentials(diff --git a/products/desktop/packages/host-router/src/router.ts b/products/desktop/packages/host-router/src/router.tsindex 94194670939a..7cdbc6124152 100644--- a/products/desktop/packages/host-router/src/router.ts+++ b/products/desktop/packages/host-router/src/router.ts@@ -13,6 +13,7 @@ import { claudeSubscriptionTokenRouter } from "./routers/claude-subscription-tokimport { cloudTaskRouter } from "./routers/cloud-task.router";import { connectivityRouter } from "./routers/connectivity.router";import { contextMenuRouter } from "./routers/context-menu.router";+import { customCloudRouter } from "./routers/custom-cloud.router";import { dashboardsRouter } from "./routers/dashboards.router";import { deepLinkRouter } from "./routers/deep-link.router";import { diskCacheRouter } from "./routers/disk-cache.router";@@ -66,6 +67,7 @@ export const hostRouter = router({cloudTask: cloudTaskRouter,connectivity: connectivityRouter,contextMenu: contextMenuRouter,+ customCloud: customCloudRouter,dashboards: dashboardsRouter,deepLink: deepLinkRouter,diskCache: diskCacheRouter,diff --git a/products/desktop/packages/host-router/src/routers/custom-cloud.router.ts b/products/desktop/packages/host-router/src/routers/custom-cloud.router.tsnew file mode 100644index 000000000000..a0967571a37b--- /dev/null+++ b/products/desktop/packages/host-router/src/routers/custom-cloud.router.ts@@ -0,0 +1,36 @@+import type { AuthService } from "@posthog/core/auth/auth";+import { AUTH_SERVICE } from "@posthog/core/auth/auth.module";+import {+ CUSTOM_CLOUD_STORE,+ type CustomCloudStore,+} from "@posthog/core/custom-cloud/identifiers";+import { publicProcedure, router } from "@posthog/host-trpc/trpc";+import { customCloudSchema } from "@posthog/shared";++export const customCloudRouter = router({+ get: publicProcedure+ .output(customCloudSchema.nullable())+ .query(({ ctx }) =>+ ctx.container.get<CustomCloudStore>(CUSTOM_CLOUD_STORE).get(),+ ),++ set: publicProcedure+ .input(customCloudSchema)+ .output(customCloudSchema.nullable())+ .mutation(async ({ ctx, input }) => {+ const store = ctx.container.get<CustomCloudStore>(CUSTOM_CLOUD_STORE);+ const auth = ctx.container.get<AuthService>(AUTH_SERVICE);+ const previous = store.get();+ const session = auth.getState();+ // A session holds a refresh token that only the instance that issued it+ // accepts. Sending it to another instance is what this logout prevents.+ const movesTarget =+ session.cloudRegion === "custom" &&+ previous?.url !== undefined &&+ previous.url !== input.url;+ if (movesTarget) {+ await auth.logout();+ }+ return store.set(input);+ }),+});diff --git a/products/desktop/packages/platform/src/host-capabilities.ts b/products/desktop/packages/platform/src/host-capabilities.tsindex a65a05bb9fcf..885ccbdc3d44 100644--- a/products/desktop/packages/platform/src/host-capabilities.ts+++ b/products/desktop/packages/platform/src/host-capabilities.ts@@ -11,6 +11,13 @@ export interface HostCapabilities {* (connected-GitHub-org) repositories and cloud workspaces.*/readonly localWorkspaces: boolean;++ /**+ * Whether the host can hold a custom PostHog instance: the sign-in screen+ * offers the Custom region, and the host serves the `customCloud` routes.+ * Desktop (Electron) has it; the browser host has no store for it.+ */+ readonly customCloud: boolean;}export const HOST_CAPABILITIES = Symbol.for(diff --git a/products/desktop/packages/shared/src/cloud-task-models.test.ts b/products/desktop/packages/shared/src/cloud-task-models.test.tsindex 6d219176f904..013ef2967479 100644--- a/products/desktop/packages/shared/src/cloud-task-models.test.ts+++ b/products/desktop/packages/shared/src/cloud-task-models.test.ts@@ -1,4 +1,4 @@-import { describe, expect, it } from "vitest";+import { afterEach, describe, expect, it } from "vitest";import {adapterForModelId,buildCloudTaskConfigOptions,@@ -7,6 +7,7 @@ import {formatGatewayModelName,type GatewayModel,getClaudeModelRecency,+ getCloudTaskGatewayUrl,isAnthropicModel,isBasetenModel,isBlockedModelId,@@ -17,6 +18,7 @@ import {normalizeGatewayModelsResponse,pickAllowedModel,} from "./cloud-task-models";+import { configureCustomCloud } from "./custom-cloud";import { isCustomModelOption } from "./models";const model = (@@ -398,3 +400,40 @@ describe("buildProviderModelGroups", () => {},);});++describe("getCloudTaskGatewayUrl with a custom cloud", () => {+ afterEach(() => {+ configureCustomCloud(null);+ });++ it("uses the gateway of the custom cloud for its own host only", () => {+ configureCustomCloud({+ url: "https://posthog.example.com",+ oauthClientId: "client-id",+ gatewayUrl: "https://gateway.example.com",+ });+ expect(getCloudTaskGatewayUrl("https://posthog.example.com")).toBe(+ "https://gateway.example.com/posthog_code",+ );+ expect(getCloudTaskGatewayUrl("https://us.posthog.com")).toBe(+ "https://gateway.us.posthog.com/posthog_code",+ );+ });++ it("keeps the derived gateway when the custom cloud has none", () => {+ configureCustomCloud({ url: "https://posthog.example.com" });+ expect(getCloudTaskGatewayUrl("https://posthog.example.com")).toBe(+ "https://gateway.us.posthog.com/posthog_code",+ );+ });++ it("refuses a built-in host as the target, so its gateway never moves", () => {+ configureCustomCloud({+ url: "https://us.posthog.com",+ gatewayUrl: "https://gateway.example.com",+ });+ expect(getCloudTaskGatewayUrl("https://us.posthog.com")).toBe(+ "https://gateway.us.posthog.com/posthog_code",+ );+ });+});diff --git a/products/desktop/packages/shared/src/cloud-task-models.ts b/products/desktop/packages/shared/src/cloud-task-models.tsindex 802d52990664..fe13de083358 100644--- a/products/desktop/packages/shared/src/cloud-task-models.ts+++ b/products/desktop/packages/shared/src/cloud-task-models.ts@@ -1,4 +1,5 @@import type { Adapter } from "./adapter";+import { getCustomCloud, isCustomCloudHost } from "./custom-cloud";import { CODEX_MODE_PRESETS } from "./execution-modes";import {customModelMeta,@@ -118,8 +119,11 @@ const KNOWN_ACRONYMS = new Set(["gpt", "glm"]);export function getCloudTaskGatewayUrl(posthogHost: string): string {const url = new URL(posthogHost);let gatewayBaseUrl: string;+ const custom = getCustomCloud();- if (url.hostname === "localhost" || url.hostname === "127.0.0.1") {+ if (custom?.gatewayUrl && isCustomCloudHost(posthogHost)) {+ gatewayBaseUrl = custom.gatewayUrl;+ } else if (url.hostname === "localhost" || url.hostname === "127.0.0.1") {gatewayBaseUrl = `${url.protocol}//localhost:3308`;} else if (url.hostname === "host.docker.internal") {gatewayBaseUrl = `${url.protocol}//host.docker.internal:3308`;diff --git a/products/desktop/packages/shared/src/custom-cloud.test.ts b/products/desktop/packages/shared/src/custom-cloud.test.tsnew file mode 100644index 000000000000..058b6123d98c--- /dev/null+++ b/products/desktop/packages/shared/src/custom-cloud.test.ts@@ -0,0 +1,135 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ configureCustomCloud,+ getCustomCloud,+ isCustomCloudHost,+ normalizeCustomCloud,+} from "./custom-cloud";++describe("custom cloud", () => {+ afterEach(() => {+ configureCustomCloud(null);+ vi.unstubAllEnvs();+ });++ describe("normalizeCustomCloud", () => {+ it("trims the values and keeps the origin only", () => {+ expect(+ normalizeCustomCloud({+ url: " https://posthog.example.com/ ",+ oauthClientId: " custom-client-id ",+ gatewayUrl: "https://gateway.example.com/",+ }),+ ).toEqual({+ url: "https://posthog.example.com",+ oauthClientId: "custom-client-id",+ gatewayUrl: "https://gateway.example.com",+ });+ });++ it.each([+ { name: "no input", url: undefined },+ { name: "an empty URL", url: " " },+ { name: "a scheme that is not http", url: "file:///etc/passwd" },+ { name: "a value that is not a URL", url: "posthog.example.com" },+ { name: "a path", url: "https://posthog.example.com/project/1" },+ { name: "a query", url: "https://posthog.example.com/?a=1" },+ { name: "a fragment", url: "https://posthog.example.com/#settings" },+ ])("returns null for $name", ({ url }) => {+ expect(+ normalizeCustomCloud(url === undefined ? null : { url }),+ ).toBeNull();+ });++ it("returns null without an OAuth client ID", () => {+ expect(+ normalizeCustomCloud({ url: "https://posthog.example.com" }),+ ).toBeNull();+ expect(+ normalizeCustomCloud({+ url: "https://posthog.example.com",+ oauthClientId: " ",+ }),+ ).toBeNull();+ });++ it("keeps an http URL only for a loopback host", () => {+ expect(+ normalizeCustomCloud({+ url: "http://localhost:8020",+ oauthClientId: "client-id",+ })?.url,+ ).toBe("http://localhost:8020");+ expect(+ normalizeCustomCloud({+ url: "http://posthog.example.com",+ oauthClientId: "client-id",+ }),+ ).toBeNull();+ });++ it("refuses a built-in host written with a trailing dot", () => {+ expect(+ normalizeCustomCloud({+ url: "https://us.posthog.com.",+ oauthClientId: "client-id",+ }),+ ).toBeNull();+ });++ it.each([+ "https://us.posthog.com",+ "https://eu.posthog.com",+ "https://app.dev.posthog.dev",+ "http://localhost:8010",+ ])("refuses the built-in host %s", (url) => {+ expect(normalizeCustomCloud({ url })).toBeNull();+ });++ it("drops a gateway URL that is not a plain origin", () => {+ expect(+ normalizeCustomCloud({+ url: "https://posthog.example.com",+ gatewayUrl: "ftp://gateway.example.com",+ })?.gatewayUrl,+ ).toBeUndefined();+ });+ });++ describe("getCustomCloud", () => {+ it("prefers the configured target over the environment", () => {+ vi.stubEnv("POSTHOG_CUSTOM_CLOUD_URL", "https://from-env.example.com");+ configureCustomCloud({+ url: "https://configured.example.com",+ oauthClientId: "configured-client-id",+ });+ expect(getCustomCloud()?.url).toBe("https://configured.example.com");+ });++ it("falls back to the environment when nothing is configured", () => {+ vi.stubEnv("POSTHOG_CUSTOM_CLOUD_URL", "https://from-env.example.com");+ vi.stubEnv("POSTHOG_CUSTOM_CLOUD_OAUTH_CLIENT_ID", "env-client-id");+ expect(getCustomCloud()).toEqual({+ url: "https://from-env.example.com",+ oauthClientId: "env-client-id",+ gatewayUrl: undefined,+ });+ });+ });++ describe("isCustomCloudHost", () => {+ it("matches the configured host only", () => {+ configureCustomCloud({+ url: "https://posthog.example.com",+ oauthClientId: "client-id",+ });+ expect(isCustomCloudHost("https://posthog.example.com/")).toBe(true);+ expect(isCustomCloudHost("https://us.posthog.com")).toBe(false);+ });++ it("matches nothing when no target is configured", () => {+ vi.stubEnv("POSTHOG_CUSTOM_CLOUD_URL", "");+ expect(isCustomCloudHost("https://posthog.example.com")).toBe(false);+ });+ });+});diff --git a/products/desktop/packages/shared/src/custom-cloud.ts b/products/desktop/packages/shared/src/custom-cloud.tsnew file mode 100644index 000000000000..13c987189fd1--- /dev/null+++ b/products/desktop/packages/shared/src/custom-cloud.ts@@ -0,0 +1,107 @@+import { z } from "zod";++export const customCloudSchema = z.object({+ url: z.string(),+ oauthClientId: z.string().optional(),+ gatewayUrl: z.string().optional(),+});++export type CustomCloud = z.infer<typeof customCloudSchema>;++const BUILT_IN_HOSTS = new Set([+ "us.posthog.com",+ "eu.posthog.com",+ "app.dev.posthog.dev",+ "localhost:8010",+]);++// A target with no OAuth client ID cannot complete sign-in, and the+// environment path has no form to catch the gap, so the target itself is+// invalid without one.+function normalizeOauthClientId(value: string | undefined): string | undefined {+ const trimmed = value?.trim();+ return trimmed ? trimmed : undefined;+}++// A base URL only. A query, a fragment, or a path would land inside the+// endpoint paths that callers append to it. HTTP is only for loopback hosts,+// because OAuth tokens cross this origin.+function httpUrl(value: string | undefined): string | undefined {+ const trimmed = value?.trim();+ if (!trimmed) return undefined;+ let parsed: URL;+ try {+ parsed = new URL(trimmed);+ } catch {+ return undefined;+ }+ if (+ parsed.protocol !== "https:" &&+ !(parsed.protocol === "http:" && isLoopbackHost(parsed.hostname))+ ) {+ return undefined;+ }+ if (parsed.search || parsed.hash || parsed.pathname !== "/") return undefined;+ return `${parsed.protocol}//${canonicalHost(parsed)}`;+}++function isLoopbackHost(hostname: string): boolean {+ const host = hostname.replace(/\.+$/, "").toLowerCase();+ return host === "localhost" || host === "127.0.0.1" || host === "::1";+}++// A trailing dot in a hostname is a DNS root hint, so `us.posthog.com.` is a+// live alias for US Cloud that an exact-string host set would miss.+function canonicalHost(parsed: URL): string {+ const port = parsed.port ? `:${parsed.port}` : "";+ return `${parsed.hostname.replace(/\.+$/, "")}${port}`;+}++export function normalizeCustomCloud(+ input: Partial<CustomCloud> | null | undefined,+): CustomCloud | null {+ const url = httpUrl(input?.url);+ const oauthClientId = normalizeOauthClientId(input?.oauthClientId);+ // A built-in host would make the region-blind gateway lookups below treat a+ // built-in region as the custom one.+ if (!url || !oauthClientId) return null;+ if (BUILT_IN_HOSTS.has(canonicalHost(new URL(url)))) return null;+ return {+ url,+ oauthClientId,+ gatewayUrl: httpUrl(input?.gatewayUrl),+ };+}++export function isCustomCloudHost(posthogHost: string): boolean {+ const custom = getCustomCloud();+ if (!custom) return false;+ try {+ return (+ canonicalHost(new URL(posthogHost)) === canonicalHost(new URL(custom.url))+ );+ } catch {+ return false;+ }+}++function fromEnv(): CustomCloud | null {+ if (typeof process === "undefined" || !process.env) return null;+ return normalizeCustomCloud({+ url: process.env.POSTHOG_CUSTOM_CLOUD_URL,+ oauthClientId: process.env.POSTHOG_CUSTOM_CLOUD_OAUTH_CLIENT_ID,+ gatewayUrl: process.env.POSTHOG_CUSTOM_CLOUD_GATEWAY_URL,+ });+}++let configured: CustomCloud | null = null;++// Every path funnels through here, so this is where a value that the rules+// refuse has to be dropped.+export function configureCustomCloud(target: CustomCloud | null): void {+ configured = normalizeCustomCloud(target);+}++export function getCustomCloud(): CustomCloud | null {+ return configured ?? fromEnv();+}diff --git a/products/desktop/packages/shared/src/deep-links.ts b/products/desktop/packages/shared/src/deep-links.tsindex bd05dd0f676a..bac2b1a7a073 100644--- a/products/desktop/packages/shared/src/deep-links.ts+++ b/products/desktop/packages/shared/src/deep-links.ts@@ -2,11 +2,23 @@ import { scoutSkillSlug } from "./scout-naming";const DEEPLINK_PROTOCOL_PRODUCTION = "posthog-code";const DEEPLINK_PROTOCOL_DEVELOPMENT = "posthog-code-dev";+const DEEPLINK_PROTOCOL_TEST = "posthog-code-test";++// The renderer cannot see app.isPackaged, so the test channel rides in the+// baked vite env. In plain node (harness, tests) import.meta.env is unset.+function isTestChannelBuild(): boolean {+ return (+ (import.meta as unknown as { env?: Record<string, string | undefined> }).env+ ?.VITE_POSTHOG_BUILD_CHANNEL === "test"+ );+}export function getDeeplinkProtocol(isDevBuild: boolean): string {- return isDevBuild- ? DEEPLINK_PROTOCOL_DEVELOPMENT- : DEEPLINK_PROTOCOL_PRODUCTION;+ if (isDevBuild) return DEEPLINK_PROTOCOL_DEVELOPMENT;+ // A test build registers its own scheme, so a release build installed on+ // the same machine cannot receive its OAuth callbacks.+ if (isTestChannelBuild()) return DEEPLINK_PROTOCOL_TEST;+ return DEEPLINK_PROTOCOL_PRODUCTION;}export function isPostHogCodeDeeplink(@@ -17,7 +29,8 @@ export function isPostHogCodeDeeplink(const protocol = new URL(href).protocol;return (protocol === `${DEEPLINK_PROTOCOL_PRODUCTION}:` ||- protocol === `${DEEPLINK_PROTOCOL_DEVELOPMENT}:`+ protocol === `${DEEPLINK_PROTOCOL_DEVELOPMENT}:` ||+ protocol === `${DEEPLINK_PROTOCOL_TEST}:`);} catch {return false;diff --git a/products/desktop/packages/shared/src/index.ts b/products/desktop/packages/shared/src/index.tsindex 08f4c85858ce..8ca3584c57bd 100644--- a/products/desktop/packages/shared/src/index.ts+++ b/products/desktop/packages/shared/src/index.ts@@ -94,6 +94,14 @@ export {normalizeGatewayModelsResponse,pickAllowedModel,} from "./cloud-task-models";+export {+ type CustomCloud,+ configureCustomCloud,+ customCloudSchema,+ getCustomCloud,+ isCustomCloudHost,+ normalizeCustomCloud,+} from "./custom-cloud";export {buildLoopDeeplink,buildScoutDeeplink,@@ -225,6 +233,8 @@ export {selectOptionHarness,} from "./models";export {+ DEV_CALLBACK_PORT,+ DEV_REDIRECT_URI,getOauthClientIdFromRegion,OAUTH_SCOPE_VERSION,OAUTH_SCOPES,@@ -280,7 +290,9 @@ export { REFUND_REASON_OPTIONS } from "./refund-reasons";export {CLOUD_REGIONS,type CloudRegion,+ describeRegion,REGION_LABELS,+ type RegionLabel,} from "./regions";export { normalizeRepoKey } from "./repo";export { getTaskRepository, parseRepository } from "./repository";diff --git a/products/desktop/packages/shared/src/oauth.ts b/products/desktop/packages/shared/src/oauth.tsindex 10d718fc4c60..634f10ee8103 100644--- a/products/desktop/packages/shared/src/oauth.ts+++ b/products/desktop/packages/shared/src/oauth.ts@@ -1,3 +1,4 @@+import { getCustomCloud } from "./custom-cloud";import type { CloudRegion } from "./regions";export const POSTHOG_US_CLIENT_ID = "HCWoE0aRFMYxIxFNTTwkOORn5LBjOt2GVDzwSw5W";@@ -27,6 +28,12 @@ export const POSTHOG_DEV_CLOUD_CLIENT_ID =//// Regenerate from the live advertised list + llm_gateway:read last; bump// OAUTH_SCOPE_VERSION whenever the set changes so installs re-authorize.+// The OAuth callback the app listens on in a development build, where no+// deep-link scheme is registered. Shared so the sign-in help text and the+// OAuth service cannot drift apart.+export const DEV_CALLBACK_PORT = 8237;+export const DEV_REDIRECT_URI = `http://localhost:${DEV_CALLBACK_PORT}/callback`;+export const OAUTH_SCOPES = ["openid","profile",@@ -256,5 +263,7 @@ export function getOauthClientIdFromRegion(region: CloudRegion): string {return POSTHOG_DEV_CLIENT_ID;case "dev-cloud":return POSTHOG_DEV_CLOUD_CLIENT_ID;+ case "custom":+ return getCustomCloud()?.oauthClientId ?? "";}}diff --git a/products/desktop/packages/shared/src/regions.test.ts b/products/desktop/packages/shared/src/regions.test.tsindex f23076195db7..6c49eb1e8950 100644--- a/products/desktop/packages/shared/src/regions.test.ts+++ b/products/desktop/packages/shared/src/regions.test.ts@@ -1,4 +1,5 @@-import { describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { configureCustomCloud } from "./custom-cloud";import {getOauthClientIdFromRegion,POSTHOG_DEV_CLIENT_ID,@@ -6,9 +7,23 @@ import {POSTHOG_EU_CLIENT_ID,POSTHOG_US_CLIENT_ID,} from "./oauth";-import { CLOUD_REGIONS, formatRegionBadge, REGION_LABELS } from "./regions";+import {+ CLOUD_REGIONS,+ describeRegion,+ formatRegionBadge,+ REGION_LABELS,+} from "./regions";import { getCloudUrlFromRegion } from "./urls";+beforeEach(() => {+ vi.stubEnv("POSTHOG_CUSTOM_CLOUD_URL", "");+});++afterEach(() => {+ configureCustomCloud(null);+ vi.unstubAllEnvs();+});+describe("getCloudUrlFromRegion", () => {it("maps each region to its cloud URL", () => {expect(getCloudUrlFromRegion("us")).toBe("https://us.posthog.com");@@ -30,14 +45,48 @@ describe("getOauthClientIdFromRegion", () => {);});- it("uses a different client id per region", () => {+ it("uses a different client id per built-in region", () => {const ids = new Set([getOauthClientIdFromRegion("us"),getOauthClientIdFromRegion("eu"),getOauthClientIdFromRegion("dev"),getOauthClientIdFromRegion("dev-cloud"),]);- expect(ids.size).toBe(CLOUD_REGIONS.length);+ expect(ids.size).toBe(4);+ });++ it("has no built-in client id for the custom region", () => {+ expect(getOauthClientIdFromRegion("custom")).toBe("");+ });+});++describe("a configured custom cloud", () => {+ beforeEach(() => {+ configureCustomCloud({+ url: "https://posthog.example.com",+ oauthClientId: "custom-client-id",+ });+ });++ it("serves the custom region only", () => {+ expect(getCloudUrlFromRegion("custom")).toBe("https://posthog.example.com");+ expect(getOauthClientIdFromRegion("custom")).toBe("custom-client-id");+ expect(getCloudUrlFromRegion("dev")).toBe("http://localhost:8010");+ expect(getOauthClientIdFromRegion("dev")).toBe(POSTHOG_DEV_CLIENT_ID);+ expect(getCloudUrlFromRegion("us")).toBe("https://us.posthog.com");+ expect(getCloudUrlFromRegion("eu")).toBe("https://eu.posthog.com");+ expect(getCloudUrlFromRegion("dev-cloud")).toBe(+ "https://app.dev.posthog.dev",+ );+ expect(getOauthClientIdFromRegion("us")).toBe(POSTHOG_US_CLIENT_ID);+ });++ it("labels the custom region with its host", () => {+ expect(describeRegion("custom")).toMatchObject({+ label: "Custom",+ hint: "posthog.example.com",+ });+ expect(describeRegion("dev")).toEqual(REGION_LABELS.dev);});});diff --git a/products/desktop/packages/shared/src/regions.ts b/products/desktop/packages/shared/src/regions.tsindex 5e1eec22a202..b40c2079769f 100644--- a/products/desktop/packages/shared/src/regions.ts+++ b/products/desktop/packages/shared/src/regions.ts@@ -1,7 +1,15 @@-export const CLOUD_REGIONS = ["us", "eu", "dev", "dev-cloud"] as const;+import { getCustomCloud } from "./custom-cloud";++export const CLOUD_REGIONS = [+ "us",+ "eu",+ "dev",+ "dev-cloud",+ "custom",+] as const;export type CloudRegion = (typeof CLOUD_REGIONS)[number];-interface RegionLabel {+export interface RegionLabel {flag: string;label: string;hint: string;@@ -28,8 +36,20 @@ export const REGION_LABELS: Record<CloudRegion, RegionLabel> = {label: "Dev Cloud",hint: "app.dev.posthog.dev",},+ custom: {+ flag: "🏠",+ label: "Custom",+ hint: "your own instance",+ },};+export function describeRegion(region: CloudRegion): RegionLabel {+ if (region !== "custom") return REGION_LABELS[region];+ const custom = getCustomCloud();+ if (!custom) return REGION_LABELS.custom;+ return { ...REGION_LABELS.custom, hint: new URL(custom.url).host };+}+export function formatRegionBadge(region: CloudRegion): string {const entry = REGION_LABELS[region];return `${entry.flag} ${entry.label}`;diff --git a/products/desktop/packages/shared/src/urls.ts b/products/desktop/packages/shared/src/urls.tsindex 5ffe19081e8b..42e28ff7df68 100644--- a/products/desktop/packages/shared/src/urls.ts+++ b/products/desktop/packages/shared/src/urls.ts@@ -1,3 +1,4 @@+import { getCustomCloud } from "./custom-cloud";import type { CloudRegion } from "./regions";export function getCloudUrlFromRegion(region: CloudRegion): string {@@ -10,5 +11,7 @@ export function getCloudUrlFromRegion(region: CloudRegion): string {return "http://localhost:8010";case "dev-cloud":return "https://app.dev.posthog.dev";+ case "custom":+ return getCustomCloud()?.url ?? "";}}diff --git a/products/desktop/packages/ui/src/features/auth/CustomCloudFields.tsx b/products/desktop/packages/ui/src/features/auth/CustomCloudFields.tsxnew file mode 100644index 000000000000..f3735537bf87--- /dev/null+++ b/products/desktop/packages/ui/src/features/auth/CustomCloudFields.tsx@@ -0,0 +1,94 @@+import { InfoIcon } from "@phosphor-icons/react";+import { Input, Text } from "@posthog/quill";+import { DEV_CALLBACK_PORT } from "@posthog/shared";+import { Tooltip } from "@posthog/ui/primitives/Tooltip";+import type { CustomCloudDraft } from "./useCustomCloud";++// The app only listens on the HTTP callback in a development build; a packaged+// build receives the OAuth callback as a deep link instead.+const REDIRECT_URI = import.meta.env.DEV+ ? `http://localhost:${DEV_CALLBACK_PORT}/callback`+ : "posthog-code://callback";++const FIELDS: {+ key: keyof CustomCloudDraft;+ type: "url" | "text";+ placeholder: string;+ label: string;+ help: string;+}[] = [+ {+ key: "url",+ type: "url",+ placeholder: "https://posthog.example.com",+ label: "PostHog instance URL",+ help: "The address of your PostHog instance. Sign-in, the API, and links use it.",+ },+ {+ key: "oauthClientId",+ type: "text",+ placeholder: "OAuth client ID",+ label: "OAuth client ID",+ help: `The client ID of the OAuth application on that instance. Make the application in Django admin, with the redirect URI ${REDIRECT_URI}.`,+ },+ {+ key: "gatewayUrl",+ type: "url",+ placeholder: "LLM gateway URL (optional)",+ label: "LLM gateway URL",+ help: "The LLM gateway for agent runs. Your instance needs its own gateway, because a PostHog Cloud gateway cannot read a token from your instance.",+ },+];++interface CustomCloudFieldsProps {+ draft: CustomCloudDraft;+ onChange: (patch: Partial<CustomCloudDraft>) => void;+ onBlur: () => void;+ error: string | null;+ disabled?: boolean;+}++export function CustomCloudFields({+ draft,+ onChange,+ onBlur,+ error,+ disabled = false,+}: CustomCloudFieldsProps) {+ return (+ <div className="flex w-full flex-col gap-2">+ {FIELDS.map(({ key, type, placeholder, label, help }) => (+ <div key={key} className="flex items-center gap-2">+ <Input+ className="flex-1"+ type={type}+ autoComplete="off"+ placeholder={placeholder}+ aria-label={label}+ value={draft[key]}+ disabled={disabled}+ onChange={(event) => onChange({ [key]: event.target.value })}+ onBlur={onBlur}+ />+ <Tooltip+ content={<span className="block max-w-[240px]">{help}</span>}+ side="right"+ >+ <button+ type="button"+ aria-label={`About ${label}`}+ className="shrink-0 cursor-help text-(--gray-10) hover:text-(--gray-12)"+ >+ <InfoIcon size={14} />+ </button>+ </Tooltip>+ </div>+ ))}+ {error && (+ <Text className="text-(--red-11) text-xs" role="alert">+ {error}+ </Text>+ )}+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/auth/OAuthControls.tsx b/products/desktop/packages/ui/src/features/auth/OAuthControls.tsxindex b1e617fd5984..54ed126619d1 100644--- a/products/desktop/packages/ui/src/features/auth/OAuthControls.tsx+++ b/products/desktop/packages/ui/src/features/auth/OAuthControls.tsx@@ -1,7 +1,10 @@import type { CloudRegion } from "@posthog/shared";import { Spinner } from "@posthog/ui/primitives/Spinner";+import { useHostCapabilities } from "@posthog/ui/shell/useHostCapabilities";import { Callout } from "@radix-ui/themes";+import { CustomCloudFields } from "./CustomCloudFields";import { RegionSelect } from "./RegionSelect";+import { useCustomCloud } from "./useCustomCloud";import { useOAuthFlow } from "./useOAuthFlow";interface OAuthControlsProps {@@ -12,8 +15,11 @@ interface OAuthControlsProps {export function OAuthControls({onAuthInitiated,- includeDevRegion = import.meta.env.DEV,+ includeDevRegion = import.meta.env.DEV ||+ import.meta.env.VITE_POSTHOG_BUILD_CHANNEL === "test",}: OAuthControlsProps = {}) {+ const { customCloud: hostHoldsCustomCloud } = useHostCapabilities();+ const includeCustomRegion = includeDevRegion && hostHoldsCustomCloud;const {region,handleAuth,@@ -22,12 +28,15 @@ export function OAuthControls({isPending,errorMessage,} = useOAuthFlow();+ const customCloud = useCustomCloud({ enabled: includeCustomRegion });+ const showCustomCloud = includeCustomRegion && region === "custom";- const handleClick = () => {+ const handleClick = async () => {if (isPending) {void handleCancel();return;}+ if (showCustomCloud && !(await customCloud.commit())) return;onAuthInitiated?.(region);handleAuth();};@@ -48,8 +57,8 @@ export function OAuthControls({<buttontype="button"- onClick={handleClick}- disabled={false}+ onClick={() => void handleClick()}+ disabled={customCloud.isSaving}className="flex h-[44px] w-full cursor-pointer items-center justify-center gap-[8px] rounded-[6px] font-medium text-[15px]"style={{border: isPending@@ -70,7 +79,18 @@ export function OAuthControls({onRegionChange={handleRegionChange}disabled={isPending}includeDevRegion={includeDevRegion}+ includeCustomRegion={includeCustomRegion}/>++ {showCustomCloud && (+ <CustomCloudFields+ draft={customCloud.draft}+ onChange={customCloud.updateDraft}+ onBlur={() => void customCloud.commit()}+ error={customCloud.error}+ disabled={isPending || customCloud.isSaving}+ />+ )}</div>);}diff --git a/products/desktop/packages/ui/src/features/auth/RegionSelect.stories.tsx b/products/desktop/packages/ui/src/features/auth/RegionSelect.stories.tsxindex 0c21f41d8fa8..1ea8979dd9e1 100644--- a/products/desktop/packages/ui/src/features/auth/RegionSelect.stories.tsx+++ b/products/desktop/packages/ui/src/features/auth/RegionSelect.stories.tsx@@ -1,5 +1,7 @@import type { CloudRegion } from "@posthog/shared";+import { CustomCloudFields } from "@posthog/ui/features/auth/CustomCloudFields";import { RegionSelect } from "@posthog/ui/features/auth/RegionSelect";+import type { CustomCloudDraft } from "@posthog/ui/features/auth/useCustomCloud";import { ProductWordmark } from "@posthog/ui/primitives/ProductWordmark";import type { Meta, StoryObj } from "@storybook/react-vite";import { useState } from "react";@@ -14,10 +16,23 @@ export default meta;/** Mirrors SignInCard's layout without the OAuth hook, so the whole block is visible. */function SignInCardPreview({includeDevRegion,+ includeCustomRegion = false,+ initialRegion = "us",+ customCloudDraft,}: {includeDevRegion: boolean;+ includeCustomRegion?: boolean;+ initialRegion?: CloudRegion;+ customCloudDraft?: CustomCloudDraft;}) {- const [region, setRegion] = useState<CloudRegion>("us");+ const [region, setRegion] = useState<CloudRegion>(initialRegion);+ const [draft, setDraft] = useState<CustomCloudDraft>(+ customCloudDraft ?? {+ url: "",+ oauthClientId: "",+ gatewayUrl: "",+ },+ );return (<div className="w-[420px] p-8"><div className="flex flex-col gap-6">@@ -41,7 +56,18 @@ function SignInCardPreview({region={region}onRegionChange={setRegion}includeDevRegion={includeDevRegion}+ includeCustomRegion={includeCustomRegion}/>+ {region === "custom" && (+ <CustomCloudFields+ draft={draft}+ onChange={(patch) =>+ setDraft((current) => ({ ...current, ...patch }))+ }+ onBlur={() => undefined}+ error={null}+ />+ )}</div></div></div>@@ -55,3 +81,28 @@ export const SignInBlock: StoryObj = {export const WithDevelopmentRegions: StoryObj = {render: () => <SignInCardPreview includeDevRegion={true} />,};++export const CustomCloudEmpty: StoryObj = {+ render: () => (+ <SignInCardPreview+ includeDevRegion={true}+ includeCustomRegion={true}+ initialRegion="custom"+ />+ ),+};++export const CustomCloudFilled: StoryObj = {+ render: () => (+ <SignInCardPreview+ includeDevRegion={true}+ includeCustomRegion={true}+ initialRegion="custom"+ customCloudDraft={{+ url: "https://posthog.example.com",+ oauthClientId: "3Fk9QwErTyUiOpAsDfGhJkLzXcVbNm12",+ gatewayUrl: "https://gateway.example.com",+ }}+ />+ ),+};diff --git a/products/desktop/packages/ui/src/features/auth/RegionSelect.test.ts b/products/desktop/packages/ui/src/features/auth/RegionSelect.test.tsindex 6d40b357b1ae..84dc50fa356a 100644--- a/products/desktop/packages/ui/src/features/auth/RegionSelect.test.ts+++ b/products/desktop/packages/ui/src/features/auth/RegionSelect.test.ts@@ -1,17 +1,34 @@import { describe, expect, it } from "vitest";-import { getSelectableRegions } from "./RegionSelect";+import { getSelectableRegions } from "./selectableRegions";describe("getSelectableRegions", () => {it.each([- { includeDevRegion: false, expected: ["us", "eu"] },+ {+ includeDevRegion: false,+ includeCustomRegion: false,+ expected: ["us", "eu"],+ },{includeDevRegion: true,+ includeCustomRegion: false,expected: ["us", "eu", "dev-cloud", "dev"],},+ {+ includeDevRegion: true,+ includeCustomRegion: true,+ expected: ["us", "eu", "dev-cloud", "dev", "custom"],+ },+ {+ includeDevRegion: false,+ includeCustomRegion: true,+ expected: ["us", "eu", "custom"],+ },])(- "returns the regions available when development regions are $includeDevRegion",- ({ includeDevRegion, expected }) => {- expect(getSelectableRegions(includeDevRegion)).toEqual(expected);+ "offers development $includeDevRegion and custom $includeCustomRegion",+ ({ includeDevRegion, includeCustomRegion, expected }) => {+ expect(+ getSelectableRegions(includeDevRegion, includeCustomRegion),+ ).toEqual(expected);},);});diff --git a/products/desktop/packages/ui/src/features/auth/RegionSelect.tsx b/products/desktop/packages/ui/src/features/auth/RegionSelect.tsxindex fa1915ae9c6c..7eee3f0ffc7a 100644--- a/products/desktop/packages/ui/src/features/auth/RegionSelect.tsx+++ b/products/desktop/packages/ui/src/features/auth/RegionSelect.tsx@@ -6,8 +6,9 @@ import {SelectValue,Text,} from "@posthog/quill";-import { type CloudRegion, REGION_LABELS } from "@posthog/shared";+import { type CloudRegion, describeRegion } from "@posthog/shared";import { Tooltip } from "@posthog/ui/primitives/Tooltip";+import { getSelectableRegions } from "./selectableRegions";interface RegionSelectProps {region: CloudRegion;@@ -15,24 +16,17 @@ interface RegionSelectProps {disabled?: boolean;/** Host decides whether development regions are offered. */includeDevRegion?: boolean;-}--const PRODUCTION_REGIONS: CloudRegion[] = ["us", "eu"];-const DEVELOPMENT_REGIONS: CloudRegion[] = ["dev-cloud", "dev"];--export function getSelectableRegions(includeDevRegion: boolean): CloudRegion[] {- return includeDevRegion- ? [...PRODUCTION_REGIONS, ...DEVELOPMENT_REGIONS]- : PRODUCTION_REGIONS;+ /** Custom needs a host that can hold the target, so it is a separate flag. */+ includeCustomRegion?: boolean;}function RegionOptionLabel({ region }: { region: CloudRegion }) {- const { flag, hint, label } = REGION_LABELS[region];+ const { flag, hint, label } = describeRegion(region);return (- <span className="flex items-center gap-2">+ <span className="flex min-w-0 items-center gap-2"><span className="shrink-0 leading-none">{flag}</span>- <span className="font-medium">{label}</span>- <span className="text-(--gray-10) text-xs">{hint}</span>+ <span className="shrink-0 font-medium">{label}</span>+ <span className="truncate text-(--gray-10) text-xs">{hint}</span></span>);}@@ -42,8 +36,9 @@ export function RegionSelect({onRegionChange,disabled = false,includeDevRegion = false,+ includeCustomRegion = false,}: RegionSelectProps) {- const offered = getSelectableRegions(includeDevRegion);+ const offered = getSelectableRegions(includeDevRegion, includeCustomRegion);return (<div className="flex items-center justify-center gap-2">@@ -57,7 +52,7 @@ export function RegionSelect({}items={offered.map((candidate) => ({value: candidate,- label: `${REGION_LABELS[candidate].label} - ${REGION_LABELS[candidate].hint}`,+ label: `${describeRegion(candidate).label} - ${describeRegion(candidate).hint}`,}))}>{/* Fixed width so switching regions never reflows the row beneath the button. */}diff --git a/products/desktop/packages/ui/src/features/auth/selectableRegions.ts b/products/desktop/packages/ui/src/features/auth/selectableRegions.tsnew file mode 100644index 000000000000..dc1d5b164a30--- /dev/null+++ b/products/desktop/packages/ui/src/features/auth/selectableRegions.ts@@ -0,0 +1,15 @@+import type { CloudRegion } from "@posthog/shared";++const PRODUCTION_REGIONS: CloudRegion[] = ["us", "eu"];+const DEVELOPMENT_REGIONS: CloudRegion[] = ["dev-cloud", "dev"];++export function getSelectableRegions(+ includeDevRegion: boolean,+ includeCustomRegion = false,+): CloudRegion[] {+ return [+ ...PRODUCTION_REGIONS,+ ...(includeDevRegion ? DEVELOPMENT_REGIONS : []),+ ...(includeCustomRegion ? (["custom"] as CloudRegion[]) : []),+ ];+}diff --git a/products/desktop/packages/ui/src/features/auth/useCustomCloud.ts b/products/desktop/packages/ui/src/features/auth/useCustomCloud.tsnew file mode 100644index 000000000000..b4088f79dd96--- /dev/null+++ b/products/desktop/packages/ui/src/features/auth/useCustomCloud.ts@@ -0,0 +1,102 @@+import { useHostTRPCClient } from "@posthog/host-router/react";+import {+ type CustomCloud,+ configureCustomCloud,+ normalizeCustomCloud,+} from "@posthog/shared";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { useEffect, useState } from "react";++export type CustomCloudDraft = Record<keyof CustomCloud, string>;++const EMPTY_DRAFT: CustomCloudDraft = {+ url: "",+ oauthClientId: "",+ gatewayUrl: "",+};++const CUSTOM_CLOUD_QUERY_KEY = ["customCloud"] as const;++const URL_SHAPE_MESSAGE =+ "with no path, query, or fragment, and not a PostHog Cloud address";++export function useCustomCloud({ enabled }: { enabled: boolean }) {+ const hostClient = useHostTRPCClient();+ const queryClient = useQueryClient();+ const [draft, setDraft] = useState<CustomCloudDraft>(EMPTY_DRAFT);+ const [error, setError] = useState<string | null>(null);++ const stored = useQuery({+ queryKey: CUSTOM_CLOUD_QUERY_KEY,+ queryFn: () => hostClient.customCloud.get.query(),+ enabled,+ });++ useEffect(() => {+ if (!stored.data) return;+ setDraft({+ url: stored.data.url,+ oauthClientId: stored.data.oauthClientId ?? "",+ gatewayUrl: stored.data.gatewayUrl ?? "",+ });+ }, [stored.data]);++ const save = useMutation({+ mutationKey: CUSTOM_CLOUD_QUERY_KEY,+ mutationFn: (target: CustomCloud) =>+ hostClient.customCloud.set.mutate(target),+ onSuccess: (saved) => {+ setError(null);+ configureCustomCloud(saved);+ queryClient.setQueryData(CUSTOM_CLOUD_QUERY_KEY, saved);+ },+ });++ const updateDraft = (patch: Partial<CustomCloudDraft>) => {+ setError(null);+ setDraft((current) => ({ ...current, ...patch }));+ };++ const commit = async (): Promise<boolean> => {+ if (!draft.url.trim()) {+ setError("Enter the URL of your PostHog instance");+ return false;+ }+ if (!draft.oauthClientId.trim()) {+ setError("Enter the client ID of the OAuth application on that instance");+ return false;+ }+ const target = normalizeCustomCloud(draft);+ if (!target) {+ setError(`Enter the full URL of the instance, ${URL_SHAPE_MESSAGE}`);+ return false;+ }+ if (draft.gatewayUrl.trim() && !target.gatewayUrl) {+ setError(`Enter the full URL of the gateway, ${URL_SHAPE_MESSAGE}`);+ return false;+ }+ try {+ const saved = await save.mutateAsync(target);+ // A host that cannot hold a target answers the write with null instead+ // of an error, so a silent refusal must read as a failed save.+ if (!saved) {+ setError(+ "This build cannot hold a custom instance. Use a development or test build.",+ );+ return false;+ }+ } catch {+ setError("Could not save these settings. Try again.");+ return false;+ }+ return true;+ };++ return {+ draft,+ updateDraft,+ commit,+ error,+ isSaving: save.isPending,+ };+}diff --git a/products/desktop/packages/ui/src/shell/useHostCapabilities.ts b/products/desktop/packages/ui/src/shell/useHostCapabilities.tsindex 756ad86c6f4c..f45dd3a13b34 100644--- a/products/desktop/packages/ui/src/shell/useHostCapabilities.ts+++ b/products/desktop/packages/ui/src/shell/useHostCapabilities.ts@@ -7,7 +7,10 @@ import {// Hosts that predate the token (and Storybook/tests, which have no host binding)// default to the desktop posture, so existing behavior is unchanged unless a host// explicitly opts out.-const DEFAULT_CAPABILITIES: HostCapabilities = { localWorkspaces: true };+const DEFAULT_CAPABILITIES: HostCapabilities = {+ localWorkspaces: true,+ customCloud: false,+};/** Read the current host's coarse capabilities. Safe when unbound. */export function useHostCapabilities(): HostCapabilities {diff --git a/products/desktop/packages/ui/src/utils/posthogLinks.ts b/products/desktop/packages/ui/src/utils/posthogLinks.tsindex a70ddaca93c2..57a1b63cde06 100644--- a/products/desktop/packages/ui/src/utils/posthogLinks.ts+++ b/products/desktop/packages/ui/src/utils/posthogLinks.ts@@ -146,17 +146,17 @@ export type ShareLinkTarget =| { kind: "canvas"; channelId: string; dashboardId: string }| { kind: "channel"; channelId: string; taskId?: string };-const POSTHOG_HOSTS = new Set(- (Object.keys(REGION_LABELS) as CloudRegion[])- .map((region) => {+function posthogHosts(): Set<string> {+ return new Set(+ (Object.keys(REGION_LABELS) as CloudRegion[]).flatMap((region) => {try {- return new URL(getCloudUrlFromRegion(region)).host;+ return [new URL(getCloudUrlFromRegion(region)).host];} catch {- return "";+ return [];}- })- .filter(Boolean),-);+ }),+ );+}interface ShareLinkRoute {pattern: string[];@@ -219,7 +219,7 @@ export function parseShareLink(href: string): ShareLinkTarget | null {} catch {return null;}- if (!POSTHOG_HOSTS.has(url.host)) return null;+ if (!posthogHosts().has(url.host)) return null;const segments = decodePathSegments(url.pathname);for (const route of SHARE_LINK_ROUTES) {diff --git a/products/desktop/packages/workspace-server/src/db/schema.ts b/products/desktop/packages/workspace-server/src/db/schema.tsindex d1526e46972a..133859f4b164 100644--- a/products/desktop/packages/workspace-server/src/db/schema.ts+++ b/products/desktop/packages/workspace-server/src/db/schema.ts@@ -134,7 +134,9 @@ export const suspensions = sqliteTable("suspensions", {export const authSessions = sqliteTable("auth_sessions", {id: integer().primaryKey(),refreshTokenEncrypted: text().notNull(),- cloudRegion: text({ enum: ["us", "eu", "dev", "dev-cloud"] }).notNull(),+ cloudRegion: text({+ enum: ["us", "eu", "dev", "dev-cloud", "custom"],+ }).notNull(),selectedProjectId: integer(),scopeVersion: integer().notNull(),createdAt: createdAt(),@@ -175,7 +177,9 @@ export const authPreferences = sqliteTable("auth_preferences",{accountKey: text().notNull(),- cloudRegion: text({ enum: ["us", "eu", "dev", "dev-cloud"] }).notNull(),+ cloudRegion: text({+ enum: ["us", "eu", "dev", "dev-cloud", "custom"],+ }).notNull(),lastSelectedProjectId: integer(),lastSelectedOrgId: text(),createdAt: createdAt(),@@ -193,7 +197,9 @@ export const authOrgProjectPreferences = sqliteTable("auth_org_project_preferences",{accountKey: text().notNull(),- cloudRegion: text({ enum: ["us", "eu", "dev", "dev-cloud"] }).notNull(),+ cloudRegion: text({+ enum: ["us", "eu", "dev", "dev-cloud", "custom"],+ }).notNull(),orgId: text().notNull(),lastSelectedProjectId: integer().notNull(),createdAt: createdAt(),diff --git a/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.test.ts b/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.test.tsindex 181519d42c8a..7faed330c940 100644--- a/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.test.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.test.ts@@ -8,6 +8,7 @@ vi.mock("@posthog/agent/posthog-api", () => ({vi.stubGlobal("fetch", mockFetch);+import { configureCustomCloud } from "@posthog/shared";import { AgentAuthAdapter } from "./auth-adapter";const baseCredentials = {@@ -131,6 +132,52 @@ describe("AgentAuthAdapter", () => {);});+ it("gives a custom instance no PostHog MCP server", async () => {+ configureCustomCloud({+ url: "https://posthog.example.com",+ oauthClientId: "client-id",+ });+ try {+ const { servers } = await adapter.buildMcpServers({+ ...baseCredentials,+ apiHost: "https://posthog.example.com",+ });++ expect(deps.mcpProxy.register).not.toHaveBeenCalledWith(+ "posthog",+ expect.anything(),+ );+ expect(+ servers.find((server) => server.name === "posthog"),+ ).toBeUndefined();+ } finally {+ configureCustomCloud(null);+ }+ });++ it("gives a loopback custom instance no default MCP port either", async () => {+ configureCustomCloud({+ url: "http://localhost:8020",+ oauthClientId: "client-id",+ });+ try {+ const { servers } = await adapter.buildMcpServers({+ ...baseCredentials,+ apiHost: "http://localhost:8020",+ });++ expect(deps.mcpProxy.register).not.toHaveBeenCalledWith(+ "posthog",+ "http://localhost:8787/mcp",+ );+ expect(+ servers.find((server) => server.name === "posthog"),+ ).toBeUndefined();+ } finally {+ configureCustomCloud(null);+ }+ });+it("identifies as the posthog-code consumer so the MCP server emits UI-app metadata", async () => {const { servers } = await adapter.buildMcpServers(baseCredentials);diff --git a/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.ts b/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.tsindex 20cb2108c561..6461d08b66b8 100644--- a/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.ts@@ -4,7 +4,11 @@ import {sanitizeMcpServerName,} from "@posthog/agent/adapters/claude/mcp/tool-metadata";import { getLlmGatewayUrl } from "@posthog/agent/posthog-api";-import type { McpServerConnection, McpToolPolicy } from "@posthog/shared";+import {+ isCustomCloudHost,+ type McpServerConnection,+ type McpToolPolicy,+} from "@posthog/shared";import { POSTHOG_PROJECT_ID_HEADER } from "@posthog/shared/posthog-property-headers";import { inject, injectable } from "inversify";import type { AuthProxyService } from "../auth-proxy/auth-proxy";@@ -147,23 +151,26 @@ export class AgentAuthAdapter {await this.getValidToken();await this.mcpProxy.start();- const proxiedPosthogUrl = this.mcpProxy.register("posthog", mcpUrl);-- const posthogServer: McpServerConnection = {- name: "posthog",- type: "http",- url: proxiedPosthogUrl,- headers: [- {- name: POSTHOG_PROJECT_ID_HEADER,- value: String(credentials.projectId),- },- { name: "x-posthog-mcp-version", value: "2" },- { name: "x-posthog-mcp-consumer", value: "posthog-code" },- ],- };- servers.push(posthogServer);- serverDescriptions.set(posthogServer, POSTHOG_MCP_DESCRIPTION);++ if (mcpUrl) {+ const proxiedPosthogUrl = this.mcpProxy.register("posthog", mcpUrl);++ const posthogServer: McpServerConnection = {+ name: "posthog",+ type: "http",+ url: proxiedPosthogUrl,+ headers: [+ {+ name: POSTHOG_PROJECT_ID_HEADER,+ value: String(credentials.projectId),+ },+ { name: "x-posthog-mcp-version", value: "2" },+ { name: "x-posthog-mcp-consumer", value: "posthog-code" },+ ],+ };+ servers.push(posthogServer);+ serverDescriptions.set(posthogServer, POSTHOG_MCP_DESCRIPTION);+ }const installations = await this.fetchMcpInstallations(credentials);@@ -280,11 +287,19 @@ export class AgentAuthAdapter {return accessToken;}- private getPostHogMcpUrl(apiHost: string): string {+ private getPostHogMcpUrl(apiHost: string): string | null {const overrideUrl = process.env.POSTHOG_MCP_URL;if (overrideUrl) {return overrideUrl;}+ // The Cloud MCP cannot read a token from another instance, and the proxy+ // adds that token to every forwarded request. So a custom instance gets no+ // PostHog MCP server unless POSTHOG_MCP_URL names one it can use. This+ // check runs before the loopback branch, because a custom target may+ // itself live on a loopback host.+ if (isCustomCloudHost(apiHost)) {+ return null;+ }if (apiHost.includes("localhost") || apiHost.includes("127.0.0.1")) {return "http://localhost:8787/mcp";}