Skip to content

The open-source app everyone uses to manage agents at work

feat: make in-app features cloud-aware (#10850)

Dotta5858ccb98171
diff --git a/doc/SPEC-implementation.md b/doc/SPEC-implementation.md
index d6fbcf097d..8c22d9d776 100644
--- a/doc/SPEC-implementation.md
+++ b/doc/SPEC-implementation.md
@@ -883,6 +883,20 @@ All endpoints are under `/api` and return JSON.
- `PATCH /companies/:companyId/branding`
- `POST /companies/:companyId/archive`
+On a Paperclip Cloud-managed instance, `POST /companies` returns `403` with
+code `cloud_managed`; the trusted-header provisioning path and company import
+routes remain the only company-creation paths there.
+
+## 10.1.1 Cloud Stack Portfolio
+
+- `GET /cloud/stacks`
+
+The route exists only on a Cloud-managed instance, requires a trusted
+`cloud_tenant` actor, and proxies the current actor's user id plus the current
+stack id to the Cloud tenant portfolio endpoint. Client-supplied user ids are
+never forwarded. Successful responses are cached briefly per user; self-hosted
+instances return `404`.
+
## 10.2 Goals
- `GET /companies/:companyId/goals`
diff --git a/server/src/__tests__/cloud-instance.test.ts b/server/src/__tests__/cloud-instance.test.ts
new file mode 100644
index 0000000000..dd5097bc69
--- /dev/null
+++ b/server/src/__tests__/cloud-instance.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from "vitest";
+import {
+ getCloudStackContext,
+ isCloudManagedInstance,
+ type CloudInstanceEnv,
+} from "../services/cloud-instance.js";
+
+describe("isCloudManagedInstance", () => {
+ it("unifies both prior signals without weakening either restrictive floor", () => {
+ const cases: CloudInstanceEnv[] = [
+ {},
+ { PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: "tenant-token" },
+ { PAPERCLIP_MANAGED_CONFIG: "" },
+ {
+ PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: "tenant-token",
+ PAPERCLIP_MANAGED_CONFIG: "managed-document",
+ },
+ ];
+
+ for (const env of cases) {
+ const priorTokenFloor = Boolean(env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN?.trim());
+ const priorManagedConfigFloor = env.PAPERCLIP_MANAGED_CONFIG !== undefined;
+ const canonicalFloor = isCloudManagedInstance(env);
+
+ expect(canonicalFloor).toBe(priorTokenFloor || priorManagedConfigFloor);
+ expect(canonicalFloor || !priorTokenFloor).toBe(true);
+ expect(canonicalFloor || !priorManagedConfigFloor).toBe(true);
+ }
+ });
+
+ it("does not treat a blank tenant token alone as a managed signal", () => {
+ expect(isCloudManagedInstance({ PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: " " })).toBe(false);
+ });
+});
+
+describe("getCloudStackContext", () => {
+ it("returns null outside Paperclip Cloud even when stray stack metadata exists", () => {
+ expect(getCloudStackContext({ PAPERCLIP_STACK_SLUG: "stray-stack" })).toBeNull();
+ });
+
+ it("returns normalized provisioner metadata for cloud instances", () => {
+ expect(getCloudStackContext({
+ PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: "tenant-token",
+ PAPERCLIP_CLOUD_STACK_ID: " stack-1 ",
+ PAPERCLIP_STACK_SLUG: " acme ",
+ PAPERCLIP_CLOUD_ACCOUNT_GROUP_ID: " account-group-1 ",
+ PAPERCLIP_PRIMARY_HOST: " acme.paperclip.app ",
+ PAPERCLIP_CLOUD_API_ORIGIN: " https://app.paperclip.app ",
+ })).toEqual({
+ stackId: "stack-1",
+ stackSlug: "acme",
+ accountGroupId: "account-group-1",
+ primaryHost: "acme.paperclip.app",
+ cloudOrigin: "https://app.paperclip.app",
+ });
+ });
+
+ it("represents missing managed metadata explicitly without failing health checks", () => {
+ expect(getCloudStackContext({ PAPERCLIP_MANAGED_CONFIG: "managed-document" })).toEqual({
+ stackId: null,
+ stackSlug: null,
+ accountGroupId: null,
+ primaryHost: null,
+ cloudOrigin: null,
+ });
+ });
+});
diff --git a/server/src/__tests__/cloud-routes.test.ts b/server/src/__tests__/cloud-routes.test.ts
new file mode 100644
index 0000000000..a6453e05a2
--- /dev/null
+++ b/server/src/__tests__/cloud-routes.test.ts
@@ -0,0 +1,149 @@
+import express from "express";
+import request from "supertest";
+import { describe, expect, it, vi } from "vitest";
+import { errorHandler } from "../middleware/index.js";
+import { cloudRoutes } from "../routes/cloud.js";
+
+const cloudEnv = {
+ PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: "tenant-secret",
+ PAPERCLIP_CLOUD_STACK_ID: "stack-current",
+ PAPERCLIP_CLOUD_API_ORIGIN: "https://cloud.example.test/control-plane",
+};
+
+function cloudActor(userId: string) {
+ return {
+ type: "board" as const,
+ source: "cloud_tenant" as const,
+ userId,
+ companyIds: ["company-1"],
+ };
+}
+
+function createApp(options: {
+ actor?: ReturnType<typeof cloudActor> | {
+ type: "board";
+ source: "session";
+ userId: string;
+ };
+ runtimeEnv?: Record<string, string | undefined>;
+ fetchImpl: typeof fetch;
+ now?: () => number;
+}) {
+ const app = express();
+ app.use((req, _res, next) => {
+ (req as any).actor = options.actor ?? cloudActor("actor-user");
+ next();
+ });
+ app.use("/api/cloud", cloudRoutes({
+ runtimeEnv: options.runtimeEnv ?? cloudEnv,
+ fetchImpl: options.fetchImpl,
+ now: options.now,
+ }));
+ app.use(errorHandler);
+ return app;
+}
+
+function jsonResponse(payload: unknown, status = 200) {
+ return new Response(JSON.stringify(payload), {
+ status,
+ headers: { "content-type": "application/json" },
+ });
+}
+
+describe("GET /api/cloud/stacks", () => {
+ it("returns the actor's portfolio without forwarding client-supplied identity", async () => {
+ const portfolio = { stacks: [{ slug: "current", displayName: "Current" }] };
+ const fetchImpl = vi.fn<typeof fetch>().mockResolvedValue(jsonResponse(portfolio));
+ const app = createApp({ fetchImpl });
+
+ const res = await request(app)
+ .get("/api/cloud/stacks?userId=client-supplied-user")
+ .set("x-paperclip-cloud-user-id", "spoofed-header-user")
+ .set("authorization", "Bearer client-token");
+
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual(portfolio);
+ expect(res.headers["cache-control"]).toBe("no-store");
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
+
+ const [url, init] = fetchImpl.mock.calls[0]!;
+ expect(url.toString()).toBe("https://cloud.example.test/v1/tenant/portfolio");
+ expect(init).toMatchObject({ method: "GET" });
+ expect(init?.headers).toEqual({
+ accept: "application/json",
+ authorization: "Bearer tenant-secret",
+ "x-paperclip-cloud-user-id": "actor-user",
+ "x-paperclip-cloud-stack-id": "stack-current",
+ });
+ expect(JSON.stringify(init)).not.toContain("client-supplied-user");
+ expect(JSON.stringify(init)).not.toContain("spoofed-header-user");
+ expect(JSON.stringify(init)).not.toContain("client-token");
+ });
+
+ it("caches successful portfolios per actor for 30 seconds", async () => {
+ let currentTime = 1_000;
+ const fetchImpl = vi.fn<typeof fetch>()
+ .mockResolvedValueOnce(jsonResponse({ generation: 1 }))
+ .mockResolvedValueOnce(jsonResponse({ generation: 2 }));
+ const app = createApp({ fetchImpl, now: () => currentTime });
+
+ const first = await request(app).get("/api/cloud/stacks");
+ currentTime += 29_999;
+ const cached = await request(app).get("/api/cloud/stacks");
+ currentTime += 1;
+ const refreshed = await request(app).get("/api/cloud/stacks");
+
+ expect(first.body).toEqual({ generation: 1 });
+ expect(cached.body).toEqual({ generation: 1 });
+ expect(refreshed.body).toEqual({ generation: 2 });
+ expect(fetchImpl).toHaveBeenCalledTimes(2);
+ });
+
+ it("keeps cache entries isolated by the server-derived actor user id", async () => {
+ const fetchImpl = vi.fn<typeof fetch>().mockImplementation(async (_url, init) => {
+ const headers = new Headers(init?.headers);
+ return jsonResponse({ userId: headers.get("x-paperclip-cloud-user-id") });
+ });
+ const app = express();
+ app.use((req, _res, next) => {
+ const userId = req.header("x-test-actor-user") ?? "user-a";
+ (req as any).actor = cloudActor(userId);
+ next();
+ });
+ app.use("/api/cloud", cloudRoutes({ runtimeEnv: cloudEnv, fetchImpl }));
+ app.use(errorHandler);
+
+ const first = await request(app).get("/api/cloud/stacks").set("x-test-actor-user", "user-a");
+ const second = await request(app).get("/api/cloud/stacks").set("x-test-actor-user", "user-b");
+ const firstAgain = await request(app).get("/api/cloud/stacks").set("x-test-actor-user", "user-a");
+
+ expect(first.body).toEqual({ userId: "user-a" });
+ expect(second.body).toEqual({ userId: "user-b" });
+ expect(firstAgain.body).toEqual({ userId: "user-a" });
+ expect(fetchImpl).toHaveBeenCalledTimes(2);
+ });
+
+ it("returns 404 on self-hosted instances without calling upstream", async () => {
+ const fetchImpl = vi.fn<typeof fetch>();
+ const app = createApp({ runtimeEnv: {}, fetchImpl });
+
+ const res = await request(app).get("/api/cloud/stacks");
+
+ expect(res.status).toBe(404);
+ expect(fetchImpl).not.toHaveBeenCalled();
+ });
+
+ it("rejects non-tenant actors on managed instances without calling upstream", async () => {
+ const fetchImpl = vi.fn<typeof fetch>();
+ const app = createApp({
+ actor: { type: "board", source: "session", userId: "session-user" },
+ fetchImpl,
+ });
+
+ const res = await request(app).get("/api/cloud/stacks");
+
+ expect(res.status).toBe(403);
+ expect(res.body.code).toBe("cloud_tenant_required");
+ expect(fetchImpl).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/src/__tests__/company-cloud-floor.test.ts b/server/src/__tests__/company-cloud-floor.test.ts
new file mode 100644
index 0000000000..bb39a87a77
--- /dev/null
+++ b/server/src/__tests__/company-cloud-floor.test.ts
@@ -0,0 +1,124 @@
+import express from "express";
+import request from "supertest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mockCompanyService = vi.hoisted(() => ({
+ create: vi.fn(),
+}));
+
+const mockAccessService = vi.hoisted(() => ({
+ ensureMembership: vi.fn(),
+ ensureRoleDefaultGrants: vi.fn(),
+}));
+
+const mockBudgetService = vi.hoisted(() => ({
+ upsertPolicy: vi.fn(),
+}));
+
+const mockLogActivity = vi.hoisted(() => vi.fn());
+
+vi.mock("../services/index.js", () => ({
+ accessService: () => mockAccessService,
+ agentService: () => ({}),
+ budgetService: () => mockBudgetService,
+ companyArtifactsService: () => ({}),
+ companyPortabilityService: () => ({}),
+ companyService: () => mockCompanyService,
+ feedbackService: () => ({}),
+ logActivity: mockLogActivity,
+ workTimelineService: () => ({}),
+}));
+
+const createdCompany = {
+ id: "company-new",
+ name: "New Company",
+ budgetMonthlyCents: 0,
+};
+
+async function createApp(actor: Record<string, unknown>) {
+ const [{ companyRoutes }, { errorHandler }] = await Promise.all([
+ import("../routes/companies.js"),
+ import("../middleware/index.js"),
+ ]);
+ const app = express();
+ app.use(express.json());
+ app.use((req, _res, next) => {
+ (req as any).actor = actor;
+ next();
+ });
+ app.use("/api/companies", companyRoutes({} as any));
+ app.use(errorHandler);
+ return app;
+}
+
+describe("POST /api/companies Cloud floor", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ delete process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN;
+ delete process.env.PAPERCLIP_MANAGED_CONFIG;
+ mockCompanyService.create.mockResolvedValue(createdCompany);
+ });
+
+ afterEach(() => {
+ delete process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN;
+ delete process.env.PAPERCLIP_MANAGED_CONFIG;
+ });
+
+ it("returns 403 cloud_managed before creating a second company on Cloud", async () => {
+ process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN = "tenant-secret";
+ const app = await createApp({
+ type: "board",
+ source: "cloud_tenant",
+ userId: "cloud-user",
+ isInstanceAdmin: true,
+ });
+
+ const res = await request(app).post("/api/companies").send({ name: "Second Company" });
+
+ expect(res.status).toBe(403);
+ expect(res.body).toMatchObject({ code: "cloud_managed" });
+ expect(mockCompanyService.create).not.toHaveBeenCalled();
+ expect(mockAccessService.ensureMembership).not.toHaveBeenCalled();
+ });
+
+ it("applies the Cloud floor before request-body validation", async () => {
+ process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN = "tenant-secret";
+ const app = await createApp({
+ type: "board",
+ source: "cloud_tenant",
+ userId: "cloud-user",
+ isInstanceAdmin: true,
+ });
+
+ const res = await request(app).post("/api/companies").send({ name: "" });
+
+ expect(res.status).toBe(403);
+ expect(res.body).toMatchObject({ code: "cloud_managed" });
+ expect(mockCompanyService.create).not.toHaveBeenCalled();
+ });
+
+ it("preserves self-hosted company creation", async () => {
+ const app = await createApp({
+ type: "board",
+ source: "local_implicit",
+ userId: "local-user",
+ isInstanceAdmin: true,
+ });
+
+ const res = await request(app).post("/api/companies").send({ name: "New Company" });
+
+ expect(res.status).toBe(201);
+ expect(res.body).toEqual(createdCompany);
+ expect(mockCompanyService.create).toHaveBeenCalledWith(expect.objectContaining({
+ name: "New Company",
+ defaultResponsibleUserId: "local-user",
+ }));
+ expect(mockAccessService.ensureMembership).toHaveBeenCalledWith(
+ "company-new",
+ "user",
+ "local-user",
+ "owner",
+ "active",
+ );
+ });
+});
diff --git a/server/src/__tests__/company-portability-routes.test.ts b/server/src/__tests__/company-portability-routes.test.ts
index 9a06ba9f5a..010d4e2b21 100644
--- a/server/src/__tests__/company-portability-routes.test.ts
+++ b/server/src/__tests__/company-portability-routes.test.ts
@@ -859,24 +859,29 @@ describe.sequential("company portability routes", () => {
expect(mockLogActivity).not.toHaveBeenCalled();
});
- it.sequential("keeps global import apply synchronous when Cloud async opt-in is absent", async () => {
+ it.sequential("keeps Cloud-managed global import apply synchronous when async opt-in is absent", async () => {
+ vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "tenant-secret");
mockCompanyPortabilityService.importBundle.mockResolvedValueOnce(createImportResult("created"));
- const app = await createApp(cloudTenantActor());
+ try {
+ const app = await createApp(cloudTenantActor());
- const res = await request(app)
- .post("/api/companies/import")
- .set(cloudHeaders)
- .send(importRequest);
+ const res = await request(app)
+ .post("/api/companies/import")
+ .set(cloudHeaders)
+ .send(importRequest);
- expect(res.status).toBe(200);
- expect(res.body.company.id).toBe(companyId);
- expect(res.body.company.action).toBe("created");
- expect(res.body.job).toBeUndefined();
- expect(mockCompanyPortabilityService.importBundle).toHaveBeenCalledWith(importRequest, "cloud-user-1", { pauseAutomations: false });
- expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
- action: "company.imported",
- companyId,
- }));
+ expect(res.status).toBe(200);
+ expect(res.body.company.id).toBe(companyId);
+ expect(res.body.company.action).toBe("created");
+ expect(res.body.job).toBeUndefined();
+ expect(mockCompanyPortabilityService.importBundle).toHaveBeenCalledWith(importRequest, "cloud-user-1", { pauseAutomations: false });
+ expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
+ action: "company.imported",
+ companyId,
+ }));
+ } finally {
+ vi.unstubAllEnvs();
+ }
});
it.sequential("forwards pauseAutomations from the global import body to the portability service", async () => {
diff --git a/server/src/__tests__/health.test.ts b/server/src/__tests__/health.test.ts
index eabeca9711..a3551f568b 100644
--- a/server/src/__tests__/health.test.ts
+++ b/server/src/__tests__/health.test.ts
@@ -44,6 +44,7 @@ function createApp(
db?: Db,
serverInfo = testServerInfo,
databaseBackupHealth?: Parameters<typeof healthRoutes>[1]["databaseBackupHealth"],
+ runtimeEnv?: Parameters<typeof healthRoutes>[1]["runtimeEnv"],
) {
const app = express();
app.use(
@@ -55,6 +56,7 @@ function createApp(
companyDeletionEnabled: true,
serverInfo,
databaseBackupHealth,
+ runtimeEnv,
}),
);
return app;
@@ -77,6 +79,43 @@ describe("GET /health", () => {
expect(res.body).toEqual({ status: "ok", version: serverVersion, serverVersion: serverVersion, commit: testServerInfo.git.fullSha, serverInfo: testServerInfo });
}, 15_000);
+ it("keeps the self-hosted health response byte-identical and omits cloud", async () => {
+ const app = createApp(undefined, testServerInfo, undefined, {});
+
+ const res = await request(app).get("/health");
+
+ const baseline = {
+ status: "ok",
+ version: serverVersion,
+ serverVersion,
+ commit: testServerInfo.git.fullSha,
+ serverInfo: testServerInfo,
+ };
+ expect(res.text).toBe(JSON.stringify(baseline));
+ expect(Object.prototype.hasOwnProperty.call(res.body, "cloud")).toBe(false);
+ });
+
+ it("exposes public stack metadata on cloud-simulated health", async () => {
+ const app = createApp(undefined, testServerInfo, undefined, {
+ PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: "tenant-token",
+ PAPERCLIP_CLOUD_STACK_ID: "stack-1",
+ PAPERCLIP_STACK_SLUG: "acme",
+ PAPERCLIP_CLOUD_ACCOUNT_GROUP_ID: "account-group-1",
+ PAPERCLIP_PRIMARY_HOST: "acme.paperclip.app",
+ PAPERCLIP_CLOUD_API_ORIGIN: "https://app.paperclip.app",
+ });
+
+ const res = await request(app).get("/health");
+
+ expect(res.status).toBe(200);
+ expect(res.body.cloud).toEqual({
+ managed: true,
+ managedBy: "paperclip-cloud",
+ stackSlug: "acme",
+ cloudBaseUrl: "https://app.paperclip.app",
+ });
+ });
+
it("returns 200 when the database probe succeeds", async () => {
const db = {
execute: vi.fn().mockResolvedValue([{ "?column?": 1 }]),
diff --git a/server/src/__tests__/openapi-routes.test.ts b/server/src/__tests__/openapi-routes.test.ts
index dde802657f..ebacf4ebfe 100644
--- a/server/src/__tests__/openapi-routes.test.ts
+++ b/server/src/__tests__/openapi-routes.test.ts
@@ -21,6 +21,7 @@ const apiPrefixes: Record<string, string> = {
"auth.ts": "/api/auth",
"board-chat.ts": "/api",
"built-in-agents.ts": "/api",
+ "cloud.ts": "/api/cloud",
"companies.ts": "/api/companies",
"company-skills.ts": "/api",
"company-skill-policy.ts": "/api",
diff --git a/server/src/app.ts b/server/src/app.ts
index ed7b19da14..581aa2baa5 100644
--- a/server/src/app.ts
+++ b/server/src/app.ts
@@ -12,6 +12,7 @@ import { boardMutationGuard } from "./middleware/board-mutation-guard.js";
import { privateHostnameGuard, resolvePrivateHostnameAllowSet } from "./middleware/private-hostname-guard.js";
import { applyTrustProxy, parseTrustProxyEnv } from "./middleware/trust-proxy.js";
import { healthRoutes } from "./routes/health.js";
+import { cloudRoutes } from "./routes/cloud.js";
import { companyRoutes } from "./routes/companies.js";
import { companySkillRoutes } from "./routes/company-skills.js";
import { companySkillPolicyRoutes } from "./routes/company-skill-policy.js";
@@ -366,6 +367,7 @@ export async function createApp(
}),
);
api.use(openApiRoutes());
+ api.use("/cloud", cloudRoutes());
api.use("/companies", companyRoutes(db, opts.storageService));
api.use(llmRoutes(db));
api.use(folderRoutes(db));
diff --git a/server/src/middleware/auth.ts b/server/src/middleware/auth.ts
index c00e6ffbd6..b8a0ee9b75 100644
--- a/server/src/middleware/auth.ts
+++ b/server/src/middleware/auth.ts
@@ -21,6 +21,8 @@ import { instanceSettingsService } from "../services/instance-settings.js";
import { ensureHumanRoleDefaultGrants } from "../services/principal-access-compatibility.js";
import { forbidden, unprocessable } from "../errors.js";
+export { isCloudManagedInstance } from "../services/cloud-instance.js";
+
function hashToken(token: string) {
return createHash("sha256").update(token).digest("hex");
}
@@ -385,22 +387,6 @@ export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHa
};
}
-/**
- * Whether this instance is managed by a Paperclip Cloud control plane.
- * When the tenant server token is configured, the control plane owns the
- * user/identity lifecycle for this instance: users arrive through trusted
- * headers (resolveCloudTenantActor) and are deliberately never granted the
- * `instance_admin` DB role. The only elevation a cloud tenant can carry is
- * computed per request at the trusted-header boundary (owner stack role +
- * the `enableOwnerInstanceAdmin` flag) and floored by code on
- * platform-owned surfaces. Surfaces that assume a self-hosted operator
- * will claim the instance (e.g. the first-admin bootstrap gate) should
- * treat a cloud-managed instance as already set up.
- */
-export function isCloudManagedInstance(): boolean {
- return Boolean(process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN?.trim());
-}
-
/**
* Whether the trusted-header actor being resolved should carry computed
* instance-admin elevation: only the stack `owner` role elevates, and only
diff --git a/server/src/routes/adapters.ts b/server/src/routes/adapters.ts
index fe0d6d6cbf..4be1b5115d 100644
--- a/server/src/routes/adapters.ts
+++ b/server/src/routes/adapters.ts
@@ -44,7 +44,7 @@ import type { ServerAdapterModule, AdapterConfigSchema } from "../adapters/types
import { loadExternalAdapterPackage, getUiParserSource, getOrExtractUiParserSource, reloadExternalAdapter } from "../adapters/plugin-loader.js";
import { logger } from "../middleware/logger.js";
import { forbidden } from "../errors.js";
-import { isCloudManagedInstance } from "../middleware/auth.js";
+import { isCloudManagedInstance } from "../services/cloud-instance.js";
import { assertBoardOrgAccess, assertInstanceAdmin } from "./authz.js";
import { BUILTIN_ADAPTER_TYPES } from "../adapters/builtin-adapter-types.js";
diff --git a/server/src/routes/cloud.ts b/server/src/routes/cloud.ts
new file mode 100644
index 0000000000..0b4aefc8fc
--- /dev/null
+++ b/server/src/routes/cloud.ts
@@ -0,0 +1,118 @@
+import { Router } from "express";
+import { forbidden, HttpError, notFound } from "../errors.js";
+import { logger } from "../middleware/logger.js";
+import {
+ getCloudStackContext,
+ type CloudInstanceEnv,
+} from "../services/cloud-instance.js";
+
+const DEFAULT_PORTFOLIO_CACHE_TTL_MS = 30_000;
+const CLOUD_PORTFOLIO_PATH = "/v1/tenant/portfolio";
+
+type PortfolioCacheEntry = {
+ expiresAt: number;
+ payload: unknown;
+};
+
+export function cloudRoutes(opts: {
+ runtimeEnv?: CloudInstanceEnv;
+ fetchImpl?: typeof fetch;
+ now?: () => number;
+ cacheTtlMs?: number;
+} = {}) {
+ const router = Router();
+ const runtimeEnv = opts.runtimeEnv ?? process.env;
+ const fetchImpl = opts.fetchImpl ?? fetch;
+ const now = opts.now ?? Date.now;
+ const cacheTtlMs = opts.cacheTtlMs ?? DEFAULT_PORTFOLIO_CACHE_TTL_MS;
+ const portfolioCache = new Map<string, PortfolioCacheEntry>();
+
+ router.get("/stacks", async (req, res) => {
+ const context = getCloudStackContext(runtimeEnv);
+ if (!context) {
+ throw notFound("Cloud stack portfolio is unavailable");
+ }
+ if (req.actor.source !== "cloud_tenant" || !req.actor.userId?.trim()) {
+ throw forbidden("Trusted Cloud tenant access required", {
+ code: "cloud_tenant_required",
+ });
+ }
+
+ const tenantToken = runtimeEnv.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN?.trim();
+ if (!context.cloudOrigin || !context.stackId || !tenantToken) {
+ throw new HttpError(503, "Paperclip Cloud portfolio is not configured", {
+ code: "cloud_portfolio_not_configured",
+ });
+ }
+
+ const actorUserId = req.actor.userId.trim();
+ const cacheKey = `${context.cloudOrigin}\n${context.stackId}\n${actorUserId}`;
+ const currentTime = now();
+ for (const [key, entry] of portfolioCache) {
+ if (entry.expiresAt <= currentTime) portfolioCache.delete(key);
+ }
+ const cached = portfolioCache.get(cacheKey);
+ if (cached) {
+ res.setHeader("Cache-Control", "no-store");
+ res.json(cached.payload);
+ return;
+ }
+
+ let portfolioUrl: URL;
+ try {
+ portfolioUrl = new URL(CLOUD_PORTFOLIO_PATH, context.cloudOrigin);
+ } catch {
+ throw new HttpError(503, "Paperclip Cloud portfolio is not configured", {
+ code: "cloud_portfolio_not_configured",
+ });
+ }
+
+ try {
+ const upstream = await fetchImpl(portfolioUrl, {
+ method: "GET",
+ headers: {
+ accept: "application/json",
+ authorization: `Bearer ${tenantToken}`,
+ "x-paperclip-cloud-user-id": actorUserId,
+ "x-paperclip-cloud-stack-id": context.stackId,
+ },
+ signal: AbortSignal.timeout(10_000),
+ });
+ if (!upstream.ok) {
+ logger.warn(
+ { status: upstream.status, stackId: context.stackId },
+ "Paperclip Cloud portfolio request failed",
+ );
+ throw new HttpError(502, "Paperclip Cloud portfolio request failed", {
+ code: "cloud_portfolio_upstream_error",
+ });
+ }
+
+ let payload: unknown;
+ try {
+ payload = await upstream.json();
+ } catch {
+ throw new HttpError(502, "Paperclip Cloud portfolio returned invalid JSON", {
+ code: "cloud_portfolio_invalid_response",
+ });
+ }
+ portfolioCache.set(cacheKey, {
+ expiresAt: currentTime + cacheTtlMs,
+ payload,
+ });
+ res.setHeader("Cache-Control", "no-store");
+ res.json(payload);
+ } catch (error) {
+ if (error instanceof HttpError) throw error;
+ logger.warn(
+ { err: error, stackId: context.stackId },
+ "Paperclip Cloud portfolio request failed",
+ );
+ throw new HttpError(502, "Paperclip Cloud portfolio request failed", {
+ code: "cloud_portfolio_upstream_error",
+ });
+ }
+ });
+
+ return router;
+}
diff --git a/server/src/routes/companies.ts b/server/src/routes/companies.ts
index 516ac95d29..19686def29 100644
--- a/server/src/routes/companies.ts
+++ b/server/src/routes/companies.ts
@@ -36,6 +36,7 @@ import {
logActivity,
workTimelineService,
} from "../services/index.js";
+import { isCloudManagedInstance } from "../services/cloud-instance.js";
import type { StorageService } from "../storage/types.js";
import { assertBoard, assertCompanyAccess, assertInstanceAdmin, getActorInfo } from "./authz.js";
import { COMPANY_IMPORT_ROUTE_PATH } from "./company-import-paths.js";
@@ -580,7 +581,15 @@ export function companyRoutes(db: Db, storage?: StorageService) {
res.json(result);
});
- router.post("/", validate(createCompanySchema), async (req, res) => {
+ router.post("/", (req, _res, next) => {
+ assertBoard(req);
+ if (isCloudManagedInstance()) {
+ throw forbidden("Company creation is managed by Paperclip Cloud", {
+ code: "cloud_managed",
+ });
+ }
+ next();
+ }, validate(createCompanySchema), async (req, res) => {
assertBoard(req);
if (!(req.actor.source === "local_implicit" || req.actor.isInstanceAdmin)) {
throw forbidden("Instance admin required");
diff --git a/server/src/routes/environments.ts b/server/src/routes/environments.ts
index 087b60c532..3de0bac7b1 100644
--- a/server/src/routes/environments.ts
+++ b/server/src/routes/environments.ts
@@ -15,7 +15,7 @@ import {
updateEnvironmentSchema,
} from "@paperclipai/shared";
import { conflict, forbidden, unprocessable } from "../errors.js";
-import { isCloudManagedInstance } from "../middleware/auth.js";
+import { isCloudManagedInstance } from "../services/cloud-instance.js";
import { getManagedInstanceConfig, SECRET_LIKE_CONFIG_KEY_PATTERN } from "../services/managed-config.js";
import { parseExecutionPolicyBootstrapEnv } from "../services/execution-policy-bootstrap.js";
import { isExecutionForcedToKubernetes } from "../services/execution-allowlist.js";
diff --git a/server/src/routes/health.ts b/server/src/routes/health.ts
index c7ac588407..f81f9098a8 100644
--- a/server/src/routes/health.ts
+++ b/server/src/routes/health.ts
@@ -5,9 +5,13 @@ import { and, count, eq, gt, inArray, isNull, sql } from "drizzle-orm";
import { heartbeatRuns, instanceUserRoles, invites } from "@paperclipai/db";
import type { DeploymentExposure, DeploymentMode } from "@paperclipai/shared";
import { readPersistedDevServerStatus, toDevServerHealthStatus, writeDevServerRestartRequest } from "../dev-server-status.js";
-import { isCloudManagedInstance } from "../middleware/auth.js";
import { logger } from "../middleware/logger.js";
import { getServerInfoSnapshot, type ServerInfoSnapshot } from "../server-info.js";
+import {
+ getCloudStackContext,
+ isCloudManagedInstance,
+ type CloudInstanceEnv,
+} from "../services/cloud-instance.js";
import {
inspectDatabaseBackupHealth,
type DatabaseBackupHealthStatus,
@@ -57,6 +61,18 @@ function redactedDatabaseBackupHealth(databaseBackup: DatabaseBackupHealthStatus
};
}
+function getCloudHealthStatus(env: CloudInstanceEnv) {
+ const context = getCloudStackContext(env);
+ if (!context) return undefined;
+
+ return {
+ managed: true as const,
+ managedBy: "paperclip-cloud" as const,
+ stackSlug: context.stackSlug,
+ cloudBaseUrl: context.cloudOrigin,
+ };
+}
+
export function healthRoutes(
db?: Db,
opts: {
@@ -66,6 +82,7 @@ export function healthRoutes(
companyDeletionEnabled: boolean;
serverInfo?: ServerInfoSnapshot;
databaseBackupHealth?: InspectDatabaseBackupHealthOptions;
+ runtimeEnv?: CloudInstanceEnv;
} = {
deploymentMode: "local_trusted",
deploymentExposure: "private",
@@ -115,6 +132,8 @@ export function healthRoutes(
actorType,
opts.deploymentMode,
);
+ const runtimeEnv = opts.runtimeEnv ?? process.env;
+ const cloud = getCloudHealthStatus(runtimeEnv);
// serverInfo (git SHA + process start) rides on the full-details responses
// only, so it reaches board/agent actors in authenticated mode or any caller
// in local_trusted dev — never anonymous authenticated callers. The
@@ -132,8 +151,20 @@ export function healthRoutes(
if (!db) {
res.json(
exposeFullDetails
- ? { status: "ok", version: serverVersion, serverVersion: serverVersion, commit, serverInfo }
- : { status: "ok", deploymentMode: opts.deploymentMode, commit },
+ ? {
+ status: "ok",
+ version: serverVersion,
+ serverVersion: serverVersion,
+ commit,
+ serverInfo,
+ ...(cloud ? { cloud } : {}),
+ }
+ : {
+ status: "ok",
+ deploymentMode: opts.deploymentMode,
+ commit,
+ ...(cloud ? { cloud } : {}),
+ },
);
return;
}
@@ -149,6 +180,7 @@ export function healthRoutes(
commit,
error: "database_unreachable",
...(exposeFullDetails ? { serverInfo } : {}),
+ ...(cloud ? { cloud } : {}),
});
return;
}
@@ -159,9 +191,9 @@ export function healthRoutes(
// plane owns identity and its trusted-header users are deliberately
// never instance_admin, so the role-count gate below would report
// bootstrap_pending forever and lock every managed tenant out at the
- // claim screen. Self-hosted deployments (no tenant server token) are
- // unaffected.
- if (opts.deploymentMode === "authenticated" && !isCloudManagedInstance()) {
+ // claim screen. Self-hosted deployments (neither canonical managed signal)
+ // are unaffected.
+ if (opts.deploymentMode === "authenticated" && !isCloudManagedInstance(runtimeEnv)) {
const roleCount = await db
.select({ count: count() })
.from(instanceUserRoles)
@@ -222,6 +254,7 @@ export function healthRoutes(
...(redactedDatabaseBackup ? { databaseBackup: redactedDatabaseBackup } : {}),
...(redactedWarnings ? { warnings: redactedWarnings } : {}),
...(devServer ? { devServer } : {}),
+ ...(cloud ? { cloud } : {}),
});
return;
}
@@ -243,6 +276,7 @@ export function healthRoutes(
...(databaseBackup ? { databaseBackup } : {}),
...(warnings ? { warnings } : {}),
...(devServer ? { devServer } : {}),
+ ...(cloud ? { cloud } : {}),
});
});
diff --git a/server/src/routes/instance-database-backups.ts b/server/src/routes/instance-database-backups.ts
index 641881c5e5..f05e3361c2 100644
--- a/server/src/routes/instance-database-backups.ts
+++ b/server/src/routes/instance-database-backups.ts
@@ -1,7 +1,7 @@
import { Router } from "express";
import type { BackupRetentionPolicy, RunDatabaseBackupResult } from "@paperclipai/db";
import { forbidden } from "../errors.js";
-import { isCloudManagedInstance } from "../middleware/auth.js";
+import { isCloudManagedInstance } from "../services/cloud-instance.js";
import { assertInstanceAdmin } from "./authz.js";
export type InstanceDatabaseBackupTrigger = "manual" | "scheduled";
diff --git a/server/src/routes/instance-settings.ts b/server/src/routes/instance-settings.ts
index 405f1817c4..6ac4f96b55 100644
--- a/server/src/routes/instance-settings.ts
+++ b/server/src/routes/instance-settings.ts
@@ -7,7 +7,7 @@ import {
patchInstanceGeneralSettingsSchema,
} from "@paperclipai/shared";
import { forbidden } from "../errors.js";
-import { isCloudManagedInstance } from "../middleware/auth.js";
+import { isCloudManagedInstance } from "../services/cloud-instance.js";
import { validate } from "../middleware/validate.js";
import { heartbeatService, instanceSettingsService, logActivity } from "../services/index.js";
import { environmentService } from "../services/environments.js";
diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts
index 76edac50a7..4302a73938 100644
--- a/server/src/routes/openapi.ts
+++ b/server/src/routes/openapi.ts
@@ -759,6 +759,7 @@ const BOARD_ONLY_PREFIXES = [
];
const BOARD_ONLY_OPERATIONS = new Set([
+ "GET /api/cloud/stacks",
"GET /api/companies",
"POST /api/companies",
"GET /api/companies/stats",
@@ -1115,6 +1116,13 @@ registry.registerPath({
// unavailable. Present on every response shape, including redacted ones.
commit: z.string().nullable(),
deploymentMode: z.string().optional(),
+ cloud: z.object({
+ managed: z.literal(true),
+ managedBy: z.literal("paperclip-cloud"),
+ stackSlug: z.string().nullable(),
+ stackDisplayName: z.string().optional(),
+ cloudBaseUrl: z.string().nullable(),
+ }).strict().optional(),
bootstrapStatus: z.enum(["ready", "bootstrap_pending"]).optional(),
bootstrapInviteActive: z.boolean().optional(),
databaseBackup: z.object({
@@ -1181,6 +1189,21 @@ registry.registerPath({
// ─── Companies ───────────────────────────────────────────────────────────────
+registry.registerPath({
+ method: "get",
+ path: "/api/cloud/stacks",
+ tags: ["cloud"],
+ summary: "List the current Cloud tenant user's stacks",
+ responses: {
+ 200: r.ok(),
+ 403: r.forbidden,
+ 404: r.notFound,
+ 502: r.serverError,
+ 503: r.serverError,
+ 500: r.serverError,
+ },
+});
+
registry.registerPath({
method: "get",
path: "/api/companies",
diff --git a/server/src/routes/plugins.ts b/server/src/routes/plugins.ts
index 54681c5818..17f1823725 100644
--- a/server/src/routes/plugins.ts
+++ b/server/src/routes/plugins.ts
@@ -86,9 +86,9 @@ import {
} from "../services/plugin-secrets-handler.js";
import {
canonicalizeLocalPluginPath,
- isCloudManagedInstance,
isWithinBundledPluginRoot,
} from "../services/plugin-install-guard.js";
+import { isCloudManagedInstance } from "../services/cloud-instance.js";
import { secretService } from "../services/secrets.js";
import { badRequest, forbidden, notFound, unauthorized, unprocessable } from "../errors.js";
diff --git a/server/src/services/cloud-instance.ts b/server/src/services/cloud-instance.ts
new file mode 100644
index 0000000000..e6825dda77
--- /dev/null
+++ b/server/src/services/cloud-instance.ts
@@ -0,0 +1,52 @@
+export type CloudInstanceEnv = Record<string, string | undefined>;
+
+export type CloudStackContext = {
+ stackId: string | null;
+ stackSlug: string | null;
+ accountGroupId: string | null;
+ primaryHost: string | null;
+ cloudOrigin: string | null;
+};
+
+function normalizeOptionalEnvValue(value: string | undefined): string | null {
+ const normalized = value?.trim();
+ return normalized ? normalized : null;
+}
+
+/**
+ * The canonical Paperclip Cloud instance predicate.
+ *
+ * The tenant token is the signal injected on live cloud stacks. The managed
+ * config document is the legacy/bootstrap signal used by managed feature and
+ * plugin floors. Their union is intentionally monotonic: either prior signal
+ * keeps every restrictive cloud floor enabled.
+ */
+export function isCloudManagedInstance(
+ env: CloudInstanceEnv = process.env,
+): boolean {
+ return (
+ normalizeOptionalEnvValue(env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN) !== null ||
+ env.PAPERCLIP_MANAGED_CONFIG !== undefined
+ );
+}
+
+/**
+ * Public stack metadata injected by the Paperclip Cloud provisioner.
+ *
+ * A managed signal can exist briefly before every metadata value is available,
+ * so absent or blank values are represented as null rather than making health
+ * checks fail. Self-hosted instances never expose a stack context.
+ */
+export function getCloudStackContext(
+ env: CloudInstanceEnv = process.env,
+): CloudStackContext | null {
+ if (!isCloudManagedInstance(env)) return null;
+
+ return {
+ stackId: normalizeOptionalEnvValue(env.PAPERCLIP_CLOUD_STACK_ID),
+ stackSlug: normalizeOptionalEnvValue(env.PAPERCLIP_STACK_SLUG),
+ accountGroupId: normalizeOptionalEnvValue(env.PAPERCLIP_CLOUD_ACCOUNT_GROUP_ID),
+ primaryHost: normalizeOptionalEnvValue(env.PAPERCLIP_PRIMARY_HOST),
+ cloudOrigin: normalizeOptionalEnvValue(env.PAPERCLIP_CLOUD_API_ORIGIN),
+ };
+}
diff --git a/server/src/services/environments.ts b/server/src/services/environments.ts
index 27ac64494f..3cfb7b38f2 100644
--- a/server/src/services/environments.ts
+++ b/server/src/services/environments.ts
@@ -28,7 +28,7 @@ import {
type UpdateEnvironment,
} from "@paperclipai/shared";
import { conflict } from "../errors.js";
-import { isCloudManagedInstance } from "../middleware/auth.js";
+import { isCloudManagedInstance } from "./cloud-instance.js";
type EnvironmentRow = typeof environments.$inferSelect;
type EnvironmentLeaseRow = typeof environmentLeases.$inferSelect;
diff --git a/server/src/services/plugin-install-guard.ts b/server/src/services/plugin-install-guard.ts
index 63497e3b4f..470ccbd6eb 100644
--- a/server/src/services/plugin-install-guard.ts
+++ b/server/src/services/plugin-install-guard.ts
@@ -28,31 +28,7 @@ import { realpath, stat } from "node:fs/promises";
import path from "node:path";
import { BUNDLED_LOCAL_PLUGIN_ROOT } from "./plugin-loader.js";
-/**
- * Environment key carrying the harness-injected managed-instance document.
- *
- * The full document contract (`mode: "cloud"`, feature overlay, plugin
- * auto-install list) is parsed fail-closed elsewhere at startup; this module
- * only cares about the variable's presence.
- */
-export const MANAGED_CONFIG_ENV_KEY = "PAPERCLIP_MANAGED_CONFIG";
-
-/**
- * Whether this instance is managed by the Paperclip Cloud harness.
- *
- * Deliberately presence-based rather than content-based: the strict startup
- * parser refuses to boot a managed instance with a malformed document, and
- * absent env means self-hosted. Deciding the security floor on presence
- * alone means a corrupted, truncated, or attacker-influenced document can
- * never *disable* the floor — the failure mode is closed, not open.
- *
- * @param env - Raw environment map (injectable for tests; defaults to `process.env`)
- */
-export function isCloudManagedInstance(
- env: Record<string, string | undefined> = process.env,
-): boolean {
- return env[MANAGED_CONFIG_ENV_KEY] !== undefined;
-}
+export { isCloudManagedInstance } from "./cloud-instance.js";
/** Result of canonicalizing a requested local plugin install path. */
export type LocalPluginPathValidation =
diff --git a/tests/e2e/sidebar-takeover.spec.ts b/tests/e2e/sidebar-takeover.spec.ts
index 7371b8ba42..ffbfa746ba 100644
--- a/tests/e2e/sidebar-takeover.spec.ts
+++ b/tests/e2e/sidebar-takeover.spec.ts
@@ -26,11 +26,13 @@ const BASE_URL = `http://127.0.0.1:${PORT}`;
const COMPANY_NAME_PREFIX = "E2E-SidebarTakeover";
const COLLAPSED_STORAGE_KEY = "paperclip.sidebar.collapsed";
-// The sidebar header's "Open search" control only renders when the app sidebar
-// is expanded (pinned or peeking); in the collapsed rail it is hidden to fit
-// the 64px width. Its presence/absence is therefore a stable proxy for the
-// app sidebar's collapsed state (see Sidebar.tsx).
-const APP_SIDEBAR_EXPANDED_MARKER = "Open search";
+// The sidebar header's "Collapse sidebar" toggle only renders when the app
+// sidebar is expanded (pinned, desktop, not takeover-locked); in the collapsed
+// rail and on takeover routes it is hidden. Its presence/absence is therefore
+// a stable proxy for the app sidebar's collapsed state (see Sidebar.tsx).
+// (Previously "Open search", but the header search icon moved into the nav,
+// where it renders in the rail too.)
+const APP_SIDEBAR_EXPANDED_MARKER = "Collapse sidebar";
async function createCompany(board: APIRequestContext): Promise<{ id: string; prefix: string }> {
const healthRes = await board.get(`${BASE_URL}/api/health`);
diff --git a/ui/src/api/cloud.ts b/ui/src/api/cloud.ts
new file mode 100644
index 0000000000..a829bcc012
--- /dev/null
+++ b/ui/src/api/cloud.ts
@@ -0,0 +1,25 @@
+import { api } from "./client";
+
+/**
+ * One entry of the Paperclip Cloud stack portfolio, proxied by
+ * `GET /api/cloud/stacks`. The payload deliberately carries no icon URL, so
+ * stack rows render the same deterministic monogram treatment companies use.
+ */
+export type CloudStackSummary = {
+ displayName: string;
+ stackSlug: string;
+ primaryHost: string | null;
+ lifecycleState: string;
+ sleepState: string;
+ role: string;
+ isCurrent: boolean;
+};
+
+export type CloudStackPortfolio = {
+ stacks: CloudStackSummary[];
+};
+
+export const cloudApi = {
+ /** Cloud-managed instances only; self-hosted servers answer 404. */
+ listStacks: () => api.get<CloudStackPortfolio>("/cloud/stacks"),
+};
diff --git a/ui/src/api/health.ts b/ui/src/api/health.ts
index 4bc4fd1a78..833b3ca837 100644
--- a/ui/src/api/health.ts
+++ b/ui/src/api/health.ts
@@ -14,6 +14,14 @@ export type DevServerHealthStatus = {
lastRestartAt: string | null;
};
+export type CloudInstanceHealthStatus = {
+ managed: true;
+ managedBy: "paperclip-cloud";
+ stackSlug: string | null;
+ stackDisplayName?: string;
+ cloudBaseUrl: string | null;
+};
+
export type HealthStatus = {
status: "ok";
version?: string;
@@ -27,6 +35,7 @@ export type HealthStatus = {
};
serverInfo?: ServerInfoSnapshot;
devServer?: DevServerHealthStatus;
+ cloud?: CloudInstanceHealthStatus;
};
export const healthApi = {
diff --git a/ui/src/components/Layout.tsx b/ui/src/components/Layout.tsx
index ccb9fb3f4f..2d0fb7ea0f 100644
--- a/ui/src/components/Layout.tsx
+++ b/ui/src/components/Layout.tsx
@@ -203,11 +203,14 @@ export function Layout() {
useEffect(() => {
if (companiesLoading || onboardingTriggered.current) return;
if (health?.deploymentMode === "authenticated") return;
+ // Cloud provisions the single company for a stack, and POST /companies is a
+ // 403 floor there — auto-opening the wizard could only dead-end.
+ if (health?.cloud) return;
if (companies.length === 0) {
onboardingTriggered.current = true;
openOnboarding();
}
- }, [companies, companiesLoading, openOnboarding, health?.deploymentMode]);
+ }, [companies, companiesLoading, openOnboarding, health?.cloud, health?.deploymentMode]);
useEffect(() => {
if (!companyPrefix || companiesLoading || companies.length === 0) return;
diff --git a/ui/src/components/Sidebar.test.tsx b/ui/src/components/Sidebar.test.tsx
index cbc0ea2a25..16b816428b 100644
--- a/ui/src/components/Sidebar.test.tsx
+++ b/ui/src/components/Sidebar.test.tsx
@@ -159,14 +159,17 @@ describe("Sidebar", () => {
vi.clearAllMocks();
});
- it("links the top search icon to the search page without showing Search in Work nav", async () => {
+ it("shows Search as a nav item instead of a header icon", async () => {
+ // The header's spare width goes to the workspace name (which otherwise
+ // truncates at ~78px), so search lives in the nav list — still
+ // exactly one pointer affordance, just relocated.
mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableIsolatedWorkspaces: false });
const root = await renderSidebar();
- const topSearchLink = container.querySelector('a[aria-label="Open search"]');
- expect(topSearchLink?.getAttribute("href")).toBe("/search");
- const workLinks = [...container.querySelectorAll("nav a")].map((anchor) => anchor.textContent?.trim());
- expect(workLinks).not.toContain("Search");
+ expect(container.querySelector('a[aria-label="Open search"]')).toBeNull();
+ const navSearchLink = [...container.querySelectorAll("nav a")]
+ .find((anchor) => anchor.textContent?.trim() === "Search");
+ expect(navSearchLink?.getAttribute("href")).toBe("/search");
flushSync(() => {
root.unmount();
@@ -569,20 +572,25 @@ describe("Sidebar", () => {
});
});
- it("keeps the collapsed rail top bar to just the company logo (no clipped search/toggle)", async () => {
- // In the narrow rail the search/toggle controls don't fit beside the logo and
+ it("keeps the collapsed rail top bar to just the company logo (no clipped toggle)", async () => {
+ // In the narrow rail the collapse toggle doesn't fit beside the logo and
// would overflow/clip, shoving the logo out of the icon column (PAP-10676), so
- // they are dropped in the rail. Expansion stays reachable via hover-peek + Pin
- // and Cmd/Ctrl+B. The full controls return as soon as the panel is expanded or
+ // it is dropped in the rail. Expansion stays reachable via hover-peek + Pin
+ // and Cmd/Ctrl+B. The toggle returns as soon as the panel is expanded or
// peeking (covered by the other top-bar tests).
mockSidebar.collapsed = true;
mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableIsolatedWorkspaces: false });
const root = await renderSidebar();
expect(container.querySelector('button[aria-label="Expand sidebar"]')).toBeNull();
- expect(container.querySelector('a[aria-label="Open search"]')).toBeNull();
// The company menu (company switcher / logo) is still present in the rail.
expect(container.textContent).toContain("Company menu");
+ // Search survives the rail as an icon-only nav item — the old
+ // header icon was dropped entirely here, leaving the rail with no visible
+ // search affordance.
+ const railSearchLink = [...container.querySelectorAll("nav a")]
+ .find((anchor) => anchor.getAttribute("href") === "/search");
+ expect(railSearchLink).toBeTruthy();
flushSync(() => {
root.unmount();
diff --git a/ui/src/components/Sidebar.tsx b/ui/src/components/Sidebar.tsx
index 910211d3cf..67d2152e1f 100644
--- a/ui/src/components/Sidebar.tsx
+++ b/ui/src/components/Sidebar.tsx
@@ -27,7 +27,6 @@ import {
} from "lucide-react";
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
-import { NavLink } from "@/lib/router";
import { SidebarSection } from "./SidebarSection";
import { SidebarNavItem } from "./SidebarNavItem";
import { SidebarAgents } from "./SidebarAgents";
@@ -120,28 +119,20 @@ export function Sidebar() {
return (
<aside className="w-full h-full min-h-0 border-r border-border bg-background flex flex-col">
- {/* Top bar: Company name (bold) + Search — aligned with top sections (no visible border) */}
+ {/* Top bar: Company name (bold) + collapse control — aligned with top
+ sections (no visible border). Search deliberately does NOT live here:
+ the header's spare width goes to the workspace/organization name,
+ which is the user's orientation anchor and truncates otherwise.
+ Search is the first nav item below instead. */}
<div className="flex items-center gap-1 px-3 h-12 shrink-0">
<SidebarCompanyMenu />
- {/* In the collapsed rail the search/toggle controls don't fit beside the
- logo — keeping them would overflow the 64px rail and squeeze the logo
- out of alignment with the icon column below it (PAP-10676). They return
- as soon as the panel is expanded (pinned) or peeking. Expansion in the
+ {/* In the collapsed rail the toggle doesn't fit beside the logo —
+ keeping it would overflow the 64px rail and squeeze the logo out of
+ alignment with the icon column below it. It returns as
+ soon as the panel is expanded (pinned) or peeking. Expansion in the
rail is still reachable via hover-peek + Pin and Cmd/Ctrl+B. */}
{!rail ? (
<>
- <Button
- asChild
- variant="ghost"
- size="icon-sm"
- className="text-muted-foreground shrink-0"
- aria-label="Open search"
- title="Open search"
- >
- <NavLink to="/search">
- <Search className="h-4 w-4" />
- </NavLink>
- </Button>
{/* Desktop-only collapse/expand affordance. While peeking (hover flyout
over the collapsed rail) it becomes a Pin that promotes the peek to a
pinned-expanded sidebar; otherwise it toggles the pinned rail. Mobile
@@ -202,6 +193,11 @@ export function Sidebar() {
newTaskButton
);
})()}
+ {/* Search moved out of the header so the workspace name keeps the
+ width; a nav row also keeps search reachable from the
+ collapsed rail, where the old header icon was dropped entirely.
+ Cmd/Ctrl+K remains the keyboard path (command palette). */}
+ <SidebarNavItem to="/search" label="Search" icon={Search} />
<SidebarNavItem to="/dashboard" label="Dashboard" icon={LayoutDashboard} liveCount={liveRunCount} />
<SidebarNavItem
to="/inbox"
diff --git a/ui/src/components/SidebarCompanyMenu.test.tsx b/ui/src/components/SidebarCompanyMenu.test.tsx
index 7b35daf002..88fd4b7c89 100644
--- a/ui/src/components/SidebarCompanyMenu.test.tsx
+++ b/ui/src/components/SidebarCompanyMenu.test.tsx
@@ -5,6 +5,7 @@ import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { queryKeys } from "@/lib/queryKeys";
import { SidebarCompanyMenu } from "./SidebarCompanyMenu";
const mockAuthApi = vi.hoisted(() => ({
@@ -24,11 +25,23 @@ const mockSidebarPreferencesApi = vi.hoisted(() => ({
getCompanyOrder: vi.fn(),
updateCompanyOrder: vi.fn(),
}));
+const mockCloudApi = vi.hoisted(() => ({
+ listStacks: vi.fn(),
+}));
+const mockNavigateTopLevel = vi.hoisted(() => vi.fn());
vi.mock("@/api/auth", () => ({
authApi: mockAuthApi,
}));
+vi.mock("@/api/cloud", () => ({
+ cloudApi: mockCloudApi,
+}));
+
+vi.mock("@/lib/browserNavigation", () => ({
+ navigateTopLevel: mockNavigateTopLevel,
+}));
+
vi.mock("@/api/sidebarPreferences", () => ({
sidebarPreferencesApi: mockSidebarPreferencesApi,
}));
@@ -108,6 +121,39 @@ async function flushReact() {
await new Promise((resolve) => window.setTimeout(resolve, 0));
}
+const CLOUD_HEALTH = {
+ status: "ok" as const,
+ cloud: {
+ managed: true as const,
+ managedBy: "paperclip-cloud" as const,
+ stackSlug: "acme-labs",
+ cloudBaseUrl: "https://cloud.example.test",
+ },
+};
+
+const CLOUD_STACKS = {
+ stacks: [
+ {
+ displayName: "Acme Labs",
+ stackSlug: "acme-labs",
+ primaryHost: "acme-labs.example.test",
+ lifecycleState: "active",
+ sleepState: "awake",
+ role: "owner",
+ isCurrent: true,
+ },
+ {
+ displayName: "Strata Systems",
+ stackSlug: "strata",
+ primaryHost: "strata.example.test",
+ lifecycleState: "active",
+ sleepState: "asleep",
+ role: "member",
+ isCurrent: false,
+ },
+ ],
+};
+
describe("SidebarCompanyMenu", () => {
let container: HTMLDivElement;
@@ -123,6 +169,7 @@ describe("SidebarCompanyMenu", () => {
},
});
mockAuthApi.signOut.mockResolvedValue(undefined);
+ mockCloudApi.listStacks.mockResolvedValue(CLOUD_STACKS);
mockSidebarPreferencesApi.getCompanyOrder.mockResolvedValue({
orderedIds: ["company-1", "company-2", "company-3"],
updatedAt: null,
@@ -140,6 +187,36 @@ describe("SidebarCompanyMenu", () => {
vi.clearAllMocks();
});
+ function renderMenu(options: { cloud?: boolean; health?: unknown } = {}) {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ // CloudAccessGate owns the health fetch in the app; seeding the cache is how
+ // useCloudInstance sees a cloud-managed instance under test.
+ if (options.cloud || options.health) {
+ queryClient.setQueryData(queryKeys.health, options.health ?? CLOUD_HEALTH);
+ }
+ const root = createRoot(container);
+ act(() => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <SidebarCompanyMenu />
+ </QueryClientProvider>,
+ );
+ });
+ return { root, queryClient };
+ }
+
+ async function openMenu(ariaLabel: string) {
+ const trigger = container.querySelector(`button[aria-label="${ariaLabel}"]`);
+ expect(trigger).not.toBeNull();
+ act(() => {
+ trigger?.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, button: 0 }));
+ trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ await flushReact();
+ }
+
it("uses company-centric create copy without the chat flag", async () => {
const root = createRoot(container);
const queryClient = new QueryClient({
@@ -322,4 +399,195 @@ describe("SidebarCompanyMenu", () => {
root.unmount();
});
});
+
+ it("keeps the in-app company wizard and never leaves the app when self-hosted", async () => {
+ const { root } = renderMenu();
+ await flushReact();
+ await flushReact();
+
+ await openMenu("Open Acme Labs company switcher");
+
+ const createItem = Array.from(document.body.querySelectorAll('[data-slot="dropdown-menu-item"]'))
+ .find((element) => element.textContent?.includes("Create new company..."));
+ expect(createItem).toBeTruthy();
+
+ act(() => {
+ createItem?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ await flushReact();
+
+ expect(mockOpenOnboarding).toHaveBeenCalledTimes(1);
+ expect(mockNavigateTopLevel).not.toHaveBeenCalled();
+ expect(mockCloudApi.listStacks).not.toHaveBeenCalled();
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
+ // The trigger sits in a fixed 240px sidebar header beside two shrink-0
+ // controls, so a long name may only truncate — never widen the row and push
+ // the chevron, search, and collapse controls out of the panel. Truncation
+ // needs `min-w-0` on EVERY flex link of the chain (a flex item's default
+ // `min-width:auto` floors it at its content width), which is invisible to
+ // behavioural assertions, so the class chain itself is the contract.
+ it("lets a long workspace name truncate instead of widening the trigger", async () => {
+ const { root } = renderMenu();
+ await flushReact();
+
+ const trigger = container.querySelector('button[aria-label="Open Acme Labs company switcher"]');
+ expect(trigger).not.toBeNull();
+ expect(trigger?.className).toContain("min-w-0");
+
+ const labelRow = trigger?.firstElementChild;
+ expect(labelRow?.className).toContain("min-w-0");
+
+ const label = labelRow?.lastElementChild;
+ expect(label?.textContent).toBe("Acme Labs");
+ expect(label?.className).toContain("min-w-0");
+ expect(label?.className).toContain("truncate");
+ // A truncated name stays recoverable on hover.
+ expect(label?.getAttribute("title")).toBe("Acme Labs");
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
+ describe("in Paperclip Cloud", () => {
+ it("switches organizations instead of companies", async () => {
+ const { root } = renderMenu({ cloud: true });
+ await flushReact();
+ await flushReact();
+
+ expect(mockCloudApi.listStacks).toHaveBeenCalledTimes(1);
+ await openMenu("Open Acme Labs organization switcher");
+
+ expect(document.body.textContent).toContain("Switch organization");
+ expect(document.body.textContent).toContain("Create new organization...");
+ expect(document.body.textContent).toContain("Organization settings");
+ expect(document.body.textContent).not.toContain("Switch company");
+ expect(document.body.textContent).not.toContain("Create new company...");
+ expect(document.body.textContent).not.toContain("Company settings");
+
+ // Stacks, not companies: both rows carry the slug badge, and the current
+ // stack is the checked one.
+ expect(document.body.textContent).toContain("Acme Labs");
+ expect(document.body.textContent).toContain("acme-labs");
+ expect(document.body.textContent).toContain("Strata Systems");
+ expect(document.body.textContent).toContain("strata");
+ expect(document.body.textContent).not.toContain("Anachronist Wiki");
+ expect(document.body.textContent).not.toContain("ANA");
+
+ const currentRow = Array.from(document.body.querySelectorAll('[data-slot="dropdown-menu-item"]'))
+ .find((element) => element.textContent?.includes("Acme Labs"));
+ expect(currentRow?.className).toContain("bg-accent");
+
+ // Long slugs must not squeeze the display name out of the row, so the
+ // badge truncates and keeps the full slug on hover.
+ const slugBadge = document.body.querySelector('[title="strata"]');
+ expect(slugBadge?.className).toContain("truncate");
+
+ // Drag-to-reorder is self-hosted only in v1.
+ expect(Array.from(document.body.querySelectorAll("button"))
+ .some((element) => element.textContent === "Edit")).toBe(false);
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
+ it("enters another stack through a full top-level navigation", async () => {
+ const { root } = renderMenu({ cloud: true });
+ await flushReact();
+ await flushReact();
+ await openMenu("Open Acme Labs organization switcher");
+
+ const strataRow = Array.from(document.body.querySelectorAll('[data-slot="dropdown-menu-item"]'))
+ .find((element) => element.textContent?.includes("Strata Systems"));
+ expect(strataRow).toBeTruthy();
+
+ act(() => {
+ strataRow?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ await flushReact();
+
+ expect(mockNavigateTopLevel).toHaveBeenCalledWith(
+ "https://cloud.example.test/stacks/strata/enter",
+ );
+ // No in-app company selection and no client-side route change.
+ expect(mockSetSelectedCompanyId).not.toHaveBeenCalled();
+ expect(mockNavigate).not.toHaveBeenCalled();
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
+ it("does not navigate when the current stack is picked again", async () => {
+ const { root } = renderMenu({ cloud: true });
+ await flushReact();
+ await flushReact();
+ await openMenu("Open Acme Labs organization switcher");
+
+ const currentRow = Array.from(document.body.querySelectorAll('[data-slot="dropdown-menu-item"]'))
+ .find((element) => element.textContent?.includes("Acme Labs"));
+
+ act(() => {
+ currentRow?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ await flushReact();
+
+ expect(mockNavigateTopLevel).not.toHaveBeenCalled();
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
+ it("sends organization creation to the cloud app, not the in-app wizard", async () => {
+ const { root } = renderMenu({ cloud: true });
+ await flushReact();
+ await flushReact();
+ await openMenu("Open Acme Labs organization switcher");
+
+ const createItem = Array.from(document.body.querySelectorAll('[data-slot="dropdown-menu-item"]'))
+ .find((element) => element.textContent?.includes("Create new organization..."));
+ expect(createItem).toBeTruthy();
+
+ act(() => {
+ createItem?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ await flushReact();
+
+ expect(mockNavigateTopLevel).toHaveBeenCalledWith("https://cloud.example.test/stacks/new");
+ expect(mockOpenOnboarding).not.toHaveBeenCalled();
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
+ it("falls back to the stack slug and hides creation without a cloud base url", async () => {
+ mockCloudApi.listStacks.mockRejectedValue(new Error("portfolio unavailable"));
+ const { root } = renderMenu({
+ cloud: true,
+ health: {
+ status: "ok" as const,
+ cloud: { ...CLOUD_HEALTH.cloud, cloudBaseUrl: null },
+ },
+ });
+ await flushReact();
+ await flushReact();
+
+ await openMenu("Open acme-labs organization switcher");
+
+ expect(document.body.textContent).toContain("Could not load organizations");
+ expect(document.body.textContent).not.toContain("Create new organization...");
+
+ act(() => {
+ root.unmount();
+ });
+ });
+ });
});
diff --git a/ui/src/components/SidebarCompanyMenu.tsx b/ui/src/components/SidebarCompanyMenu.tsx
index a8340528fa..167c7b1f48 100644
--- a/ui/src/components/SidebarCompanyMenu.tsx
+++ b/ui/src/components/SidebarCompanyMenu.tsx
@@ -23,6 +23,7 @@ import { CSS } from "@dnd-kit/utilities";
import type { Company } from "@paperclipai/shared";
import { Link, useLocation, useNavigate } from "@/lib/router";
import { authApi } from "@/api/auth";
+import { cloudApi, type CloudStackSummary } from "@/api/cloud";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
@@ -34,7 +35,10 @@ import {
} from "@/components/ui/dropdown-menu";
import { useCompany } from "@/context/CompanyContext";
import { useDialogActions } from "@/context/DialogContext";
+import { useCloudInstance } from "@/hooks/useCloudInstance";
import { useCompanyOrder } from "@/hooks/useCompanyOrder";
+import { navigateTopLevel } from "@/lib/browserNavigation";
+import { cloudStackCreateUrl, cloudStackEnterUrl } from "@/lib/cloudLinks";
import { queryKeys } from "@/lib/queryKeys";
import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "@/lib/utils";
import { useSidebar } from "../context/SidebarContext";
@@ -45,17 +49,59 @@ interface SidebarCompanyMenuProps {
onOpenChange?: (open: boolean) => void;
}
+const WORKSPACE_ICON_CLASS = "size-5 shrink-0 rounded-md text-(length:--text-micro)";
+const WORKSPACE_BADGE_CLASS =
+ "shrink-0 rounded bg-muted px-1.5 py-0.5 font-mono text-(length:--text-nano) text-muted-foreground";
+
function WorkspaceIcon({ company }: { company: Company }) {
return (
<CompanyPatternIcon
companyName={company.name}
logoUrl={company.logoUrl}
brandColor={company.brandColor}
- className="size-5 shrink-0 rounded-md text-(length:--text-micro)"
+ className={WORKSPACE_ICON_CLASS}
/>
);
}
+/**
+ * Cloud stacks have no hot-linkable icon URL in the portfolio payload, so v1
+ * renders the same deterministic monogram treatment cloud's own portfolio page
+ * uses — seeded by the display name, never fetched.
+ */
+function StackIcon({ displayName }: { displayName: string }) {
+ return <CompanyPatternIcon companyName={displayName} className={WORKSPACE_ICON_CLASS} />;
+}
+
+function CloudStackItem({
+ stack,
+ isSelected,
+ onSelect,
+}: {
+ stack: CloudStackSummary;
+ isSelected: boolean;
+ onSelect: (stack: CloudStackSummary) => void;
+}) {
+ return (
+ <DropdownMenuItem
+ onSelect={() => onSelect(stack)}
+ className={cn("min-w-0 gap-2 py-2", isSelected && "bg-accent text-accent-foreground")}
+ >
+ <StackIcon displayName={stack.displayName} />
+ <span className="min-w-0 flex-1 truncate" title={stack.displayName}>
+ {stack.displayName}
+ </span>
+ {/* Company badges are 3-4 character issue prefixes, but stack slugs are
+ user-chosen and can be long enough to truncate the name to a single
+ letter — the name is the primary identifier, so the badge yields. */}
+ <span className={cn(WORKSPACE_BADGE_CLASS, "max-w-24 truncate")} title={stack.stackSlug}>
+ {stack.stackSlug}
+ </span>
+ {isSelected ? <Check className="size-4 shrink-0 text-muted-foreground" /> : null}
+ </DropdownMenuItem>
+ );
+}
+
function SortableCompanyItem({
company,
isEditing,
@@ -118,9 +164,7 @@ function SortableCompanyItem({
</button>
) : (
<>
- <span className="shrink-0 rounded bg-muted px-1.5 py-0.5 font-mono text-(length:--text-nano) text-muted-foreground">
- {company.issuePrefix}
- </span>
+ <span className={WORKSPACE_BADGE_CLASS}>{company.issuePrefix}</span>
{isSelected ? <Check className="size-4 text-muted-foreground" /> : null}
</>
)}
@@ -163,6 +207,33 @@ export function SidebarCompanyMenu({ open: controlledOpen, onOpenChange }: Sideb
userId: currentUserId,
});
+ // In Paperclip Cloud the switcher lists the signed-in user's stacks
+ // (organizations) instead of the instance's companies: a cloud instance holds
+ // exactly one company, and switching means leaving this tenant host entirely.
+ const cloud = useCloudInstance();
+ const isCloud = Boolean(cloud);
+ const cloudBaseUrl = cloud?.cloudBaseUrl ?? null;
+ const stacksQuery = useQuery({
+ queryKey: queryKeys.cloud.stacks,
+ queryFn: () => cloudApi.listStacks(),
+ enabled: isCloud,
+ staleTime: 30_000,
+ retry: false,
+ });
+ const stacks = stacksQuery.data?.stacks ?? [];
+ const currentStack = isCloud
+ ? stacks.find((stack) => stack.isCurrent)
+ ?? stacks.find((stack) => Boolean(cloud?.stackSlug) && stack.stackSlug === cloud?.stackSlug)
+ ?? null
+ : null;
+ const createStackUrl = isCloud ? cloudStackCreateUrl(cloudBaseUrl) : null;
+ const switcherNoun = isCloud ? "organization" : "company";
+ // The one name the chrome shows for "where am I": the stack in cloud, the
+ // company when self-hosted.
+ const currentName = isCloud
+ ? currentStack?.displayName ?? cloud?.stackDisplayName ?? cloud?.stackSlug ?? null
+ : selectedCompany?.name ?? null;
+
const signOutMutation = useMutation({
mutationFn: () => authApi.signOut(),
onSuccess: async () => {
@@ -200,9 +271,29 @@ export function SidebarCompanyMenu({ open: controlledOpen, onOpenChange }: Sideb
}
}
+ /**
+ * Switching stacks is a full top-level navigation, not client routing: the
+ * cloud entry-code handoff authenticates the user for the target stack and
+ * wakes it if it is asleep before landing on its own tenant host.
+ */
+ function selectStack(stack: CloudStackSummary) {
+ setOpen(false);
+ if (isMobile) setSidebarOpen(false);
+ if (stack.stackSlug === currentStack?.stackSlug) return;
+ const target = cloudStackEnterUrl(cloudBaseUrl, stack.stackSlug);
+ if (!target) return;
+ navigateTopLevel(target);
+ }
+
function addCompany() {
setOpen(false);
if (isMobile) setSidebarOpen(false);
+ // Cloud creates organizations in the cloud app; the in-app company wizard
+ // is unreachable there (POST /companies is a 403 floor on managed stacks).
+ if (isCloud) {
+ if (createStackUrl) navigateTopLevel(createStackUrl);
+ return;
+ }
openOnboarding();
}
@@ -231,13 +322,34 @@ export function SidebarCompanyMenu({ open: controlledOpen, onOpenChange }: Sideb
// the Button's default size adds `has-[>svg]:px-3`, so with the chevron
// svg present (expanded) it was already 12px but without it (rail) it fell
// back to 8px — a 4px horizontal jump on collapse (PAP-10676).
- className="h-9 flex-1 justify-start gap-2 px-3 text-left"
- aria-label={selectedCompany ? `Open ${selectedCompany.name} company switcher` : "Open company switcher"}
+ // `min-w-0` on every link of the flex chain (button → label row → label)
+ // is what lets the name truncate: a flex item's default `min-width:auto`
+ // floors it at its content width, so without it a long name widens the
+ // trigger past the sidebar and pushes the chevron out of bounds. Company
+ // names were short in practice; cloud stack names are user-chosen.
+ className="h-9 min-w-0 flex-1 justify-start gap-2 px-3 text-left"
+ aria-label={
+ currentName
+ ? `Open ${currentName} ${switcherNoun} switcher`
+ : `Open ${switcherNoun} switcher`
+ }
>
<span className="flex min-w-0 flex-1 items-center gap-2">
- {selectedCompany ? <WorkspaceIcon company={selectedCompany} /> : null}
- <span className={cn("truncate text-sm font-bold text-foreground", rail && SIDEBAR_RAIL_HIDDEN_LABEL)}>
- {selectedCompany?.name ?? "Select company"}
+ {isCloud
+ ? currentName ? <StackIcon displayName={currentName} /> : null
+ : selectedCompany ? <WorkspaceIcon company={selectedCompany} /> : null}
+ {/* The header has room for ~110px of name beside the collapse
+ control (~142px on mobile, which hides it) — search moved to
+ the nav to buy that width. A name that still
+ truncates stays hover-recoverable via title. */}
+ <span
+ className={cn(
+ "min-w-0 truncate text-sm font-bold text-foreground",
+ rail && SIDEBAR_RAIL_HIDDEN_LABEL,
+ )}
+ title={currentName ?? undefined}
+ >
+ {currentName ?? (isCloud ? "Select organization" : "Select company")}
</span>
</span>
{!rail && <ChevronsUpDown className="size-3.5 shrink-0 text-muted-foreground" />}
@@ -246,55 +358,89 @@ export function SidebarCompanyMenu({ open: controlledOpen, onOpenChange }: Sideb
<DropdownMenuContent align="start" sideOffset={8} className="w-64 p-1">
<div className="flex items-center justify-between gap-2 px-2 py-1.5">
<DropdownMenuLabel className="p-0 text-(length:--text-micro) font-semibold uppercase text-muted-foreground">
- Switch company
+ {isCloud ? "Switch organization" : "Switch company"}
</DropdownMenuLabel>
- <button
- type="button"
- onClick={(event) => {
- event.preventDefault();
- event.stopPropagation();
- setIsEditingOrder((current) => !current);
- }}
- className="rounded px-1.5 py-0.5 text-(length:--text-micro) font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
- >
- {isEditingOrder ? "Done" : "Edit"}
- </button>
+ {/* Stack order is owned by cloud's own portfolio in v1, so the
+ drag-to-reorder affordance stays self-hosted-only. */}
+ {isCloud ? null : (
+ <button
+ type="button"
+ onClick={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ setIsEditingOrder((current) => !current);
+ }}
+ className="rounded px-1.5 py-0.5 text-(length:--text-micro) font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
+ >
+ {isEditingOrder ? "Done" : "Edit"}
+ </button>
+ )}
</div>
<div className="max-h-96 overflow-y-auto">
- <DndContext
- sensors={sensors}
- collisionDetection={closestCenter}
- onDragEnd={handleDragEnd}
- >
- <SortableContext
- items={orderedCompanies.map((company) => company.id)}
- strategy={verticalListSortingStrategy}
- >
- {orderedCompanies.map((company) => (
- <SortableCompanyItem
- key={company.id}
- company={company}
- isEditing={isEditingOrder}
- isSelected={company.id === selectedCompany?.id}
- onSelect={selectCompany}
+ {isCloud ? (
+ <>
+ {stacks.map((stack) => (
+ <CloudStackItem
+ key={stack.stackSlug}
+ stack={stack}
+ isSelected={stack.stackSlug === currentStack?.stackSlug}
+ onSelect={selectStack}
/>
))}
- </SortableContext>
- </DndContext>
- {orderedCompanies.length === 0 ? (
- <DropdownMenuItem disabled>No companies</DropdownMenuItem>
- ) : null}
+ {stacks.length === 0 ? (
+ <DropdownMenuItem disabled>
+ {stacksQuery.isLoading
+ ? "Loading organizations..."
+ : stacksQuery.isError
+ ? "Could not load organizations"
+ : "No organizations"}
+ </DropdownMenuItem>
+ ) : null}
+ </>
+ ) : (
+ <>
+ <DndContext
+ sensors={sensors}
+ collisionDetection={closestCenter}
+ onDragEnd={handleDragEnd}
+ >
+ <SortableContext
+ items={orderedCompanies.map((company) => company.id)}
+ strategy={verticalListSortingStrategy}
+ >
+ {orderedCompanies.map((company) => (
+ <SortableCompanyItem
+ key={company.id}
+ company={company}
+ isEditing={isEditingOrder}
+ isSelected={company.id === selectedCompany?.id}
+ onSelect={selectCompany}
+ />
+ ))}
+ </SortableContext>
+ </DndContext>
+ {orderedCompanies.length === 0 ? (
+ <DropdownMenuItem disabled>No companies</DropdownMenuItem>
+ ) : null}
+ </>
+ )}
</div>
<DropdownMenuSeparator />
- <DropdownMenuItem
- onClick={addCompany}
- className="gap-2 py-2 text-muted-foreground"
- disabled={isEditingOrder}
- >
- <Plus className="size-4" />
- <span>Create new company...</span>
- </DropdownMenuItem>
- <DropdownMenuSeparator />
+ {/* A cloud instance without a configured cloud origin has nowhere to
+ send the user, so the row (and its separator) drop out entirely. */}
+ {isCloud && !createStackUrl ? null : (
+ <>
+ <DropdownMenuItem
+ onClick={addCompany}
+ className="gap-2 py-2 text-muted-foreground"
+ disabled={isEditingOrder}
+ >
+ <Plus className="size-4" />
+ <span>{isCloud ? "Create new organization..." : "Create new company..."}</span>
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ </>
+ )}
<DropdownMenuItem asChild disabled={isEditingOrder}>
<Link
to="/company/settings/invites"
@@ -308,7 +454,7 @@ export function SidebarCompanyMenu({ open: controlledOpen, onOpenChange }: Sideb
>
<UserPlus className="size-4" />
<span className="truncate">
- {selectedCompany ? `Invite people to ${selectedCompany.name}` : "Invite people"}
+ {currentName ? `Invite people to ${currentName}` : "Invite people"}
</span>
</Link>
</DropdownMenuItem>
@@ -324,7 +470,7 @@ export function SidebarCompanyMenu({ open: controlledOpen, onOpenChange }: Sideb
}}
>
<Settings className="size-4" />
- <span>Company settings</span>
+ <span>{isCloud ? "Organization settings" : "Company settings"}</span>
</Link>
</DropdownMenuItem>
{session?.session ? (
diff --git a/ui/src/hooks/useCloudInstance.test.tsx b/ui/src/hooks/useCloudInstance.test.tsx
new file mode 100644
index 0000000000..bb5dc83948
--- /dev/null
+++ b/ui/src/hooks/useCloudInstance.test.tsx
@@ -0,0 +1,67 @@
+// @vitest-environment jsdom
+
+import { flushSync } from "react-dom";
+import { createRoot } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { CloudInstanceHealthStatus, HealthStatus } from "@/api/health";
+import { queryKeys } from "@/lib/queryKeys";
+import { useCloudInstance } from "./useCloudInstance";
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+let captured: CloudInstanceHealthStatus | null = null;
+
+function Harness() {
+ captured = useCloudInstance();
+ return null;
+}
+
+describe("useCloudInstance", () => {
+ let container: HTMLDivElement;
+ let queryClient: QueryClient;
+
+ beforeEach(() => {
+ captured = null;
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ });
+
+ afterEach(() => {
+ queryClient.clear();
+ container.remove();
+ vi.unstubAllGlobals();
+ });
+
+ it("reactively reads the existing health cache without making another request", async () => {
+ const fetch = vi.fn();
+ vi.stubGlobal("fetch", fetch);
+ const cloud: CloudInstanceHealthStatus = {
+ managed: true,
+ managedBy: "paperclip-cloud",
+ stackSlug: "acme",
+ cloudBaseUrl: "https://app.paperclip.app",
+ };
+ queryClient.setQueryData<HealthStatus>(queryKeys.health, { status: "ok", cloud });
+ const root = createRoot(container);
+
+ flushSync(() => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <Harness />
+ </QueryClientProvider>,
+ );
+ });
+
+ expect(captured).toEqual(cloud);
+ expect(fetch).not.toHaveBeenCalled();
+
+ queryClient.setQueryData<HealthStatus>(queryKeys.health, { status: "ok" });
+ await vi.waitFor(() => expect(captured).toBeNull());
+ expect(fetch).not.toHaveBeenCalled();
+
+ flushSync(() => root.unmount());
+ });
+});
diff --git a/ui/src/hooks/useCloudInstance.ts b/ui/src/hooks/useCloudInstance.ts
new file mode 100644
index 0000000000..19b9e6066e
--- /dev/null
+++ b/ui/src/hooks/useCloudInstance.ts
@@ -0,0 +1,18 @@
+import { useQuery } from "@tanstack/react-query";
+import { healthApi } from "@/api/health";
+import { queryKeys } from "@/lib/queryKeys";
+
+/**
+ * Reads Paperclip Cloud metadata from the app-wide health query cache.
+ * CloudAccessGate owns the fetch; disabling this observer's query function
+ * prevents consumers from adding another health request when they mount.
+ */
+export function useCloudInstance() {
+ const healthQuery = useQuery({
+ queryKey: queryKeys.health,
+ queryFn: () => healthApi.get(),
+ enabled: false,
+ });
+
+ return healthQuery.data?.cloud ?? null;
+}
diff --git a/ui/src/lib/cloudLinks.test.ts b/ui/src/lib/cloudLinks.test.ts
new file mode 100644
index 0000000000..95c0c3303d
--- /dev/null
+++ b/ui/src/lib/cloudLinks.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from "vitest";
+import { cloudAppUrl, cloudStackCreateUrl, cloudStackEnterUrl } from "./cloudLinks";
+
+describe("cloudLinks", () => {
+ it("resolves stack links against the cloud origin", () => {
+ expect(cloudStackEnterUrl("https://app.paperclip.app", "acme")).toBe(
+ "https://app.paperclip.app/stacks/acme/enter",
+ );
+ expect(cloudStackCreateUrl("https://app.paperclip.app")).toBe(
+ "https://app.paperclip.app/stacks/new",
+ );
+ });
+
+ it("drops a control-plane path suffix on the configured origin", () => {
+ expect(cloudStackEnterUrl("https://cloud.example.test/control-plane", "acme")).toBe(
+ "https://cloud.example.test/stacks/acme/enter",
+ );
+ });
+
+ it("escapes slugs so a crafted portfolio entry cannot climb the path", () => {
+ expect(cloudStackEnterUrl("https://app.paperclip.app", "../../evil")).toBe(
+ "https://app.paperclip.app/stacks/..%2F..%2Fevil/enter",
+ );
+ });
+
+ it("returns null without a usable base or slug", () => {
+ expect(cloudStackEnterUrl(null, "acme")).toBeNull();
+ expect(cloudStackEnterUrl(" ", "acme")).toBeNull();
+ expect(cloudStackEnterUrl("https://app.paperclip.app", " ")).toBeNull();
+ expect(cloudStackEnterUrl("not a url", "acme")).toBeNull();
+ expect(cloudStackCreateUrl(undefined)).toBeNull();
+ });
+
+ it("refuses non-web schemes", () => {
+ expect(cloudAppUrl("javascript:alert(1)", "/stacks/new")).toBeNull();
+ expect(cloudAppUrl("file:///etc", "/stacks/new")).toBeNull();
+ });
+});
diff --git a/ui/src/lib/cloudLinks.ts b/ui/src/lib/cloudLinks.ts
new file mode 100644
index 0000000000..4ec385dc34
--- /dev/null
+++ b/ui/src/lib/cloudLinks.ts
@@ -0,0 +1,44 @@
+/**
+ * Links out of a tenant instance and into the Paperclip Cloud app.
+ *
+ * The base always comes from the health `cloud` block (derived from
+ * `PAPERCLIP_CLOUD_API_ORIGIN`) — the cloud domain is never hardcoded, because
+ * aliases move and self-hosted instances have no cloud block at all. Only the
+ * origin of that value is used; a control-plane path suffix is dropped, exactly
+ * as the server-side portfolio proxy resolves it.
+ *
+ * These are always full top-level navigations, never in-app routes: the cloud
+ * harness shadows GET `/stacks` and `/stacks/*` on tenant hosts, so an in-app
+ * route under that prefix would be unreachable.
+ */
+export function cloudAppUrl(cloudBaseUrl: string | null | undefined, path: string): string | null {
+ const base = cloudBaseUrl?.trim();
+ if (!base) return null;
+ try {
+ const url = new URL(path, base);
+ // The base is server-supplied, but a stray non-web scheme must never reach
+ // `window.location.assign`.
+ if (url.protocol !== "https:" && url.protocol !== "http:") return null;
+ return url.toString();
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Entry-code handoff for another stack: cloud authenticates the user for that
+ * stack and wakes it if it is asleep before redirecting to its tenant host.
+ */
+export function cloudStackEnterUrl(
+ cloudBaseUrl: string | null | undefined,
+ stackSlug: string | null | undefined,
+): string | null {
+ const slug = stackSlug?.trim();
+ if (!slug) return null;
+ return cloudAppUrl(cloudBaseUrl, `/stacks/${encodeURIComponent(slug)}/enter`);
+}
+
+/** Cloud's own create-a-stack flow, which replaces the in-app company wizard. */
+export function cloudStackCreateUrl(cloudBaseUrl: string | null | undefined): string | null {
+ return cloudAppUrl(cloudBaseUrl, "/stacks/new");
+}
diff --git a/ui/src/lib/queryKeys.ts b/ui/src/lib/queryKeys.ts
index c0437c5bd8..f6e4529271 100644
--- a/ui/src/lib/queryKeys.ts
+++ b/ui/src/lib/queryKeys.ts
@@ -367,6 +367,9 @@ export const queryKeys = {
experimentalSettings: ["instance", "experimental-settings"] as const,
},
health: ["health"] as const,
+ cloud: {
+ stacks: ["cloud", "stacks"] as const,
+ },
secrets: {
list: (companyId: string) => ["secrets", companyId] as const,
providers: (companyId: string) => ["secret-providers", companyId] as const,
diff --git a/ui/src/pages/Companies.test.tsx b/ui/src/pages/Companies.test.tsx
new file mode 100644
index 0000000000..e80c305a8c
--- /dev/null
+++ b/ui/src/pages/Companies.test.tsx
@@ -0,0 +1,126 @@
+// @vitest-environment jsdom
+
+import { flushSync } from "react-dom";
+import { createRoot } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { queryKeys } from "@/lib/queryKeys";
+import { Companies } from "./Companies";
+
+const mockCompaniesApi = vi.hoisted(() => ({
+ stats: vi.fn(),
+ update: vi.fn(),
+ remove: vi.fn(),
+}));
+const mockOpenOnboarding = vi.hoisted(() => vi.fn());
+
+vi.mock("../api/companies", () => ({
+ companiesApi: mockCompaniesApi,
+}));
+
+vi.mock("../context/CompanyContext", () => ({
+ useCompany: () => ({
+ companies: [
+ {
+ id: "company-1",
+ issuePrefix: "PAP",
+ name: "Acme Labs",
+ status: "active",
+ budgetMonthlyCents: 0,
+ spentMonthlyCents: 0,
+ },
+ ],
+ selectedCompanyId: "company-1",
+ setSelectedCompanyId: vi.fn(),
+ loading: false,
+ error: null,
+ }),
+}));
+
+vi.mock("../context/DialogContext", () => ({
+ useDialogActions: () => ({ openOnboarding: mockOpenOnboarding }),
+}));
+
+vi.mock("../context/BreadcrumbContext", () => ({
+ useBreadcrumbs: () => ({ setBreadcrumbs: vi.fn() }),
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+function act(callback: () => void) {
+ flushSync(callback);
+}
+
+async function flushReact() {
+ await Promise.resolve();
+ await new Promise((resolve) => window.setTimeout(resolve, 0));
+}
+
+const CLOUD_HEALTH = {
+ status: "ok" as const,
+ cloud: {
+ managed: true as const,
+ managedBy: "paperclip-cloud" as const,
+ stackSlug: "acme-labs",
+ cloudBaseUrl: "https://cloud.example.test",
+ },
+};
+
+describe("Companies page", () => {
+ let container: HTMLDivElement;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ mockCompaniesApi.stats.mockResolvedValue({});
+ });
+
+ afterEach(() => {
+ container.remove();
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+ });
+
+ async function renderPage({ cloud }: { cloud?: boolean } = {}) {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ if (cloud) queryClient.setQueryData(queryKeys.health, CLOUD_HEALTH);
+ const root = createRoot(container);
+ act(() => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <Companies />
+ </QueryClientProvider>,
+ );
+ });
+ await flushReact();
+ await flushReact();
+ return root;
+ }
+
+ it("offers the company wizard when self-hosted", async () => {
+ const root = await renderPage();
+
+ expect(container.textContent).toContain("New Company");
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
+ it("hides the company wizard on a cloud-managed instance", async () => {
+ const root = await renderPage({ cloud: true });
+
+ // Cloud stacks hold exactly one company and POST /companies is a 403 floor,
+ // so the entry point must not be offered at all.
+ expect(container.textContent).not.toContain("New Company");
+ expect(container.textContent).toContain("Acme Labs");
+ expect(mockOpenOnboarding).not.toHaveBeenCalled();
+
+ act(() => {
+ root.unmount();
+ });
+ });
+});
diff --git a/ui/src/pages/Companies.tsx b/ui/src/pages/Companies.tsx
index cc21eabb5a..a1f42297c8 100644
--- a/ui/src/pages/Companies.tsx
+++ b/ui/src/pages/Companies.tsx
@@ -3,6 +3,7 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCompany } from "../context/CompanyContext";
import { useDialogActions } from "../context/DialogContext";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
+import { useCloudInstance } from "../hooks/useCloudInstance";
import { companiesApi } from "../api/companies";
import { queryKeys } from "../lib/queryKeys";
import { formatCents, relativeTime } from "../lib/utils";
@@ -41,6 +42,9 @@ export function Companies() {
const { openOnboarding } = useDialogActions();
const { setBreadcrumbs } = useBreadcrumbs();
const queryClient = useQueryClient();
+ // A cloud stack holds exactly one company; creating another is a 403 floor
+ // server-side, so the wizard entry point is hidden rather than dead-ending.
+ const isCloud = Boolean(useCloudInstance());
const { data: stats } = useQuery({
queryKey: queryKeys.companies.stats,
@@ -92,10 +96,12 @@ export function Companies() {
return (
<div className="space-y-6">
<div className="flex items-center justify-end">
- <Button size="sm" onClick={() => openOnboarding()}>
- <Plus className="h-3.5 w-3.5 mr-1.5" />
- New Company
- </Button>
+ {isCloud ? null : (
+ <Button size="sm" onClick={() => openOnboarding()}>
+ <Plus className="h-3.5 w-3.5 mr-1.5" />
+ New Company
+ </Button>
+ )}
</div>
<div className="h-6">