Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat: support cookie auth for locked Cloud Canvas (#1819)

Rohit Malhotraa422d87a4f86
diff --git a/__tests__/api/agent-server-config.test.ts b/__tests__/api/agent-server-config.test.ts
index 303db69edb..21a3b7fd31 100644
--- a/__tests__/api/agent-server-config.test.ts
+++ b/__tests__/api/agent-server-config.test.ts
@@ -6,8 +6,11 @@ import {
getAgentServerFormDefaults,
getAgentServerSessionApiKey,
getAgentServerWorkingDir,
+ getCookieAuthCloudHost,
+ getLockedCloudAuthMode,
getLockedCloudHost,
isAuthRequired,
+ isSameCloudHost,
isAuthRequiredAndMissing,
} from "#/api/agent-server-config";
@@ -78,13 +81,13 @@ describe("agent server config", () => {
});
});
-describe("getLockedCloudHost", () => {
- function setInjectedCloudHost(value: unknown) {
- (
- window as unknown as Record<string, unknown>
- ).__AGENT_CANVAS_LOCK_TO_CLOUD__ = value;
- }
+function setInjectedCloudHost(value: unknown) {
+ (
+ window as unknown as Record<string, unknown>
+ ).__AGENT_CANVAS_LOCK_TO_CLOUD__ = value;
+}
+describe("getLockedCloudHost", () => {
it("returns null when no Cloud lock is configured", () => {
expect(getLockedCloudHost()).toBeNull();
});
@@ -117,6 +120,63 @@ describe("getLockedCloudHost", () => {
});
});
+describe("isSameCloudHost", () => {
+ it.each([
+ ["https://staging.openhands.dev", "https://staging.all-hands.dev"],
+ [
+ "https://pr-254.staging.openhands.dev",
+ "https://pr-254.staging.all-hands.dev",
+ ],
+ ["https://openhands.dev", "https://app.all-hands.dev"],
+ ])("treats transition domains as equivalent (%s, %s)", (a, b) => {
+ expect(isSameCloudHost(a, b)).toBe(true);
+ expect(isSameCloudHost(b, a)).toBe(true);
+ });
+
+ it("does not treat different preview numbers as equivalent", () => {
+ expect(
+ isSameCloudHost(
+ "https://pr-254.staging.openhands.dev",
+ "https://pr-255.staging.all-hands.dev",
+ ),
+ ).toBe(false);
+ });
+});
+
+describe("getLockedCloudAuthMode", () => {
+ it("uses cookie auth when the locked Cloud host matches the current origin", () => {
+ mockWindowLocation("https://app.all-hands.dev/canvas");
+ setInjectedCloudHost("https://app.all-hands.dev");
+
+ expect(getLockedCloudAuthMode()).toBe("cookie");
+ });
+
+ it("uses cookie auth for equivalent openhands.dev and all-hands.dev preview hosts", () => {
+ mockWindowLocation("https://pr-254.staging.openhands.dev/canvas");
+ setInjectedCloudHost("https://pr-254.staging.all-hands.dev");
+
+ expect(getLockedCloudAuthMode()).toBe("cookie");
+ expect(getCookieAuthCloudHost()).toBe(
+ "https://pr-254.staging.openhands.dev",
+ );
+ });
+
+ it("uses cookie auth when production moves from app.all-hands.dev to openhands.dev", () => {
+ mockWindowLocation("https://openhands.dev/canvas");
+ setInjectedCloudHost("https://app.all-hands.dev");
+
+ expect(getLockedCloudAuthMode()).toBe("cookie");
+ expect(getCookieAuthCloudHost()).toBe("https://openhands.dev");
+ });
+
+ it("uses API-key auth when the locked Cloud host is cross-origin", () => {
+ mockWindowLocation("https://canvas.example.dev/");
+ setInjectedCloudHost("https://app.all-hands.dev");
+
+ expect(getLockedCloudAuthMode()).toBe("api-key");
+ });
+});
+
describe("isAuthRequired", () => {
afterEach(() => {
delete (window as unknown as Record<string, unknown>)
diff --git a/__tests__/api/backend-registry/storage.test.ts b/__tests__/api/backend-registry/storage.test.ts
index 0e0d7fa1ed..b8ed9b0c5d 100644
--- a/__tests__/api/backend-registry/storage.test.ts
+++ b/__tests__/api/backend-registry/storage.test.ts
@@ -9,9 +9,25 @@ import {
} from "#/api/backend-registry/storage";
import type { Backend } from "#/api/backend-registry/types";
+const ORIGINAL_LOCATION = window.location;
+
+function mockWindowLocation(url: string) {
+ Object.defineProperty(window, "location", {
+ configurable: true,
+ value: new URL(url),
+ });
+}
+
afterEach(() => {
window.localStorage.clear();
window.sessionStorage.clear();
+ delete (window as unknown as Record<string, unknown>)
+ .__AGENT_CANVAS_LOCK_TO_CLOUD__;
+ Object.defineProperty(window, "location", {
+ configurable: true,
+ value: ORIGINAL_LOCATION,
+ });
+
vi.unstubAllEnvs();
});
@@ -69,6 +85,81 @@ describe("backend-registry storage", () => {
expect(readStoredBackends()).toEqual(result);
});
+ it("seeds a cookie-auth Cloud backend when locked to the current origin", () => {
+ (
+ window as unknown as Record<string, unknown>
+ ).__AGENT_CANVAS_LOCK_TO_CLOUD__ = window.location.origin;
+ window.localStorage.setItem(
+ BACKENDS_STORAGE_KEY,
+ JSON.stringify([
+ {
+ id: "stale-local",
+ name: "Stale Local",
+ host: "http://localhost:18000",
+ apiKey: "stale-session",
+ kind: "local",
+ },
+ ]),
+ );
+
+ const result = readStoredBackends();
+
+ expect(result).toEqual([
+ {
+ id: "locked-cloud",
+ name: "OpenHands Cloud",
+ host: window.location.origin,
+ apiKey: "",
+ kind: "cloud",
+ authMode: "cookie",
+ },
+ ]);
+ expect(readStoredActiveBackend()).toEqual({
+ backendId: "locked-cloud",
+ orgId: null,
+ });
+ });
+
+ it("seeds the cookie-auth Cloud backend on the current origin when the locked host is an equivalent transition domain", () => {
+ mockWindowLocation("https://pr-254.staging.openhands.dev/canvas");
+ (
+ window as unknown as Record<string, unknown>
+ ).__AGENT_CANVAS_LOCK_TO_CLOUD__ = "https://pr-254.staging.all-hands.dev";
+
+ expect(readStoredBackends()).toEqual([
+ {
+ id: "locked-cloud",
+ name: "OpenHands Cloud",
+ host: "https://pr-254.staging.openhands.dev",
+ apiKey: "",
+ kind: "cloud",
+ authMode: "cookie",
+ },
+ ]);
+ });
+
+ it("preserves an existing locked Cloud org selection while reseeding", () => {
+ (
+ window as unknown as Record<string, unknown>
+ ).__AGENT_CANVAS_LOCK_TO_CLOUD__ = window.location.origin;
+ writeStoredActiveBackend({ backendId: "locked-cloud", orgId: "org-1" });
+
+ expect(readStoredBackends()[0]).toMatchObject({ id: "locked-cloud" });
+ expect(readStoredActiveBackend()).toEqual({
+ backendId: "locked-cloud",
+ orgId: "org-1",
+ });
+ });
+
+ it("does not seed a cookie-auth Cloud backend when locked cross-origin", () => {
+ (
+ window as unknown as Record<string, unknown>
+ ).__AGENT_CANVAS_LOCK_TO_CLOUD__ = "https://app.all-hands.dev";
+ vi.stubEnv("VITE_SESSION_API_KEY", "");
+
+ expect(readStoredBackends()).toEqual([]);
+ });
+
it("re-seeds the default Local backend when storage holds an empty array and launcher details are available", () => {
vi.stubEnv("VITE_BACKEND_BASE_URL", "http://localhost:9000");
vi.stubEnv("VITE_SESSION_API_KEY", "fresh-session-key");
diff --git a/__tests__/api/cloud/proxy.test.ts b/__tests__/api/cloud/proxy.test.ts
index 75799f61bb..8a3cb09615 100644
--- a/__tests__/api/cloud/proxy.test.ts
+++ b/__tests__/api/cloud/proxy.test.ts
@@ -23,6 +23,15 @@ const cloudAcme: Backend = {
kind: "cloud",
};
+const cookieCloud: Backend = {
+ id: "cloud-cookie",
+ name: "Production - Cookie",
+ host: "https://app.all-hands.dev",
+ apiKey: "",
+ kind: "cloud",
+ authMode: "cookie",
+};
+
const originalFetch = global.fetch;
const fetchMock = vi.fn();
@@ -105,6 +114,44 @@ describe("callCloudProxy X-Org-Id injection", () => {
});
});
+describe("callCloudProxy cookie auth", () => {
+ it("omits bearer auth for same-origin cookie-backed Cloud requests", async () => {
+ setRegisteredBackends([cookieCloud]);
+ setActiveSelection({ backendId: cookieCloud.id, orgId: null });
+
+ await callCloudProxy({
+ backend: cookieCloud,
+ method: "GET",
+ path: "/api/v1/users/me",
+ });
+
+ const [url, init] = fetchMock.mock.calls[0]!;
+ expect(url).toBe(`${cookieCloud.host}/api/v1/users/me`);
+ expect(init).toMatchObject({ method: "GET" });
+ expect(
+ (init as { headers: Record<string, string> }).headers,
+ ).not.toHaveProperty("Authorization");
+ });
+
+ it("omits bearer auth in runtime proxy envelope requests", async () => {
+ setRegisteredBackends([cookieCloud]);
+ setActiveSelection({ backendId: cookieCloud.id, orgId: null });
+
+ await callCloudProxy({
+ backend: cookieCloud,
+ method: "GET",
+ path: "/api/bash/bash_events/search",
+ hostOverride: "https://abc123.prod-runtime.all-hands.dev",
+ });
+
+ const [, init] = fetchMock.mock.calls[0]!;
+ const envelope = JSON.parse((init as { body: string }).body);
+ expect(
+ (envelope as { headers: Record<string, string> }).headers,
+ ).not.toHaveProperty("Authorization");
+ });
+});
+
describe("callCloudProxy automation direct routing", () => {
it("sends automation requests straight to the cloud host with the API key instead of the /api/cloud-proxy envelope", async () => {
// Arrange β€” the automation service grants permissive CORS to API-key
diff --git a/__tests__/components/backends/backend-selector.test.tsx b/__tests__/components/backends/backend-selector.test.tsx
index 784cd01c46..1f9cf3d083 100644
--- a/__tests__/components/backends/backend-selector.test.tsx
+++ b/__tests__/components/backends/backend-selector.test.tsx
@@ -292,6 +292,52 @@ describe("BackendSelector", () => {
expect(screen.queryByText(/Beta Co/)).not.toBeInTheDocument();
});
+ it("shows every organization as a separate row for cookie-auth cloud backends", async () => {
+ vi.mocked(getCloudOrganizations).mockResolvedValue({
+ items: [
+ { id: "org-personal", name: "Personal" },
+ { id: "org-acme", name: "Acme Inc" },
+ ],
+ currentOrgId: "org-acme",
+ });
+ vi.mocked(getCurrentCloudApiKey).mockResolvedValue({
+ orgId: "org-personal",
+ isLegacyKey: false,
+ });
+
+ renderWithProviders(
+ <TestSeed
+ onMount={(ctx) => {
+ ctx.addBackend({
+ name: "OpenHands Cloud",
+ host: "https://app.all-hands.dev",
+ apiKey: "",
+ kind: "cloud",
+ authMode: "cookie",
+ });
+ }}
+ >
+ <BackendSelector />
+ </TestSeed>,
+ );
+
+ await waitFor(() => {
+ const wrapper = screen.getByTestId("backend-selector");
+ const input = wrapper.querySelector("input") as HTMLInputElement;
+ expect(input.value).toBe("OpenHands Cloud – Acme Inc");
+ });
+
+ await openDropdown();
+
+ await waitFor(() => {
+ expect(
+ screen.getByText("OpenHands Cloud – Personal"),
+ ).toBeInTheDocument();
+ });
+ expect(screen.getByText("OpenHands Cloud – Acme Inc")).toBeInTheDocument();
+ expect(getCurrentCloudApiKey).not.toHaveBeenCalled();
+ });
+
it("labels an org as 'Personal Workspace' when /me reports user_id === org.id", async () => {
const personalOrgId = "0b93b5f2-5396-49f2-8d98-61f906184270";
vi.mocked(getCloudOrganizations).mockResolvedValue({
@@ -341,14 +387,14 @@ describe("BackendSelector", () => {
).not.toBeInTheDocument();
});
- it("self-heals (cloud, null) β†’ (cloud, personal-workspace org) locally once orgs + /me resolve", async () => {
+ it("self-heals (cloud, null) β†’ Cloud's current org before personal workspace", async () => {
const personalOrgId = "0b93b5f2-5396-49f2-8d98-61f906184270";
vi.mocked(getCloudOrganizations).mockResolvedValue({
items: [
{ id: personalOrgId, name: "Auto-generated personal" },
{ id: "org-2", name: "Acme Inc" },
],
- currentOrgId: personalOrgId,
+ currentOrgId: "org-2",
});
vi.mocked(getCloudOrganizationMe).mockResolvedValue({
orgId: personalOrgId,
@@ -370,15 +416,15 @@ describe("BackendSelector", () => {
</TestSeed>,
);
- // After orgs + /me resolve, the selector snaps the active selection
- // onto the personal-workspace org locally β€” without round-tripping
- // /switch on the cloud backend (which would have mutated the cloud UI's
- // user.current_org_id as a side effect).
+ // After orgs resolve, the selector snaps the active selection onto the
+ // Cloud API's current_org_id locally β€” without round-tripping /switch on
+ // the cloud backend (which would have mutated the cloud UI's current org
+ // as a side effect).
await waitFor(() => {
const stored = JSON.parse(
window.localStorage.getItem("openhands-active-backend") ?? "null",
);
- expect(stored).toEqual({ backendId: cloudId, orgId: personalOrgId });
+ expect(stored).toEqual({ backendId: cloudId, orgId: "org-2" });
});
});
diff --git a/__tests__/hooks/query/use-backends-health.test.tsx b/__tests__/hooks/query/use-backends-health.test.tsx
index bc8b11445e..f755a645a7 100644
--- a/__tests__/hooks/query/use-backends-health.test.tsx
+++ b/__tests__/hooks/query/use-backends-health.test.tsx
@@ -24,6 +24,7 @@ import {
const getSettingsMock = vi.fn();
const getServerInfoMock = vi.fn();
const getCurrentCloudApiKeyMock = vi.fn();
+const getCloudOrganizationsMock = vi.fn();
vi.mock("@openhands/typescript-client/clients", () => ({
ServerClient: vi.fn(function ServerClientMock() {
@@ -35,6 +36,8 @@ vi.mock("@openhands/typescript-client/clients", () => ({
}));
vi.mock("#/api/cloud/organization-service.api", () => ({
+ getCloudOrganizations: (...args: unknown[]) =>
+ getCloudOrganizationsMock(...args),
getCurrentCloudApiKey: (...args: unknown[]) =>
getCurrentCloudApiKeyMock(...args),
}));
@@ -67,6 +70,7 @@ beforeEach(() => {
getServerInfoMock.mockReset();
getServerInfoMock.mockResolvedValue({ version: "1.28.0" });
getCurrentCloudApiKeyMock.mockReset();
+ getCloudOrganizationsMock.mockReset();
vi.mocked(ServerClient).mockClear();
vi.mocked(SettingsClient).mockClear();
window.localStorage.clear();
@@ -189,6 +193,26 @@ describe("useBackendsHealth", () => {
expect(getSettingsMock).not.toHaveBeenCalled();
});
+ it("probes cookie-auth cloud backends via organizations without an API key", async () => {
+ const cookieBackend: Backend = {
+ ...cloudBackend,
+ id: "cloud-cookie",
+ apiKey: "",
+ authMode: "cookie",
+ };
+ getCloudOrganizationsMock.mockResolvedValue({ items: [], currentOrgId: null });
+
+ const { result } = renderHook(() => useBackendsHealth([cookieBackend]), {
+ wrapper,
+ });
+
+ await waitFor(() =>
+ expect(result.current[cookieBackend.id].isConnected).toBe(true),
+ );
+ expect(getCloudOrganizationsMock).toHaveBeenCalledWith(cookieBackend);
+ expect(getCurrentCloudApiKeyMock).not.toHaveBeenCalled();
+ });
+
it("reports disconnected when the cloud probe throws", async () => {
getCurrentCloudApiKeyMock.mockRejectedValue(new Error("Network Error"));
diff --git a/__tests__/root.test.tsx b/__tests__/root.test.tsx
index 2eece23d09..fa0ba1d28d 100644
--- a/__tests__/root.test.tsx
+++ b/__tests__/root.test.tsx
@@ -1,7 +1,7 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createRoutesStub } from "react-router";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { http, HttpResponse } from "msw";
import App, { links } from "#/root";
import { server } from "#/mocks/node";
@@ -64,6 +64,8 @@ vi.mock("#/components/features/onboarding/onboarding-modal", async () => {
};
});
+const ORIGINAL_LOCATION = window.location;
+
const RouterStub = createRoutesStub([
{
Component: App,
@@ -112,6 +114,13 @@ describe("App root agent-server availability guard", () => {
__resetActiveStoreForTests();
});
+ afterEach(() => {
+ Object.defineProperty(window, "location", {
+ configurable: true,
+ value: ORIGINAL_LOCATION,
+ });
+ });
+
it("shows first-run onboarding before the auth gate when public mode has no backend key", async () => {
vi.stubEnv("VITE_AUTH_REQUIRED", "true");
vi.stubEnv("VITE_SESSION_API_KEY", "");
@@ -639,6 +648,41 @@ describe("App root agent-server availability guard", () => {
expect(screen.queryByTestId("app-outlet")).not.toBeInTheDocument();
});
+ it("redirects unauthenticated locked-cookie deployments to main app login", async () => {
+ const assign = vi.fn();
+ Object.defineProperty(window, "location", {
+ configurable: true,
+ value: {
+ ...ORIGINAL_LOCATION,
+ origin: "https://pr-254.staging.openhands.dev",
+ hostname: "pr-254.staging.openhands.dev",
+ pathname: "/canvas",
+ search: "?tab=home",
+ hash: "#top",
+ assign,
+ },
+ });
+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://pr-254.staging.all-hands.dev");
+ vi.stubEnv("VITE_SESSION_API_KEY", "");
+ delete (window as unknown as Record<string, unknown>)
+ .__AGENT_CANVAS_SESSION_API_KEY__;
+ server.use(
+ http.post("*/api/authenticate", () =>
+ HttpResponse.json({ error: "unauthenticated" }, { status: 401 }),
+ ),
+ );
+ __resetActiveStoreForTests();
+
+ renderApp(["/"]);
+
+ await waitFor(() => {
+ expect(assign).toHaveBeenCalledWith(
+ "/login?returnTo=%2Fcanvas%3Ftab%3Dhome%23top",
+ );
+ });
+ expect(screen.queryByTestId("app-outlet")).not.toBeInTheDocument();
+ });
+
it("hides first-run onboarding immediately after Cloud login completes in locked-to-Cloud mode (no flicker)", async () => {
// Regression for hieptl's flicker report on PR #1389: after Cloud
// login succeeds in locked-to-Cloud mode, the onboarding modal's
diff --git a/__tests__/routes/root-index-route.test.ts b/__tests__/routes/root-index-route.test.ts
new file mode 100644
index 0000000000..86dc020c7a
--- /dev/null
+++ b/__tests__/routes/root-index-route.test.ts
@@ -0,0 +1,11 @@
+import { describe, expect, it } from "vitest";
+import routes from "#/routes";
+
+describe("root index route", () => {
+ it("renders the home screen at the deployment root without redirecting to /conversations", () => {
+ const rootLayout = routes.find((route) => route.file === "routes/root-layout.tsx");
+ const indexRoute = rootLayout?.children?.find((route) => route.index);
+
+ expect(indexRoute?.file).toBe("routes/index-home.tsx");
+ });
+});
diff --git a/src/api/agent-server-config.ts b/src/api/agent-server-config.ts
index fba4d7c518..923c5b352d 100644
--- a/src/api/agent-server-config.ts
+++ b/src/api/agent-server-config.ts
@@ -1,5 +1,7 @@
export const DEFAULT_WORKING_DIR = "workspace/project";
+export type LockedCloudAuthMode = "api-key" | "cookie";
+
export interface AgentServerFormDefaults {
baseUrl: string;
sessionApiKey: string;
@@ -10,6 +12,11 @@ export interface AgentServerFormDefaults {
// server (`scripts/static-server.mjs`) and its tests reference the literal
// string directly, not this constant.
const LOCK_TO_CLOUD_WINDOW_KEY = "__AGENT_CANVAS_LOCK_TO_CLOUD__";
+const LEGACY_CLOUD_DOMAIN = "all-hands.dev";
+const CURRENT_CLOUD_DOMAIN = "openhands.dev";
+const LEGACY_PRODUCTION_APP_HOST = `app.${LEGACY_CLOUD_DOMAIN}`;
+const CURRENT_PRODUCTION_APP_HOST = CURRENT_CLOUD_DOMAIN;
+const PRODUCTION_APP_HOST_ALIAS = `app.${CURRENT_CLOUD_DOMAIN}`;
function trimToNull(value?: string | null): string | null {
return value?.trim() || null;
@@ -45,6 +52,49 @@ function normalizeCloudHost(value?: string | null): string | null {
return `https://${trimmed}`;
}
+function canonicalizeCloudHostname(hostname: string): string {
+ const lower = hostname.toLowerCase();
+ if (
+ lower === LEGACY_PRODUCTION_APP_HOST ||
+ lower === PRODUCTION_APP_HOST_ALIAS
+ ) {
+ return CURRENT_PRODUCTION_APP_HOST;
+ }
+
+ if (lower === LEGACY_CLOUD_DOMAIN) return CURRENT_CLOUD_DOMAIN;
+ if (lower.endsWith(`.${LEGACY_CLOUD_DOMAIN}`)) {
+ return `${lower.slice(0, -LEGACY_CLOUD_DOMAIN.length)}${CURRENT_CLOUD_DOMAIN}`;
+ }
+
+ return lower;
+}
+
+function getCloudHostComparisonKey(value?: string | null): string | null {
+ const normalized = normalizeCloudHost(value);
+ if (!normalized) return null;
+
+ try {
+ const url = new URL(normalized);
+ const port = url.port ? `:${url.port}` : "";
+ return `${url.protocol}//${canonicalizeCloudHostname(url.hostname)}${port}`;
+ } catch {
+ return normalized.toLowerCase();
+ }
+}
+
+export function getCookieAuthCloudHost(): string | null {
+ const lockedHost = getLockedCloudHost();
+ if (
+ !lockedHost ||
+ typeof window === "undefined" ||
+ !isSameCloudHost(window.location.origin, lockedHost)
+ ) {
+ return null;
+ }
+
+ return window.location.origin;
+}
+
function getConfiguredBaseUrl(): string | null {
return normalizeBaseUrl(import.meta.env.VITE_BACKEND_BASE_URL);
}
@@ -118,10 +168,14 @@ export function isSameCloudHost(
host: string | null | undefined,
lockedHost: string | null | undefined,
): boolean {
- const a = normalizeCloudHost(host);
- const b = normalizeCloudHost(lockedHost);
+ const a = getCloudHostComparisonKey(host);
+ const b = getCloudHostComparisonKey(lockedHost);
if (!a || !b) return false;
- return a.toLowerCase() === b.toLowerCase();
+ return a === b;
+}
+
+export function getLockedCloudAuthMode(): LockedCloudAuthMode {
+ return getCookieAuthCloudHost() ? "cookie" : "api-key";
}
export function getAgentServerBaseUrl(): string | null {
diff --git a/src/api/backend-registry/auth.ts b/src/api/backend-registry/auth.ts
index 6a273cbe33..2d9fb3d1da 100644
--- a/src/api/backend-registry/auth.ts
+++ b/src/api/backend-registry/auth.ts
@@ -7,6 +7,7 @@ import type { Backend } from "./types";
* token in the `Authorization` header.
*/
export function buildAuthHeaders(backend: Backend): Record<string, string> {
+ if (backend.kind === "cloud" && backend.authMode === "cookie") return {};
if (!backend.apiKey) return {};
if (backend.kind === "cloud") {
diff --git a/src/api/backend-registry/default-backend.ts b/src/api/backend-registry/default-backend.ts
index a9a6ba4890..00bd9ba033 100644
--- a/src/api/backend-registry/default-backend.ts
+++ b/src/api/backend-registry/default-backend.ts
@@ -1,6 +1,7 @@
import {
getAgentServerBaseUrl,
getAgentServerSessionApiKey,
+ getCookieAuthCloudHost,
getLockedCloudHost,
} from "../agent-server-config";
import type { Backend } from "./types";
@@ -15,6 +16,24 @@ import type { Backend } from "./types";
export const SEEDED_DEFAULT_BACKEND_ID = "default-local";
export const DEFAULT_LOCAL_BACKEND_NAME = "Local";
+export const LOCKED_CLOUD_BACKEND_ID = "locked-cloud";
+export const LOCKED_CLOUD_BACKEND_NAME = "OpenHands Cloud";
+
+export function makeLockedCloudBackend(): Backend | null {
+ if (!getLockedCloudHost()) return null;
+
+ const host = getCookieAuthCloudHost();
+ if (!host) return null;
+
+ return {
+ id: LOCKED_CLOUD_BACKEND_ID,
+ name: LOCKED_CLOUD_BACKEND_NAME,
+ host,
+ apiKey: "",
+ kind: "cloud",
+ authMode: "cookie",
+ };
+}
/**
* Construct the default local backend from environment/runtime config.
diff --git a/src/api/backend-registry/storage.ts b/src/api/backend-registry/storage.ts
index e2fb656ecb..eb74b4c68c 100644
--- a/src/api/backend-registry/storage.ts
+++ b/src/api/backend-registry/storage.ts
@@ -1,8 +1,14 @@
import {
SEEDED_DEFAULT_BACKEND_ID,
makeDefaultLocalBackend,
+ makeLockedCloudBackend,
} from "./default-backend";
-import type { Backend, BackendKind, BackendSelection } from "./types";
+import type {
+ Backend,
+ BackendAuthMode,
+ BackendKind,
+ BackendSelection,
+} from "./types";
export const BACKENDS_STORAGE_KEY = "openhands-backends";
export const ACTIVE_BACKEND_STORAGE_KEY = "openhands-active-backend";
@@ -11,6 +17,10 @@ function isValidKind(value: unknown): value is BackendKind {
return value === "local" || value === "cloud";
}
+function isValidAuthMode(value: unknown): value is BackendAuthMode {
+ return value === undefined || value === "api-key" || value === "cookie";
+}
+
function isValidBackend(value: unknown): value is Backend {
if (typeof value !== "object" || value === null) return false;
const v = value as Partial<Backend>;
@@ -20,7 +30,8 @@ function isValidBackend(value: unknown): value is Backend {
typeof v.name === "string" &&
typeof v.host === "string" &&
typeof v.apiKey === "string" &&
- isValidKind(v.kind)
+ isValidKind(v.kind) &&
+ isValidAuthMode(v.authMode)
);
}
@@ -90,6 +101,16 @@ export function readStoredBackends(): Backend[] {
if (typeof window === "undefined") return [];
try {
+ const lockedCloudBackend = makeLockedCloudBackend();
+ if (lockedCloudBackend) {
+ writeStoredBackends([lockedCloudBackend]);
+ const activeSelection = readStoredActiveBackend();
+ if (activeSelection?.backendId !== lockedCloudBackend.id) {
+ writeStoredActiveBackend({ backendId: lockedCloudBackend.id });
+ }
+ return [lockedCloudBackend];
+ }
+
const raw = window.localStorage.getItem(BACKENDS_STORAGE_KEY);
// First install: seed only when the launcher supplied enough information
diff --git a/src/api/backend-registry/types.ts b/src/api/backend-registry/types.ts
index fb50708dff..3a3c2e861f 100644
--- a/src/api/backend-registry/types.ts
+++ b/src/api/backend-registry/types.ts
@@ -1,4 +1,5 @@
export type BackendKind = "local" | "cloud";
+export type BackendAuthMode = "api-key" | "cookie";
export interface Backend {
id: string;
@@ -6,6 +7,7 @@ export interface Backend {
host: string;
apiKey: string;
kind: BackendKind;
+ authMode?: BackendAuthMode;
}
export interface BackendSelection {
diff --git a/src/api/main-app-auth.ts b/src/api/main-app-auth.ts
new file mode 100644
index 0000000000..e01ac34706
--- /dev/null
+++ b/src/api/main-app-auth.ts
@@ -0,0 +1,50 @@
+import axios from "axios";
+import { getLockedCloudAuthMode } from "./agent-server-config";
+
+export const MAIN_APP_AUTHENTICATE_PATH = "/api/authenticate";
+export const MAIN_APP_LOGIN_PATH = "/login";
+export const MAIN_APP_LOGIN_REDIRECT_PARAM = "returnTo";
+
+const LOCAL_BROWSER_HOSTNAMES = new Set(["localhost", "127.0.0.1", "::1"]);
+
+function getCurrentPathForRedirect(): string {
+ if (typeof window === "undefined") return "/";
+ return `${window.location.pathname}${window.location.search}${window.location.hash}`;
+}
+
+export function isLocalBrowserHost(): boolean {
+ if (typeof window === "undefined") return false;
+ return LOCAL_BROWSER_HOSTNAMES.has(window.location.hostname);
+}
+
+export function shouldUseMainAppCookieAuth(): boolean {
+ return getLockedCloudAuthMode() === "cookie" && !isLocalBrowserHost();
+}
+
+export async function authenticateWithMainAppCookie(): Promise<boolean> {
+ try {
+ await axios.post(MAIN_APP_AUTHENTICATE_PATH, null, {
+ withCredentials: true,
+ });
+ return true;
+ } catch (error) {
+ if (axios.isAxiosError(error) && error.response?.status === 401) {
+ return false;
+ }
+ throw error;
+ }
+}
+
+export function buildMainAppLoginRedirect(
+ redirectPath = getCurrentPathForRedirect(),
+): string {
+ const params = new URLSearchParams({
+ [MAIN_APP_LOGIN_REDIRECT_PARAM]: redirectPath,
+ });
+ return `${MAIN_APP_LOGIN_PATH}?${params.toString()}`;
+}
+
+export function redirectToMainAppLogin(): void {
+ if (typeof window === "undefined") return;
+ window.location.assign(buildMainAppLoginRedirect());
+}
diff --git a/src/api/no-direct-agent-server-calls.test.ts b/src/api/no-direct-agent-server-calls.test.ts
index d640e898f2..3144c8c1a2 100644
--- a/src/api/no-direct-agent-server-calls.test.ts
+++ b/src/api/no-direct-agent-server-calls.test.ts
@@ -7,6 +7,7 @@ const EXCLUDED_SEGMENTS = new Set(["mocks", "routeTree.gen.ts"]);
const ALLOWED_AD_HOC_HTTP_FILES = new Set([
"api/automation-service/automation-service.api.ts",
"api/cloud/proxy.ts",
+ "api/main-app-auth.ts",
]);
function collectSourceFiles(dir: string): string[] {
diff --git a/src/components/features/backends/backend-selector.tsx b/src/components/features/backends/backend-selector.tsx
index b93b9f6e4f..fca0406602 100644
--- a/src/components/features/backends/backend-selector.tsx
+++ b/src/components/features/backends/backend-selector.tsx
@@ -209,10 +209,10 @@ export function BackendSelector({
// per-org rows for it β€” the `(backendId, null)` row disappears, so
// selecting that shape would drift from what the dropdown can render
// (UI says "Local", APIs hit cloud). When we detect the drift, snap
- // the selection onto the personal-workspace org (or, lacking a /me
- // result, the first org). The selection is recorded locally only;
- // the cloud request scope follows from the API key's bound org and the
- // X-Org-Id header sent by `callCloudProxy`, so the cloud UI's
+ // the selection onto Cloud's current org first, then fall back to the
+ // personal workspace (or, lacking a /me result, the first org). The
+ // selection is recorded locally only; the cloud request scope follows
+ // from the X-Org-Id header sent by `callCloudProxy`, so the cloud UI's
// org choice is never mutated as a side effect.
React.useEffect(() => {
if (noBackendSelected || active.backend.kind !== "cloud" || active.orgId)
@@ -221,11 +221,14 @@ export function BackendSelector({
const entry = cloudOrgs[backend.id];
if (!entry || entry.orgs.length === 0) return;
+ const currentOrg = entry.currentOrgId
+ ? entry.orgs.find((o) => o.id === entry.currentOrgId)
+ : undefined;
const userId = currentUserIds[backend.id]?.userId ?? null;
const personal = userId
? entry.orgs.find((o) => o.id === userId)
: undefined;
- const target = personal ?? entry.orgs[0];
+ const target = currentOrg ?? personal ?? entry.orgs[0];
if (target) {
setActive(backend.id, target.id);
}
diff --git a/src/hooks/query/query-keys.ts b/src/hooks/query/query-keys.ts
index 5bbd11cb0d..16b4af8883 100644
--- a/src/hooks/query/query-keys.ts
+++ b/src/hooks/query/query-keys.ts
@@ -8,6 +8,8 @@ import { SettingsScope } from "#/types/settings";
export const QUERY_KEYS = {
/** Web client configuration from the server */
WEB_CLIENT_CONFIG: ["web-client-config"] as const,
+ /** Same-origin OpenHands app cookie authentication status */
+ MAIN_APP_COOKIE_AUTH: ["main-app-cookie-auth"] as const,
} as const;
export const SETTINGS_QUERY_KEYS = {
diff --git a/src/hooks/query/use-backends-health.ts b/src/hooks/query/use-backends-health.ts
index 1e0c7ac1ee..ded3c0b571 100644
--- a/src/hooks/query/use-backends-health.ts
+++ b/src/hooks/query/use-backends-health.ts
@@ -6,7 +6,10 @@ import {
ServerClient,
SettingsClient,
} from "@openhands/typescript-client/clients";
-import { getCurrentCloudApiKey } from "#/api/cloud/organization-service.api";
+import {
+ getCloudOrganizations,
+ getCurrentCloudApiKey,
+} from "#/api/cloud/organization-service.api";
import {
assertAgentServerVersionIsSupported,
isSdkHttpStatusError,
@@ -52,7 +55,11 @@ export function isCloudBackendApiKeyOrNetworkHealthError(
}
function hasMissingBackendApiKey(backend: Backend): boolean {
- return backend.kind === "cloud" && !backend.apiKey.trim();
+ return (
+ backend.kind === "cloud" &&
+ backend.authMode !== "cookie" &&
+ !backend.apiKey.trim()
+ );
}
export function isCloudBackendLoggedOutHealthError(
@@ -79,12 +86,16 @@ export function isCloudBackendLoggedOutHealthError(
*/
async function probeBackend(backend: Backend): Promise<true> {
if (backend.kind === "cloud") {
- if (!backend.apiKey?.trim()) {
+ if (backend.authMode !== "cookie" && !backend.apiKey?.trim()) {
throw new Error(MISSING_BACKEND_API_KEY_ERROR);
}
try {
- await getCurrentCloudApiKey(backend);
+ if (backend.authMode === "cookie") {
+ await getCloudOrganizations(backend);
+ } else {
+ await getCurrentCloudApiKey(backend);
+ }
} catch (error) {
if (
(axios.isAxiosError(error) && error.response?.status === 401) ||
diff --git a/src/hooks/query/use-cloud-organizations.ts b/src/hooks/query/use-cloud-organizations.ts
index 7263a4801a..4c76d029a1 100644
--- a/src/hooks/query/use-cloud-organizations.ts
+++ b/src/hooks/query/use-cloud-organizations.ts
@@ -26,10 +26,10 @@ export function useAllCloudOrganizations() {
// selector would advertise orgs the key cannot use. Legacy keys
// with no binding fall through unfiltered.
queryFn: async () => {
- const [orgs, key] = await Promise.all([
- getCloudOrganizations(backend),
- getCurrentCloudApiKey(backend),
- ]);
+ const orgs = await getCloudOrganizations(backend);
+ if (backend.authMode === "cookie") return orgs;
+
+ const key = await getCurrentCloudApiKey(backend);
if (key.isLegacyKey || key.orgId === null) return orgs;
return {
...orgs,
@@ -49,6 +49,7 @@ export function useAllCloudOrganizations() {
backend: Backend;
isLoading: boolean;
orgs: { id: string; name: string; is_personal?: boolean }[];
+ currentOrgId: string | null;
}
> = {};
cloudBackends.forEach((backend, index) => {
@@ -57,6 +58,7 @@ export function useAllCloudOrganizations() {
backend,
isLoading: q.isLoading,
orgs: q.data?.items ?? [],
+ currentOrgId: q.data?.currentOrgId ?? null,
};
});
diff --git a/src/root.tsx b/src/root.tsx
index 37bd76a800..006a6c0847 100644
--- a/src/root.tsx
+++ b/src/root.tsx
@@ -13,7 +13,7 @@ import {
import "./tailwind.css";
import "./index.css";
import React from "react";
-import { useQueryClient } from "@tanstack/react-query";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Toaster } from "react-hot-toast";
import {
clearCachedAgentServerInfo,
@@ -21,10 +21,16 @@ import {
isAgentServerAuthError,
} from "#/api/agent-server-compatibility";
import {
+ getLockedCloudAuthMode,
getLockedCloudHost,
isAuthRequiredAndMissing,
isSameCloudHost,
} from "#/api/agent-server-config";
+import {
+ authenticateWithMainAppCookie,
+ redirectToMainAppLogin,
+ shouldUseMainAppCookieAuth,
+} from "#/api/main-app-auth";
import { getEffectiveLocalBackend } from "#/api/backend-registry/active-store";
import { useActiveBackendContext } from "#/contexts/active-backend-context";
import {
@@ -244,6 +250,7 @@ export default function App() {
// onboarding instead of the Manage Backends recovery modal β€” the onboarding
// flow owns the Cloud login that replaces the stale backend.
const lockedCloudHost = getLockedCloudHost();
+ const lockedCloudAuthMode = getLockedCloudAuthMode();
const isLockedToCloud = lockedCloudHost !== null;
// True only when the active backend IS the configured locked Cloud host
// (normalized comparison so trailing slash / case / protocol differences
@@ -273,19 +280,48 @@ export default function App() {
// active suppresses reopen flicker. (The flag is only honored when the
// active backend really is the locked Cloud host, so the stale-flag bypass
// concerns above don't apply here.)
+ const shouldCheckMainAppAuth = shouldUseMainAppCookieAuth();
const showFirstRunOnboarding = isLockedToCloud
- ? !isActiveLockedCloudBackend || !onboardingCompleted
+ ? !shouldCheckMainAppAuth &&
+ (!isActiveLockedCloudBackend ||
+ (lockedCloudAuthMode !== "cookie" && !onboardingCompleted))
: !onboardingCompleted;
+ const mainAppAuth = useQuery({
+ queryKey: QUERY_KEYS.MAIN_APP_COOKIE_AUTH,
+ queryFn: authenticateWithMainAppCookie,
+ enabled: shouldCheckMainAppAuth && !showFirstRunOnboarding,
+ retry: false,
+ staleTime: 1000 * 60 * 5,
+ meta: { disableToast: true },
+ });
+ const waitingForMainAppAuth =
+ shouldCheckMainAppAuth &&
+ !showFirstRunOnboarding &&
+ mainAppAuth.isPending &&
+ !mainAppAuth.isError;
+ const redirectingToMainAppLogin =
+ shouldCheckMainAppAuth && mainAppAuth.data === false;
+ const mainAppAuthAllowsBackendQueries =
+ !shouldCheckMainAppAuth || mainAppAuth.data === true || mainAppAuth.isError;
+
+ React.useEffect(() => {
+ if (redirectingToMainAppLogin) redirectToMainAppLogin();
+ }, [redirectingToMainAppLogin]);
// Skip the /server_info probe entirely when we already know auth is
// required and missing β€” it would just 401 and waste time. Also keep the
// root bootstrap quiet while the first-run onboarding modal owns backend
// collection; the onboarding steps issue their own backend-specific queries.
const config = useConfig({
- enabled: !authMissing && !showFirstRunOnboarding,
+ enabled:
+ !authMissing &&
+ !showFirstRunOnboarding &&
+ mainAppAuthAllowsBackendQueries,
});
const activeCloudHealth = useBackendsHealth(
- active.backend.kind === "cloud" ? [active.backend] : [],
+ active.backend.kind === "cloud" && mainAppAuthAllowsBackendQueries
+ ? [active.backend]
+ : [],
)[active.backend.id];
const activeCloudLoggedOut =
active.backend.kind === "cloud" &&
@@ -305,6 +341,10 @@ export default function App() {
return <FirstRunOnboardingScreen onClose={markCompleted} />;
}
+ if (waitingForMainAppAuth || redirectingToMainAppLogin) {
+ return <AgentServerBootstrapLoading />;
+ }
+
// No key at all after onboarding was skipped/completed β†’ auth screen.
// Stale key β†’ /server_info 401 β†’ auth screen (public mode only).
if (authMissing || isAgentServerAuthError(config.error)) {
diff --git a/src/routes.ts b/src/routes.ts
index c078266a21..a14ef8860d 100644
--- a/src/routes.ts
+++ b/src/routes.ts
@@ -7,7 +7,7 @@ import {
export default [
layout("routes/root-layout.tsx", [
- index("routes/index-redirect.tsx"),
+ index("routes/index-home.tsx"),
route("conversations", "routes/home.tsx"),
route(
"conversations/:conversationId/panel",
diff --git a/src/routes/index-home.tsx b/src/routes/index-home.tsx
new file mode 100644
index 0000000000..ba04027686
--- /dev/null
+++ b/src/routes/index-home.tsx
@@ -0,0 +1 @@
+export { default } from "./home";