diff --git a/.env.example b/.env.example
index e0073b4fb..fb8123bc7 100644
--- a/.env.example
+++ b/.env.example
@@ -251,7 +251,8 @@ GITHUB_APP_SLUG=openship-io
# Set these in the deployed API environment. Both Compose stacks load this
# root .env; they do NOT load apps/api/.env.saas (used by dev:saas).
# Use the production account's credentials for the production SaaS.
-# OBLIEN_API_URL=https://api.oblien.com
+# Optional complete API mount override. Unset uses the Oblien SDK default.
+# OBLIEN_API_URL=https://your-proxy.example/api/v1
# OBLIEN_CLIENT_ID=
# OBLIEN_CLIENT_SECRET=
# Optional public base-image pack for NEW managed Cloud spaces only.
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index eaa8f7546..6c3f05b42 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -150,6 +150,7 @@ jobs:
command: >-
RUN_DOCKER_E2E=1 bun run --cwd apps/api test:e2e
test/e2e/platform-import-data.e2e.test.ts
+ test/e2e/platform-import-project.e2e.test.ts
# Separate independent daemons keep real-Docker coverage within the job
# budget. Tests remain serial inside each daemon to preserve isolation.
- suite: Compose cutover and rollback
diff --git a/.github/workflows/release-gate.yml b/.github/workflows/release-gate.yml
index fee238c02..0a225dfb5 100644
--- a/.github/workflows/release-gate.yml
+++ b/.github/workflows/release-gate.yml
@@ -226,18 +226,24 @@ jobs:
# https://github.com/actions/runner-images/issues/15005
runs-on: ${{ matrix.scope == 'fast' && 'ubuntu-22.04' || 'ubuntu-latest' }}
# Files remain serial within each disposable daemon. Split the growing
- # ordinary suite across two hosts so it fits the gate without relaxing tests.
+ # ordinary suite across four hosts so it fits the gate without relaxing tests.
timeout-minutes: ${{ matrix.scope == 'fast' && 45 || 30 }}
strategy:
fail-fast: false
matrix:
include:
- scope: fast
- label: fast 1/2
- shard: 1/2
+ label: fast 1/4
+ shard: 1/4
- scope: fast
- label: fast 2/2
- shard: 2/2
+ label: fast 2/4
+ shard: 2/4
+ - scope: fast
+ label: fast 3/4
+ shard: 3/4
+ - scope: fast
+ label: fast 4/4
+ shard: 4/4
- scope: heavy
label: heavy
shard: ""
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 850b8fe80..0d57b1d29 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,37 @@ All notable changes to OpenShip. Versions follow [semver](https://semver.org);
the in-app updater surfaces critical advisories from `release-advisories.json`.
Runtime security notices use the signed feed published from `security-advisories.json`.
+## Unreleased
+
+### Authorization
+
+- Require administrative authority for admin operations across HTTP, SDK, native and
+ MCP access. Ordinary organization membership no longer grants host command execution;
+ token grants remain bounded by the user's current built-in role (#1783).
+
+### Cloud billing
+
+- Open checkout only when its payment URL is ready, with a visible fallback button.
+ Recover unfinished Cloud purchases when reopening setup instead of creating duplicate
+ unpaid spaces. Show pending-plan warnings in the Plans & billing sidebar entry.
+
+### Backups
+
+- Back up verified existing empty Docker volumes and bind directories without blocking
+ populated sibling sources. Reject missing sources before capture and preserve failures
+ for unavailable backing storage (#1767).
+
+### CLI
+
+- Run the container-to-host connectivity probe with Node.js, matching the API image,
+ so `openship up` and `openship doctor` can diagnose the host channel without Bun.
+
+### Instance relocation
+
+- Fence event-stream admission while moving the controller so a late subscriber cannot
+ keep the source draining indefinitely. Restore stream access when the controller resumes,
+ and link server preparation to its build view while deployment reads remain available.
+
## 0.9.12
**Critical update** for build-secret protection, database upgrade repairs and
@@ -56,6 +87,8 @@ website.
### Domains
+- Configure static HTML, JSON or text responses on a domain through its normal
+ route editor, including maintenance and verification responses without an app container.
- Avoid rewriting unchanged edge route files and repeating remote reads during a
registration. Preserve exact file contents and permissions while retaining route
validation, reloads, certificate activation and transactional rollback.
@@ -71,6 +104,12 @@ website.
destination review, progress reporting and cancellation.
- Keep migration environment fields visible while entering missing secrets, with
a plain section heading instead of a nested disclosure that collapses during editing.
+- Preserve source project boundaries during platform imports: one project contains
+ its native services, private DNS, encrypted service environments and separate volumes.
+ Keep service environment values scoped correctly during source builds too.
+- Carry imported custom domains and aliases through the existing migration routing
+ flow, pending normal verification. Show DNS cutover guidance and replacement
+ notices for Railway and Vercel URLs in review and saved migration progress.
- Restore portable instance exports with their server credentials and workspace
ownership. Normalize restored data for the destination schema and keep the
instance import and server selection views consistent.
@@ -104,6 +143,8 @@ website.
### Dashboard, billing and website
+- Keep the shared destination dropdown available with one server or Cloud plan,
+ with Add server in its menu across deployment and migration flows.
- Refresh deployment state after navigation and browser resume. Unify project
settings and shared environment controls with the existing service views.
- Keep plan overview, usage and payments together under Plans & billing, align
diff --git a/SECURITY.md b/SECURITY.md
index 87c2474ab..29b19ad67 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -57,6 +57,12 @@ violation.
## Scope
+Organization owners and administrators can perform host administration. Ordinary
+members retain read/write access but cannot perform operations requiring `admin`,
+including server shell execution. Restricted users require explicit resource grants;
+scoped tokens also respect their user's current built-in role. Host commands execute
+as the server's configured account, so delegate server administration accordingly.
+
In scope — all Openship components:
- Managed Openship Cloud
diff --git a/apps/api/.env.saas.example b/apps/api/.env.saas.example
index a4f391f91..0c1556ce6 100644
--- a/apps/api/.env.saas.example
+++ b/apps/api/.env.saas.example
@@ -31,7 +31,8 @@ BETTER_AUTH_SECRET=change-me-in-production
INTERNAL_TOKEN=change-me-32-byte-random-hex
# Required for cloud deployments.
-OBLIEN_API_URL=https://api.oblien.com
+# Leave unset to use the installed SDK's default API version.
+# OBLIEN_API_URL=https://your-proxy.example/api/v1
OBLIEN_CLIENT_ID=
OBLIEN_CLIENT_SECRET=
# Optional: enable only after this software preset is published on your provider.
diff --git a/apps/api/assets/geoip/GeoLite2-Country.mmdb b/apps/api/assets/geoip/GeoLite2-Country.mmdb
index 53584f011..50f78498c 100644
Binary files a/apps/api/assets/geoip/GeoLite2-Country.mmdb and b/apps/api/assets/geoip/GeoLite2-Country.mmdb differ
diff --git a/apps/api/package.json b/apps/api/package.json
index 6c8dfc4ef..80b6158d5 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -1,6 +1,6 @@
{
"name": "@repo/api",
- "version": "0.9.11",
+ "version": "0.9.12",
"license": "Apache-2.0",
"private": true,
"type": "module",
diff --git a/apps/api/scripts/cloud-readiness.ts b/apps/api/scripts/cloud-readiness.ts
index 1c2330b94..0a483cae5 100644
--- a/apps/api/scripts/cloud-readiness.ts
+++ b/apps/api/scripts/cloud-readiness.ts
@@ -1,4 +1,5 @@
/** Read-only release checks. Does not create tokens, checkouts, or resources. */
+import { oblienApiBaseUrl, oblienApiUrl } from "@repo/adapters";
import { runtimeTarget } from "@repo/core";
import { assertOblienEntitlementMatchesSubscription, OblienBillingApi } from "@repo/platform/engine/lib/oblien-billing-api";
import { OBLIEN_WEBHOOK_EVENTS, oblienWebhookUrl } from "@repo/platform/engine/lib/oblien-webhook-config";
@@ -7,13 +8,13 @@ const results: Array<{ check: string; ok: boolean; skipped?: boolean; detail?: s
const record = (check: string, ok: boolean, detail?: string) => results.push({ check, ok, ...(detail ? { detail } : {}) });
const clientId = process.env.OBLIEN_CLIENT_ID;
const clientSecret = process.env.OBLIEN_CLIENT_SECRET;
-const apiBase = process.env.OBLIEN_API_URL ?? "https://api.oblien.com";
+const apiBase = oblienApiBaseUrl(process.env.OBLIEN_API_URL);
record("Cloud mode", process.env.CLOUD_MODE === "true");
record("Oblien credentials configured", Boolean(clientId && clientSecret));
record("Webhook secret configured", Boolean(process.env.OBLIEN_WEBHOOK_SECRET));
record("Subscription purchases enabled", process.env.BILLING_ENABLED === "true");
-const billing = new OblienBillingApi({ clientId, clientSecret, baseUrl: apiBase });
+const billing = new OblienBillingApi({ clientId, clientSecret, baseUrl: apiBase.toString() });
const checks = await Promise.allSettled([
(async () => {
await billing.assertResellerSupport();
@@ -35,13 +36,13 @@ const checks = await Promise.allSettled([
(async () => {
const callback = oblienWebhookUrl(process.env.OBLIEN_WEBHOOK_URL, runtimeTarget.api);
if (!clientId || !clientSecret) throw new Error("Oblien credentials are missing");
- const response = await fetch(`${apiBase.replace(/\/+$/, "")}/webhooks`, {
+ const response = await fetch(oblienApiUrl(apiBase, "/webhooks"), {
headers: { "X-Client-ID": clientId, "X-Client-Secret": clientSecret },
redirect: "error", signal: AbortSignal.timeout(15_000),
});
if (!response.ok) throw new Error(`Webhook registry HTTP ${response.status}`);
const body = await response.json() as { success: boolean; webhooks?: Array<{ url: string; active: boolean; namespace?: string | null; events: string[]; secret?: string | null }> };
- const webhook = body.success && body.webhooks?.find((item) => item.url === callback && !item.namespace && item.active);
+ const webhook = body.success ? body.webhooks?.find((item) => item.url === callback && !item.namespace && item.active) : undefined;
const missing = OBLIEN_WEBHOOK_EVENTS.filter((event) => !webhook || !webhook.events.includes(event));
const maskedSecret = typeof webhook?.secret === "string" && /^[*•*…]+$/u.test(webhook.secret);
const matchingSecret = Boolean(webhook?.secret && webhook.secret === process.env.OBLIEN_WEBHOOK_SECRET);
@@ -56,7 +57,7 @@ const checks = await Promise.allSettled([
})(),
(async () => {
if (!clientId || !clientSecret) throw new Error("Oblien credentials are missing");
- const response = await fetch(`${apiBase.replace(/\/+$/, "")}/namespaces?limit=1`, {
+ const response = await fetch(oblienApiUrl(apiBase, "/namespaces?limit=1"), {
headers: { "X-Client-ID": clientId, "X-Client-Secret": clientSecret },
redirect: "error", signal: AbortSignal.timeout(15_000),
});
diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts
index 264549493..0363ab976 100644
--- a/apps/api/src/app.ts
+++ b/apps/api/src/app.ts
@@ -23,6 +23,7 @@ import {
registerControllerLifecycle,
} from "./modules/system/instance/controller-state";
import { resumeControllerSockets } from "./lib/ws";
+import { resumeControllerStreams } from "./lib/sse";
import { trackBackgroundWork } from "@repo/platform/engine/lib/background-work";
import { instanceAuthorityGuard } from "./modules/system/instance/authority-guard";
import { quiesceController } from "./modules/system/instance/quiescence";
@@ -408,6 +409,7 @@ async function startControllerBackground(): Promise {
backgroundStarted = true;
try {
resumeControllerSockets();
+ resumeControllerStreams();
// ─── Backup job runner + boot reconcile ─────────────────────────────
//
// One JobRunner powers all backup work — BullMQ when Redis is
diff --git a/apps/api/src/lib/route-permission.ts b/apps/api/src/lib/route-permission.ts
index 39337096d..36deb84ae 100644
--- a/apps/api/src/lib/route-permission.ts
+++ b/apps/api/src/lib/route-permission.ts
@@ -276,6 +276,8 @@ export interface McpRouteMeta {
description: string;
/** Override the inferred hint for actions such as destructive migration cutover. */
destructive?: boolean;
+ /** Whether this tool may interact with external systems; defaults to true. */
+ openWorld?: boolean;
}
export interface PermissionSpec {
@@ -474,13 +476,10 @@ export function isPublicSpec(spec: RouteSpec): spec is PublicSpec {
* Be precise about what that org-wide check buys, because it is easy to misread as
* a defense it is not: it is strict only for a RESTRICTED principal (a scoped
* token), which needs an all-GitHub grant to pass. For a session-authenticated
- * owner/admin/**member** it is satisfied by bare membership —
- * `roleAllowsResourceType` (permission.ts) ignores the action level for those
- * roles, so `github:admin` is no higher a bar than `github:read`. The per-repo,
- * read-vs-write authority for those principals is enforced ONLY by
- * `github-access.ts` at the token funnel and at the mutating service helpers.
- * Reading this comment as "the route layer already gates writes" is what let
- * GHSA-hp2g-hw7g-f3vm sit behind a `github:admin` tag.
+ * owner/admin it is satisfied by broad membership authority. Ordinary members
+ * cannot satisfy an admin action. Per-repo read/write authority still belongs
+ * to `github-access.ts` at the token funnel and mutating service helpers; an
+ * org-wide tag never substitutes for that repository-specific check.
* Paramless GitHub routes (/home, /status, /repos) also stay on the org-wide
* path: `filterToolsForPrincipal` already hides them from a scoped token via
* `perm.wildcard`, and their handlers narrow results through
diff --git a/apps/api/src/lib/sse.ts b/apps/api/src/lib/sse.ts
index 210f16549..469f5dde6 100644
--- a/apps/api/src/lib/sse.ts
+++ b/apps/api/src/lib/sse.ts
@@ -41,7 +41,12 @@ import { SYSTEM } from "@repo/core";
import { trackBackgroundWork } from "@repo/platform/engine/lib/background-work";
const controllerStreams = new Set();
+let accepting = true;
+export function resumeControllerStreams(): void {
+ accepting = true;
+}
export function closeControllerStreams(): void {
+ accepting = false;
for (const stream of controllerStreams) stream.abort();
}
@@ -182,6 +187,16 @@ export function streamSSE(
c: Context,
cb: (stream: SSEStreamingApi) => Promise,
) {
+ // An admitted request can finish its permission/metadata read after the HTTP
+ // fence closed existing streams. Do not give the drain a new live subscriber.
+ if (!accepting) {
+ c.header("Retry-After", "5");
+ c.header("Cache-Control", "no-store");
+ return c.json({
+ code: "INSTANCE_CONTROLLER_INACTIVE",
+ error: "Your instance is moving. Reconnect after the handoff.",
+ }, 503);
+ }
const context = currentErrorContext();
// Disable reverse-proxy response buffering. nginx/OpenResty buffer proxied
// responses by default, which holds SSE events back until the buffer fills —
diff --git a/apps/api/src/modules/billing/billing-capacity-catalog.test.ts b/apps/api/src/modules/billing/billing-capacity-catalog.test.ts
index e49d13054..eea7004b3 100644
--- a/apps/api/src/modules/billing/billing-capacity-catalog.test.ts
+++ b/apps/api/src/modules/billing/billing-capacity-catalog.test.ts
@@ -9,6 +9,7 @@ import type { OblienSubscription } from "@repo/platform/engine/lib/oblien-billin
import { savedOffer, savedMetadata, savedMonthlyHobby } from "../../../test/helpers/saved-cloud-offer";
import capacityFixture from "../../../test/fixtures/oblien-capacity-catalog.json";
import { oblienCapacityCatalogSchema } from "@repo/platform/engine/lib/oblien-capacity";
+import { cloudBillingContract } from "@repo/adapters";
const savedPro = (): NonNullable => ({ tierId: "reseller", status: "active", billingInterval: "monthly",
periodStart: "2026-09-01T00:00:00Z", periodEnd: "2026-10-01T00:00:00Z", cancelAtPeriodEnd: false, canceledAt: null,
@@ -17,7 +18,7 @@ const monthlyPro = (): NonNullable => ({ ...savedPro(),
offer: subscriptionOffer("pro", "monthly"), metadata: subscriptionMetadata("pro", "org-a", "ns-a") });
describe("funded Cloud offers and isolated capacity", () => {
- it.each([undefined, oblienCapacityCatalogSchema.parse(capacityFixture)])(
+ it.each([undefined, oblienCapacityCatalogSchema.parse(cloudBillingContract(capacityFixture))])(
"publishes only subscription plans without prepaid compute offers (with or without provider capacity)",
(provider) => {
const catalog = presentCloudPlans("en", provider);
diff --git a/apps/api/src/modules/billing/billing-checkout.test.ts b/apps/api/src/modules/billing/billing-checkout.test.ts
index 9bfae4ea9..58bfb2d97 100644
--- a/apps/api/src/modules/billing/billing-checkout.test.ts
+++ b/apps/api/src/modules/billing/billing-checkout.test.ts
@@ -37,7 +37,7 @@ vi.mock("@repo/platform/engine/lib/cloud-workspace-host", () => ({
readCloudWorkspaceHost: async () => ({ provider: null }),
}));
vi.mock("@repo/platform/engine/lib/oblien-client", () => ({
- getOblienClient: () => ({ workspaces: { getQuota: h.quota } }),
+ getOblienClient: () => ({ vms: { getQuota: h.quota } }),
getOblienBillingApi: () => ({
createCheckout: h.checkout,
createPortal: h.portal,
diff --git a/apps/api/src/modules/billing/billing-reconcile.test.ts b/apps/api/src/modules/billing/billing-reconcile.test.ts
index 5d92b3621..3ee761206 100644
--- a/apps/api/src/modules/billing/billing-reconcile.test.ts
+++ b/apps/api/src/modules/billing/billing-reconcile.test.ts
@@ -116,15 +116,25 @@ describe("Oblien-managed entitlements", () => {
h.balance.mockResolvedValue({ ...state.balance, billingMode: "payg" });
await expect(assertCloudCanSpend("org_1")).rejects.toMatchObject({ code: "CLOUD_BILLING_BLOCKED" });
});
- it("allows billing recovery after an unpaid renewal without granting compute or credits", async () => {
+ it.each(["active", "past_due"] as const)("allows billing recovery during a %s unpaid renewal without granting compute or credits", async status => {
const state = unpaidMonthlyCloudBilling();
+ state.subscription.status = status;
h.entitlement.mockResolvedValue(state.entitlement);
h.subscription.mockResolvedValue({ namespace: state.entitlement.namespace, subscription: state.subscription });
h.balance.mockResolvedValue(state.balance);
const result = await syncOblienEntitlement("org_1", { syncResourceLimits: false });
- expect(result).toMatchObject({ tier: "pro", subscription: { status: "past_due" }, entitlement: { status: "canceled", computeCovered: false } });
+ expect(result).toMatchObject({ tier: "pro", subscription: { status }, entitlement: { status: "canceled", computeCovered: false } });
await expect(assertNamespaceHasQuota("org_1")).resolves.toBeUndefined();
await expect(assertCloudCanSpend("org_1")).rejects.toMatchObject({ statusCode: 402, code: "CLOUD_BILLING_BLOCKED" });
+ expect(h.mirror).toHaveBeenCalledWith("workspace_1", "org_1", "os-customer", {
+ planTierId: "pro", subscriptionStatus: "canceled",
+ currentPeriodStart: new Date(state.entitlement.periodStart!),
+ currentPeriodEnd: new Date(state.entitlement.periodEnd!),
+ });
+ // A newer balance response alone must not turn old, uncovered capacity into
+ // paid compute. Both authoritative reads must confirm the funded month.
+ h.balance.mockResolvedValue({ ...state.balance, blocking: false, computeCovered: true });
+ await expect(assertCloudCanSpend("org_1")).rejects.toMatchObject({ statusCode: 402, code: "CLOUD_BILLING_BLOCKED" });
expect(h.limits).not.toHaveBeenCalled();
expect(h.setQuota).not.toHaveBeenCalled();
expect(h.resetQuota).not.toHaveBeenCalled();
diff --git a/apps/api/src/modules/billing/oblien-billing-api.test.ts b/apps/api/src/modules/billing/oblien-billing-api.test.ts
index 16fd45c0e..1723cabb3 100644
--- a/apps/api/src/modules/billing/oblien-billing-api.test.ts
+++ b/apps/api/src/modules/billing/oblien-billing-api.test.ts
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
import { OblienBillingApi, oblienOfferSchema, assertOblienEntitlementMatchesSubscription } from "@repo/platform/engine/lib/oblien-billing-api";
import { BillingOperationSchemas } from "@repo/contracts";
import { Value } from "@sinclair/typebox/value";
+import { providerBillingFixture } from "../../../test/helpers/oblien-vm-billing";
import capacityCatalog from "../../../test/fixtures/oblien-capacity-catalog.json";
import { monthlyCloudBilling, unpaidMonthlyCloudBilling } from "../../../test/helpers/monthly-cloud-offer";
@@ -25,7 +26,7 @@ const subscription = { success: true, namespace: "os-one", subscription: {
cancelAtPeriodEnd: true, canceledAt: "2026-09-15T00:00:00Z",
} };
function setup(body: unknown, status = 200) {
- const fetcher = vi.fn(async (_url: Parameters[0], _init?: RequestInit) => Response.json(body, { status }));
+ const fetcher = vi.fn(async (_url: Parameters[0], _init?: RequestInit) => Response.json(providerBillingFixture(body), { status }));
const api = new OblienBillingApi({ clientId: "test-id", clientSecret: "test-secret", fetch: fetcher as unknown as typeof fetch });
return { api, fetcher };
}
@@ -47,7 +48,7 @@ describe("Oblien billing SDK and transport contract", () => {
await api.createCheckout({ namespace: "os-one", kind: "subscription", billingInterval: "yearly",
offer: { ...monthlyCloudBilling().subscription.offer!, unitAmount: 12000 }, metadata,
affiliateBuyer, affiliateCode: "AF-0123456789", successUrl: "https://app.openship.io", cancelUrl: "https://app.openship.io", idempotencyKey: "referral-transport" });
- expect(fetcher).toHaveBeenCalledExactlyOnceWith("https://api.oblien.com/billing/checkout", expect.objectContaining({
+ expect(fetcher).toHaveBeenCalledExactlyOnceWith("https://api.oblien.com/v1/billing/checkout", expect.objectContaining({
method: "POST", redirect: "error", signal: expect.any(AbortSignal),
headers: expect.objectContaining({ "X-Client-ID": "test-id", "X-Client-Secret": "test-secret" }),
}));
@@ -59,7 +60,7 @@ describe("Oblien billing SDK and transport contract", () => {
const live = { success: true, credits_per_dollar: 100, rate_card_id: "live", rates: { cpu_per_min: 1.5, memory_per_gb_min: 0.2, disk_per_gb: 0, network_per_gb: 0.15 } };
const { api, fetcher } = setup({ ...live, compute_rate_cards: [{ chargeEnabled: false, cpu_per_min: 0.001 }] });
expect(await api.getMeteredPricing()).toEqual(live);
- expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/pricing/calculator", expect.objectContaining({ method: "GET", redirect: "error", headers: { Accept: "application/json" } }));
+ expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/pricing/calculator", expect.objectContaining({ method: "GET", redirect: "error", headers: { Accept: "application/json" } }));
});
it.each([
{ credits_per_dollar: 50, rate_card_id: "new", rates: { cpu_per_min: 1, memory_per_gb_min: 1, disk_per_gb: 0, network_per_gb: 0 } },
@@ -74,14 +75,14 @@ describe("Oblien billing SDK and transport contract", () => {
const { api, fetcher } = setup({ success: true, namespace: "os-one", pendingCheckout, wallet: { balance: 12000 } });
expect(await api.getPendingCapacityCheckout("os-one")).toEqual({ success: true, namespace: "os-one",
pendingCheckout: { ...pendingCheckout, quote: { id: "quote_pending", namespace: "os-one", paymentSource: "stripe" } } });
- expect(fetcher.mock.calls[0]![0]).toBe("https://api.oblien.com/billing/capacity?namespace=os-one");
+ expect(fetcher.mock.calls[0]![0]).toBe("https://api.oblien.com/v1/billing/capacity?namespace=os-one");
await expect(api.getPendingCapacityCheckout("os-other")).rejects.toMatchObject({ code: "OBLIEN_BILLING_NAMESPACE_MISMATCH" });
});
it("cancels a capacity payment with the saved provider quote and retry identity", async () => {
const { api, fetcher } = setup({ success: true, namespace: "os-one", pendingCheckout: null });
const input = { quoteId: "quote_pending", idempotencyKey: "cancel-once" };
await expect(api.cancelCapacityCheckout("os-one", input)).resolves.toMatchObject({ pendingCheckout: null });
- expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/capacity/change/cancel", expect.objectContaining({
+ expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/capacity/change/cancel", expect.objectContaining({
method: "POST",
}));
expect(JSON.parse(fetcher.mock.calls[0]![1]!.body as string)).toEqual({ namespace: "os-one", ...input });
@@ -101,7 +102,7 @@ describe("Oblien billing SDK and transport contract", () => {
(await api.cancelCheckout("os-one", checkout.id, { idempotencyKey: "cancel-once" })).checkout,
).toEqual(checkout);
expect(fetcher).toHaveBeenCalledWith(
- "https://api.oblien.com/billing/checkout/bco_original/cancel",
+ "https://api.oblien.com/v1/billing/checkout/bco_original/cancel",
expect.objectContaining({
method: "POST",
body: JSON.stringify({ namespace: "os-one", idempotencyKey: "cancel-once" }),
@@ -123,7 +124,7 @@ describe("Oblien billing SDK and transport contract", () => {
it.each([
{ quote: { id: "quote_pending", namespace: "os-other", paymentSource: "stripe" }, checkoutId: "cs_requested", url: null },
{ quote: { id: "quote_pending", namespace: "os-one", paymentSource: "stripe" }, checkoutId: "cs_requested", url: "https://evil.example/pay" },
- { quote: { id: "quote_pending", namespace: "os-one", paymentSource: "stripe" }, checkoutId: "cs_requested", url: "https://api.oblien.com/not-a-payment#secret" },
+ { quote: { id: "quote_pending", namespace: "os-one", paymentSource: "stripe" }, checkoutId: "cs_requested", url: "https://api.oblien.com/v1/not-a-payment#secret" },
])("rejects foreign capacity scope and untrusted resume URLs", async pendingCheckout => {
await expect(setup({ success: true, namespace: "os-one", pendingCheckout }).api.getPendingCapacityCheckout("os-one")).rejects.toThrow();
});
@@ -135,16 +136,16 @@ describe("Oblien billing SDK and transport contract", () => {
});
it("scopes complimentary policy writes to the requested namespace and validates the response", async () => {
const policy = { quotaLimit: 3000, overdraft: 60, suspendThreshold: 60, onOverdraftAction: "stop_workspaces" as const };
- const result = { success: true, namespace: "os-one", service: "workspace_vm", ...policy };
+ const result = { success: true, namespace: "os-one", service: "vm_compute", ...policy };
const { api, fetcher } = setup(result);
expect(await api.setPolicy("os-one", policy)).toEqual(result);
- expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/policy/os-one", expect.objectContaining({ method: "PUT", body: JSON.stringify(policy) }));
+ expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/policy/os-one", expect.objectContaining({ method: "PUT", body: JSON.stringify(providerBillingFixture(policy)) }));
await expect(api.setPolicy("os-two", policy)).rejects.toMatchObject({ code: "OBLIEN_BILLING_NAMESPACE_MISMATCH" });
});
it("keeps the same provider reset key on retry and rejects an unscoped reset response", async () => {
const { api, fetcher } = setup({ success: true, namespace: "os-one", applied: false });
expect(await api.resetQuota("os-one", "2026-10-25T14:00:00.000Z")).toMatchObject({ applied: false });
- expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/policy/os-one/reset", expect.objectContaining({ method: "POST", body: JSON.stringify({ periodEnd: "2026-10-25T14:00:00.000Z" }) }));
+ expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/policy/os-one/reset", expect.objectContaining({ method: "POST", body: JSON.stringify({ periodEnd: "2026-10-25T14:00:00.000Z" }) }));
await expect(setup({ success: true, applied: true }).api.resetQuota("os-one", "2026-10-25T14:00:00.000Z"))
.rejects.toMatchObject({ code: "OBLIEN_BILLING_INVALID_RESPONSE" });
});
@@ -215,7 +216,7 @@ describe("Oblien billing SDK and transport contract", () => {
expect(state.checkout).not.toHaveProperty("walletCredits");
expect(state.checkout).not.toHaveProperty("paymentId");
expect(fetcher.mock.calls[0]![0]).toBe(
- "https://api.oblien.com/billing/checkout/cs_requested?namespace=os-one",
+ "https://api.oblien.com/v1/billing/checkout/cs_requested?namespace=os-one",
);
await expect(api.getCheckout("os-other", "cs_requested")).rejects.toMatchObject({
code: "OBLIEN_BILLING_NAMESPACE_MISMATCH",
@@ -251,7 +252,7 @@ describe("Oblien billing SDK and transport contract", () => {
it("authenticates server requests and validates the returned customer namespace", async () => {
const { api, fetcher } = setup(entitlement);
expect((await api.getEntitlement("os-one")).quota.used).toBe(-50);
- expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/entitlement?namespace=os-one", expect.objectContaining({
+ expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/entitlement?namespace=os-one", expect.objectContaining({
headers: expect.objectContaining({ "X-Client-ID": "test-id", "X-Client-Secret": "test-secret" }), redirect: "error",
}));
await expect(api.getEntitlement("os-two")).rejects.toMatchObject({ code: "OBLIEN_BILLING_NAMESPACE_MISMATCH" });
@@ -275,22 +276,24 @@ describe("Oblien billing SDK and transport contract", () => {
idempotencyKey: "checkout-123",
};
await api.createCheckout(input);
- expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/checkout", expect.objectContaining({ method: "POST" }));
+ expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/checkout", expect.objectContaining({ method: "POST" }));
expect(JSON.parse(String(fetcher.mock.calls[0]![1]!.body))).toEqual({ ...input, allowPromotionCodes: true });
});
- it("accepts the exact Oblien promotion checkout and preserves its opaque ID", async () => {
+ it("keeps the hosted payment page unversioned while sending checkout requests to /v1", async () => {
const checkoutId = "bco_24f15202-6a3d-4b27-b7c2-c3abbc401bee";
const url = `https://api.oblien.com/billing/pay#${"a".repeat(43)}`;
- const { api } = setup({ success: true, url, checkoutId });
+ const { api, fetcher } = setup({ success: true, url, checkoutId });
await expect(api.createCheckout({ namespace: "os-one", kind: "topup", offer, metadata,
successUrl: "https://app.openship.io", cancelUrl: "https://app.openship.io", idempotencyKey: "promotion-checkout" }))
.resolves.toMatchObject({ url, checkoutId });
+ expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/checkout", expect.objectContaining({ method: "POST" }));
});
it.each([
"http://api.oblien.com/billing/pay", "https://api.oblien.com.evil.example/billing/pay",
- "https://api.oblien.com/billing/pay?return=https://evil.example", "https://api.oblien.com/other",
+ "https://api.oblien.com/billing/pay?return=https://evil.example", "https://api.oblien.com/v1/other",
"https://api.oblien.com/billing/pay", "https://user@api.oblien.com/billing/pay",
"https://api.oblien.com:8443/billing/pay", "https://api.oblien.com/billing/pay/",
+ "https://api.oblien.com/v1/billing/pay",
])("rejects an invalid promotion checkout URL: %s", async (value) => {
const url = value + (value === "https://api.oblien.com/billing/pay" ? "#short" : `#${"a".repeat(43)}`);
await expect(setup({ success: true, url, checkoutId: "bco_24f15202-6a3d-4b27-b7c2-c3abbc401bee" }).api.createCheckout({
@@ -553,7 +556,7 @@ describe("Oblien billing SDK and transport contract", () => {
const { api, fetcher } = setup({ success: true, namespace: "os-one", url: "https://billing.stripe.com/p/session/test" });
const input = { namespace: "os-one", returnUrl: "https://app.openship.io/billing/overview" };
expect((await api.createPortal(input)).url).toBe("https://billing.stripe.com/p/session/test");
- expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/portal", expect.objectContaining({ method: "POST", body: JSON.stringify(input), redirect: "error", signal: expect.any(AbortSignal) }));
+ expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/portal", expect.objectContaining({ method: "POST", body: JSON.stringify(input), redirect: "error", signal: expect.any(AbortSignal) }));
await expect(api.createPortal({ ...input, namespace: "os-two" })).rejects.toMatchObject({ code: "OBLIEN_BILLING_NAMESPACE_MISMATCH" });
});
it("rejects a legacy owner portal even when its hosted URL is otherwise valid", async () => {
@@ -572,7 +575,7 @@ describe("Oblien billing SDK and transport contract", () => {
] as const)("uses the SDK %s method and checks the response namespace", async (method, verb, path) => {
const { api, fetcher } = setup(subscription);
expect(await api[method]("os-one")).toEqual(subscription);
- expect(fetcher).toHaveBeenCalledWith(`https://api.oblien.com${path}`, expect.objectContaining({
+ expect(fetcher).toHaveBeenCalledWith(`https://api.oblien.com/v1${path}`, expect.objectContaining({
method: verb, ...(verb === "POST" ? { body: JSON.stringify({ namespace: "os-one" }) } : {}),
}));
await expect(api[method]("os-two")).rejects.toMatchObject({ code: "OBLIEN_BILLING_NAMESPACE_MISMATCH" });
@@ -612,7 +615,7 @@ describe("Oblien monthly capacity contract", () => {
const catalog = await api.assertMonthlyCapacitySupport();
expect(catalog.tariff.usage).toEqual({ activeVcpuHourCents: 3, reservedGiBHourCents: 0.8, retainedGiBMonthCents: 5, monthHours: 720 });
const [url, request] = fetcher.mock.calls[0]!;
- expect(String(url)).toBe("https://api.oblien.com/billing/capacity/catalog");
+ expect(String(url)).toBe("https://api.oblien.com/v1/billing/capacity/catalog");
expect(request?.headers).not.toHaveProperty("X-Client-Secret");
expect(request?.headers).not.toHaveProperty("X-Client-ID");
});
@@ -656,7 +659,7 @@ describe("Oblien monthly capacity contract", () => {
.toThrow(/does not match/);
}
});
- it.each(["past_due", "unpaid", "paused", "canceled"] as const)("keeps billing readable for an expired paid month and a %s renewal", async status => {
+ it.each(["active", "past_due", "unpaid", "paused", "canceled"] as const)("keeps billing readable for an expired paid month and a %s renewal", async status => {
const state = unpaidMonthlyCloudBilling("org-one", "os-one");
state.subscription.status = status;
const entitlement = await setup(state.entitlement).api.getEntitlement("os-one");
@@ -665,9 +668,8 @@ describe("Oblien monthly capacity contract", () => {
expect(entitlement).toMatchObject({ status: "canceled", computeCovered: false, capacity: { status: "expired", computeCovered: false } });
expect(entitlement.periodEnd).not.toBe(subscription!.periodEnd);
});
- it("still rejects funded, overlapping, foreign or inconsistent unpaid renewal records", () => {
+ it.each(["active", "past_due"] as const)("still rejects funded, overlapping, foreign or inconsistent %s renewal records", status => {
for (const mutate of [
- (state: ReturnType) => { state.subscription.status = "active"; },
(state: ReturnType) => { state.subscription.status = "trialing"; },
(state: ReturnType) => { state.entitlement.status = "active"; },
(state: ReturnType) => { state.entitlement.computeCovered = state.entitlement.capacity!.computeCovered = true; },
@@ -678,9 +680,12 @@ describe("Oblien monthly capacity contract", () => {
(state: ReturnType) => { state.subscription.periodStart = "2026-10-15T00:00:00Z"; },
(state: ReturnType) => { state.subscription.periodStart = null; },
(state: ReturnType) => { state.subscription.periodEnd = state.subscription.periodStart; },
+ (state: ReturnType) => { state.entitlement.periodStart = state.entitlement.capacity!.periodStart = state.entitlement.periodEnd!; },
(state: ReturnType) => { state.entitlement.capacity!.periodEnd = "2026-10-31T00:00:00Z"; },
]) {
- const state = unpaidMonthlyCloudBilling(); mutate(state);
+ const state = unpaidMonthlyCloudBilling();
+ state.subscription.status = status;
+ mutate(state);
expect(() => assertOblienEntitlementMatchesSubscription(state.entitlement, state.subscription)).toThrow(/does not match/);
}
});
@@ -692,9 +697,9 @@ describe("Oblien monthly capacity contract", () => {
offer: subscription.offer!, metadata: subscription.metadata!, idempotencyKey: "saved-monthly-order",
successUrl: "https://app.openship.io/billing/overview", cancelUrl: "https://app.openship.io/billing/plans" });
const [url, request] = fetcher.mock.calls[0]!;
- expect(String(url)).toBe("https://api.oblien.com/billing/checkout");
+ expect(String(url)).toBe("https://api.oblien.com/v1/billing/checkout");
const sent = JSON.parse(String(request?.body));
- expect(sent.offer).toMatchObject({ unitAmount, credits: 0, billingMode: "monthly", capacity: { vcpus: 4, memoryMb: 16384, diskGb: 128, workspaces: 1 } });
+ expect(sent.offer).toMatchObject({ unitAmount, credits: 0, billingMode: "monthly", capacity: { vcpus: 4, memoryMb: 16384, diskGb: 128, vms: 1 } });
expect(sent.offer).not.toHaveProperty("policy");
expect(sent.idempotencyKey).toBe("saved-monthly-order");
expect(sent.allowPromotionCodes).toBe(unitAmount > 0);
@@ -763,18 +768,18 @@ describe("Oblien subscription changes", () => {
it("delegates all four methods to the official SDK and preserves provider cents and fractional credits", async () => {
const preview = setup({ success: true, namespace: "os-one", quote });
expect((await preview.api.previewPlanChange("os-one", input)).quote).toEqual(quote);
- expect(preview.fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/subscription/changes/preview",
+ expect(preview.fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/subscription/changes/preview",
expect.objectContaining({ method: "POST" }));
expect(JSON.parse(String(preview.fetcher.mock.calls[0]![1]!.body))).toEqual({ namespace: "os-one", ...input });
const accept = setup({ success: true, namespace: "os-one", change }, 202);
expect((await accept.api.changePlan("os-one", { quoteId: quote.id, idempotencyKey: "confirm-request" })).change.status).toBe("payment_pending");
- expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/billing/subscription/changes",
+ expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/v1/billing/subscription/changes",
expect.objectContaining({ method: "POST" }));
expect(JSON.parse(String(accept.fetcher.mock.calls.at(-1)![1]!.body))).toEqual({ namespace: "os-one", quoteId: quote.id, idempotencyKey: "confirm-request" });
await accept.api.getPlanChange("os-one", change.id);
- expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/billing/subscription/changes/change_one?namespace=os-one", expect.objectContaining({ method: "GET" }));
+ expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/v1/billing/subscription/changes/change_one?namespace=os-one", expect.objectContaining({ method: "GET" }));
await accept.api.cancelPlanChange("os-one", change.id, "cancel-request");
- expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/billing/subscription/changes/change_one/cancel",
+ expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/v1/billing/subscription/changes/change_one/cancel",
expect.objectContaining({ method: "POST" }));
expect(JSON.parse(String(accept.fetcher.mock.calls.at(-1)![1]!.body))).toEqual({ namespace: "os-one", idempotencyKey: "cancel-request" });
});
diff --git a/apps/api/src/modules/billing/oblien-managed-transfer.test.ts b/apps/api/src/modules/billing/oblien-managed-transfer.test.ts
index fb2ed26a8..c43a1504f 100644
--- a/apps/api/src/modules/billing/oblien-managed-transfer.test.ts
+++ b/apps/api/src/modules/billing/oblien-managed-transfer.test.ts
@@ -1,11 +1,12 @@
import { describe, expect, it } from "vitest";
import { Value } from "@sinclair/typebox/value";
import { BillingComputeSchema } from "@repo/contracts";
+import { providerBillingFixture } from "../../../test/helpers/oblien-vm-billing";
import { OblienBillingApi, assertOblienEntitlementMatchesSubscription } from "@repo/platform/engine/lib/oblien-billing-api";
import { monthlyCloudBilling } from "../../../test/helpers/monthly-cloud-offer";
import transfer from "../../../test/fixtures/oblien-managed-transfer.json";
-// SDK 2.10's live response shape, with synthetic counters and no customer data.
+// Native provider transfer counters with synthetic data.
const unlimited = { ...transfer, unlimited: true, includedBytes: null,
includedAvailableBytes: null, availableBytes: null };
async function readTransfer(network: unknown, covered = true) {
@@ -14,7 +15,7 @@ async function readTransfer(network: unknown, covered = true) {
...entitlement.capacity, computeCovered: covered, network,
} };
const api = new OblienBillingApi({ clientId: "test-id", clientSecret: "test-secret",
- fetch: (async () => Response.json(payload)) as typeof fetch });
+ fetch: (async () => Response.json(providerBillingFixture(payload))) as typeof fetch });
const result = await api.getEntitlement("os-one");
assertOblienEntitlementMatchesSubscription(result, subscription);
return result.capacity!;
diff --git a/apps/api/src/modules/billing/oblien-webhook-crypto.test.ts b/apps/api/src/modules/billing/oblien-webhook-crypto.test.ts
index d92cc82fe..25c707895 100644
--- a/apps/api/src/modules/billing/oblien-webhook-crypto.test.ts
+++ b/apps/api/src/modules/billing/oblien-webhook-crypto.test.ts
@@ -64,7 +64,7 @@ describe("deriveOblienEventId", () => {
const base: OblienEventEnvelope = {
event: "credits.usage",
timestamp: "2026-07-21T10:00:00Z",
- data: { namespace: "os-abc", workspace_id: "ws_1", period_end: "2026-08-01T00:00:00Z" },
+ data: { namespace: "os-abc", vm_id: "ws_1", period_end: "2026-08-01T00:00:00Z" },
};
it("is deterministic for the same payload", () => {
diff --git a/apps/api/src/modules/billing/oblien-webhook.controller.test.ts b/apps/api/src/modules/billing/oblien-webhook.controller.test.ts
index 360375850..2302b9d73 100644
--- a/apps/api/src/modules/billing/oblien-webhook.controller.test.ts
+++ b/apps/api/src/modules/billing/oblien-webhook.controller.test.ts
@@ -294,7 +294,7 @@ describe("oblienWebhook — dispatch", () => {
describe("durable quota alert receipt", () => {
it("returns 503 without a checkpoint when notification storage fails, then retries the same event", async () => {
- const body = JSON.stringify({ id: "evt-critical", event: "credits.depleted", data: { namespace: "os-abc", service: "workspace_vm" } });
+ const body = JSON.stringify({ id: "evt-critical", event: "credits.depleted", data: { namespace: "os-abc", service: "vm_compute" } });
h.enqueue.mockRejectedValueOnce(new Error("database unavailable"));
expect(((await oblienWebhook(makeCtx(body, sign(body), "evt-critical"))) as unknown as JsonResult).status).toBe(503);
expect(h.processed.size).toBe(0);
@@ -305,7 +305,7 @@ describe("durable quota alert receipt", () => {
expect(h.processed.size).toBe(1);
});
it("leaves the event retryable when exhaustion activity cannot be recorded", async () => {
- const body = JSON.stringify({ id: "evt-activity", event: "credits.depleted", data: { namespace: "os-abc", service: "workspace_vm" } });
+ const body = JSON.stringify({ id: "evt-activity", event: "credits.depleted", data: { namespace: "os-abc", service: "vm_compute" } });
h.auditRecord.mockRejectedValueOnce(new Error("activity storage unavailable"));
expect(((await oblienWebhook(makeCtx(body, sign(body), "evt-activity"))) as unknown as JsonResult).status).toBe(503);
expect(h.processed.size).toBe(0);
diff --git a/apps/api/src/modules/cloud/cloud-pages.service.ts b/apps/api/src/modules/cloud/cloud-pages.service.ts
index 9530a4f99..f2b18387a 100644
--- a/apps/api/src/modules/cloud/cloud-pages.service.ts
+++ b/apps/api/src/modules/cloud/cloud-pages.service.ts
@@ -5,7 +5,7 @@ import { authorizeCloudRelayWorkspace } from "./cloud-relay-access";
export async function createCloudPage(
ctx: RequestContext,
- input: { workspace_id: string; path: string; name: string; slug: string; domain?: string },
+ input: { vm_id: string; path: string; name: string; slug: string; domain?: string },
): Promise {
const workspaceId = await authorizeCloudRelayWorkspace(ctx);
const namespace = await ensureNamespace(ctx.organizationId, workspaceId);
diff --git a/apps/api/src/modules/cloud/cloud-resource.controller.ts b/apps/api/src/modules/cloud/cloud-resource.controller.ts
index db9cd5e26..34ac7305e 100644
--- a/apps/api/src/modules/cloud/cloud-resource.controller.ts
+++ b/apps/api/src/modules/cloud/cloud-resource.controller.ts
@@ -10,9 +10,9 @@ import { authorizeCloudRelayWorkspace } from "./cloud-relay-access";
const id = z.string().regex(/^[a-zA-Z0-9_-]{1,128}$/);
const path = z.string().min(1).max(2048);
const domain = z.string().min(1).max(253);
-const source = z.object({ workspace_id: id, path }).strict();
+const source = z.object({ vm_id: id, path }).strict();
const action = z.discriminatedUnion("kind", [
- z.object({ kind: z.literal("proxy"), workspace: id, port: z.number().int().min(1).max(65535),
+ z.object({ kind: z.literal("proxy"), vm: id, port: z.number().int().min(1).max(65535),
stripPrefix: z.boolean().optional(), path: path.optional() }).strict(),
z.object({ kind: z.literal("rewrite"), to: path }).strict(),
z.object({ kind: z.literal("redirect"), to: path, status: z.union([z.literal(301), z.literal(302), z.literal(307), z.literal(308)]).optional() }).strict(),
diff --git a/apps/api/src/modules/cloud/cloud-saas.controller.ts b/apps/api/src/modules/cloud/cloud-saas.controller.ts
index 03810ef70..10adfda66 100644
--- a/apps/api/src/modules/cloud/cloud-saas.controller.ts
+++ b/apps/api/src/modules/cloud/cloud-saas.controller.ts
@@ -635,11 +635,11 @@ export async function checkEdgeVerification(c: Context) {
// ─── Pages proxy ────────────────────────────────────────────────────────────
/**
- * POST /api/cloud/pages { workspace_id, path, name, slug, domain? }
+ * POST /api/cloud/pages { vm_id, path, name, slug, domain? }
*
* Forwards to Oblien with the caller's namespace token. Oblien
* enforces:
- * - `workspace_id` must belong to the caller's namespace (or 404)
+ * - `vm_id` must belong to the caller's namespace (or 404)
* - `slug` must be free on the shared zone (or 409 SLUG_TAKEN)
*
* Returns the raw Oblien SDK shape so the caller's infrastructure adapter
@@ -648,18 +648,18 @@ export async function checkEdgeVerification(c: Context) {
export async function pagesProxy(c: Context) {
const ctx = getRequestContext(c);
const body = await c.req.json<{
- workspace_id?: string;
+ vm_id?: string;
path?: string;
name?: string;
slug?: string;
domain?: string;
}>();
- if (!body.workspace_id || !body.path || !body.name || !body.slug) {
- return c.json({ error: "workspace_id, path, name and slug are required" }, 400);
+ if (!body.vm_id || !body.path || !body.name || !body.slug) {
+ return c.json({ error: "vm_id, path, name and slug are required" }, 400);
}
try {
const result = await createCloudPage(ctx, {
- workspace_id: body.workspace_id,
+ vm_id: body.vm_id,
path: body.path,
name: body.name,
slug: body.slug,
diff --git a/apps/api/src/modules/deployments/build-pipeline.prebuilt-image.test.ts b/apps/api/src/modules/deployments/build-pipeline.prebuilt-image.test.ts
index 4e5d91744..f4df5dde0 100644
--- a/apps/api/src/modules/deployments/build-pipeline.prebuilt-image.test.ts
+++ b/apps/api/src/modules/deployments/build-pipeline.prebuilt-image.test.ts
@@ -92,7 +92,7 @@ vi.mock("@repo/db", () => ({
listByProject: vi.fn(async () => []),
remove: vi.fn(async () => undefined),
},
- project: { findById: mocks.findProjectById, update: vi.fn(async () => undefined) },
+ project: { findById: mocks.findProjectById, update: vi.fn(async () => undefined), getEnvMap: vi.fn(async () => ({})) },
},
}));
diff --git a/apps/api/src/modules/deployments/cancel-is-final.test.ts b/apps/api/src/modules/deployments/cancel-is-final.test.ts
index 841363250..062a62169 100644
--- a/apps/api/src/modules/deployments/cancel-is-final.test.ts
+++ b/apps/api/src/modules/deployments/cancel-is-final.test.ts
@@ -43,7 +43,6 @@ vi.mock("@repo/platform/engine/modules/projects/cleanup-keep-set", () => ({
// Terminal-event side channels, each of which drags in auth/github/mail wiring.
vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ notification: { emit: mocks.notify } }));
vi.mock("../../lib/audit", () => ({ audit: { recordAsync: vi.fn(), record: vi.fn() } }));
-vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: vi.fn(async () => {}) }));
vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({
onWebmailDeployed: vi.fn(async () => {}),
}));
diff --git a/apps/api/src/modules/deployments/compose/build-cancel.test.ts b/apps/api/src/modules/deployments/compose/build-cancel.test.ts
index 86d366a08..fcb82ccb5 100644
--- a/apps/api/src/modules/deployments/compose/build-cancel.test.ts
+++ b/apps/api/src/modules/deployments/compose/build-cancel.test.ts
@@ -4,9 +4,11 @@ import { describe, expect, it, vi } from "vitest";
// Same stubs as build.service.test.ts: the DB row read and the SSE broadcast are
// side effects this contract doesn't depend on (and importing the real @repo/db
// would risk the PGlite single-instance lock).
-const { listByProjectMock } = vi.hoisted(() => ({ listByProjectMock: vi.fn() }));
+const { listByProjectMock, getEnvMapMock } = vi.hoisted(() => ({
+ listByProjectMock: vi.fn(), getEnvMapMock: vi.fn(async () => ({})),
+}));
vi.mock("@repo/db", () => ({
- repos: { service: { listByProject: listByProjectMock } },
+ repos: { project: { getEnvMap: getEnvMapMock }, service: { listByProject: listByProjectMock } },
}));
vi.mock("@repo/platform/engine/modules/deployments/session-manager", () => ({
broadcastServiceStatus: vi.fn(),
diff --git a/apps/api/src/modules/deployments/compose/build.service.test.ts b/apps/api/src/modules/deployments/compose/build.service.test.ts
index f8e2770d9..9023d7848 100644
--- a/apps/api/src/modules/deployments/compose/build.service.test.ts
+++ b/apps/api/src/modules/deployments/compose/build.service.test.ts
@@ -1,4 +1,5 @@
import { existsSync, readdirSync } from "node:fs";
+import { encrypt } from "@repo/platform/engine/lib/encryption";
import { readFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { isAbsolute, join } from "node:path";
@@ -12,9 +13,11 @@ import { describe, expect, it, vi } from "vitest";
// status. Both are side effects the inline-build materialization contract does not
// depend on — stub them so the test exercises ONLY the materialize/COPY path.
// (Importing the real @repo/db would also risk the PGlite single-instance lock.)
-const { listByProjectMock } = vi.hoisted(() => ({ listByProjectMock: vi.fn() }));
+const { listByProjectMock, getEnvMapMock } = vi.hoisted(() => ({
+ listByProjectMock: vi.fn(), getEnvMapMock: vi.fn(async () => ({})),
+}));
vi.mock("@repo/db", () => ({
- repos: { service: { listByProject: listByProjectMock, startServiceDeploymentTiming: vi.fn(async () => {}) } },
+ repos: { project: { getEnvMap: getEnvMapMock }, service: { listByProject: listByProjectMock, startServiceDeploymentTiming: vi.fn(async () => {}) } },
}));
vi.mock("@repo/platform/engine/modules/deployments/session-manager", () => ({
broadcastServiceStatus: vi.fn(),
@@ -567,6 +570,19 @@ describe("buildComposeImages — inline catalog build materialization", () => {
* These pin the producer side: which rows get a narrowed context, and which must not.
*/
describe("buildComposeImages — declared build context", () => {
+ it("uses each service's encrypted saved environment for its own build", async () => {
+ getEnvMapMock.mockResolvedValueOnce({ API_SECRET: encrypt("api-only"), PORT: encrypt("3000") });
+ getEnvMapMock.mockResolvedValueOnce({ WORKER_SECRET: encrypt("worker-only"), PORT: encrypt("8000") });
+ const { captured } = await run([
+ repoService({ id: "api", name: "api", build: "." }),
+ repoService({ id: "worker", name: "worker", build: "." }),
+ ], undefined, undefined, { SHARED: "shared" });
+ expect(captured.map(({ config }) => config.envVars)).toEqual([
+ { SHARED: "shared", API_SECRET: "api-only", PORT: "3000" },
+ { SHARED: "shared", WORKER_SECRET: "worker-only", PORT: "8000" },
+ ]);
+ });
+
it("#795 carries project env into the posted root-Dockerfile setup without duplicate service env", async () => {
const projectEnv = {
DATABASE_URI: "postgres://db/app",
diff --git a/apps/api/src/modules/deployments/route-issues-warning.test.ts b/apps/api/src/modules/deployments/route-issues-warning.test.ts
index ef824d981..662d10f40 100644
--- a/apps/api/src/modules/deployments/route-issues-warning.test.ts
+++ b/apps/api/src/modules/deployments/route-issues-warning.test.ts
@@ -1,12 +1,11 @@
import { describe, expect, it, vi } from "vitest";
// The function under test is pure; everything else this module reaches (DB, SSE,
-// notifications, favicon probing) is a side effect the assertion doesn't want.
+// notifications) is a side effect the assertion doesn't want.
// `@repo/adapters` stays REAL — `isEdgeDownMessage` is the branch being pinned.
vi.mock("@repo/db", () => ({ repos: {} }));
vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ notification: {} }));
vi.mock("../../lib/audit", () => ({ audit: {} }));
-vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: vi.fn() }));
vi.mock("@repo/platform/engine/modules/deployments/session-manager", () => ({}));
vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({
onWebmailDeployed: vi.fn(),
diff --git a/apps/api/src/modules/domains/routing-apply.service.test.ts b/apps/api/src/modules/domains/routing-apply.service.test.ts
index c3a3b8933..c63228aff 100644
--- a/apps/api/src/modules/domains/routing-apply.service.test.ts
+++ b/apps/api/src/modules/domains/routing-apply.service.test.ts
@@ -132,7 +132,7 @@ describe("Cloud Docker route tables", () => {
} as Record
)[`${container}:${port}`];
if (!published) throw new Error("service port is not published");
- return { workspace: "shared-vm", port: published };
+ return { vm: "shared-vm", port: published };
});
});
it("repairs an existing single static container route without rebuilding", async () => {
@@ -149,7 +149,7 @@ describe("Cloud Docker route tables", () => {
};
domainRepo.listByProject.mockResolvedValue([savedDomain]);
domainRepo.findByHostname.mockResolvedValue(savedDomain);
- target.mockResolvedValue({ workspace: "shared-vm", port: 30000 });
+ target.mockResolvedValue({ vm: "shared-vm", port: 30000 });
await applyCloudRouting({
project: { ...base, workloadType: "static", hasServer: false, port: 3000 } as never,
deployment: {
@@ -186,9 +186,9 @@ describe("Cloud Docker route tables", () => {
["stack-api.opsh.io", 30003, false],
]);
expect(publish.mock.calls.map((call) => call[3].routes[0].action)).toEqual([
- { kind: "proxy", workspace: "shared-vm", port: 30001 },
- { kind: "proxy", workspace: "shared-vm", port: 30002 },
- { kind: "proxy", workspace: "shared-vm", port: 30003 },
+ { kind: "proxy", vm: "shared-vm", port: 30001 },
+ { kind: "proxy", vm: "shared-vm", port: 30002 },
+ { kind: "proxy", vm: "shared-vm", port: 30003 },
]);
});
it("resolves project-level domains to their service's exact published port", async () => {
@@ -209,7 +209,7 @@ describe("Cloud Docker route tables", () => {
expect.objectContaining({
routes: [
expect.objectContaining({
- action: { kind: "proxy", workspace: "shared-vm", port: 30002 },
+ action: { kind: "proxy", vm: "shared-vm", port: 30002 },
}),
],
}),
@@ -235,15 +235,15 @@ describe("Cloud Docker route tables", () => {
expect(writes[0]![3].routes).toEqual([
{
match: { path: "/api/status", type: "exact" },
- action: { kind: "proxy", workspace: "shared-vm", port: 30001 },
+ action: { kind: "proxy", vm: "shared-vm", port: 30001 },
},
{
match: { path: "/api/", type: "prefix" },
- action: { kind: "proxy", workspace: "shared-vm", port: 30003 },
+ action: { kind: "proxy", vm: "shared-vm", port: 30003 },
},
{
match: { path: "/", type: "prefix" },
- action: { kind: "proxy", workspace: "shared-vm", port: 30001 },
+ action: { kind: "proxy", vm: "shared-vm", port: 30001 },
},
]);
});
@@ -259,7 +259,7 @@ describe("Cloud Docker route tables", () => {
}],
});
expect(publish).toHaveBeenCalledWith("api.onvo.me", undefined, true, {
- routes: [{ match: { path: "/v3", type: "prefix" }, action: { kind: "proxy", workspace: "shared-vm", port: 30003 } }],
+ routes: [{ match: { path: "/v3", type: "prefix" }, action: { kind: "proxy", vm: "shared-vm", port: 30003 } }],
});
});
it("keeps the old composite table if any path target is missing, while updating other hosts", async () => {
@@ -296,11 +296,11 @@ describe("Cloud Docker route tables", () => {
expect(rules).toEqual([
{
match: { path: "/api/", type: "prefix" },
- action: { kind: "proxy", workspace: "shared-vm", port: 30003 },
+ action: { kind: "proxy", vm: "shared-vm", port: 30003 },
},
{
match: { path: "/", type: "prefix" },
- action: { kind: "proxy", workspace: "shared-vm", port: 30001 },
+ action: { kind: "proxy", vm: "shared-vm", port: 30001 },
},
]);
});
diff --git a/apps/api/src/modules/images/images.service.ts b/apps/api/src/modules/images/images.service.ts
index b62749d95..6b24ab6c9 100644
--- a/apps/api/src/modules/images/images.service.ts
+++ b/apps/api/src/modules/images/images.service.ts
@@ -91,7 +91,7 @@ export async function listImages(
if (hit) return hit;
const client = await getClientForOrg(organizationId);
- const response = await client.workspaces.images.list(params);
+ const response = await client.vms.images.list(params);
const images = normalizeImages(response);
await store.set(key, images, CACHE_TTL_S);
return images;
diff --git a/apps/api/src/modules/mcp/mcp-tools.ts b/apps/api/src/modules/mcp/mcp-tools.ts
index 737e8e1fe..12cf298e5 100644
--- a/apps/api/src/modules/mcp/mcp-tools.ts
+++ b/apps/api/src/modules/mcp/mcp-tools.ts
@@ -42,7 +42,7 @@ export interface McpToolDef {
name: string;
description: string;
inputSchema: Record;
- annotations: { readOnlyHint: boolean; destructiveHint: boolean };
+ annotations: { readOnlyHint: boolean; destructiveHint: boolean; openWorldHint: boolean };
// Dispatch metadata (not sent to the client):
method: string;
path: string; // full path with :params, e.g. /api/projects/:id
@@ -76,6 +76,8 @@ export interface McpPrincipal {
/** Resolved with the same persisted instance-authority policy as HTTP calls. */
instanceAdmin?: boolean;
role: "owner" | "admin" | "member" | "restricted";
+ /** For scoped tokens, the current membership in their bound organization. */
+ membershipRole?: "owner" | "admin" | "member" | "restricted";
readOnly: boolean;
/** Resource types the token holds grants on — only consulted when role === "restricted". */
grantedRootTypes: ReadonlySet;
@@ -184,9 +186,12 @@ function inputSchema(
function annotationsFor(route: RegisteredRoute): {
readOnlyHint: boolean;
destructiveHint: boolean;
+ openWorldHint: boolean;
} {
const spec = route.spec;
- if (isPublicSpec(spec)) return { readOnlyHint: true, destructiveHint: false };
+ if (isPublicSpec(spec)) {
+ return { readOnlyHint: true, destructiveHint: false, openWorldHint: true };
+ }
const parsed = parsePermissionTag(spec.tag);
const readOnlyHint = route.method === "GET" || spec.readOnly === true;
const destructiveHint =
@@ -195,7 +200,7 @@ function annotationsFor(route: RegisteredRoute): {
(route.method === "DELETE" ||
parsed.action === "admin" ||
/delete|teardown|destroy|remove|wipe|revoke/i.test(route.path)));
- return { readOnlyHint, destructiveHint };
+ return { readOnlyHint, destructiveHint, openWorldHint: spec.mcp?.openWorld ?? true };
}
let cached: McpToolDef[] | null = null;
@@ -350,6 +355,10 @@ export function filterToolsForPrincipal(
principal: McpPrincipal,
): McpToolDef[] {
return tools.filter((t) => {
+ const action = assertedAction(t.perm.action);
+ const role = principal.membershipRole ?? principal.role;
+ if (role !== "restricted" &&
+ !roleAllowsResourceType(role, t.perm.leaf as CheckedResourceType, action)) return false;
// Read-only tokens can only call GET — the runtime gate rejects mutations by
// HTTP method, so mirror that exactly rather than guessing from the tag.
if (principal.readOnly && t.method !== "GET") return false;
@@ -373,9 +382,7 @@ export function filterToolsForPrincipal(
if (principal.role === "restricted" && !caps?.has(needed)) return false;
}
- if (principal.role !== "restricted") {
- return roleAllowsResourceType(principal.role, t.perm.leaf as CheckedResourceType);
- }
+ if (principal.role !== "restricted") return true;
// "Own projects" scope: the create-capable project wildcard grant reaches the
// dedicated create routes (POST /projects, POST /apps) and the project list
// (which the caller filters to its self-created projects). Checked before the
@@ -401,11 +408,11 @@ export function filterToolsForPrincipal(
// A per-id grant still fails here, correctly: `wildcardGrants` holds only
// resourceId "*" rows.
const held = principal.wildcardGrants.get(t.perm.leaf);
- return held ? permitsAction(held, assertedAction(t.perm.action)) : false;
+ return held ? permitsAction(held, action) : false;
}
if (principalHasGrantFor(principal.grantedRootTypes, t.perm.grantRoot)) return true;
// Same mapping the permission check uses: `domain:admin` ⇒ `domains:delete`.
- const capability = capabilityFor(t.perm.leaf, assertedAction(t.perm.action));
+ const capability = capabilityFor(t.perm.leaf, action);
return !!capability && !!principal.grantedCapabilities?.has(capability);
});
}
@@ -419,6 +426,7 @@ export function toClientTool(t: McpToolDef) {
annotations: {
readOnlyHint: t.annotations.readOnlyHint,
destructiveHint: t.annotations.destructiveHint,
+ openWorldHint: t.annotations.openWorldHint,
},
};
}
diff --git a/apps/api/src/modules/mcp/mcp.routes.ts b/apps/api/src/modules/mcp/mcp.routes.ts
index 9a80ecf68..16d90eab1 100644
--- a/apps/api/src/modules/mcp/mcp.routes.ts
+++ b/apps/api/src/modules/mcp/mcp.routes.ts
@@ -128,6 +128,7 @@ async function resolveMcpCaller(token: string, headers: Headers): Promise ({
pinned: vi.fn(),
source: vi.fn(),
target: vi.fn(),
+ list: vi.fn(),
+ handle: vi.fn(),
produce: vi.fn(),
restore: vi.fn(),
dispose: vi.fn(),
@@ -28,7 +30,7 @@ vi.mock("@repo/db", () => ({
activeDeploymentId: "build",
}),
},
- service: { listByProject: async () => [] },
+ service: { listByProject: h.list },
deployment: { findById: async () => ({ containerId: "target-container" }) },
},
}));
@@ -52,7 +54,7 @@ vi.mock("@repo/platform/engine/lib/project-runtime-lock", () => ({
withProjectRuntimeLock: async (_id: string, work: () => Promise) => work(),
}));
vi.mock("@repo/platform/engine/modules/backups/service-handle", () => ({
- serviceHandleFor: vi.fn(),
+ serviceHandleFor: h.handle,
}));
vi.mock("@repo/platform/engine/modules/services/service-container", () => ({
containerIdForService: vi.fn(),
@@ -107,6 +109,8 @@ let target: BackupExecutor;
beforeEach(() => {
vi.resetAllMocks();
h.workspaceId = undefined;
+ h.list.mockResolvedValue([{ id: "db", name: "db", projectId: "project" }]);
+ h.handle.mockResolvedValue(handle);
h.activity.mockImplementation(async (_id: string, work: () => Promise) => work());
h.pinned.mockResolvedValue({ ip: "203.0.113.8" });
target = {
@@ -121,12 +125,23 @@ beforeEach(() => {
});
});
describe("provider data copy", () => {
+ it("rejects a missing native target service before opening a source or restoring data", async () => {
+ h.list.mockResolvedValue([{ id: "other-service", name: "api", projectId: "project" }]);
+ await expect(copyPlatformData({
+ runId: "run", service, projectId: "project", serviceId: "db", deploymentId: "build",
+ signal: new AbortController().signal, log: vi.fn(), progress: vi.fn(),
+ })).rejects.toMatchObject({ code: "IMPORT_TARGET_SERVICE_MISSING" });
+ expect(h.source).not.toHaveBeenCalled();
+ expect(h.restore).not.toHaveBeenCalled();
+ expect(h.handle).not.toHaveBeenCalled();
+ });
it("leaves a destination changed by the operator untouched", async () => {
await expect(
copyPlatformData({
runId: "run",
service,
projectId: "project",
+ serviceId: "db",
deploymentId: "replaced-build",
signal: new AbortController().signal,
log: vi.fn(),
@@ -174,6 +189,10 @@ describe("provider data copy", () => {
).rejects.toMatchObject({ code: "IMPORT_DATABASE_EXTENSIONS_MISSING" });
});
it("streams every byte with backpressure, verifies after restore and closes both transports", async () => {
+ const targetRow = { id: "db", name: "database", projectId: "project" };
+ h.list.mockResolvedValue([
+ { id: "api", name: "api", projectId: "project" }, targetRow,
+ ]);
const payload = Buffer.alloc(256 * 1024, 0x41);
let producerCompleted = false;
h.produce.mockImplementation(async function* () {
@@ -197,12 +216,14 @@ describe("provider data copy", () => {
runId: "run",
service,
projectId: "project",
+ serviceId: "db",
deploymentId: "build",
signal: new AbortController().signal,
log: vi.fn(),
progress,
});
expect(restored).toEqual(payload);
+ expect(h.handle).toHaveBeenCalledWith(targetRow, expect.objectContaining({ projectSlug: "app" }));
expect(producerCompleted).toBe(true);
expect(h.dispose).toHaveBeenCalledOnce();
expect(h.source).not.toHaveBeenCalled();
@@ -228,6 +249,7 @@ describe("provider data copy", () => {
runId: "run",
service,
projectId: "project",
+ serviceId: "db",
deploymentId: "build",
signal: new AbortController().signal,
log: vi.fn(),
@@ -245,6 +267,7 @@ describe("provider data copy", () => {
runId: "run",
service,
projectId: "project",
+ serviceId: "db",
deploymentId: "build",
signal: new AbortController().signal,
log: vi.fn(),
@@ -269,6 +292,7 @@ it("holds the owning Cloud workspace activity lock for the whole transfer", asyn
runId: "run",
service,
projectId: "project",
+ serviceId: "db",
deploymentId: "build",
signal,
log: vi.fn(),
diff --git a/apps/api/src/modules/migration/platform-import-plan.test.ts b/apps/api/src/modules/migration/platform-import-plan.test.ts
index 910545e3f..2acc649ba 100644
--- a/apps/api/src/modules/migration/platform-import-plan.test.ts
+++ b/apps/api/src/modules/migration/platform-import-plan.test.ts
@@ -134,7 +134,7 @@ async function review(
}
describe("reviewed platform imports", () => {
- it("keeps secrets server-side and replaces provider database addresses with shared project bindings", async () => {
+ it("keeps secrets server-side and replaces provider database addresses with native service aliases", async () => {
const plan = await review();
expect(plan.ready).toBe(true);
expect(plan.requiresWritePause).toBe(true);
@@ -147,7 +147,15 @@ describe("reviewed platform imports", () => {
valueTemplate: "postgres://app:source-secret@${host}/app",
},
]);
- expect(privatePlan.services[1].environment).not.toHaveProperty("DATABASE_URL");
+ expect(privatePlan.services[1].environment.DATABASE_URL).toBe(
+ "postgres://app:source-secret@database/app",
+ );
+ expect(privatePlan.projects[0].create.name).toBe("Project");
+ expect(privatePlan.projects[0].create.services?.map((row) => row.name)).toEqual([
+ "database",
+ "website",
+ ]);
+ expect(JSON.stringify(privatePlan.projects)).not.toContain("source-secret");
expect(privatePlan.services[0].environment.PGHOST).toBe(
privatePlan.services[0].create.internalAlias,
);
@@ -175,6 +183,113 @@ describe("reviewed platform imports", () => {
code: "IMPORT_SOURCE_CHANGED",
});
});
+ it("names storage per service inside one destination project", async () => {
+ inventory.services[1].volumes = [{ id: "files", mountPath: "/data" }];
+ const plan = await loadReviewedImport(ctx, (await review()).planId);
+ expect(plan.projects[0].create.services?.flatMap((service) => service.volumes ?? [])).toEqual([
+ "database-data-0:/var/lib/postgresql/data",
+ "website-data-0:/data",
+ ]);
+ expect(plan.projects[0].create.services?.[1].dependsOn).toEqual(["database"]);
+ });
+ it.each(["repository", "commit", "branch"])(
+ "splits incompatible Git %s without losing revisions or private connections",
+ async (difference) => {
+ inventory.services = ["one", "two"].map((id) =>
+ service({
+ id,
+ name: id,
+ image: undefined,
+ repository: difference === "repository" ? `owner/${id}` : "owner/repo",
+ commit: (difference === "commit" && id === "two" ? "b" : "a").repeat(40),
+ branch: difference === "branch" ? id : "main",
+ privateDomain: `${id}.railway.internal`,
+ env: id === "two" ? { API_URL: "http://one.railway.internal:3000/api?secret=keep" } : {},
+ }),
+ );
+ const result = await review(
+ inventory.services.map((service) => ({
+ id: service.id,
+ name: service.name,
+ data: "empty",
+ })),
+ );
+ expect(result.ready, JSON.stringify(result)).toBe(true);
+ expect(result.projects).toEqual([
+ { name: "project-one", serviceIds: ["one"] },
+ { name: "project-two", serviceIds: ["two"] },
+ ]);
+ const plan = await loadReviewedImport(ctx, result.planId);
+ expect(plan.projects.map((project) => project.create.gitRepo)).toEqual(
+ difference === "repository" ? ["one", "two"] : ["repo", "repo"],
+ );
+ expect(plan.services[1].bindings).toEqual([
+ {
+ sourceId: "one",
+ envKey: "API_URL",
+ valueTemplate: "http://${host}:3000/api?secret=keep",
+ },
+ ]);
+ expect(plan.services.map((s) => s.source.commit)).toEqual(
+ inventory.services.map((s) => s.commit),
+ );
+ expect(h.info.mock.calls.map(([input]) => input.owner)).toEqual(["owner", "owner"]);
+ expect(h.info.mock.calls.map(([input]) => input.branch)).toEqual(
+ inventory.services.map((s) => s.commit),
+ );
+ },
+ );
+ it("keeps compatible source services together and rejects composite cross-project variables during review", async () => {
+ const git = (id: string, repository: string) =>
+ service({
+ id,
+ name: id,
+ image: undefined,
+ repository,
+ commit: "a".repeat(40),
+ privateDomain: `${id}.railway.internal`,
+ });
+ inventory.services = [git("one", "owner/repo"), git("two", "owner/repo")];
+ const choices = () =>
+ inventory.services.map((s) => ({ id: s.id, name: s.name, data: "empty" as const }));
+ expect((await review(choices())).projects).toEqual([
+ { name: "Project", serviceIds: ["one", "two"] },
+ ]);
+ inventory.services.push(git("three", "owner/other"));
+ inventory.services[2].env = { HOSTS: "one.railway.internal,two.railway.internal" };
+ const result = await review(choices());
+ expect(result.ready).toBe(false);
+ expect(result.services[2].blockers.join(" ")).toContain("separate connection variable");
+ });
+ it("blocks unavailable private listeners and ambiguous host templates before source downtime", async () => {
+ inventory.services = [
+ service({
+ id: "store",
+ name: "store",
+ port: undefined,
+ privateDomain: "store.railway.internal",
+ }),
+ ...["one", "two"].map((id) =>
+ service({
+ id,
+ name: id,
+ image: undefined,
+ repository: `owner/${id}`,
+ commit: "a".repeat(40),
+ env:
+ id === "one"
+ ? { HOST: "store.railway.internal" }
+ : { HOST: "store.railway.internal-${host}" },
+ }),
+ ),
+ ];
+ const result = await review(
+ inventory.services.map((s) => ({ id: s.id, name: s.name, data: "empty" })),
+ );
+ expect(result.ready).toBe(false);
+ expect(result.services[1].blockers.join(" ")).toContain("private listener port");
+ expect(result.services[2].blockers.join(" ")).toContain("cannot be safely converted");
+ });
it("ignores pagination order and changing volume size, but never ignores changed configuration", () => {
const next = structuredClone(inventory);
next.services.reverse();
@@ -202,16 +317,22 @@ describe("reviewed platform imports", () => {
const reviewed = await review();
expect(reviewed.ready).toBe(true);
expect(
- (await loadReviewedImport(ctx, reviewed.planId)).services[1].bindings[0].valueTemplate,
- ).toBe("postgres://app:source-secret@${host}/app");
+ (await loadReviewedImport(ctx, reviewed.planId)).services[1].environment.DATABASE_URL,
+ ).toBe("postgres://app:source-secret@database/app");
});
- it("rejects conflicting project names and enforces destination access before planning", async () => {
+ it("rejects conflicting service names and enforces destination access before planning", async () => {
await expect(
review([
{ id: "db", name: "Same Name", data: "copy" },
{ id: "app", name: "same-name", data: "empty" },
]),
).rejects.toMatchObject({ code: "IMPORT_NAME_INVALID" });
+ await expect(
+ review([
+ { id: "db", name: "api.v2", data: "copy" },
+ { id: "app", name: "api v2", data: "empty" },
+ ]),
+ ).rejects.toMatchObject({ code: "IMPORT_NAME_INVALID" });
h.authorize.mockRejectedValue(new Error("forbidden"));
await expect(review()).rejects.toThrow("forbidden");
});
@@ -252,7 +373,7 @@ describe("reviewed platform imports", () => {
{ sourceId: external.id, envKey: "DATABASE_URL" },
]);
expect(privatePlan.services[1].create.services?.[0].volumes).toEqual([
- "data-0:/var/lib/postgresql",
+ "database-data-0:/var/lib/postgresql",
]);
// Supplying secrets does not falsely report provider configuration drift.
expect(h.discover).toHaveBeenCalledTimes(2);
@@ -281,6 +402,9 @@ it("uses the existing Compose build for a custom Dockerfile and preserves readin
readiness: { path: "/health" },
services: [{ build: "apps/api", dockerfile: "docker/production.Dockerfile" }],
});
+ expect(plan.projects[0].create.services?.[0].advanced).toMatchObject({
+ readiness: { path: "/health", port: 3000 },
+ });
expect(h.info).not.toHaveBeenCalled();
});
it("blocks an unavailable custom Dockerfile before import", async () => {
diff --git a/apps/api/src/modules/migration/platform-import-worker.test.ts b/apps/api/src/modules/migration/platform-import-worker.test.ts
index 2f4eaf5e9..446bd3f5c 100644
--- a/apps/api/src/modules/migration/platform-import-worker.test.ts
+++ b/apps/api/src/modules/migration/platform-import-worker.test.ts
@@ -1,20 +1,26 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { AppError } from "@repo/core";
+import { AppError, ConflictError } from "@repo/core";
import { withProjectRuntimeLock } from "@repo/platform/engine/lib/project-runtime-lock";
import type { ExecutionContext } from "@repo/platform";
import type {
PrivateImportPlan,
PlannedImportService,
} from "@repo/platform/engine/modules/migration/platform-import-plan";
+import { platformImportProjects } from "@repo/platform/engine/modules/migration/platform-import-project";
const h = vi.hoisted(() => ({
ensure: vi.fn(),
merge: vi.fn(),
- connect: vi.fn(),
+ list: vi.fn(),
+ project: vi.fn(),
+ sourceService: vi.fn(),
+ rows: [] as Array<{ id: string; projectId: string; name: string }>,
view: vi.fn(),
+ connect: vi.fn(),
deploy: vi.fn(),
copy: vi.fn(),
preflight: vi.fn(),
prepareTarget: vi.fn(),
+ routes: vi.fn(),
authorize: vi.fn(),
disable: vi.fn(),
bind: vi.fn(),
@@ -29,7 +35,8 @@ const h = vi.hoisted(() => ({
vi.mock("@repo/db", () => ({
withAdvisoryLock: async (_key: string, fn: () => Promise) => fn(),
repos: {
- project: { update: h.update, findById: async (id: string) => ({ id, workspaceId: null }) },
+ service: { listByProject: h.list },
+ project: { update: h.update, findById: h.project },
dockerMigrationRun: {
bindImportedProject: h.bind,
findById: h.find,
@@ -40,11 +47,11 @@ vi.mock("@repo/db", () => ({
vi.mock("@repo/platform/engine/modules/projects/project-crud.service", () => ({
ensureProject: h.ensure,
}));
-vi.mock("@repo/platform/engine/modules/projects/project-env.service", () => ({
- mergeEnvVars: h.merge,
+vi.mock("@repo/platform/engine/modules/services/service-environment-state", () => ({
+ mergeServiceEnvVars: h.merge,
}));
-vi.mock("@repo/platform/engine/modules/projects/project-connection.service", () => ({
- createConnection: h.connect,
+vi.mock("@repo/platform/engine/modules/services/service.service", () => ({
+ createService: h.sourceService,
}));
vi.mock("@repo/platform/engine/modules/projects/project-runtime.service", () => ({
disableProject: h.disable,
@@ -52,6 +59,9 @@ vi.mock("@repo/platform/engine/modules/projects/project-runtime.service", () =>
vi.mock("@repo/platform/engine/modules/apps/app-settings.service", () => ({
getAppConnectionView: h.view,
}));
+vi.mock("@repo/platform/engine/modules/projects/project-connection.service", () => ({
+ createConnection: h.connect,
+}));
vi.mock("@repo/platform/engine/modules/deployments/build.service", () => ({
triggerDeployment: h.deploy,
}));
@@ -62,6 +72,9 @@ vi.mock("@repo/platform/engine/modules/migration/platform-import-data", () => ({
vi.mock("@repo/platform/engine/modules/migration/migration-runtime", () => ({
prepareMigrationTarget: h.prepareTarget,
}));
+vi.mock("@repo/platform/engine/modules/migration/migration-routes", () => ({
+ saveMigrationRoutes: h.routes,
+}));
vi.mock("@repo/platform/engine/modules/migration/platform-import-health", () => ({
verifyPlatformDeployment: h.verify,
}));
@@ -96,7 +109,11 @@ const service = (id: string, kind: "app" | "database" | "worker"): PlannedImport
...(kind === "database" ? { database: "pg_dump" } : { commit: "a".repeat(40), branch: "main" }),
},
data: "copy",
- create: { name: id },
+ create: {
+ name: id,
+ internalAlias: id,
+ services: [{ name: id, image: "image:1", volumes: [`${id}-data:/data`] }],
+ },
environment: { TOKEN: "secret" },
bindings: [],
});
@@ -107,11 +124,19 @@ const planFor = (services: PlannedImportService[]) =>
userId: "user",
targetServerId: "server",
services,
+ projectName: "imported-project",
+ projects: platformImportProjects("imported-project", "server", services),
}) as PrivateImportPlan;
let row: any;
beforeEach(() => {
vi.resetAllMocks();
h.events.length = 0;
+ h.rows.length = 0;
+ h.routes.mockResolvedValue([]);
+ h.project.mockImplementation(async (id) => ({ id, workspaceId: null }));
+ h.list.mockImplementation(async (projectId) =>
+ h.rows.filter((row) => row.projectId === projectId),
+ );
row = {
id: "run",
organizationId: "org",
@@ -129,24 +154,43 @@ beforeEach(() => {
});
h.ensure.mockImplementation(async (body) => {
h.events.push(`create:${body.name}`);
+ h.rows.push(
+ ...body.services.map((row: { name: string }) => ({
+ ...row,
+ id: `${body.name}-${row.name}`,
+ projectId: body.name,
+ })),
+ );
return { project_id: body.name };
});
+ h.sourceService.mockImplementation(async (_ctx, projectId, body) => {
+ h.rows.push({ ...body, id: `${projectId}-${body.name}`, projectId });
+ });
+ let deploymentCount = 0;
h.deploy.mockImplementation(async (_ctx, input) => {
- h.events.push(`deploy:${input.projectId}`);
- return { deployment: { id: `${input.projectId}-build` } };
+ h.events.push(`deploy:${input.projectId}:${input.serviceIds.length}`);
+ return { deployment: { id: `${input.projectId}-build-${++deploymentCount}` } };
});
h.copy.mockImplementation(async (input) => {
- h.events.push(`copy:${input.projectId}`);
- });
- h.view.mockResolvedValue({
- outputs: [{ id: "database-url", internal: true, value: "postgres://new" }],
+ h.events.push(`copy:${input.service.source.id}`);
});
+ h.view.mockImplementation(async () => ({
+ outputs: h.rows.map((row) => ({
+ id: `${row.id}:url`,
+ sourceServiceId: row.id,
+ internal: true,
+ value: "postgres://new",
+ })),
+ }));
h.prepareSource.mockImplementation(async () => {
h.events.push("pause-project");
});
h.restoreSource.mockImplementation(async (_run, resume) => {
h.events.push(resume ? "resume-project" : "restore-config");
});
+ h.connect.mockImplementation(async (_ctx, target, input) => {
+ h.events.push(`connect:${input.sourceProjectId}:${target}`);
+ });
});
const lifecycle = (signal = new AbortController().signal) => ({
signal,
@@ -159,6 +203,149 @@ const lifecycle = (signal = new AbortController().signal) => ({
}),
});
describe("provider import through normal project operations", () => {
+ it("copies all volumes before deploying multiple repositories in dependency order with native links", async () => {
+ const db = service("db", "database"),
+ app = service("app", "app"),
+ worker = service("worker", "worker");
+ for (const entry of [app, worker])
+ Object.assign(entry.create, {
+ gitProvider: "github",
+ gitOwner: "owner",
+ gitRepo: entry.source.id,
+ gitBranch: "main",
+ });
+ worker.source.commit = "b".repeat(40);
+ app.bindings = [
+ { sourceId: "db", envKey: "DB_URL", valueTemplate: "postgres://secret@${host}:5432/store" },
+ ];
+ worker.bindings = [{ sourceId: "app", envKey: "APP_HOST", valueTemplate: "${host}" }];
+ app.environment.DB_URL = "postgres://secret@db:5432/store";
+ worker.environment.APP_HOST = "app";
+ const services = [worker, app, db];
+ const plan = { ...planFor(services), sourceControl: "railway-project" as const };
+ await executePlatformImport(ctx, "run", plan, lifecycle());
+ expect(h.ensure.mock.calls.map(([body]) => body.gitRepo)).toEqual(["worker", "app", undefined]);
+ expect(
+ h.ensure.mock.calls.every(([body]) => body.services.every((s: any) => !s.dependsOn.length)),
+ ).toBe(true);
+ expect(h.copy.mock.calls.map(([input]) => [input.projectId, input.serviceId])).toEqual([
+ ["imported-project-db", "imported-project-db-db"],
+ ["imported-project-app", "imported-project-app-app"],
+ ["imported-project-worker", "imported-project-worker-worker"],
+ ]);
+ expect(h.events.indexOf("copy:worker")).toBeLessThan(
+ h.events.indexOf("deploy:imported-project-db:1"),
+ );
+ expect(h.events.indexOf("healthy:imported-project-db-build-1")).toBeLessThan(
+ h.events.indexOf("connect:imported-project-db:imported-project-app"),
+ );
+ expect(h.events.indexOf("connect:imported-project-db:imported-project-app")).toBeLessThan(
+ h.events.indexOf("deploy:imported-project-app:1"),
+ );
+ expect(h.connect).toHaveBeenCalledWith(
+ ctx,
+ "imported-project-app",
+ {
+ sourceProjectId: "imported-project-db",
+ outputId: "imported-project-db-db:url",
+ envKey: "DB_URL",
+ mode: "internal",
+ valueTemplate: "postgres://secret@${host}:5432/store",
+ },
+ { defer: true },
+ );
+ expect(
+ h.merge.mock.calls.flatMap(([, , , input]) => input.upserts.map((v: any) => v.key)),
+ ).not.toContain("DB_URL");
+ expect(h.deploy.mock.calls.map(([, input]) => [input.projectId, input.commitSha])).toEqual([
+ ["imported-project-db", undefined],
+ ["imported-project-app", "a".repeat(40)],
+ ["imported-project-worker", "b".repeat(40)],
+ ]);
+ expect(h.verify).toHaveBeenCalledTimes(3);
+ expect(row.recovery.providerImport.completed).toEqual(["db", "app", "worker"]);
+ });
+ it("does not start a cross-project consumer if its private connection fails", async () => {
+ const db = service("db", "database"),
+ app = service("app", "app"),
+ worker = service("worker", "worker");
+ for (const entry of [app, worker])
+ Object.assign(entry.create, { gitOwner: "owner", gitRepo: entry.source.id });
+ app.bindings = [{ sourceId: "db", envKey: "DB_URL" }];
+ const plan = { ...planFor([app, db, worker]), sourceControl: "railway-project" as const };
+ row.recovery.providerImport.planEnc = JSON.stringify(plan);
+ h.connect.mockRejectedValue(new Error("Private network unavailable"));
+ await expect(executePlatformImport(ctx, "run", plan, lifecycle())).rejects.toThrow(
+ "Private network unavailable",
+ );
+ expect(h.deploy).toHaveBeenCalledTimes(1);
+ expect(row.recovery.providerImport.completed).toEqual([]);
+ expect(h.restoreSource).not.toHaveBeenCalledWith("run", true, expect.anything());
+ await pauseFailedPlatformImport("run");
+ expect(h.disable).toHaveBeenCalledExactlyOnceWith(
+ "imported-project-db",
+ "org",
+ "imported-project-db-build-1",
+ );
+ expect(h.restoreSource).toHaveBeenLastCalledWith("run", true);
+ expect(h.disable.mock.invocationCallOrder[0]).toBeLessThan(
+ h.restoreSource.mock.invocationCallOrder[1],
+ );
+ });
+ it("stages custom domains through native migration routing before pausing the source", async () => {
+ const web = service("web", "app");
+ web.create.name = "storefront";
+ web.source.domains = [
+ { hostname: "shop.example.com", portable: true },
+ { hostname: "www.example.com", portable: true },
+ { hostname: "shop.up.railway.app", portable: false },
+ ];
+ const plan = { ...planFor([web]), sourceControl: "railway-project" as const };
+ const flow = lifecycle();
+ await executePlatformImport(ctx, "run", plan, flow);
+ expect(h.routes).toHaveBeenCalledWith(
+ ctx,
+ "imported-project",
+ {
+ storefront: [
+ { domainType: "custom", customDomain: "shop.example.com" },
+ { domainType: "custom", customDomain: "www.example.com" },
+ ],
+ },
+ flow.log,
+ );
+ expect(h.routes.mock.invocationCallOrder[0]).toBeLessThan(
+ h.prepareSource.mock.invocationCallOrder[0],
+ );
+ expect(h.routes.mock.invocationCallOrder[0]).toBeLessThan(h.copy.mock.invocationCallOrder[0]);
+ });
+
+ it("reports domain conflicts without pausing Railway or deploying the destination", async () => {
+ const app = service("app", "app");
+ app.source.domains = [{ hostname: "taken.example.com", portable: true }];
+ h.routes.mockRejectedValueOnce(
+ new ConflictError("The domain is already connected to another project."),
+ );
+ await expect(
+ executePlatformImport(
+ ctx,
+ "run",
+ {
+ ...planFor([app]),
+ sourceControl: "railway-project",
+ },
+ lifecycle(),
+ ),
+ ).rejects.toMatchObject({
+ statusCode: 409,
+ code: "IMPORT_DOMAIN_REVIEW_REQUIRED",
+ message: "The domain is already connected to another project.",
+ });
+ expect(h.prepareSource).not.toHaveBeenCalled();
+ expect(h.copy).not.toHaveBeenCalled();
+ expect(h.deploy).not.toHaveBeenCalled();
+ });
+
it("prepares managed capacity before pausing Railway and does not stop the source if provisioning fails", async () => {
const plan = { ...planFor([service("app", "app")]), sourceControl: "railway-project" as const };
const flow = lifecycle();
@@ -194,6 +381,136 @@ describe("provider import through normal project operations", () => {
expect(h.events.indexOf("pause-project")).toBeLessThan(h.events.indexOf("copy:db"));
expect(h.events.indexOf("restore-config")).toBeLessThan(firstDeployment);
expect(h.copy.mock.calls.every(([input]) => input.deploymentId === undefined)).toBe(true);
+ expect(h.ensure).toHaveBeenCalledTimes(1);
+ expect(h.deploy).toHaveBeenCalledTimes(1);
+ expect(new Set(h.copy.mock.calls.map(([input]) => input.projectId))).toEqual(
+ new Set(["imported-project"]),
+ );
+ expect(new Set(h.copy.mock.calls.map(([input]) => input.serviceId)).size).toBe(3);
+ expect(new Set(Object.values(row.recovery.providerImport.projects))).toEqual(
+ new Set(["imported-project"]),
+ );
+ });
+ it("imports two source projects as two native projects, keeping identical service names separate", async () => {
+ for (const name of ["first-project", "second-project"]) {
+ const services = [service("db", "database"), service("app", "app")];
+ services.forEach((service) => (service.transfer = "cold-volume"));
+ const plan = { ...planFor(services), sourceControl: "railway-project" as const };
+ plan.projectName = name;
+ plan.projects[0].create.name = name;
+ await executePlatformImport(ctx, name, plan, lifecycle());
+ expect(new Set(Object.values(row.recovery.providerImport.projects))).toEqual(new Set([name]));
+ }
+ expect(h.ensure.mock.calls.map(([body]) => body.name)).toEqual([
+ "first-project",
+ "second-project",
+ ]);
+ expect(h.rows.map((row) => row.projectId)).toEqual([
+ "first-project",
+ "first-project",
+ "second-project",
+ "second-project",
+ ]);
+ expect(h.copy.mock.calls.map(([input]) => [input.projectId, input.serviceId])).toEqual([
+ ["first-project", "first-project-db"],
+ ["first-project", "first-project-app"],
+ ["second-project", "second-project-db"],
+ ["second-project", "second-project-app"],
+ ]);
+ });
+ it("stores each service's environment separately instead of merging it into project-wide values", async () => {
+ const app = service("app", "app"),
+ db = service("db", "database");
+ app.environment = { PORT: "3000", TOKEN: "app-secret" };
+ db.environment = { PORT: "5432", TOKEN: "database-secret" };
+ await executePlatformImport(ctx, "run", planFor([app, db]), lifecycle());
+ for (const entry of [app, db]) {
+ expect(h.merge).toHaveBeenCalledWith(
+ ctx,
+ "imported-project",
+ `imported-project-${entry.source.id}`,
+ {
+ environment: "production",
+ deletes: [],
+ upserts: Object.entries(entry.environment).map(([key, value]) => ({
+ key,
+ value,
+ isSecret: true,
+ sourceId: null,
+ })),
+ },
+ );
+ }
+ });
+ it("adds a source-built app through the native service creator in the same project", async () => {
+ const app = service("app", "app");
+ app.create = {
+ name: "app",
+ gitOwner: "owner",
+ gitRepo: "repo",
+ gitBranch: "main",
+ framework: "nextjs",
+ rootDirectory: "apps/web",
+ installCommand: "bun install",
+ startCommand: "bun start",
+ port: 3000,
+ };
+ await executePlatformImport(ctx, "run", planFor([app, service("db", "database")]), lifecycle());
+ expect(h.ensure).toHaveBeenCalledTimes(1);
+ expect(h.sourceService).toHaveBeenCalledWith(
+ ctx,
+ "imported-project",
+ expect.objectContaining({
+ name: "app",
+ kind: "monorepo",
+ rootDirectory: "apps/web",
+ framework: "nextjs",
+ ports: ["3000"],
+ exposed: false,
+ }),
+ );
+ expect(h.deploy).toHaveBeenLastCalledWith(
+ ctx,
+ expect.objectContaining({
+ projectId: "imported-project",
+ commitSha: "a".repeat(40),
+ }),
+ );
+ });
+ it("rejects reviews without destination projects before allocating a destination", async () => {
+ const plan = planFor([service("app", "app")]);
+ delete (plan as Partial).projects;
+ await expect(executePlatformImport(ctx, "run", plan, lifecycle())).rejects.toMatchObject({
+ code: "IMPORT_REVIEW_EXPIRED",
+ });
+ expect(h.ensure).not.toHaveBeenCalled();
+ expect(h.prepareSource).not.toHaveBeenCalled();
+ });
+ it("pauses a shared destination once before restoring the Railway source", async () => {
+ const plan = planFor([service("app", "app"), service("db", "database")]);
+ Object.assign(row.recovery.providerImport, {
+ planEnc: JSON.stringify(plan),
+ projects: { app: "shared-project", db: "shared-project" },
+ deployments: { app: "shared-build", db: "shared-build" },
+ });
+ await pauseFailedPlatformImport("run");
+ expect(h.disable).toHaveBeenCalledExactlyOnceWith("shared-project", "org", "shared-build");
+ expect(h.restoreSource).toHaveBeenCalledTimes(1);
+ expect(h.disable.mock.invocationCallOrder[0]).toBeLessThan(
+ h.restoreSource.mock.invocationCallOrder[0],
+ );
+ });
+ it("can pause its own database-only predecessor when a complete deployment fails", async () => {
+ const plan = planFor([service("app", "app"), service("db", "database")]);
+ Object.assign(row.recovery.providerImport, {
+ planEnc: JSON.stringify(plan),
+ projects: { app: "shared", db: "shared" },
+ deployments: { app: "failed-build", db: "failed-build" },
+ ownedDeploymentIds: ["database-build", "failed-build"],
+ });
+ h.project.mockResolvedValue({ id: "shared", activeDeploymentId: "database-build" });
+ await pauseFailedPlatformImport("run");
+ expect(h.disable).toHaveBeenCalledExactlyOnceWith("shared", "org", "database-build");
});
it("stops every imported Railway workload before resuming the source on failure", async () => {
const plan = {
@@ -219,29 +536,43 @@ describe("provider import through normal project operations", () => {
const plan = planFor([worker, app, db]);
await executePlatformImport(ctx, "run", plan, lifecycle());
expect(h.events).toEqual([
- "create:db",
- "create:app",
- "create:worker",
- "deploy:db",
- "healthy:db-build",
+ "create:imported-project",
+ "deploy:imported-project:1",
+ "healthy:imported-project-build-1",
"copy:db",
"copy:app",
- "deploy:app",
- "healthy:app-build",
"copy:worker",
- "deploy:worker",
- "healthy:worker-build",
+ "deploy:imported-project:3",
+ "healthy:imported-project-build-2",
]);
- expect(h.ensure).toHaveBeenCalledWith(app.create, "org", ctx, { mustCreate: true });
- expect(h.connect).toHaveBeenCalledWith(
+ expect(h.ensure).toHaveBeenCalledExactlyOnceWith(plan.projects[0].create, "org", ctx, {
+ mustCreate: true,
+ });
+ expect(h.merge).toHaveBeenCalledWith(
ctx,
- "app",
- { sourceProjectId: "db", outputId: "database-url", envKey: "DATABASE_URL", mode: "internal" },
- { defer: true },
+ "imported-project",
+ "imported-project-app",
+ expect.objectContaining({
+ upserts: [{ key: "DATABASE_URL", value: "postgres://new", sourceId: null, isSecret: true }],
+ }),
);
- expect(h.deploy).toHaveBeenCalledWith(
+ expect(h.deploy).toHaveBeenNthCalledWith(
+ 1,
ctx,
- expect.objectContaining({ projectId: "app", commitSha: "a".repeat(40), branch: "main" }),
+ expect.objectContaining({
+ projectId: "imported-project",
+ serviceIds: ["imported-project-db"],
+ strictServiceScope: true,
+ }),
+ );
+ expect(h.deploy).toHaveBeenNthCalledWith(
+ 2,
+ ctx,
+ expect.objectContaining({
+ projectId: "imported-project",
+ serviceIds: ["imported-project-db", "imported-project-app", "imported-project-worker"],
+ strictServiceScope: true,
+ }),
);
expect(row.recovery.providerImport.completed).toEqual(["db", "app", "worker"]);
});
@@ -253,7 +584,13 @@ describe("provider import through normal project operations", () => {
executePlatformImport(ctx, "run", planFor([app, service("db", "database")]), lifecycle()),
).rejects.toThrow("restore failed");
expect(h.deploy).toHaveBeenCalledTimes(1);
- expect(h.deploy).toHaveBeenCalledWith(ctx, expect.objectContaining({ projectId: "db" }));
+ expect(h.deploy).toHaveBeenCalledWith(
+ ctx,
+ expect.objectContaining({
+ projectId: "imported-project",
+ serviceIds: ["imported-project-db"],
+ }),
+ );
});
it("checkpoints the created deployment before observing a cancelled phase", async () => {
const flow = lifecycle();
@@ -263,7 +600,7 @@ describe("provider import through normal project operations", () => {
await expect(
executePlatformImport(ctx, "run", planFor([service("app", "app")]), flow),
).rejects.toThrow("cancelled");
- expect(row.recovery.providerImport.deployments).toEqual({ app: "app-build" });
+ expect(row.recovery.providerImport.deployments).toEqual({ app: "imported-project-build-1" });
});
it("rejects dependency cycles rather than starting a partial recursive import", () => {
const a = service("a", "app"),
@@ -272,7 +609,7 @@ describe("provider import through normal project operations", () => {
b.bindings = [{ sourceId: "a", envKey: "URL" }];
expect(() => orderedImports([a, b])).toThrow(/cycle/);
});
- it("retains databases and pauses only the import's own app deployment identities on failure", async () => {
+ it("pauses imported deployment identities before releasing source recovery", async () => {
const plan = planFor([service("app", "app"), service("db", "database")]);
Object.assign(row.recovery.providerImport, {
planEnc: JSON.stringify(plan),
@@ -280,7 +617,8 @@ describe("provider import through normal project operations", () => {
deployments: { app: "app-build", db: "db-build" },
});
await pauseFailedPlatformImport("run");
- expect(h.disable).toHaveBeenCalledExactlyOnceWith("p-app", "org", "app-build");
+ expect(h.disable).toHaveBeenCalledWith("p-app", "org", "app-build");
+ expect(h.disable).toHaveBeenCalledWith("p-db", "org", "db-build");
expect(row.recovery.providerImport.cleanupPending).toBe(false);
});
it("leaves the cleanup checkpoint pending if the destination cannot be reached", async () => {
diff --git a/apps/api/src/modules/migration/railway-wiring.test.ts b/apps/api/src/modules/migration/railway-wiring.test.ts
index f0ab87402..d21c42e47 100644
--- a/apps/api/src/modules/migration/railway-wiring.test.ts
+++ b/apps/api/src/modules/migration/railway-wiring.test.ts
@@ -42,6 +42,27 @@ describe("provider-independent connection values", () => {
});
});
describe("Railway project wiring", () => {
+ it("preserves self references and repeated case-insensitive dependency hosts in one connection", () => {
+ const db = service("db", {}, 5432);
+ const app = service("app", {
+ HOSTS: "DB.railway.internal,db.railway.internal,app.railway.internal",
+ });
+ expect(
+ resolveRailwayBindings(
+ app,
+ new Map([
+ ["db", db],
+ ["app", app],
+ ]),
+ ),
+ ).toEqual([
+ {
+ sourceId: "db",
+ envKey: "HOSTS",
+ valueTemplate: "${host},${host},import-app",
+ },
+ ]);
+ });
it("binds any private service without inferring its type from its image or variable names", () => {
const store = service("store");
const app = service("app", {
@@ -62,7 +83,9 @@ describe("Railway project wiring", () => {
},
]);
expect(store.source.port).toBe(7878);
- expect(app.source.env).toEqual({});
+ expect(app.source.env).toEqual({
+ ARBITRARY_SETTING: "custom://alice:password@import-store:7878/second-db?option=1",
+ });
});
it("keeps literal shared secrets and rewrites self-hosts without a recursive connection", () => {
const store = service("store", { TOKEN: "secret", HOST: "store.railway.internal" }, 7878);
@@ -78,4 +101,23 @@ describe("Railway project wiring", () => {
expect(app.source.blockers.join(" ")).toMatch(/MISSING/);
expect(app.source.blockers.join(" ")).toMatch(/UNRESOLVED/);
});
+ it("keeps hostname-only and multi-host values on the native project network", () => {
+ const db = service("db"),
+ redis = service("redis");
+ const app = service("app", {
+ HOST: "db.railway.internal",
+ HOSTS: "db.railway.internal,redis.railway.internal",
+ });
+ const bindings = resolveRailwayBindings(
+ app,
+ new Map([
+ ["db", db],
+ ["redis", redis],
+ ["app", app],
+ ]),
+ );
+ expect(app.source.env).toEqual({ HOST: "import-db", HOSTS: "import-db,import-redis" });
+ expect(new Set(bindings.map((binding) => binding.sourceId))).toEqual(new Set(["db", "redis"]));
+ expect(app.source.blockers).toEqual([]);
+ });
});
diff --git a/apps/api/src/modules/projects/folder/folder.service.test.ts b/apps/api/src/modules/projects/folder/folder.service.test.ts
index 02b956160..ac85c40ac 100644
--- a/apps/api/src/modules/projects/folder/folder.service.test.ts
+++ b/apps/api/src/modules/projects/folder/folder.service.test.ts
@@ -59,7 +59,7 @@ describe("scanFolderSession", () => {
expect(resolveFromLocalMock).toHaveBeenCalledWith(stagingDir, {
env: { MY_VERSION: "1.2.3" },
composePath: "deploy/compose.yaml",
- });
+ }, "app");
expect(result.services).toBe(refreshed);
expect(upload.services).toBe(initial);
});
diff --git a/apps/api/src/modules/projects/project-cleanup.ref-shape.test.ts b/apps/api/src/modules/projects/project-cleanup.ref-shape.test.ts
index f66e072ba..ef4088610 100644
--- a/apps/api/src/modules/projects/project-cleanup.ref-shape.test.ts
+++ b/apps/api/src/modules/projects/project-cleanup.ref-shape.test.ts
@@ -225,7 +225,7 @@ describe("Cloud Docker project teardown", () => {
slug,
domain: "opsh.io",
namespace: fixture.namespace,
- source_workspace_id: fixture.scope.workspaceId,
+ source_vm_id: fixture.scope.workspaceId,
exported_path: `${cloudDockerProjectPaths(owner).routes}/${slug}`,
});
return { ...fixture, addPage };
diff --git a/apps/api/src/modules/projects/project-clone.test.ts b/apps/api/src/modules/projects/project-clone.test.ts
index 497aa8279..864a94be8 100644
--- a/apps/api/src/modules/projects/project-clone.test.ts
+++ b/apps/api/src/modules/projects/project-clone.test.ts
@@ -32,8 +32,7 @@ const h = {
deletedAt: null,
deletionInProgress: false,
lifecycleOperation: { kind: "delete", status: "failed", error: "Previous cleanup failure" },
- favicon: "https://clincai.example/favicon.ico",
- faviconCheckedAt: new Date(),
+ iconUrl: "https://clincai.example/icon.png",
compositeRoutes: [{ host: "clincai.example" }],
workspaceId: null,
gitProvider: "github",
@@ -194,6 +193,7 @@ describe("the copy direction is COPY-by-default", () => {
await clone();
const p = clonedProject();
expect(p.framework).toBe("nextjs");
+ expect(p.iconUrl).toBe("https://clincai.example/icon.png");
expect(p.routeStrategy).toBe("loopback");
expect(p.rollbackWindow).toBe(5);
// Same for the service rows: a build command exists in no container.
@@ -231,7 +231,7 @@ describe("what it deliberately does NOT copy", () => {
const p = clonedProject();
// `id`/`groupId` are the insert's, and name/slug/serverId/workspaceId/activeDeploymentId are set
// explicitly above — the rest must simply be absent.
- for (const field of ["deletedAt", "deletionInProgress", "lifecycleOperation", "disabledAt", "favicon", "faviconCheckedAt", "compositeRoutes", "cloudPromotion", "id", "groupId", "createdAt", "updatedAt"]) {
+ for (const field of ["deletedAt", "deletionInProgress", "lifecycleOperation", "disabledAt", "compositeRoutes", "cloudPromotion", "id", "groupId", "createdAt", "updatedAt"]) {
expect(p, field).not.toHaveProperty(field);
}
});
diff --git a/apps/api/src/modules/system/setup.controller.ts b/apps/api/src/modules/system/setup.controller.ts
index 47a90997f..4770e16f6 100644
--- a/apps/api/src/modules/system/setup.controller.ts
+++ b/apps/api/src/modules/system/setup.controller.ts
@@ -356,7 +356,7 @@ export async function resetAdminPassword(c: Context) {
// multi-user box the reset never lands on an arbitrary member row.
const admin = await repos.user.findFoundingAdmin();
if (!admin) {
- return c.json({ error: "No admin account exists yet — run `openship` to create one." }, 409);
+ return c.json({ error: "No admin account exists yet — run `openship` and choose Create first admin, or run `openship up --non-interactive --admin-email ` with OPENSHIP_ADMIN_PASSWORD set." }, 409);
}
const email =
diff --git a/apps/api/test/e2e/catalog-inline-build.e2e.test.ts b/apps/api/test/e2e/catalog-inline-build.e2e.test.ts
index a78afccd9..4acac1da7 100644
--- a/apps/api/test/e2e/catalog-inline-build.e2e.test.ts
+++ b/apps/api/test/e2e/catalog-inline-build.e2e.test.ts
@@ -42,7 +42,10 @@ import { describeDockerE2E, dockerSocketPath, requireDocker } from "../helpers/d
// real @repo/db.
const { listByProjectMock } = vi.hoisted(() => ({ listByProjectMock: vi.fn() }));
vi.mock("@repo/db", () => ({
- repos: { service: { listByProject: listByProjectMock } },
+ repos: {
+ service: { listByProject: listByProjectMock },
+ project: { getEnvMap: async () => ({}) },
+ },
}));
import { buildComposeImages } from "@repo/platform/engine/modules/deployments/compose/build.service";
@@ -136,6 +139,7 @@ describeDockerE2E("catalog inline build through the real build pipeline", () =>
dep: {
id: "d-widget",
branch: "main",
+ environment: "production",
commitSha: null,
trigger: "deploy",
meta: null,
diff --git a/apps/api/test/e2e/cloud-shared-workspace.e2e.test.ts b/apps/api/test/e2e/cloud-shared-workspace.e2e.test.ts
index e7c29259f..15bc3624e 100644
--- a/apps/api/test/e2e/cloud-shared-workspace.e2e.test.ts
+++ b/apps/api/test/e2e/cloud-shared-workspace.e2e.test.ts
@@ -152,13 +152,13 @@ describeDockerE2E("multiple projects on one subscribed Docker workspace", () =>
};
const vm = { id: providerVm, namespace, status: "running" };
const provider = {
- workspaces: {
+ vms: {
get: async () => vm,
create: () => {
throw new Error("Project operation attempted to create a second host");
},
},
- workspace: () => ({
+ vm: () => ({
get: async () => vm,
runtime: async () => providerRuntime,
workloads: { list: async () => [] },
@@ -185,7 +185,7 @@ describeDockerE2E("multiple projects on one subscribed Docker workspace", () =>
domain: "opsh.io",
url: `https://${input.slug}.opsh.io`,
namespace,
- source_workspace_id: input.workspace_id,
+ source_vm_id: input.vm_id,
exported_path: input.path,
};
pages.set(input.slug, page);
@@ -359,7 +359,7 @@ describeDockerE2E("multiple projects on one subscribed Docker workspace", () =>
);
expect((await a.listAllContainers()).map((row) => row.id)).toEqual([aId]);
expect(routes.get(`${ids[0]}.opsh.io`).routes[0].action).toMatchObject({
- workspace: providerVm,
+ vm: providerVm,
port: first.hostPortByContainerPort?.[8080],
});
});
diff --git a/apps/api/test/e2e/fixtures/instance-api.ts b/apps/api/test/e2e/fixtures/instance-api.ts
index 97f198dea..7bf882126 100644
--- a/apps/api/test/e2e/fixtures/instance-api.ts
+++ b/apps/api/test/e2e/fixtures/instance-api.ts
@@ -135,7 +135,7 @@ export async function startApi(input: {
}
export async function stopApi(api: RunningApi): Promise {
- if (api.child.exitCode === null) {
+ if (api.child.exitCode === null && api.child.signalCode === null) {
api.child.kill("SIGTERM");
const exited = new Promise((resolve) => api.child.once("exit", () => resolve(true)));
if (!(await Promise.race([exited, delay(15_000).then(() => false)]))) {
diff --git a/apps/api/test/e2e/instance-handoff.e2e.test.ts b/apps/api/test/e2e/instance-handoff.e2e.test.ts
index 0bb185c46..e39c61903 100644
--- a/apps/api/test/e2e/instance-handoff.e2e.test.ts
+++ b/apps/api/test/e2e/instance-handoff.e2e.test.ts
@@ -5,7 +5,7 @@ import { createRequire } from "node:module";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { afterAll, expect, it } from "vitest";
-import { createServer, type Server } from "node:http";
+import { createServer, request as httpRequest, type Server } from "node:http";
import { createHmac } from "node:crypto";
import { freePort, startApi, stopApi, jsonRequest, type RunningApi } from "./fixtures/instance-api";
import type { DataTransferFile } from "../../src/modules/system/data-transfer/types";
@@ -433,6 +433,47 @@ it("resumes after a lost activation acknowledgement without reimporting or start
).toBe(newer.id);
}, 120_000);
+it.each(["resume", "cancel"] as const)("recovers a persisted quiescing source after restart with %s", async action => {
+ const { source, target } = await pair();
+ const original = await createProject(source, "Before interrupted drain");
+ const offer = await post<{ code: string }>(target, "/api/system/instance/offer", { direction: "target" });
+ // A real admitted mutation waits for its remaining request body. The move must
+ // keep waiting for it, rather than treating an incomplete drain as a snapshot.
+ const held = httpRequest(`${source.baseUrl}/api/projects`, {
+ method: "POST", headers: { "content-type": "application/json" },
+ });
+ held.on("error", () => { /* The fixture intentionally interrupts this request. */ });
+ held.write('{"name":');
+ let restarted: RunningApi | undefined;
+ try {
+ await post(source, "/api/system/instance/move", { code: offer.code, confirmReplace: true });
+ await expect.poll(async () => (await state(source)).role, { timeout: 15_000 }).toBe("quiescing");
+ const exited = new Promise(resolve => source.child.once("exit", () => resolve()));
+ source.child.kill("SIGKILL"); // simulate a crash after the durable fence
+ await exited;
+ held.destroy();
+ restarted = await startApi({ dbDir: source.dbDir, port: source.port, secret: source.secret });
+ apis.push(restarted);
+ expect(await state(restarted)).toMatchObject({ role: "quiescing", handoff: { running: false } });
+ expect((await fetch(`${restarted.baseUrl}/api/health`)).status).toBe(200);
+ expect((await fetch(`${restarted.baseUrl}/api/projects`)).status).toBe(503);
+ await post(restarted, `/api/system/instance/${action}`);
+ if (action === "resume") {
+ await waitMove(restarted);
+ expect((await state(target)).role).toBe("active");
+ expect((await jsonRequest<{ data: { id: string } }>(target.baseUrl, `/api/projects/${original.id}`)).data.id).toBe(original.id);
+ } else {
+ expect(await state(restarted)).toMatchObject({ role: "active", handoff: { status: "aborted" } });
+ expect((await jsonRequest<{ data: { id: string } }>(restarted.baseUrl, `/api/projects/${original.id}`)).data.id).toBe(original.id);
+ }
+ } finally {
+ held.destroy();
+ await stopApi(source);
+ await stopApi(target);
+ if (restarted) await stopApi(restarted);
+ }
+}, 120_000);
+
it("cancels a prepared but unactivated receiver and restores its recovery archive", async () => {
const { source, target } = await pair();
const old = await createProject(target, "Receiver original");
diff --git a/apps/api/test/e2e/platform-import-data.e2e.test.ts b/apps/api/test/e2e/platform-import-data.e2e.test.ts
index ef24f936c..ac15215ea 100644
--- a/apps/api/test/e2e/platform-import-data.e2e.test.ts
+++ b/apps/api/test/e2e/platform-import-data.e2e.test.ts
@@ -23,14 +23,15 @@ import { describeDockerE2E, requireDocker, dockerSocketPath } from "../helpers/d
const h = vi.hoisted(() => ({
project: {} as any,
source: undefined as unknown,
+ service: undefined as any,
runtime: undefined as unknown,
workspaceId: undefined as string | undefined,
exportOnly: vi.fn(),
}));
vi.mock("@repo/db", () => ({
repos: {
- project: { findById: async () => h.project },
- service: { listByProject: async () => [] },
+ project: { findById: async () => h.project, getEnvMap: async () => ({}) },
+ service: { listByProject: async () => h.service ? [h.service] : [] },
},
}));
vi.mock("@repo/platform/engine/modules/migration/migration-access", () => ({
@@ -378,10 +379,16 @@ describeDockerE2E("generic stopped-volume provider import", () => {
environment: {},
bindings: [],
} as PlannedImportService;
+ h.service = {
+ id: `${projectId}-service`, projectId, name: fixture.name,
+ image: fixture.image, environment: {},
+ volumes: service.create.volumes, namespaceVolumes: true,
+ };
const args = {
runId: tag,
service,
projectId,
+ serviceId: h.service.id,
signal: new AbortController().signal,
log: () => {},
progress: vi.fn(),
diff --git a/apps/api/test/e2e/platform-import-project.e2e.test.ts b/apps/api/test/e2e/platform-import-project.e2e.test.ts
new file mode 100644
index 000000000..b8de6a4ca
--- /dev/null
+++ b/apps/api/test/e2e/platform-import-project.e2e.test.ts
@@ -0,0 +1,569 @@
+import { afterAll, beforeAll, expect, it, vi } from "vitest";
+import { randomUUID } from "node:crypto";
+import { spawn } from "node:child_process";
+import { createConnection } from "node:net";
+import { once } from "node:events";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import {
+ BuildLogger,
+ CommandSourceBackupExecutor,
+ CloudDockerRuntime,
+ DockerRuntime,
+ type CommandExecutor,
+} from "@repo/adapters";
+import { CloudServerConnection } from "../../../../packages/adapters/src/runtime/cloud/server-connection";
+import { CloudWorkspaceExecutor } from "../../../../packages/adapters/src/runtime/cloud/workspace-executor";
+import { db, repos, schema } from "@repo/db";
+import type { ExecutionContext } from "@repo/platform";
+import type { ProviderInventory } from "@repo/platform/engine/modules/migration/providers/types";
+import { encrypt, decryptEnvMap } from "@repo/platform/engine/lib/encryption";
+import { deployComposeServices } from "@repo/platform/engine/modules/deployments/compose/deploy.service";
+import { projectServicesToDeployableServices } from "@repo/platform/engine/modules/deployments/compose/project-services";
+import { seedDeployment, seedOrg, setActive } from "../helpers/seed";
+import { describeDockerE2E, requireDocker, dockerSocketPath } from "../helpers/docker-e2e";
+import { refreshConnectionEnv } from "@repo/platform/engine/modules/projects/project-connection.service";
+import {
+ sharedServiceAlias,
+ sharedServiceNetwork,
+} from "@repo/platform/engine/modules/projects/shared-service-network";
+
+// Substitute Railway's control/SSH boundary, Git checkout, destination resolution
+// and the asynchronous build queue. All runtime operations use an isolated daemon.
+// Review, project creation, encrypted environments, migration checkpoints,
+// volume transfer and the ordinary Compose deployment engine remain real.
+const h = vi.hoisted(() => ({
+ discover: vi.fn(),
+ prepare: vi.fn(),
+ assertStopped: vi.fn(),
+ openSource: vi.fn(),
+ runtime: vi.fn(),
+ deploy: vi.fn(),
+}));
+vi.mock("@repo/platform/engine/modules/credentials/connection-authorization", () => ({
+ getProviderAccess: async () => ({ provider: "railway", publicFields: {}, secrets: {} }),
+}));
+vi.mock("@repo/platform/engine/modules/migration/providers/railway", () => ({
+ railwayMigrationProvider: { discover: h.discover },
+}));
+vi.mock("@repo/platform/engine/modules/migration/providers/railway-project-transfer", () => ({
+ prepareRailwayProjectTransfer: h.prepare,
+ assertRailwayExportOnly: h.assertStopped,
+ restoreRailwayProjectTransfer: async () => {},
+}));
+vi.mock("@repo/platform/engine/modules/migration/providers/railway-data", () => ({
+ openRailwayDataSource: h.openSource,
+}));
+vi.mock("@repo/platform/engine/modules/migration/migration-runtime", async (original) => ({
+ ...(await original
+ {t.auth.register.hasAccount}{" "}
- {t.auth.verifyEmail.backToSignIn}
+ {t.auth.register.signIn}
+
+ {t.auth.forgotPassword.title}
+
);
diff --git a/apps/dashboard/src/app/(dashboard)/DashboardHomeClient.tsx b/apps/dashboard/src/app/(dashboard)/DashboardHomeClient.tsx
index 138d19258..b9513fcc3 100644
--- a/apps/dashboard/src/app/(dashboard)/DashboardHomeClient.tsx
+++ b/apps/dashboard/src/app/(dashboard)/DashboardHomeClient.tsx
@@ -143,7 +143,7 @@ export default function DashboardHomeClient({
) : (
{sourceProjects.slice(0, 5).map((p) => (
-
removeProject(p.id)} />
+ removeProject(p.id)} />
))}
)}
diff --git a/apps/dashboard/src/app/(dashboard)/apps/page.tsx b/apps/dashboard/src/app/(dashboard)/apps/page.tsx
index 4ba8cd845..377e5f5f2 100644
--- a/apps/dashboard/src/app/(dashboard)/apps/page.tsx
+++ b/apps/dashboard/src/app/(dashboard)/apps/page.tsx
@@ -184,7 +184,7 @@ export default function AppsPage() {
{filteredApps.length > 0 ? filteredApps.map(app => (
-
removeProject(app.id)} />
+ removeProject(app.id)} />
)) : (
{copy.catalogNoResults}
)}
diff --git a/apps/dashboard/src/app/(dashboard)/deployments/components/DeploymentCard.tsx b/apps/dashboard/src/app/(dashboard)/deployments/components/DeploymentCard.tsx
index 105bd759e..92eaf168a 100644
--- a/apps/dashboard/src/app/(dashboard)/deployments/components/DeploymentCard.tsx
+++ b/apps/dashboard/src/app/(dashboard)/deployments/components/DeploymentCard.tsx
@@ -8,10 +8,8 @@ import { DeploymentMenu } from "./DeploymentMenu";
import { CommitDetailsModal } from "./CommitDetailsModal";
import type { Deployment } from "../types";
import { formatDistanceToNow, formatBuildTime, getStatusConfig } from "../utils";
-import { ProjectStackIcon } from "@/components/shared/ProjectStackIcon";
-import { AppLogo } from "@/components/AppLogo";
+import { ProjectIcon } from "@/components/shared/ProjectIcon";
import { useI18n, interpolate } from "@/components/i18n-provider";
-import { useImageFallback } from "@/hooks/useImageFallback";
type ServiceStatusLabels = {
deployed: string;
@@ -122,7 +120,6 @@ export const DeploymentCard: React.FC = ({
const { t } = useI18n();
const [isCommitModalOpen, setIsCommitModalOpen] = useState(false);
const [isMenuOpen, setIsMenuOpen] = useState(false);
- const favicon = useImageFallback(deployment.favicon);
const statusConfig = getStatusConfig(deployment.status);
const statusLabelMap: Record = {
@@ -151,21 +148,9 @@ export const DeploymentCard: React.FC = ({
aria-label={deployment.projectName || t.deployments.card.unknownProject}
className="absolute inset-0 z-0"
/>
- {/* App logo (catalog apps) → project favicon → framework icon → initials */}
+ {/* Project icon → catalog logo → framework or service icon */}
- {appTemplateId ? (
-
- ) : favicon.showImage ? (
-

- ) : (
-
- )}
+
{/* Main info */}
diff --git a/apps/dashboard/src/app/(dashboard)/deployments/types.ts b/apps/dashboard/src/app/(dashboard)/deployments/types.ts
index 213fb5e83..a49f53391 100644
--- a/apps/dashboard/src/app/(dashboard)/deployments/types.ts
+++ b/apps/dashboard/src/app/(dashboard)/deployments/types.ts
@@ -56,9 +56,8 @@ export interface Deployment {
branch?: string;
projectId?: string;
projectName?: string;
- /** Auto-detected favicon of the deployed site, cached on the project.
- * When present it replaces the framework/Docker glyph as the row logo. */
- favicon?: string | null;
+ /** Project icon shared with project lists and settings. */
+ iconUrl?: string | null;
failureReason?: string;
/** Rollback state — populated by the orchestrator-aware listing endpoint.
* `artifactRetainedAt` non-null = artifact is archived, rollback-eligible.
diff --git a/apps/dashboard/src/app/(dashboard)/deployments/utils.ts b/apps/dashboard/src/app/(dashboard)/deployments/utils.ts
index f2bc27c23..711c32894 100644
--- a/apps/dashboard/src/app/(dashboard)/deployments/utils.ts
+++ b/apps/dashboard/src/app/(dashboard)/deployments/utils.ts
@@ -41,7 +41,7 @@ export const mapRowToDeployment = (row: any): Deployment => {
branch: row.branch ?? undefined,
projectId: row.projectId,
projectName: row.projectName,
- favicon: row.favicon ?? null,
+ iconUrl: row.iconUrl ?? null,
failureReason: row.errorMessage ?? undefined,
/* Rollback state — flows from the listing endpoint, which enriches
* each row with isActive and surfaces the orchestrator-owned
diff --git a/apps/dashboard/src/app/(dashboard)/layout.tsx b/apps/dashboard/src/app/(dashboard)/layout.tsx
index abb88ac76..cc8c81f0c 100644
--- a/apps/dashboard/src/app/(dashboard)/layout.tsx
+++ b/apps/dashboard/src/app/(dashboard)/layout.tsx
@@ -173,10 +173,9 @@ export default async function DashboardLayout({ children }: { children: React.Re
hostDomain={deploymentInfo.hostDomain}
>
- {/* Update + platform-status surface — full app width, ABOVE the sidebar.
- Renders nothing unless there's an advisory / platform notice (SaaS:
- partial outage, maintenance) / available update / what's-new, so it
- adds no chrome when idle. */}
+ {/* Full-width update surface. Managed Cloud shows workload security;
+ Desktop and self-hosted also show installation updates, operator
+ notices and what's new. Empty state adds no chrome. */}
{children}
diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/AdvancedSettings.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/AdvancedSettings.tsx
index fa09be27a..96b71d21c 100644
--- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/AdvancedSettings.tsx
+++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/AdvancedSettings.tsx
@@ -27,6 +27,7 @@ import { isSchemaAppTemplate } from "@/components/app-settings/AppSettingsForm";
import { AppConfiguration } from "./AppConfiguration";
import { BuildSettings } from "./BuildSettings";
import { CloudStaticHosting } from "@/components/project-settings/CloudStaticHosting";
+import { ProjectIconSetting } from "@/components/project-settings/ProjectIconSetting";
interface Props {
onDeleteProject: (wipeVolumes?: boolean, recordOnly?: boolean) => void;
@@ -357,6 +358,7 @@ export const AdvancedSettings = ({ onDeleteProject }: Props) => {
and collided — and since this card has no `overflow-hidden` (the ⋮ menu needs
to escape it), the collision spilled into the neighbouring card. */}
+
{
/** One shared editor, accessible here and through workload shortcuts. */
export function ProjectEnvironmentSettings() {
- const { id } = useProjectSettings();
+ const { id, projectData, servicesData } = useProjectSettings();
const { t } = useI18n();
const [envOpen, setEnvOpen] = useState(false);
+ const application = projectApplication(projectData, servicesData.services);
+ const opensApplication = application?.mode === "project" &&
+ !servicesData.services.some((service) => !service.applicationMode);
return (
<>
+ {t.projectDetail.services.detail.tabs.env}
+
+
+ ) : (
- }
+ )}
/>
- setEnvOpen(false)} />
+ {!opensApplication && (
+ setEnvOpen(false)} />
+ )}
>
);
}
diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/DomainSettings.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/DomainSettings.tsx
index 43691ed49..49a48108e 100644
--- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/DomainSettings.tsx
+++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/DomainSettings.tsx
@@ -11,6 +11,7 @@ import { useRouter } from "next/navigation";
import { useProjectSettings } from "@/context/ProjectSettingsContext";
import { RoutingConfigCard } from "./RoutingConfigCard";
import { RouteRules } from "./RouteRules";
+import { DomainResponseRoutes } from "@/components/routing/DomainResponseRoutes";
import { RoutingUnsyncedCallout } from "./RoutingUnsyncedCallout";
import { localizeDiagnosisMessage } from "@/lib/i18n/localize-issues";
import { invalidateProjectCaches } from "@/hooks/useProjectEndpoints";
@@ -1580,7 +1581,7 @@ export const DomainSettings = ({ applicationScope = false, serviceScope, onRoute
// Per-service domains have no endpoint order to reorder — primary is the
// domain row's isPrimary flag. Flip it via the API, then reflect locally
// (exactly one primary per project). getPrimaryByProject picks this up for
- // the project's canonical URL / favicon / analytics, and it survives
+ // the project's canonical URL / analytics, and it survives
// redeploys (service route registration preserves an existing isPrimary).
const handleSetPrimaryServiceDomain = async (summary: DomainSummaryItem) => {
if (!summary.domainId || summary.isPrimary) return;
@@ -2008,6 +2009,11 @@ export const DomainSettings = ({ applicationScope = false, serviceScope, onRoute
+ ) : undefined}
protectionControl={}
menuActions={menuActions}
@@ -3109,6 +3115,7 @@ function DiagnosablePill({
function DomainOverviewCard({
domain,
+ responseRoutes,
protectionControl,
menuActions = [],
sslActionBusy = false,
@@ -3128,6 +3135,7 @@ function DomainOverviewCard({
ingressSettings,
}: {
domain: DomainSummaryItem;
+ responseRoutes?: React.ReactNode;
protectionControl?: React.ReactNode;
/** Secondary actions (edit, renew, …) collapsed into a ⋯ menu. Visit is a
* plain icon; Verify is a direct inline button below, not a menu item. */
@@ -3501,6 +3509,7 @@ function DomainOverviewCard({
) : null}
+ {responseRoutes}
);
}
diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/RouteRules.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/RouteRules.tsx
index e10f0b21b..845559b21 100644
--- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/RouteRules.tsx
+++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/RouteRules.tsx
@@ -69,7 +69,7 @@ export function RouteRules() {
setLoading(true);
try {
const res = await projectsApi.listRouteRules(projectData.id);
- const list = res?.rules ?? [];
+ const list = (res?.rules ?? []).filter(rule => !rule.spec.response);
setRules(list);
if (!autoOpened.current && list.length > 0) {
setOpen(true);
diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.test.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.test.tsx
index 598bfb73c..a4c904295 100644
--- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.test.tsx
+++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.test.tsx
@@ -89,6 +89,7 @@ beforeEach(() => {
afterEach(async () => {
await act(async () => root.unmount());
host.remove();
+ vi.restoreAllMocks();
vi.unstubAllGlobals();
});
@@ -106,6 +107,21 @@ async function choose(scope: ParentNode, name: string) {
await click(option!);
}
+it("shows the saved project icon in the connection picker", async () => {
+ vi.spyOn(HTMLImageElement.prototype, "complete", "get").mockReturnValue(false);
+ h.candidates.mockResolvedValue({
+ data: [{ id: "web", name: "Web app", description: "production", appTemplateId: "redis", iconUrl: "https://cdn.example.test/project.svg" }],
+ });
+ await act(async () => root.render(
+ ,
+ ));
+ const dialog = document.querySelector("[data-modal-surface]")!;
+ await click(dialog.querySelector('[aria-haspopup="listbox"]')!);
+ const image = document.querySelector('[role="option"] img');
+ expect(image?.getAttribute("src")).toBe("https://cdn.example.test/project.svg");
+ expect(image?.getAttribute("referrerpolicy")).toBe("no-referrer");
+});
+
describe("connection form copy", () => {
it("names the count and project, and points at the deployment status, after sharing values", async () => {
h.candidates.mockResolvedValue({
diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.tsx
index 4975561d6..b0d0c3df0 100644
--- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.tsx
+++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.tsx
@@ -5,10 +5,11 @@ import { Icon as UiIcon } from "@repo/ui/icons";
import { useEffect, useMemo, useState } from "react";
import { resolveLocalized } from "@repo/core";
+import type { ProjectConnectionCandidate } from "@repo/contracts";
import { Modal } from "@/components/ui/Modal";
import { CustomSelect } from "@/components/ui/CustomSelect";
import { Checkbox } from "@/components/ui/Checkbox";
-import { AppLogo } from "@/components/AppLogo";
+import { ProjectIcon } from "@/components/shared/ProjectIcon";
import { connectionsApi, type ConnectionMode } from "@/lib/api/connections";
import { getApiErrorMessage } from "@/lib/api/client";
import { useToast } from "@/context/ToastContext";
@@ -49,15 +50,6 @@ function InlineHint({ text }: { text: string }) {
);
}
-interface TargetProject {
- id: string;
- name: string;
- description: string;
- appTemplateId?: string;
- favicon?: string | null;
- clusterId?: string | null;
-}
-
interface ConnectionFormProps {
onClose: () => void;
hideHeader?: boolean;
@@ -104,7 +96,7 @@ export function ProjectConnectionForm({
(!sourceDatabaseId || output.sourceDatabaseId === sourceDatabaseId),
), [suppliedOutputs, view, sourceServiceId, sourceDatabaseId]);
- const [targets, setTargets] = useState([]);
+ const [targets, setTargets] = useState([]);
const [loadingProjects, setLoadingProjects] = useState(true);
const [targetId, setTargetId] = useState(fixedTargetId ?? "");
const [mode, setMode] = useState(guide?.defaultMode ?? "internal");
@@ -164,7 +156,7 @@ export function ProjectConnectionForm({
setLoadingProjects(true);
connectionsApi.candidates(fixedSourceId ?? fixedTargetId ?? "")
.then(result => {
- if (!cancelled) setTargets(result.data.map(project => ({ ...project, appTemplateId: project.appTemplateId ?? undefined })));
+ if (!cancelled) setTargets(result.data);
})
.catch(error => { if (!cancelled) setLoadError(getApiErrorMessage(error, c.failed)); })
.finally(() => { if (!cancelled) setLoadingProjects(false); });
@@ -237,7 +229,7 @@ export function ProjectConnectionForm({
label: p.name,
description: p.description || undefined,
icon: (
-
+
),
}))}
onChange={fixedTargetId ? setSourceProjectId : setTargetId}
diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/domain-routing-retry.test.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/domain-routing-retry.test.tsx
index 8045f5187..e23c9279f 100644
--- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/domain-routing-retry.test.tsx
+++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/domain-routing-retry.test.tsx
@@ -41,6 +41,7 @@ vi.mock("@/lib/api", async (original) => {
...actual.projectsApi,
getEdgeStatus: mocks.edgeStatus,
listRouteProtection: async () => ({ data: [] }),
+ listRouteRules: async () => ({ rules: [] }),
},
domainsApi: { ...actual.domainsApi, list: mocks.listDomains, verifySsl: mocks.verifySsl },
deployApi: {
diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/environment-scope.test.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/environment-scope.test.tsx
index a60f81f64..d0ef8b87c 100644
--- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/environment-scope.test.tsx
+++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/environment-scope.test.tsx
@@ -8,6 +8,7 @@ import { ProjectSettingsProvider, useProjectSettings } from "@/context/ProjectSe
import { BuildSettings } from "./BuildSettings";
import { AppConfiguration } from "./AppConfiguration";
import { ApplicationSettingsForm } from "@/components/project-settings/ApplicationSettingsForm";
+import { ProjectEnvironmentPanel } from "@/components/project-settings/ProjectEnvironmentPanel";
import { ProjectApplicationPanel } from "./services/ProjectApplicationPanel";
const api = vi.hoisted(() => ({
@@ -269,8 +270,7 @@ describe("project environment access (GH-881)", () => {
])(
"rebuilds saved environment changes for $framework on $deployTarget",
async ({ framework, ...extra }) => {
- await mountProject(framework, , extra);
- await act(async () => button("Edit").click());
+ await mountProject(framework, , extra);
await editInput(
[...document.querySelectorAll("input")].find((input) => input.value === "old")!,
"new",
@@ -293,8 +293,7 @@ describe("project environment access (GH-881)", () => {
},
{ framework: "docker-compose", deployTarget: "cloud" as const, options: {} },
])("preserves runtime refresh for $framework on $deployTarget", async ({ framework, ...extra }) => {
- await mountProject(framework, , extra);
- await act(async () => button("Edit").click());
+ await mountProject(framework, , extra);
await editInput(
[...document.querySelectorAll("input")].find((input) => input.value === "old")!,
"new",
@@ -307,8 +306,7 @@ describe("project environment access (GH-881)", () => {
it("keeps a static site's saved values available when starting the rebuild fails", async () => {
api.trigger.mockRejectedValueOnce(new Error("unavailable"));
- await mountProject("static", , { options: { workloadType: "static" } });
- await act(async () => button("Edit").click());
+ await mountProject("static", , { options: { workloadType: "static" } });
await editInput(
[...document.querySelectorAll("input")].find((input) => input.value === "old")!,
"new",
@@ -329,6 +327,7 @@ describe("project environment access (GH-881)", () => {
it.each(["nextjs", "docker-compose"])(
"keeps %s Settings reachable and edits shared project inputs without overwriting secrets",
async (framework) => {
+ api.services.mockResolvedValue({ success: true, services: [{ id: "cache", name: "redis", kind: "compose" }] });
await mountProject(framework);
expect(host.querySelector('nav a[href$="/advanced"]')).not.toBeNull();
expect(host.textContent).toContain("Project environment");
@@ -400,15 +399,21 @@ describe("permanent configuration ownership", () => {
const saved = { id: "project", name: "Test", slug: "test", description: "", framework: "nextjs",
runtimeMode: "bare", ...options, port: 3000 };
- it.each([false, true])("keeps project limits and the shared editor in Settings with companions=%s", async (companions) => {
+ it.each([false, true])("opens the correct environment scope from Settings with companions=%s", async (companions) => {
if (companions) api.services.mockResolvedValue({ success: true, services: [{ id: "db", name: "postgres", kind: "compose" }] });
await mountProject("nextjs", , { options });
expect(host.querySelectorAll('section[aria-label="Machine power"]')).toHaveLength(1);
expect(host.textContent).toContain("Project environment");
- expect(host.querySelector('a[href$="/application/env"]')).toBeNull();
expect(host.querySelector('a[href$="/application/settings"]')).not.toBeNull();
- await act(async () => button("Edit").click());
- expect(document.querySelector('[data-modal-surface] input[value="BUILD_VALUE"]')).not.toBeNull();
+ if (companions) {
+ expect(host.querySelector('a[href$="/application/env"]')).toBeNull();
+ await act(async () => button("Edit").click());
+ expect(document.querySelector('[data-modal-surface] input[value="BUILD_VALUE"]')).not.toBeNull();
+ } else {
+ expect(host.querySelector('a[href="/projects/project/services/application/env"]')?.textContent).toBe("Environment");
+ expect(document.querySelector('[data-modal-surface]')).toBeNull();
+ expect(api.getEnv).not.toHaveBeenCalled();
+ }
});
it("saves only edited app configuration inline without touching environment or deploying", async () => {
diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/services/service-domains.test.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/services/service-domains.test.tsx
index 28825b05d..b776ee564 100644
--- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/services/service-domains.test.tsx
+++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/services/service-domains.test.tsx
@@ -32,7 +32,7 @@ vi.mock("@/lib/api", async (original) => {
return {
...actual,
servicesApi: { ...actual.servicesApi, get: mocks.get, update: mocks.update },
- projectsApi: { ...actual.projectsApi, update: mocks.updateProject, connectDomain: mocks.connect, getEdgeStatus: async () => ({ ready: true }), listRouteProtection: async () => ({ data: [] }) },
+ projectsApi: { ...actual.projectsApi, update: mocks.updateProject, connectDomain: mocks.connect, getEdgeStatus: async () => ({ ready: true }), listRouteProtection: async () => ({ data: [] }), listRouteRules: async () => ({ rules: [] }) },
deployApi: { ...actual.deployApi, checkPorts: async () => ({ data: [] }), checkOutput: async () => ({ data: [] }) },
domainsApi: { ...actual.domainsApi, remove: mocks.remove, verify: mocks.verify, records: mocks.records,
list: mocks.listDomains, dnsChallenge: mocks.dnsChallenge, startDnsChallenge: mocks.startDnsChallenge, dnsPlan: mocks.dnsPlan,
diff --git a/apps/dashboard/src/app/(dashboard)/projects/components/ProjectCard.tsx b/apps/dashboard/src/app/(dashboard)/projects/components/ProjectCard.tsx
index f662bcf33..85e0967bb 100644
--- a/apps/dashboard/src/app/(dashboard)/projects/components/ProjectCard.tsx
+++ b/apps/dashboard/src/app/(dashboard)/projects/components/ProjectCard.tsx
@@ -5,8 +5,7 @@ import { Icon as UiIcon } from "@repo/ui/icons";
import React, { useState } from "react";
import Link from "next/link";
import { type Project } from "@/constants/mock";
-import { AppLogo } from "@/components/AppLogo";
-import { ProjectStackIcon } from "@/components/shared/ProjectStackIcon";
+import { ProjectIcon } from "@/components/shared/ProjectIcon";
import { getFrameworkConfig } from "@/components/import-project/Frameworks";
import { getProjectStatus, projectCardHref, projectDisplayDomain } from "@/utils/project-status";
import { ProjectStatusBadge } from "@/components/shared/ProjectStatusBadge";
@@ -15,7 +14,6 @@ import { useModal } from "@/context/ModalContext";
import { useToast } from "@/context/ToastContext";
import { projectsApi, getApiErrorMessage } from "@/lib/api";
import { timeAgo } from "@/lib/time";
-import { useImageFallback } from "@/hooks/useImageFallback";
import type { Dictionary } from "@/i18n";
/* ── Helpers ──────────────────────────────────────────────────────── */
@@ -50,9 +48,6 @@ interface Props {
* every row by the projects list and `/info`, but isn't declared on `Project`
* (constants/mock) yet, so it's spelled out here rather than cast away. */
project: Project & { primaryDomain?: string | null };
- /** On the Apps page: show the catalog app's brand logo instead of the
- * framework/service fallback icon. */
- preferAppLogo?: boolean;
/** Show an "update available" badge (fed by the update scan). Off by default
* so the Projects page is unaffected. */
updateAvailable?: boolean;
@@ -61,14 +56,13 @@ interface Props {
onChanged?: () => void;
}
-const ProjectCard: React.FC = ({ project, preferAppLogo, updateAvailable, onChanged }) => {
+const ProjectCard: React.FC = ({ project, updateAvailable, onChanged }) => {
const { t } = useI18n();
const { showModal, hideModal } = useModal();
const { showToast } = useToast();
const [menuOpen, setMenuOpen] = useState(false);
const status = getProjectStatus(project);
const fw = getFrameworkConfig(project.framework);
- const favicon = useImageFallback(project.favicon);
const isLocal = !!project.localPath;
const hasRepo = !!(project.gitOwner && project.gitRepo);
@@ -118,22 +112,8 @@ const ProjectCard: React.FC = ({ project, preferAppLogo, updateAvailable,
- {/* Icon — on the Apps page show the catalog app's brand logo; otherwise
- the project favicon, falling back to the framework/service glyph. */}
- {preferAppLogo && project.isApp ? (
-
- ) : favicon.showImage ? (
-

- ) : (
-
- )}
+
{/* Name + domain */}
diff --git a/apps/dashboard/src/app/(dashboard)/projects/components/ProjectGridCard.tsx b/apps/dashboard/src/app/(dashboard)/projects/components/ProjectGridCard.tsx
index 66f51f1f7..f1aaa56c9 100644
--- a/apps/dashboard/src/app/(dashboard)/projects/components/ProjectGridCard.tsx
+++ b/apps/dashboard/src/app/(dashboard)/projects/components/ProjectGridCard.tsx
@@ -6,14 +6,12 @@ import Link from "next/link";
import { useRouter } from "next/navigation";
import DropdownMenu from "@/components/ui/DropdownMenu";
import { type Project } from "@/constants/mock";
-import { AppLogo } from "@/components/AppLogo";
-import { ProjectStackIcon } from "@/components/shared/ProjectStackIcon";
+import { ProjectIcon } from "@/components/shared/ProjectIcon";
import { getProjectStatus, projectCardHref, projectDisplayDomain } from "@/utils/project-status";
import { ProjectStatusBadge } from "@/components/shared/ProjectStatusBadge";
import { ServiceStatusIndicator } from "@/components/services/ServiceStatusBadge";
import { useI18n, interpolate } from "@/components/i18n-provider";
import { timeAgo } from "@/lib/time";
-import { useImageFallback } from "@/hooks/useImageFallback";
import { getHostingLabel } from "./ProjectCard";
/** Compact project summary with direct links to its management screens. */
@@ -22,12 +20,10 @@ const ProjectGridCard: React.FC<{
* every row by the projects list and `/info`, but isn't declared on `Project`
* (constants/mock) yet, so it's spelled out here rather than cast away. */
project: Project & { primaryDomain?: string | null };
- preferAppLogo?: boolean;
updateAvailable?: boolean;
-}> = ({ project, preferAppLogo, updateAvailable }) => {
+}> = ({ project, updateAvailable }) => {
const { t } = useI18n();
const router = useRouter();
- const favicon = useImageFallback(project.favicon);
const domain = projectDisplayDomain(project);
const hosting = getHostingLabel(project.deployTarget, project.serverName, t);
@@ -65,20 +61,7 @@ const ProjectGridCard: React.FC<{
- {preferAppLogo && project.isApp ? (
-
- ) : favicon.showImage ? (
- // eslint-disable-next-line @next/next/no-img-element
-

- ) : (
-
- )}
+
diff --git a/apps/dashboard/src/app/(dashboard)/projects/components/project-favicon.test.tsx b/apps/dashboard/src/app/(dashboard)/projects/components/project-icon.test.tsx
similarity index 67%
rename from apps/dashboard/src/app/(dashboard)/projects/components/project-favicon.test.tsx
rename to apps/dashboard/src/app/(dashboard)/projects/components/project-icon.test.tsx
index 2165098d3..e2482db84 100644
--- a/apps/dashboard/src/app/(dashboard)/projects/components/project-favicon.test.tsx
+++ b/apps/dashboard/src/app/(dashboard)/projects/components/project-icon.test.tsx
@@ -39,10 +39,35 @@ afterEach(async () => {
});
for (const [name, Card] of [["list", ProjectCard], ["grid", ProjectGridCard]] as const) {
- const render = (favicon = "/favicon-old.ico") => (
-
+ const render = (iconUrl = "/icon-old.png") => (
+
);
- describe(`${name} favicon`, () => {
+ describe(`${name} iconUrl`, () => {
+ it("uses a custom icon before the catalog logo on the Apps page", async () => {
+ complete = false;
+ root = createRoot(container);
+ await act(async () => root!.render(
+
,
+ ));
+ expect(container.querySelector('img[alt=""]')?.getAttribute("src")).toBe("https://cdn.example.test/custom.png");
+ });
+
+ it("uses the same catalog fallback when a custom icon fails or is cleared", async () => {
+ complete = false;
+ root = createRoot(container);
+ const custom = "https://cdn.example.test/custom.png";
+ const view = (iconUrl: string | null) => (
+
+ );
+ await act(async () => root!.render(view(custom)));
+ await act(async () => container.querySelector('img[alt=""]')!.dispatchEvent(new Event("error")));
+ const fallback = container.querySelector('img[alt=""]')?.getAttribute("src");
+ expect(fallback).toBeTruthy();
+ expect(fallback).not.toBe(custom);
+ await act(async () => root!.render(view(null)));
+ expect(container.querySelector('img[alt=""]')?.getAttribute("src")).toBe(fallback);
+ });
+
it("falls back when the image failed before hydration attached its error listener", async () => {
const view = render();
container.innerHTML = renderToString(view);
@@ -59,16 +84,16 @@ for (const [name, Card] of [["list", ProjectCard], ["grid", ProjectGridCard]] as
await act(async () => root!.render(render()));
await act(async () => container.querySelector('img[alt=""]')!.dispatchEvent(new Event("error")));
expect(container.querySelector('img[alt=""]')).toBeNull();
- await act(async () => root!.render(render("/favicon-new.ico")));
- expect(container.querySelector('img[alt=""]')?.getAttribute("src")).toBe("/favicon-new.ico");
+ await act(async () => root!.render(render("/icon-new.png")));
+ expect(container.querySelector('img[alt=""]')?.getAttribute("src")).toBe("/icon-new.png");
});
- it("keeps a successfully cached favicon", async () => {
+ it("keeps an image that loaded before hydration", async () => {
naturalWidth = 32;
const view = render();
container.innerHTML = renderToString(view);
await act(async () => { root = hydrateRoot(container, view); });
- expect(container.querySelector('img[alt=""]')?.getAttribute("src")).toBe("/favicon-old.ico");
+ expect(container.querySelector('img[alt=""]')?.getAttribute("src")).toBe("/icon-old.png");
});
});
}
diff --git a/apps/dashboard/src/app/(dashboard)/projects/page.tsx b/apps/dashboard/src/app/(dashboard)/projects/page.tsx
index c692c689e..46aab35f3 100644
--- a/apps/dashboard/src/app/(dashboard)/projects/page.tsx
+++ b/apps/dashboard/src/app/(dashboard)/projects/page.tsx
@@ -109,11 +109,11 @@ export default function ProjectsPage() {
) : filtered.length > 0 ? (
view === "grid" ? (
- {filtered.map(project =>
)}
+ {filtered.map(project =>
)}
) : (
- {filtered.map(project =>
removeProject(project.id)} />)}
+ {filtered.map(project => removeProject(project.id)} />)}
)
) : (
diff --git a/apps/dashboard/src/app/(dashboard)/providers.tsx b/apps/dashboard/src/app/(dashboard)/providers.tsx
index e1407a0f6..c6c3d0e49 100644
--- a/apps/dashboard/src/app/(dashboard)/providers.tsx
+++ b/apps/dashboard/src/app/(dashboard)/providers.tsx
@@ -7,6 +7,7 @@ import { PlatformProvider } from "@/context/PlatformContext";
import { MailScopeProvider } from "@/context/MailScopeContext";
import { AuthProvider, type AuthUser } from "@/context/AuthContext";
import { ModalProvider } from "@/context/ModalContext";
+import { DashboardPaymentsProvider } from "@/components/billing/PendingCheckoutsContext";
import type { ProductView } from "@/lib/product-view";
interface DashboardProvidersProps {
@@ -50,7 +51,7 @@ export function DashboardProviders({
// Modal content renders where its provider lives, even when opened by a
// descendant. Keep dashboard dialogs inside their platform/auth/mail context;
// the root layout's provider serves public screens outside this shell.
- const content =
{children};
+ const content =
{children};
return (
+ {
+ const result = await authClient.updateUser({ image });
+ if (result.error) throw new Error(result.error.message || t.settings.imageUrl.failed);
+ }}
+ />
+
+ );
+}
diff --git a/apps/dashboard/src/app/(dashboard)/settings/page.tsx b/apps/dashboard/src/app/(dashboard)/settings/page.tsx
index 2e4e5cea0..6b63ae685 100644
--- a/apps/dashboard/src/app/(dashboard)/settings/page.tsx
+++ b/apps/dashboard/src/app/(dashboard)/settings/page.tsx
@@ -32,6 +32,7 @@ import { useI18n } from "@/components/i18n-provider";
import { BuildPreferences } from "./_components/BuildPreferences";
import { AppearanceSetting } from "./_components/AppearanceSetting";
+import { ProfileSetting } from "./_components/ProfileSetting";
import { AppearanceEditor } from "@/components/appearance/AppearanceEditor";
import { RoutePreferences } from "./_components/RoutePreferences";
import { DeployDefaults } from "./_components/DeployDefaults";
@@ -144,6 +145,7 @@ function SettingsPageInner() {
{activeTab === "general" && !customizeAppearance && (
<>
+
{/* Deploy Defaults + Routing hidden for now — advanced/rarely-needed,
reduces general-settings noise. The edge defaults to loopback-port
diff --git a/apps/dashboard/src/app/api/proxy/[...path]/route.test.ts b/apps/dashboard/src/app/api/proxy/[...path]/route.test.ts
index 7859cba96..1626849fa 100644
--- a/apps/dashboard/src/app/api/proxy/[...path]/route.test.ts
+++ b/apps/dashboard/src/app/api/proxy/[...path]/route.test.ts
@@ -1,4 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { createHash } from "node:crypto";
import { NextRequest } from "next/server";
import { errorReporter, consoleErrorSink, type ErrorEvent } from "@repo/core/diagnostics";
@@ -27,6 +28,21 @@ afterEach(async () => {
upstreamFetch.mockReset();
});
+it("streams folder uploads larger than the middleware default without changing their bytes", async () => {
+ const bytes = new Uint8Array(12 * 1024 * 1024).fill(117);
+ upstreamFetch.mockImplementationOnce(async (_url, init) => {
+ const received = new Uint8Array(await new Response(init?.body).arrayBuffer());
+ expect(createHash("sha256").update(received).digest("hex")).toBe(createHash("sha256").update(bytes).digest("hex"));
+ expect(new Headers(init?.headers).get("authorization")).toBe("Bearer upload-test");
+ return Response.json({ received: received.length });
+ });
+ const response = await POST(new NextRequest("https://ops.example.com/api/proxy/api/projects/folder/upload/session", {
+ method: "POST", headers: { authorization: "Bearer upload-test", "Content-Type": "application/gzip" }, body: bytes,
+ }), { params: Promise.resolve({ path: ["api", "projects", "folder", "upload", "session"] }) });
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({ received: bytes.length });
+});
+
it("correlates proxy network failures without logging credentials or request contents", async () => {
upstreamFetch.mockRejectedValueOnce(Object.assign(new Error("Connection refused"), {
code: "ECONNREFUSED", headers: { authorization: "private-proxy-token-913" },
diff --git a/apps/dashboard/src/components/actions/ActionBudget.test.tsx b/apps/dashboard/src/components/actions/ActionBudget.test.tsx
index 15d557a6d..8b7819c01 100644
--- a/apps/dashboard/src/components/actions/ActionBudget.test.tsx
+++ b/apps/dashboard/src/components/actions/ActionBudget.test.tsx
@@ -15,8 +15,6 @@ const h = vi.hoisted(() => ({
checkout: vi.fn(),
resume: vi.fn(),
navigate: vi.fn(),
- begin: vi.fn(),
- closeTab: vi.fn(),
closeDialog: vi.fn(),
}));
vi.mock("@/lib/api/billing", () => ({
@@ -28,10 +26,7 @@ vi.mock("@/lib/api/billing", () => ({
},
}));
vi.mock("@/lib/checkout-navigation", () => ({
- beginCheckoutNavigation: (preserve: boolean) => {
- h.begin(preserve);
- return { navigate: h.navigate, close: h.closeTab };
- },
+ navigateToCheckout: (url: string, preserve: boolean) => h.navigate(url, preserve),
}));
vi.mock("next/navigation", () => ({ useSearchParams: () => new URLSearchParams(h.query) }));
vi.mock("@/lib/auth-client", () => ({
@@ -105,25 +100,24 @@ describe("Actions funding UI", () => {
h.navigate.mockImplementation((url: string) => url);
await render(true);
await act(async () => button("Add $5").click());
- expect(h.begin).toHaveBeenCalledWith(true);
- expect(h.begin.mock.invocationCallOrder[0]).toBeLessThan(h.checkout.mock.invocationCallOrder[0]!);
+ expect(h.navigate).toHaveBeenCalledWith(expect.any(String), true);
expect(document.querySelector('a[href="https://checkout.stripe.com/saved"]')?.getAttribute("target")).toBe("_blank");
expect(h.closeDialog).not.toHaveBeenCalled();
await act(async () => button("Back to workflow").click());
expect(h.closeDialog).toHaveBeenCalledOnce();
});
- it("closes an unused payment tab on failure and does not expose an invalid payment link", async () => {
+ it("does not navigate on failure or expose an invalid payment link", async () => {
h.budget.mockResolvedValue({ ...initial(), purchasesAvailable: true });
h.checkout.mockRejectedValueOnce(new Error("Provider unavailable"));
await render(true);
await act(async () => button("Add $5").click());
- expect(h.closeTab).toHaveBeenCalledOnce();
+ expect(h.navigate).not.toHaveBeenCalled();
h.checkout.mockResolvedValue({ checkoutUrl: "javascript:invalid" });
h.navigate.mockImplementationOnce(() => { throw new Error("Invalid checkout URL"); });
await act(async () => button("Add $5").click());
expect(document.querySelector('a[href="javascript:invalid"]')).toBeNull();
- expect(h.closeTab).toHaveBeenCalledTimes(2);
+ expect(h.navigate).toHaveBeenCalledExactlyOnceWith("javascript:invalid", true);
});
it("shows live VM estimates and one usage balance without a separate transfer allowance", async () => {
@@ -223,7 +217,7 @@ describe("Actions funding UI", () => {
await act(async () => button("Add $5").click());
await act(async () => button("Add $5").click());
expect(h.checkout.mock.calls[0]).toEqual(h.checkout.mock.calls[1]);
- expect(h.navigate).toHaveBeenCalledWith("https://checkout.stripe.com/saved");
+ expect(h.navigate).toHaveBeenCalledWith("https://checkout.stripe.com/saved", false);
});
it("distinguishes a funded but paused budget from a balance that needs topping up", async () => {
diff --git a/apps/dashboard/src/components/actions/ActionBudget.tsx b/apps/dashboard/src/components/actions/ActionBudget.tsx
index 5fe5f8876..fb5659368 100644
--- a/apps/dashboard/src/components/actions/ActionBudget.tsx
+++ b/apps/dashboard/src/components/actions/ActionBudget.tsx
@@ -6,7 +6,7 @@ import { useSearchParams } from "next/navigation";
import { Icon } from "@repo/ui/icons";
import type { ActionBudget as BudgetData, ActionCreditPurchase } from "@repo/contracts";
import { billingApi } from "@/lib/api/billing";
-import { beginCheckoutNavigation } from "@/lib/checkout-navigation";
+import { navigateToCheckout } from "@/lib/checkout-navigation";
import { randomUUID } from "@/lib/random-uuid";
import { PageContainer } from "@/components/ui/PageContainer";
import { Button } from "@/components/ui/button";
@@ -72,7 +72,6 @@ function Budget({ onClose }: { onClose?: () => void }) {
async function checkout(id?: string) {
if (!data?.purchasesAvailable || mutation.busy) return;
- const navigation = beginCheckoutNavigation(!!onClose);
setCheckoutUrl(null);
if (!attempts.current.has(deposit)) attempts.current.set(deposit, randomUUID());
const result = await mutation.execute(() =>
@@ -85,15 +84,13 @@ function Budget({ onClose }: { onClose?: () => void }) {
);
if (result?.checkoutUrl) {
const url = result.checkoutUrl;
- const destination = await mutation.execute(async () => navigation.navigate(url));
+ const destination = await mutation.execute(async () => navigateToCheckout(url, !!onClose));
if (destination) setCheckoutUrl(destination);
- else navigation.close();
} else if (result && !id) {
// A completed/expired intent is no longer a new deposit. A subsequent
// explicit purchase gets its own key; uncertain responses keep this one.
attempts.current.delete(deposit);
}
- if (!result?.checkoutUrl) navigation.close();
budget.refresh();
}
diff --git a/apps/dashboard/src/components/billing/CheckoutRecovery.tsx b/apps/dashboard/src/components/billing/CheckoutRecovery.tsx
index 5851f8c66..30467cccc 100644
--- a/apps/dashboard/src/components/billing/CheckoutRecovery.tsx
+++ b/apps/dashboard/src/components/billing/CheckoutRecovery.tsx
@@ -15,7 +15,8 @@ import { getApiErrorCode, getApiErrorMessage } from "@/lib/api/client";
import { useSession } from "@/lib/auth-client";
import { useCloudResourceKey } from "@/context/CloudResourceContext";
import { newServerBillingHref, scopedBillingHref } from "@/lib/billing-links";
-import { beginCheckoutNavigation } from "@/lib/checkout-navigation";
+import { navigateToCheckout } from "@/lib/checkout-navigation";
+import { invalidatePayments } from "@/lib/billing-events";
import { ManagedServerActionFeedback } from "@/components/servers/managed/ManagedServerActionFeedback";
import { useManagedServerActions } from "@/components/servers/managed/useManagedServerActions";
import { useBillingScope } from "./BillingWorkspaceContext";
@@ -244,33 +245,27 @@ function CheckoutRow({
setBusy(operation);
setError(null);
setConfirmCancel(false);
- const navigation = operation === "resume" ? beginCheckoutNavigation(preserveProject) : null;
if (operation === "cancel") setCancelAttempted(true);
try {
const response = await billingApi[
operation === "resume" ? "resumeCheckout" : "cancelCheckout"
]({ workspaceId: item.server.id, id: item.id });
- if (!mounted.current) {
- navigation?.close();
- return;
- }
+ if (!mounted.current) return;
setResult(response);
if (response.status === "ready") {
- if (!response.checkoutUrl || !navigation) throw new Error(copy.actionError);
- const url = navigation.navigate(response.checkoutUrl);
+ if (!response.checkoutUrl || operation !== "resume") throw new Error(copy.actionError);
+ const url = navigateToCheckout(response.checkoutUrl, preserveProject);
if (preserveProject) {
setCheckoutUrl(url);
onCheckoutStarted?.(url);
}
void onRefresh();
} else {
- navigation?.close();
setCheckoutUrl(null);
if (response.status === "expired") onCleared?.();
router.refresh();
}
} catch (err) {
- navigation?.close();
if (!mounted.current) return;
setError(getApiErrorMessage(err, copy.actionError));
if (getApiErrorCode(err) === "BILLING_CHECKOUT_CANCEL_UNAVAILABLE") setCancelAttempted(false);
@@ -278,6 +273,7 @@ function CheckoutRow({
// Refresh reads persisted recovery state; it never starts another checkout.
void onRefresh();
} finally {
+ if (mounted.current) invalidatePayments();
busyRef.current = false;
if (mounted.current) setBusy(null);
}
diff --git a/apps/dashboard/src/components/billing/CloudPlanPicker.tsx b/apps/dashboard/src/components/billing/CloudPlanPicker.tsx
index e7f552876..d2f236ad1 100644
--- a/apps/dashboard/src/components/billing/CloudPlanPicker.tsx
+++ b/apps/dashboard/src/components/billing/CloudPlanPicker.tsx
@@ -13,7 +13,7 @@ import { useI18n } from "@/components/i18n-provider";
import type { BillingSubscription } from "@repo/contracts";
import type { BillingState } from "@/lib/api/billing";
import { needsCloudPlan } from "@/lib/billing-presentation";
-import { useCloudCheckout, useCloudPlans } from "./useCloudBilling";
+import { useCloudCheckout, useCloudPlans, type PreparedCheckoutWorkspace } from "./useCloudBilling";
import { useBillingWorkspace } from "./BillingWorkspaceContext";
import { CustomPlanConfigurator } from "./CustomPlanConfigurator";
import type { ApiPlan } from "./PricingCards";
@@ -86,7 +86,7 @@ function PlanPicker({
preserveProject?: boolean;
onCheckoutStarted?: (checkoutUrl?: string) => void;
/** New server acquisition resolves its identity only after choosing a plan. */
- prepareWorkspace?: () => Promise
;
+ prepareWorkspace?: () => Promise;
onWorkspaceRemoved?: (workspaceId: string) => void;
purchaseDetails?: ReactNode;
purchaseDisabled?: boolean;
@@ -101,8 +101,9 @@ function PlanPicker({
Boolean(workspaceId ?? billingWorkspaceId) ||
(currentPlan === "free" && !subscription && !complimentary);
const { payload, loading, error, retry } = useCloudPlans();
- // Preserve the website choice. Older links without an interval advertised monthly billing.
- const [purchaseInterval, setInterval] = useState<"monthly" | "annual">(requestedInterval ?? (autoCheckout ? "monthly" : "annual"));
+ // Preserve an explicit website choice; new purchases start with monthly billing.
+ const [purchaseInterval, setInterval] = useState<"monthly" | "annual">(requestedInterval ?? "monthly");
+ const annualSavings = payload && payload.annual.monthsFree > 0 ? payload.ui.monthsFree : undefined;
const interval =
subscription && subscription.status !== "canceled" ? subscription.interval : !complimentary && payload?.annual.enabled ? purchaseInterval : "monthly";
const hasPlan = !needsCloudPlan({ tier: currentPlan, subscription, complimentary });
@@ -427,13 +428,14 @@ function PlanPicker({
) : (
@@ -485,16 +488,13 @@ function PlanPicker({
export function CloudCheckoutNotice({ checkoutUrl }: { checkoutUrl: string }) {
const { t } = useI18n();
return (
-
-
{t.billing.deployGate.checkoutOpened}
-
- {t.billing.deployGate.continueCheckout}
-
+
);
}
diff --git a/apps/dashboard/src/components/billing/CustomPlanConfigurator.tsx b/apps/dashboard/src/components/billing/CustomPlanConfigurator.tsx
index 63794a6a5..5d4ad750d 100644
--- a/apps/dashboard/src/components/billing/CustomPlanConfigurator.tsx
+++ b/apps/dashboard/src/components/billing/CustomPlanConfigurator.tsx
@@ -24,6 +24,7 @@ export function CustomPlanConfigurator({
allocatedDiskGb,
actionLabel,
interval = "monthly",
+ annualSavings,
}: {
catalog: NonNullable
;
plans: ApiPlan[];
@@ -36,6 +37,7 @@ export function CustomPlanConfigurator({
allocatedDiskGb?: number | null;
actionLabel?: string;
interval?: "monthly" | "annual";
+ annualSavings?: string;
onSelect: (quote: BillingCustomQuote) => void;
}) {
const { t } = useI18n();
@@ -68,9 +70,7 @@ export function CustomPlanConfigurator({
currentOffer?.price[interval] === quote.priceCents &&
currentOffer.monthlyCredits === quote.monthlyCredits)),
);
- const annualRates = interval === "annual" ? catalog.extraAnnualCents : undefined;
- const rates = annualRates ?? catalog.extraMonthlyCents;
- const rateMonths = annualRates ? 12 : 1;
+ const rates = interval === "annual" ? catalog.extraAnnualCents : catalog.extraMonthlyCents;
const bundle = plans.find((plan) => plan.id === quote?.basePlanTierId);
const money = (cents: number) => `$${(cents / 100).toFixed(cents % 100 === 0 ? 0 : 2)}`;
@@ -102,7 +102,9 @@ export function CustomPlanConfigurator({
)}
-
- {interpolate(copy.rates, {
- cpu: money(rates.cpuCore / rateMonths),
- memory: money(rates.memoryGb / rateMonths),
- disk: money(rates.diskGb / rateMonths),
- })}
-
+ {rates && (
+
+ {interpolate(interval === "annual" ? copy.yearlyRates : copy.rates, {
+ cpu: money(rates.cpuCore),
+ memory: money(rates.memoryGb),
+ disk: money(rates.diskGb),
+ })}
+
+ )}
{subscription && {copy.applyNotice}
}
diff --git a/apps/dashboard/src/components/billing/PendingCheckoutsContext.tsx b/apps/dashboard/src/components/billing/PendingCheckoutsContext.tsx
index 25446098e..d0fbed04f 100644
--- a/apps/dashboard/src/components/billing/PendingCheckoutsContext.tsx
+++ b/apps/dashboard/src/components/billing/PendingCheckoutsContext.tsx
@@ -1,5 +1,6 @@
"use client";
+import { reportCaughtError } from "@repo/core/diagnostics";
import {
createContext,
useCallback,
@@ -14,13 +15,19 @@ import { useResourceScope } from "@/hooks/use-scoped-resource";
import { useSession } from "@/lib/auth-client";
import { billingApi } from "@/lib/api/billing";
import { getApiErrorMessage } from "@/lib/api/client";
+import { managementApi } from "@/lib/api/management";
+import { subscriptionNeedsPayment } from "@/lib/billing-presentation";
+import { usePlatform } from "@/context/PlatformContext";
+import { useCloud } from "@/context/CloudContext";
import { useI18n } from "@/components/i18n-provider";
import { useBillingScope } from "./BillingWorkspaceContext";
+import { PAYMENTS_CHANGED } from "@/lib/billing-events";
type PendingCheckouts = {
workspaceId?: string;
items: BillingPendingCheckout[];
count: number;
+ attentionCount: number;
loading: boolean;
error: string | null;
refresh: () => Promise;
@@ -30,29 +37,43 @@ type PendingCheckouts = {
const PendingCheckoutsContext = createContext(null);
export const usePendingCheckouts = () => useContext(PendingCheckoutsContext);
+/** One organization-wide payment read supplies the rail and billing hub. */
+export function DashboardPaymentsProvider({ children }: { children: ReactNode }) {
+ const { selfHosted, deployMode } = usePlatform();
+ const { connected } = useCloud();
+ return
+ {children}
+ ;
+}
+
/** Share one read between billing navigation and recovery; never share customer data across scopes. */
export function PendingCheckoutsProvider({
children,
workspaceId,
enabled = true,
+ includeManagement = false,
}: {
children: ReactNode;
workspaceId?: string;
enabled?: boolean;
+ includeManagement?: boolean;
}) {
const scope = useResourceScope();
const { data: session, isPending } = useSession();
const { organizationId } = useBillingScope();
+ const parent = usePendingCheckouts();
const allowed =
enabled &&
!isPending &&
(!organizationId || organizationId === session?.session.activeOrganizationId);
+ if (parent && parent.workspaceId === workspaceId && allowed && !includeManagement) return children;
return (
{children}
@@ -64,11 +85,13 @@ function PendingCheckoutsState({
workspaceId,
enabled,
waiting,
+ includeManagement,
}: {
children: ReactNode;
workspaceId?: string;
enabled: boolean;
waiting?: boolean;
+ includeManagement: boolean;
}) {
const { t } = useI18n();
const parent = usePendingCheckouts();
@@ -77,6 +100,7 @@ function PendingCheckoutsState({
const [closed, setClosed] = useState>(() => new Set());
const [loading, setLoading] = useState(enabled);
const [error, setError] = useState(null);
+ const [managementPending, setManagementPending] = useState(false);
const mounted = useRef(false);
const revision = useRef(0);
const refreshing = useRef(false);
@@ -86,6 +110,16 @@ function PendingCheckoutsState({
refreshing.current = true;
setLoading(true);
setError(null);
+ if (includeManagement) {
+ // Keep compute recovery usable if this account cannot read Manage billing.
+ void managementApi.get().then(state => {
+ if (mounted.current && revision.current === request) setManagementPending(Boolean(
+ state.pendingCheckout || state.change?.paymentUrl || subscriptionNeedsPayment(state.subscription?.status),
+ ));
+ }).catch(error => {
+ reportCaughtError(error, "dashboard/components/billing/PendingCheckoutsContext");
+ });
+ }
try {
const result = await billingApi.listCheckouts(workspaceId);
if (!mounted.current || revision.current !== request) return;
@@ -102,7 +136,7 @@ function PendingCheckoutsState({
setLoading(false);
}
}
- }, [enabled, workspaceId, t.billing.pendingPayments.loadError]);
+ }, [enabled, workspaceId, includeManagement, t.billing.pendingPayments.loadError]);
useEffect(() => {
mounted.current = true;
void refresh();
@@ -111,10 +145,13 @@ function PendingCheckoutsState({
if (document.visibilityState === "visible" && !refreshing.current) void refresh();
};
window.addEventListener("focus", onFocus);
+ const onChanged = () => { void refresh(); };
+ window.addEventListener(PAYMENTS_CHANGED, onChanged);
return () => {
mounted.current = false;
revision.current++;
window.removeEventListener("focus", onFocus);
+ window.removeEventListener(PAYMENTS_CHANGED, onChanged);
};
}, [refresh]);
const markCleared = useCallback(
@@ -135,6 +172,7 @@ function PendingCheckoutsState({
refresh,
markCleared,
count: enabled ? items.filter((item) => !closed.has(item.id)).length : 0,
+ attentionCount: enabled ? new Set(items.filter(item => !closed.has(item.id)).map(item => item.server.id)).size + Number(managementPending) : 0,
}}
>
{children}
diff --git a/apps/dashboard/src/components/billing/PricingCards.tsx b/apps/dashboard/src/components/billing/PricingCards.tsx
index 33b050e8b..05dd4db3c 100644
--- a/apps/dashboard/src/components/billing/PricingCards.tsx
+++ b/apps/dashboard/src/components/billing/PricingCards.tsx
@@ -115,6 +115,7 @@ interface PricingCardsProps {
subscribingPlan?: string | null;
purchasesDisabled?: boolean;
interval?: "monthly" | "annual";
+ annualSavings?: string;
workspaceScoped?: boolean;
selectionLabel?: string;
referralOffer?: ReferralPublicOffer;
@@ -131,11 +132,10 @@ function formatPrice(
): { label: string; suffix: string | null } {
if (cents === null) return { label: ui.custom, suffix: null };
if (cents === 0) return { label: ui.free, suffix: null };
- const monthlyCents = interval === "annual" ? cents / 12 : cents;
// Whole dollars stay whole ($39, not $39.00); a cents-precise price keeps them.
return {
- label: `$${(monthlyCents / 100).toFixed(monthlyCents % 100 === 0 ? 0 : 2)}`,
- suffix: ui.perMonth,
+ label: `$${(cents / 100).toFixed(cents % 100 === 0 ? 0 : 2)}`,
+ suffix: interval === "annual" ? ui.perYear : ui.perMonth,
};
}
@@ -193,6 +193,7 @@ export const PricingCards: React.FC = ({
subscribingPlan,
purchasesDisabled = false,
interval = "monthly",
+ annualSavings,
workspaceScoped = false,
selectionLabel,
referralOffer,
@@ -218,7 +219,6 @@ export const PricingCards: React.FC = ({
const referral = referralOffer && referralPlans([plan], referralOffer, interval).length
? referralOffer : null;
const { listCents, chargedCents, discounted } = resolveCardPrice(plan, interval, referral);
- // Compare monthly equivalents; annual cards disclose the full charge below.
const { label, suffix } = formatPrice(
discounted ? chargedCents : listCents,
ui,
@@ -307,7 +307,7 @@ export const PricingCards: React.FC = ({
{isPaid
? interval === "annual"
- ? interpolate(t.billing.pricing.annualTotal, { price: `$${(chargedCents! / 100).toFixed(chargedCents! % 100 === 0 ? 0 : 2)}` })
+ ? annualSavings ?? t.billing.pricing.billedAnnually
: ui.billedMonthly
: ""}
diff --git a/apps/dashboard/src/components/billing/checkout-recovery.test.tsx b/apps/dashboard/src/components/billing/checkout-recovery.test.tsx
index 0d2daa8fc..19a048b40 100644
--- a/apps/dashboard/src/components/billing/checkout-recovery.test.tsx
+++ b/apps/dashboard/src/components/billing/checkout-recovery.test.tsx
@@ -69,12 +69,6 @@ const ready = {
const expired = { status: "expired", checkoutId: "cs_pending", checkoutUrl: null };
let root: Root;
let host: HTMLDivElement;
-let popup: {
- opener: object | null;
- closed: boolean;
- location: { href: string };
- close: ReturnType;
-};
const recovery = () => (
{
h.get.mockImplementation(async () => ({ data: { items: [structuredClone(item)] } }));
h.post.mockResolvedValue({ data: ready });
h.remove.mockResolvedValue({ ...server, state: "deleting" });
- popup = { opener: {}, closed: false, location: { href: "about:blank" }, close: vi.fn() };
- vi.spyOn(window, "open").mockReturnValue(popup as unknown as Window);
+ vi.spyOn(window, "open").mockReturnValue(null);
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
@@ -157,8 +150,7 @@ describe("unfinished checkout recovery", () => {
workspaceId: server.id,
id: item.id,
});
- expect(popup.location.href).toBe(ready.checkoutUrl);
- expect(popup.opener).toBeNull();
+ expect(window.open).toHaveBeenCalledExactlyOnceWith(ready.checkoutUrl, "_blank", "noopener,noreferrer");
expect(h.started).toHaveBeenCalledExactlyOnceWith(ready.checkoutUrl);
expect(dialog()?.querySelector('a[target="_blank"]')?.getAttribute("href")).toBe(
ready.checkoutUrl,
@@ -374,7 +366,7 @@ describe("unfinished checkout recovery", () => {
expect(h.get).toHaveBeenCalledTimes(2);
});
- it.each(["local", "cloud"])("ignores earlier payment results after switching the %s account and closes its reserved tab", async (account) => {
+ it.each(["local", "cloud"])("ignores earlier payment results after switching the %s account without opening checkout", async (account) => {
let finish!: (value: unknown) => void;
h.post.mockReturnValueOnce(
new Promise((resolve) => {
@@ -392,8 +384,7 @@ describe("unfinished checkout recovery", () => {
h.get.mockResolvedValueOnce({ data: { items: [] } });
await render();
await act(async () => finish({ data: ready }));
- expect(popup.location.href).toBe("about:blank");
- expect(popup.close).toHaveBeenCalled();
+ expect(window.open).not.toHaveBeenCalled();
expect(h.started).not.toHaveBeenCalled();
expect(dialog()?.textContent).not.toContain(item.name);
});
@@ -421,4 +412,15 @@ describe("unfinished checkout recovery", () => {
expect(host.querySelector("output")?.textContent).toBe("0");
expect(dialog()?.textContent).toContain(copy.canceled);
});
+
+ it("does not reuse the organization's payment data in a foreign billing scope", async () => {
+ function Count({ id }: { id: string }) { return ; }
+ await render(
+
+
+ );
+ expect(host.querySelector("#current")?.textContent).toBe("1");
+ expect(host.querySelector("#foreign")?.textContent).toBe("0");
+ expect(h.get).toHaveBeenCalledOnce();
+ });
});
diff --git a/apps/dashboard/src/components/billing/cloud-deploy-pricing.test.tsx b/apps/dashboard/src/components/billing/cloud-deploy-pricing.test.tsx
index 0d6b443f0..aa1eb806d 100644
--- a/apps/dashboard/src/components/billing/cloud-deploy-pricing.test.tsx
+++ b/apps/dashboard/src/components/billing/cloud-deploy-pricing.test.tsx
@@ -65,7 +65,6 @@ function Harness() {
let root: Root;
let container: HTMLDivElement;
-let checkoutTab: { opener: unknown; closed: boolean; location: { href: string }; close: ReturnType };
let open: ReturnType;
const restriction = () => new ApiError(402, "Payment Required", { code: "CLOUD_BILLING_BLOCKED" });
function button(label: string) {
@@ -89,8 +88,7 @@ beforeEach(() => {
mocks.get.mockResolvedValue({ data: { locale: "en", annual: { enabled: true, monthsFree: 0 }, ui: pricingUi("en"), plans } });
mocks.deploy.mockRejectedValue(restriction());
mocks.post.mockResolvedValue({ data: { checkoutUrl: "https://checkout.example.test/session" } });
- checkoutTab = { opener: window, closed: false, location: { href: "about:blank" }, close: vi.fn() };
- open = vi.spyOn(window, "open").mockReturnValue(checkoutTab as unknown as Window);
+ open = vi.spyOn(window, "open").mockReturnValue(null);
container = document.createElement("div");
document.body.append(container);
root = createRoot(container);
@@ -142,13 +140,13 @@ describe("deployment plan selection", () => {
let resolveCheckout!: (value: unknown) => void;
mocks.post.mockReturnValueOnce(new Promise((resolve) => { resolveCheckout = resolve; }));
await act(async () => { button("Choose Hobby").click(); button("Choose Hobby").click(); });
- expect(open).toHaveBeenCalledOnce();
- expect(checkoutTab.opener).toBeNull();
- expect(checkoutTab.location.href).toBe("about:blank");
+ expect(open).not.toHaveBeenCalled();
expect(mocks.post).toHaveBeenCalledTimes(1);
- expect(mocks.post).toHaveBeenCalledWith("billing/subscription", expect.objectContaining({ planTierId: "starter", interval: "annual", idempotencyKey: expect.any(String) }));
+ expect(mocks.post).toHaveBeenCalledWith("billing/subscription", expect.objectContaining({ planTierId: "starter", interval: "monthly", idempotencyKey: expect.any(String) }));
await act(async () => resolveCheckout({ data: { checkoutUrl: "https://checkout.example.test/session" } }));
- expect(checkoutTab.location.href).toBe("https://checkout.example.test/session");
+ expect(open).toHaveBeenCalledExactlyOnceWith("https://checkout.example.test/session", "_blank", "noopener,noreferrer");
+ await click("Choose Hobby");
+ expect(mocks.post).toHaveBeenCalledTimes(1);
expect(container.querySelector("input")?.value).toBe("My configured project");
expect(mocks.deploy).toHaveBeenCalledTimes(1);
await click(copy.deployGate.checkPlan);
@@ -211,7 +209,7 @@ describe("deployment plan selection", () => {
await click("Deploy");
await click("Choose Hobby");
expect(document.querySelector('[role="alert"]')?.textContent).toBe("Checkout temporarily unavailable");
- expect(checkoutTab.close).toHaveBeenCalledOnce();
+ expect(open).not.toHaveBeenCalled();
await click("Choose Hobby");
expect(mocks.post.mock.calls[1]![1].idempotencyKey).toBe(mocks.post.mock.calls[0]![1].idempotencyKey);
});
diff --git a/apps/dashboard/src/components/billing/server-plan-picker.test.tsx b/apps/dashboard/src/components/billing/server-plan-picker.test.tsx
index 87dfc56d0..03937e70b 100644
--- a/apps/dashboard/src/components/billing/server-plan-picker.test.tsx
+++ b/apps/dashboard/src/components/billing/server-plan-picker.test.tsx
@@ -59,7 +59,6 @@ function customQuote(resources: CustomServerResources): BillingCustomQuote {
let management: ManagementState;
let root: Root;
let host: HTMLDivElement;
-let popup: { opener: object | null; closed: boolean; location: { href: string }; close: ReturnType };
function SidebarState() {
const { autoCollapse } = useSidebarLayout();
const { collapsed } = useSidebarCollapse("plans", autoCollapse);
@@ -101,16 +100,16 @@ beforeEach(() => {
vi.resetAllMocks(); vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
h.user = "user-a"; h.org = "org-a"; h.connected = true; h.sessionPending = false;
window.location.href = "http://localhost:3000/";
+ sessionStorage.clear();
management = { pricing: PRICING.management, purchasesAvailable: true, cloudIncluded: false,
active: false, serverLimit: 0, connectedServers: 0, pendingCheckout: false, subscription: null, change: null };
- h.get.mockImplementation(async (path, options) => path === "/billing/manage" ? { data: management } : path.endsWith("/quote")
+ h.get.mockImplementation(async (path, options) => path === "billing/checkouts" ? { data: { items: [] } } : path === "/billing/manage" ? { data: management } : path.endsWith("/quote")
? { data: customQuote(options.params) } : catalog);
h.create.mockResolvedValue(server);
h.readServer.mockResolvedValue({ id: server.serverId, name: server.name, managed: server });
h.available.mockResolvedValue({ servers: [] });
h.post.mockResolvedValue({ data: { checkoutUrl: "https://checkout.example.test/new-server" } });
- popup = { opener: {}, closed: false, location: { href: "about:blank" }, close: vi.fn() };
- vi.spyOn(window, "open").mockReturnValue(popup as unknown as Window);
+ vi.spyOn(window, "open").mockReturnValue(null);
host = document.createElement("div"); document.body.append(host); root = createRoot(host);
});
afterEach(async () => {
@@ -230,16 +229,18 @@ describe("referral checkout handoff", () => {
: ordinary(path, options));
await render();
const card = (name: string) => host.querySelector(`article[aria-label="${name}"]`)!;
- expect(card("Hobby").textContent).toContain("$9");
- expect(card("Hobby").querySelector("s")?.textContent).toBe("$10");
+ expect(card("Hobby").querySelector("s")).toBeNull();
+ await click("Yearly");
+ expect(card("Hobby").querySelector(".text-2xl")?.textContent).toBe("$108");
+ expect(card("Hobby").querySelector("s")?.textContent).toBe("$120");
expect(card("Starter").querySelector("s")).toBeNull();
await click("Monthly");
expect(card("Hobby").querySelector("s")).toBeNull();
await click("Yearly");
- expect(card("Hobby").querySelector("s")?.textContent).toBe("$10");
+ expect(card("Hobby").querySelector("s")?.textContent).toBe("$120");
await click(baseDictionary.referrals.remove);
expect(card("Hobby").querySelector("s")).toBeNull();
- expect(card("Hobby").textContent).toContain("$10");
+ expect(card("Hobby").querySelector(".text-2xl")?.textContent).toBe("$120");
expect(h.post).not.toHaveBeenCalled();
});
@@ -257,6 +258,7 @@ describe("referral checkout handoff", () => {
describe("annual Cloud purchases", () => {
beforeEach(() => {
h.get.mockImplementation(async (path, options) => {
+ if (path === "billing/checkouts") return { data: { items: [] } };
if (path.endsWith("/quote")) {
const annual = options.params.interval === "annual";
return { data: { ...customQuote(options.params), reference: annual ? "quote-annual" : "quote-monthly",
@@ -283,15 +285,20 @@ describe("annual Cloud purchases", () => {
expect(h.post).not.toHaveBeenCalled();
});
- it("shows monthly equivalents with the upfront annual charge and submits yearly checkout", async () => {
+ it("defaults to monthly, shows full yearly prices with savings, and submits the selected interval", async () => {
await render(purchase());
- expect(buttons(copy.pricing.annual)[0]?.getAttribute("aria-pressed")).toBe("true");
- expect(host.querySelector("article .text-2xl")?.textContent).toBe("$10");
- await click(copy.pricing.monthly);
+ expect(buttons(copy.pricing.monthly)[0]?.getAttribute("aria-pressed")).toBe("true");
expect(host.querySelector("article .text-2xl")?.textContent).toBe("$12");
await click(copy.pricing.annual);
- expect(host.querySelector("article")?.textContent).toContain("$10");
- expect(host.querySelector("article")?.textContent).toContain("$120 billed yearly");
+ expect(host.querySelector("article .text-2xl")?.textContent).toBe("$120");
+ expect(host.querySelector("article")?.textContent).toContain(pricingUi("en").perYear);
+ expect(host.querySelector("article")?.textContent).toContain("2 months free");
+ expect(host.querySelector("article")?.textContent).not.toContain(pricingUi("en").perMonth);
+ expect(host.querySelector("article")?.textContent).not.toContain("$120 billed yearly");
+ await click(copy.pricing.monthly);
+ expect(host.querySelector("article .text-2xl")?.textContent).toBe("$12");
+ expect(host.querySelector("article")?.textContent).not.toContain("2 months free");
+ await click(copy.pricing.annual);
await click("Choose Hobby");
expect(h.post).toHaveBeenCalledExactlyOnceWith("billing/subscription", expect.objectContaining({
planTierId: "hobby", interval: "annual", workspaceId: "cws-production",
@@ -304,7 +311,12 @@ describe("annual Cloud purchases", () => {
expect(host.querySelector('form button[type="submit"]')?.hasAttribute("disabled")).toBe(true);
expect(h.post).not.toHaveBeenCalled();
await flushQuote();
- expect(host.querySelector("aside")?.textContent).toContain("$1188 billed yearly");
+ expect(host.querySelector("aside .text-3xl")?.textContent).toBe("$1188");
+ expect(host.querySelector("aside")?.textContent).toContain(copy.custom.yearlyTotal);
+ expect(host.querySelector("aside")?.textContent).toContain(pricingUi("en").perYear);
+ expect(host.querySelector("aside")?.textContent).toContain("2 months free");
+ expect(host.querySelector("aside")?.textContent).toContain("Yearly extras: $60/vCPU");
+ expect(host.querySelector("aside")?.textContent).not.toContain("Monthly");
await act(async () => host.querySelector("form")!.requestSubmit());
expect(h.post).toHaveBeenCalledExactlyOnceWith("billing/subscription", expect.objectContaining({
interval: "annual", custom: expect.objectContaining({ quoteReference: "quote-annual" }),
@@ -534,7 +546,83 @@ describe("buying another managed server", () => {
expect(h.create).not.toHaveBeenCalled();
expect(h.post).not.toHaveBeenCalled();
await click("Choose Starter");
- expect(h.create).toHaveBeenCalledExactlyOnceWith({ name: copy.workspaces.defaultName });
+ expect(h.create).toHaveBeenCalledExactlyOnceWith({ name: copy.workspaces.defaultName, idempotencyKey: expect.any(String) });
+ });
+
+ it("reuses the manual server identity after a lost response and reopening the modal", async () => {
+ h.create.mockRejectedValueOnce(new Error("Creation response lost"));
+ await render();
+ await click("Choose Hobby");
+ expect(h.post).not.toHaveBeenCalled();
+ const first = h.create.mock.calls[0];
+ await act(async () => root.unmount()); root = createRoot(host);
+ await render();
+ await click("Choose Hobby");
+ expect(h.create.mock.calls[1]).toEqual(first);
+ expect(h.post).toHaveBeenCalledOnce();
+ await click("Choose Hobby");
+ expect(h.post).toHaveBeenCalledOnce();
+ });
+
+ it("reopens an existing unpaid purchase without creating another Cloud space", async () => {
+ await render();
+ await click("Add a destination"); await click("Choose Hobby");
+ expect(h.create).toHaveBeenCalledOnce();
+ await click(copy.workspaces.returnToSetup);
+ const ordinary = h.get.getMockImplementation()!;
+ h.get.mockImplementation((path, options) => path === "billing/checkouts" ? Promise.resolve({ data: { items: [{
+ id: "a".repeat(64), checkoutId: "cs_pending", server, kind: "subscription", name: "Saved Hobby",
+ amountCents: 1200, currency: "usd", interval: "monthly", state: "open", canResume: true, canCancel: true,
+ }] } }) : ordinary(path, options));
+ await click("Add a destination"); await click("Choose Hobby");
+ expect(h.create).toHaveBeenCalledOnce();
+ expect(document.body.textContent).toContain("Saved Hobby");
+ expect(h.post).toHaveBeenCalledOnce();
+ h.post.mockResolvedValueOnce({ data: { status: "ready", checkoutId: "cs_pending", checkoutUrl: "https://checkout.example.test/original" } });
+ await click(copy.pendingPayments.resume);
+ expect(h.post).toHaveBeenLastCalledWith("billing/checkout/resume", { workspaceId: server.id, id: "a".repeat(64) });
+ expect(window.open).toHaveBeenLastCalledWith("https://checkout.example.test/original", "_blank", "noopener,noreferrer");
+ });
+
+ it("never creates resources when pending payments cannot be checked", async () => {
+ const ordinary = h.get.getMockImplementation()!;
+ h.get.mockImplementation((path, options) => path === "billing/checkouts" ? Promise.reject(new Error("Payment status unavailable")) : ordinary(path, options));
+ await render(); await click("Choose Hobby");
+ expect(h.create).not.toHaveBeenCalled(); expect(h.post).not.toHaveBeenCalled();
+ expect(window.open).not.toHaveBeenCalled();
+ expect(host.textContent).toContain("Payment status unavailable");
+ });
+
+ it("opens recovery for a submitted payment without attempting another subscription", async () => {
+ const ordinary = h.get.getMockImplementation()!;
+ h.get.mockImplementation((path, options) => path === "billing/checkouts" ? Promise.resolve({ data: { items: [{
+ id: "a".repeat(64), checkoutId: "cs_processing", server: { ...server, planTierId: "hobby" },
+ kind: "subscription", name: "Submitted Hobby payment", amountCents: 1200, currency: "usd",
+ interval: "monthly", state: "processing", canResume: false, canCancel: false,
+ }] } }) : ordinary(path, options));
+ await render(); await click("Choose Hobby");
+ expect(h.create).not.toHaveBeenCalled(); expect(h.post).not.toHaveBeenCalled();
+ expect(document.body.textContent).toContain("Submitted Hobby payment");
+ expect(document.body.textContent).toContain(copy.pendingPayments.states.processing);
+ });
+
+ it("starts a new manual space after the previous purchase completed", async () => {
+ h.create.mockResolvedValueOnce({ ...server, planTierId: "hobby", state: "running" });
+ await render(); await click("Choose Hobby");
+ expect(h.create).toHaveBeenCalledTimes(2);
+ expect(h.create.mock.calls[1][0].idempotencyKey).not.toBe(h.create.mock.calls[0][0].idempotencyKey);
+ expect(h.post).toHaveBeenCalledOnce();
+ });
+
+ it("does not create a space after the pending-payment read resolves for a different account", async () => {
+ let finish!: (value: unknown) => void;
+ const ordinary = h.get.getMockImplementation()!;
+ h.get.mockImplementation((path, options) => path === "billing/checkouts" ? new Promise(resolve => { finish = resolve; }) : ordinary(path, options));
+ await render(); await click("Choose Hobby");
+ h.org = "org-b"; await render();
+ await act(async () => finish({ data: { items: [] } }));
+ expect(h.create).not.toHaveBeenCalled(); expect(h.post).not.toHaveBeenCalled();
+ expect(window.open).not.toHaveBeenCalled();
});
it("keeps the landing-page plan using the live offer without creating anything on arrival", async () => {
@@ -633,9 +721,8 @@ describe("buying another managed server", () => {
id: "a".repeat(64), checkoutId: "cs_pending", server, kind: "subscription", name: "Starter", amountCents: 2000,
currency: "usd", interval: "monthly", state: "open", canResume: true, canCancel: true,
}] } } : catalog);
- h.post.mockRejectedValueOnce(new ApiError(409, "Already pending", { code: "CLOUD_WORKSPACE_CHECKOUT_PENDING" }));
await render();
- const first = h.post.mock.calls[0][1].idempotencyKey;
+ expect(h.post).not.toHaveBeenCalled();
await click(copy.pendingPayments.cancel);
h.post.mockResolvedValueOnce({ data: { status: "expired", checkoutId: "cs_pending", checkoutUrl: null } });
await click(copy.pendingPayments.confirmCancel);
@@ -643,14 +730,15 @@ describe("buying another managed server", () => {
expect(url.searchParams.has("startCheckout")).toBe(false);
expect(url.searchParams.get("checkoutIntent")).toBe(key);
expect(url.searchParams.get("checkoutAttempt")).not.toBe(key);
- expect(h.post).toHaveBeenCalledTimes(2);
+ expect(h.post).toHaveBeenCalledOnce();
+ h.get.mockImplementation(async path => path === "billing/checkouts" ? { data: { items: [] } } : catalog);
await act(async () => root.unmount()); root = createRoot(host);
await render();
- expect(h.post).toHaveBeenCalledTimes(2);
+ expect(h.post).toHaveBeenCalledOnce();
await click("Choose Starter");
- expect(h.create.mock.calls[1]).toEqual(h.create.mock.calls[0]);
- expect(h.post.mock.calls[2][1].idempotencyKey).not.toBe(first);
- expect(h.post.mock.calls[2][1].workspaceId).toBe(server.id);
+ expect(h.create).toHaveBeenCalledExactlyOnceWith({ name: copy.workspaces.defaultName, idempotencyKey: key });
+ expect(h.post.mock.calls[1][1].idempotencyKey).toBe(`${url.searchParams.get("checkoutAttempt")}-starter-monthly`);
+ expect(h.post.mock.calls[1][1].workspaceId).toBe(server.id);
});
it("starts a fresh explicit purchase after removing the cancelled draft", async () => {
@@ -660,7 +748,6 @@ describe("buying another managed server", () => {
id: "a".repeat(64), checkoutId: "cs_pending", server, kind: "subscription", name: "Starter", amountCents: 2000,
currency: "usd", interval: "monthly", state: "open", canResume: true, canCancel: true,
}] } } : catalog);
- h.post.mockRejectedValueOnce(new ApiError(409, "Already pending", { code: "CLOUD_WORKSPACE_CHECKOUT_PENDING" }));
await render();
await click(copy.pendingPayments.cancel);
h.post.mockResolvedValueOnce({ data: { status: "expired", checkoutId: "cs_pending", checkoutUrl: null } });
@@ -668,11 +755,12 @@ describe("buying another managed server", () => {
h.remove.mockResolvedValueOnce({ data: { accepted: true } });
await click(copy.pendingPayments.deleteServer);
await click(copy.workspaces.confirmDelete);
- expect(h.create).toHaveBeenCalledOnce();
+ expect(h.create).not.toHaveBeenCalled();
+ h.get.mockImplementation(async path => path === "billing/checkouts" ? { data: { items: [] } } : catalog);
expect(new URL(window.location.href).searchParams.get("checkoutIntent")).not.toBe(key);
expect(new URL(window.location.href).searchParams.has("startCheckout")).toBe(false);
await click("Choose Starter");
- expect(h.create.mock.calls[1][0].idempotencyKey).not.toBe(key);
+ expect(h.create.mock.calls[0][0].idempotencyKey).not.toBe(key);
});
it("does not continue a pending pricing purchase in another account or organization", async () => {
@@ -694,7 +782,7 @@ describe("buying another managed server", () => {
currentPeriod: { start: null, end: null }, monthlyCreditLimit: 0, buildTimeMinutes: 0,
balance: { total: 0, quotaLimit: 0, quotaUsed: 0, quotaRemaining: 0 },
workspace: server, billing: { enabled: true } };
- h.get.mockImplementation(async path => path === "billing/state" ? { data: billing } : catalog);
+ h.get.mockImplementation(async path => path === "billing/checkouts" ? { data: { items: [] } } : path === "billing/state" ? { data: billing } : catalog);
const location = window.location.href;
await render();
await click("Add a destination");
@@ -729,7 +817,7 @@ describe("buying another managed server", () => {
const started = vi.fn();
await render();
await act(async () => { buttons("Choose Starter")[0]!.click(); buttons("Choose Starter")[0]!.click(); });
- expect(h.create).toHaveBeenCalledExactlyOnceWith({ name: copy.workspaces.defaultName });
+ expect(h.create).toHaveBeenCalledExactlyOnceWith({ name: copy.workspaces.defaultName, idempotencyKey: expect.any(String) });
expect(h.post).not.toHaveBeenCalled();
await act(async () => created(server));
expect(h.post).toHaveBeenCalledWith("billing/subscription", expect.objectContaining({ workspaceId: server.id, planTierId: "starter" }));
@@ -738,8 +826,7 @@ describe("buying another managed server", () => {
expect(h.create).toHaveBeenCalledOnce();
expect(h.post.mock.calls[1]).toEqual(h.post.mock.calls[0]);
expect(started).toHaveBeenCalledWith(server, "https://checkout.example.test/new-server");
- expect(popup.location.href).toBe("https://checkout.example.test/new-server");
- expect(popup.opener).toBeNull();
+ expect(window.open).toHaveBeenCalledExactlyOnceWith("https://checkout.example.test/new-server", "_blank", "noopener,noreferrer");
});
it("keeps the new server and exact purchase when retrying from unavailable-capacity feedback", async () => {
@@ -750,7 +837,7 @@ describe("buying another managed server", () => {
await click("Choose Pro");
expect(document.querySelector('[role="dialog"]')?.textContent).toContain(copy.checkoutUnavailable.capacityTitle);
expect(document.body.textContent).not.toContain("Raw provider failure");
- expect(popup.close).toHaveBeenCalledOnce();
+ expect(window.open).not.toHaveBeenCalled();
expect(h.post.mock.calls[0]![1]).toMatchObject({ workspaceId: server.id, planTierId: "pro" });
await click(copy.checkoutUnavailable.retry);
expect(h.create).toHaveBeenCalledOnce();
@@ -763,7 +850,6 @@ describe("buying another managed server", () => {
id: "a".repeat(64), checkoutId: "cs_pending", server, kind: "subscription", name: "Saved Starter",
amountCents: 2000, currency: "usd", interval: "monthly", state: "open", canResume: true, canCancel: true,
}] } } : catalog);
- h.post.mockRejectedValueOnce(new ApiError(409, "Blocked", { code: "CLOUD_WORKSPACE_CHECKOUT_PENDING", error: "Raw pending error" }));
h.post.mockImplementation(async path => path === "billing/checkout/cancel"
? { data: { status: "expired", checkoutId: "cs_pending", checkoutUrl: null } }
: { data: { checkoutUrl: "https://checkout.example.test/new-server" } });
@@ -773,6 +859,7 @@ describe("buying another managed server", () => {
expect(document.querySelector('[role="dialog"]')?.textContent).toContain(copy.pendingPayments.title);
expect(document.body.textContent).not.toContain("Raw pending error");
await click(copy.pendingPayments.cancel); await click(copy.pendingPayments.confirmCancel);
+ h.get.mockImplementation(async path => path === "billing/checkouts" ? { data: { items: [] } } : catalog);
if (remove) {
await click(copy.pendingPayments.deleteServer); await click(copy.workspaces.confirmDelete);
h.create.mockResolvedValueOnce({ ...server, id: "cws-replacement", serverId: "server-replacement" });
@@ -780,10 +867,9 @@ describe("buying another managed server", () => {
await act(async () => document.querySelector(`button[aria-label="${copy.checkoutUnavailable.close}"]`)!.click());
await click("Choose Starter");
const attempts = h.post.mock.calls.filter(([path]) => path === "billing/subscription").map(([, input]) => input);
- expect(attempts).toHaveLength(2);
- expect(attempts[1].idempotencyKey).not.toBe(attempts[0].idempotencyKey);
- expect(attempts[1].workspaceId).toBe(remove ? "cws-replacement" : server.id);
- expect(h.create).toHaveBeenCalledTimes(remove ? 2 : 1);
+ expect(attempts).toHaveLength(1);
+ expect(attempts[0].workspaceId).toBe(remove ? "cws-replacement" : server.id);
+ expect(h.create).toHaveBeenCalledTimes(remove ? 1 : 0);
});
it("discards an unavailable checkout when the customer changes organization", async () => {
@@ -806,7 +892,7 @@ describe("buying another managed server", () => {
await render();
await act(async () => created(server));
expect(h.post).not.toHaveBeenCalled();
- expect(popup.close).toHaveBeenCalled();
+ expect(window.open).not.toHaveBeenCalled();
h.create.mockResolvedValueOnce({ ...server, id: "cws-org-b" });
await click("Choose Starter");
expect(h.post).toHaveBeenCalledWith("billing/subscription", expect.objectContaining({ workspaceId: "cws-org-b" }));
diff --git a/apps/dashboard/src/components/billing/useCloudBilling.ts b/apps/dashboard/src/components/billing/useCloudBilling.ts
index 97fc55b83..8abbeea39 100644
--- a/apps/dashboard/src/components/billing/useCloudBilling.ts
+++ b/apps/dashboard/src/components/billing/useCloudBilling.ts
@@ -7,12 +7,12 @@ import type { PlanTierId } from "@repo/core";
import type { BillingPlans, CustomSubscriptionSelection } from "@repo/contracts";
import { useI18n } from "@/components/i18n-provider";
import { api, ApiError, getApiErrorCode, getApiErrorMessage } from "@/lib/api/client";
-import { beginCheckoutNavigation } from "@/lib/checkout-navigation";
+import { navigateToCheckout } from "@/lib/checkout-navigation";
+import { invalidatePayments } from "@/lib/billing-events";
import { endpoints } from "@/lib/api/endpoints";
import { randomUUID } from "@/lib/random-uuid";
import { checkoutFailureKind, type CheckoutFailure } from "@/lib/checkout-failure";
-import { useSession } from "@/lib/auth-client";
-import { useCloudResourceKey } from "@/context/CloudResourceContext";
+import { useResourceScope } from "@/hooks/use-scoped-resource";
import type { ApiPlan, ApiPricingUi } from "./PricingCards";
interface PlansPayload extends Omit {
@@ -20,6 +20,8 @@ interface PlansPayload extends Omit {
plans: ApiPlan[];
}
+export type PreparedCheckoutWorkspace = string | { workspaceId: string; checkoutPending: true };
+
/** Both the recommendation and comparison use the same live checkout catalog. */
export function useCloudPlans() {
const { t, locale } = useI18n();
@@ -47,7 +49,7 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS
workspaceId?: string;
preserveProject?: boolean;
onCheckoutStarted?: (checkoutUrl: string) => void;
- prepareWorkspace?: () => Promise;
+ prepareWorkspace?: () => Promise;
onWorkspaceRemoved?: (workspaceId: string) => void;
idempotencyKey?: string;
referralCode?: string;
@@ -55,9 +57,8 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS
}) {
const { t } = useI18n();
const { workspaceId: billingWorkspaceId, organizationId } = useBillingScope();
- const { data: session } = useSession();
- const cloudKey = useCloudResourceKey();
- const ownerKey = `${cloudKey}:${session?.user.id}:${organizationId ?? session?.session?.activeOrganizationId}`;
+ const scope = useResourceScope();
+ const ownerKey = `${scope}:${organizationId ?? ""}`;
const workspaceId = selectedWorkspaceId ?? billingWorkspaceId ?? undefined;
const [subscribing, setSubscribing] = useState(null);
const [error, setError] = useState(null);
@@ -78,11 +79,10 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS
useEffect(() => { attempts.current.clear(); }, [idempotencyKey]);
async function startCheckout(planTierId: PlanTierId, interval: "monthly" | "annual", custom?: CustomSubscriptionSelection) {
- if (!enabled || busy.current || planTierId === "free" || planTierId === "enterprise") return;
+ if (!enabled || busy.current || checkoutUrl || planTierId === "free" || planTierId === "enterprise") return;
busy.current = true;
const version = generation.current;
- // Open within the user's click, preserving unfinished project configuration.
- const navigation = beginCheckoutNavigation(preserveProject);
+ let checkoutStarted = false;
setSubscribing(custom ? "custom" : planTierId);
setError(null);
setCheckoutUrl(null);
@@ -91,8 +91,13 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS
let targetWorkspaceId = workspaceId;
let requestId: string | undefined;
try {
- targetWorkspaceId = prepareWorkspace ? await prepareWorkspace() : workspaceId;
- if (version !== generation.current) { navigation.close(); return; }
+ const prepared = prepareWorkspace ? await prepareWorkspace() : workspaceId;
+ targetWorkspaceId = typeof prepared === "object" ? prepared.workspaceId : prepared;
+ if (version !== generation.current) return;
+ if (typeof prepared === "object" && prepared.checkoutPending) {
+ setPending({ workspaceId: prepared.workspaceId });
+ return;
+ }
if (prepareWorkspace && !targetWorkspaceId) throw new Error(t.billing.plansRoute.checkoutError);
const attempt = `${targetWorkspaceId ?? "initial"}:${custom?.quoteReference ?? planTierId}:${interval}:${referralCode ?? ""}`;
if (!attempts.current.has(attempt)) attempts.current.set(attempt,
@@ -102,14 +107,14 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS
planTierId, interval, workspaceId: targetWorkspaceId, custom, idempotencyKey: requestId,
...(referralCode ? { referralCode } : {}),
});
- if (version !== generation.current) { navigation.close(); return; }
- const url = navigation.navigate(res.data.checkoutUrl);
+ if (version !== generation.current) return;
+ const url = navigateToCheckout(res.data.checkoutUrl, preserveProject);
if (preserveProject) {
+ checkoutStarted = true;
setCheckoutUrl(url);
onCheckoutStarted?.(url);
}
} catch (err) {
- navigation.close();
if (version !== generation.current) return;
const kind = checkoutFailureKind(err);
if (getApiErrorCode(err) === "CLOUD_WORKSPACE_CHECKOUT_PENDING") setPending({ workspaceId: targetWorkspaceId });
@@ -120,8 +125,9 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS
}
} finally {
if (version === generation.current) {
- busy.current = false;
+ busy.current = checkoutStarted;
setSubscribing(null);
+ invalidatePayments();
}
}
}
@@ -129,7 +135,7 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS
recovery: {
isOpen: pending !== null, workspaceId: pending?.workspaceId, preserveProject,
onClose: () => setPending(null),
- onCleared: () => { attempts.current.clear(); setError(null); onCheckoutSettled?.(); },
+ onCleared: () => { busy.current = false; attempts.current.clear(); setCheckoutUrl(null); setError(null); onCheckoutSettled?.(); },
onCheckoutStarted: (url: string) => { setCheckoutUrl(url); onCheckoutStarted?.(url); },
onServerRemoved: (id: string) => {
attempts.current.clear(); setCheckoutUrl(null); onWorkspaceRemoved?.(id);
diff --git a/apps/dashboard/src/components/import-project/DeploymentContainerConflictNotice.test.tsx b/apps/dashboard/src/components/import-project/DeploymentContainerConflictNotice.test.tsx
new file mode 100644
index 000000000..838edb9f4
--- /dev/null
+++ b/apps/dashboard/src/components/import-project/DeploymentContainerConflictNotice.test.tsx
@@ -0,0 +1,89 @@
+// @vitest-environment happy-dom
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { baseDictionary } from "@/i18n";
+import {
+ DEFAULT_CONFIG,
+ INITIAL_STATE,
+ type DeploymentContextType,
+} from "@/context/deployment/types";
+import { DeploymentContainerConflictNotice } from "./DeploymentContainerConflictNotice";
+
+let deployment: Pick;
+vi.mock("@/context/DeploymentContext", () => ({ useDeployment: () => deployment }));
+vi.mock("@/components/i18n-provider", () => ({ useI18n: () => ({ t: baseDictionary }) }));
+let root: Root;
+let host: HTMLDivElement;
+const copy = baseDictionary.deployments.containerConflict;
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ deployment = {
+ config: {
+ ...structuredClone(DEFAULT_CONFIG),
+ serverId: "server-current",
+ workspaceId: "space-current",
+ },
+ state: {
+ ...structuredClone(INITIAL_STATE),
+ deploymentId: "attempt-original",
+ deploymentFailed: true,
+ errorCode: "SERVICE_CONTAINER_CONFLICT",
+ errorDetails: {
+ containerNames: ['
', "app-duplicate"],
+ serverId: "server-original",
+ },
+ },
+ deploymentStatus: "failed",
+ };
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+});
+afterEach(async () => {
+ await act(async () => root.unmount());
+ host.remove();
+ vi.unstubAllGlobals();
+});
+async function render() {
+ await act(async () => root.render());
+}
+
+it("explains the conflict and links to the recorded server and support, without destructive actions", async () => {
+ await render();
+ expect(host.textContent).toContain(copy.title);
+ expect(host.textContent).toContain("app-duplicate");
+ expect(host.textContent).toContain("attempt-original");
+ expect(host.querySelector('a[href="/servers/server-original"]')).not.toBeNull();
+ expect(host.querySelector('a[href="/support"]')).not.toBeNull();
+ expect(host.querySelectorAll("button")).toHaveLength(0);
+ expect(host.querySelector("img")).toBeNull();
+});
+it("opens the recorded managed space when no standalone server was recorded", async () => {
+ deployment.state.errorDetails = { containerNames: ["a", "b"], workspaceId: "space-original" };
+ await render();
+ expect(host.querySelector('a[href="/resources?pool=space-original"]')).not.toBeNull();
+});
+it("does not guess a missing historical target from current configuration", async () => {
+ deployment.state.errorDetails = null;
+ await render();
+ expect(host.querySelectorAll("a")).toHaveLength(1);
+ expect(host.querySelector('a[href="/support"]')).not.toBeNull();
+});
+it.each(["building", "verifying", "ready", "cancelled"] as const)(
+ "clears the notice for %s",
+ async (status) => {
+ deployment.deploymentStatus = status;
+ await render();
+ expect(host.textContent).toBe("");
+ },
+);
+it("does not reinterpret another error or a cancelled attempt as a container conflict", async () => {
+ deployment.state.errorCode = "HOST_UNREACHABLE";
+ await render();
+ expect(host.textContent).toBe("");
+ deployment.state.errorCode = "SERVICE_CONTAINER_CONFLICT";
+ deployment.state.deploymentCanceled = true;
+ await render();
+ expect(host.textContent).toBe("");
+});
diff --git a/apps/dashboard/src/components/import-project/DeploymentContainerConflictNotice.tsx b/apps/dashboard/src/components/import-project/DeploymentContainerConflictNotice.tsx
new file mode 100644
index 000000000..5c30828b0
--- /dev/null
+++ b/apps/dashboard/src/components/import-project/DeploymentContainerConflictNotice.tsx
@@ -0,0 +1,61 @@
+"use client";
+
+import Link from "next/link";
+import { useDeployment } from "@/context/DeploymentContext";
+import { useI18n } from "@/components/i18n-provider";
+import { Button } from "@/components/ui/button";
+
+/** Use this attempt's recorded target, even after the project has moved. */
+export function DeploymentContainerConflictNotice() {
+ const { state, deploymentStatus } = useDeployment();
+ const { t } = useI18n();
+ if (
+ deploymentStatus !== "failed" ||
+ state.deploymentCanceled ||
+ state.errorCode !== "SERVICE_CONTAINER_CONFLICT"
+ )
+ return null;
+ const copy = t.deployments.containerConflict;
+ const details = state.errorDetails;
+ const names = Array.isArray(details?.containerNames)
+ ? details.containerNames.filter((value): value is string => typeof value === "string")
+ : [];
+ const serverId = typeof details?.serverId === "string" && details.serverId;
+ const workspaceId = typeof details?.workspaceId === "string" && details.workspaceId;
+ const targetHref = serverId
+ ? `/servers/${encodeURIComponent(serverId)}`
+ : workspaceId
+ ? `/resources?pool=${encodeURIComponent(workspaceId)}`
+ : null;
+
+ return (
+
+ {copy.title}
+ {copy.description}
+ {names.length > 0 && (
+
+ {names.map((name, index) => (
+ -
+
{name}
+
+ ))}
+
+ )}
+ {state.deploymentId && (
+
+ {copy.reference}: {state.deploymentId}
+
+ )}
+
+ {targetHref && (
+
+ )}
+
+
+
+ );
+}
diff --git a/apps/dashboard/src/components/import-project/compose/ComposeDeploymentProcessing.tsx b/apps/dashboard/src/components/import-project/compose/ComposeDeploymentProcessing.tsx
index cf4cc6d1c..ee5d48346 100644
--- a/apps/dashboard/src/components/import-project/compose/ComposeDeploymentProcessing.tsx
+++ b/apps/dashboard/src/components/import-project/compose/ComposeDeploymentProcessing.tsx
@@ -12,6 +12,7 @@ import { DeploymentHeader } from "../DeploymentHeader";
import { DeploymentHealthWarning } from "../DeploymentHealthWarning";
import { CloudBuildQueueNotice } from "../CloudBuildQueueNotice";
import { CloudDeploymentResourceNotice } from "../CloudDeploymentResourceNotice";
+import { DeploymentContainerConflictNotice } from "../DeploymentContainerConflictNotice";
import { DeploymentLayout } from "../DeploymentLayout";
import { DeploymentLogsPanel } from "../DeploymentLogsPanel";
import { PageContainer } from "@/components/ui/PageContainer";
@@ -576,7 +577,7 @@ function ComposeDeploymentBody({
return (
}
+ notice={<>>}
details={}
navigation={
diff --git a/apps/dashboard/src/components/instance/InstanceLocation.tsx b/apps/dashboard/src/components/instance/InstanceLocation.tsx
index 80efb4396..5b893c744 100644
--- a/apps/dashboard/src/components/instance/InstanceLocation.tsx
+++ b/apps/dashboard/src/components/instance/InstanceLocation.tsx
@@ -129,9 +129,9 @@ export function InstanceProgress({
Cancel move
)}
- {h?.provisioning?.deploymentId && (
+ {state.role === "active" && h?.provisioning?.deploymentId && (
)}
diff --git a/apps/dashboard/src/components/instance/instance-location.test.tsx b/apps/dashboard/src/components/instance/instance-location.test.tsx
index 171377bd4..37ab3fa0e 100644
--- a/apps/dashboard/src/components/instance/instance-location.test.tsx
+++ b/apps/dashboard/src/components/instance/instance-location.test.tsx
@@ -41,4 +41,14 @@ describe("instance handoff recovery UI", () => {
expect(html).not.toContain("Cancel move");
expect(instanceProgress(retired)).toBe("Connecting to the new control plane");
});
+ it("links server preparation to its build view while the source controller is active", () => {
+ const preparing: InstanceStatus = { ...state, role: "active", handoff: {
+ ...state.handoff!, provisioning: { projectId: "project", deploymentId: "deploy", access: "desktop" },
+ } };
+ const html = renderToStaticMarkup( {}} />);
+ expect(html).toContain('href="/build/deploy"');
+ expect(html).not.toContain('href="/deployments/deploy"');
+ const frozen = renderToStaticMarkup( {}} />);
+ expect(frozen).not.toContain("View deployment");
+ });
});
diff --git a/apps/dashboard/src/components/migration/PlatformImportDomains.tsx b/apps/dashboard/src/components/migration/PlatformImportDomains.tsx
new file mode 100644
index 000000000..63257c72b
--- /dev/null
+++ b/apps/dashboard/src/components/migration/PlatformImportDomains.tsx
@@ -0,0 +1,69 @@
+"use client";
+
+import type { PlatformImportService } from "@repo/contracts";
+import { useI18n } from "@/components/i18n-provider";
+
+export type ImportDomainService = Pick;
+
+/** Discovery and saved runs share the same public domain inventory. */
+export function PlatformImportDomains({
+ services,
+ cutover = false,
+}: {
+ services: ImportDomainService[];
+ cutover?: boolean;
+}) {
+ const { t } = useI18n();
+ const copy = t.migration.platformDomains;
+ const domains = services.flatMap((service) =>
+ (service.domains ?? []).map((domain) => ({ ...domain, service })),
+ );
+ if (!cutover && !domains.length) return null;
+
+ return (
+
+
+
{copy.title}
+
{copy.intro}
+
+ {domains.length > 0 ? (
+
+ {domains.map(({ hostname, portable, service }) => (
+ -
+
+
+ {hostname}
+
+
{service.name}
+
+
+ {portable ? copy.customAction : copy.providerAction}
+
+
+ ))}
+
+ ) : (
+ {copy.empty}
+ )}
+ {!cutover && domains.some((domain) => domain.portable) && (
+ {copy.customHint}
+ )}
+ {domains.some((domain) => !domain.portable) && (
+ {copy.providerHint}
+ )}
+ {cutover && domains.length > 0 && (
+
+
{copy.next}
+
+ - {copy.test}
+ {domains.some((domain) => domain.portable) && - {copy.dns}
}
+ - {copy.verify}
+
+
+ )}
+
+ );
+}
diff --git a/apps/dashboard/src/components/migration/PlatformImportProgress.tsx b/apps/dashboard/src/components/migration/PlatformImportProgress.tsx
index 1f6361e11..6c7efe969 100644
--- a/apps/dashboard/src/components/migration/PlatformImportProgress.tsx
+++ b/apps/dashboard/src/components/migration/PlatformImportProgress.tsx
@@ -9,6 +9,7 @@ import { InstallStepper, type StepStatus } from "@/components/deploy/InstallStep
import { useI18n } from "@/components/i18n-provider";
import { formatBytes } from "@/lib/formatBytes";
import { statusTone } from "./MigrationRunList";
+import { PlatformImportDomains, type ImportDomainService } from "./PlatformImportDomains";
export const importFinished = (status: string) =>
["failed", "rolled_back", "succeeded"].includes(status);
@@ -48,7 +49,10 @@ export function PlatformImportProgress({
run.status,
);
const stopped = run.status === "rolled_back" && run.cancelRequested === true;
- const projects = Object.entries(run.importedProjects ?? {});
+ const services = (run.inputSnapshot?.services ?? []) as ImportDomainService[];
+ const projects = [
+ ...new Map(Object.entries(run.importedProjects ?? {}).map(([source, id]) => [id, source])),
+ ].map(([id, source]) => ({ id, source }));
const steps: Array<{ id: string; label: string; status: StepStatus }> = [
{
id: "import",
@@ -77,7 +81,9 @@ export function PlatformImportProgress({
-
Imported projects
+
+ {projects.length > 1 ? "Imported projects" : "Imported project"}
+
@@ -104,47 +110,37 @@ export function PlatformImportProgress({
)}
- {projects.map(([source, id], index) => (
-
-
-
- {(
- run.inputSnapshot?.services as Array<{ id: string; name: string }> | undefined
- )?.find((s) => s.id === source)?.name ?? `Project ${index + 1}`}
-
-
Open project
-
-
+ {projects.map(({ source, id }, index) => (
+
+
+
+
+ {projects.length === 1
+ ? run.projectName
+ : (services.find((s) => s.id === source)?.name ?? `Project ${index + 1}`)}
+
+ Open project
+
+
+ {run.status === "awaiting_cutover" && (
+
+ )}
+
))}
{!projects.length && (
- Created projects will appear here as the import progresses.
+ The imported project will appear here as the import progresses.
)}
- {run.status === "awaiting_cutover" && (
-
-
-
Verify before moving traffic
-
- Open each project, check its data, and add a test domain in Domains & Routes.
- Then move your existing domains and confirm below.
-
-
-
- Keep source writers paused until cutover. Retire the old services at the provider
- after verifying the destination.
-
-
-
- )}
{run.status === "succeeded" && (
Migration complete. Your source resources remain at the provider until you retire
@@ -163,6 +159,24 @@ export function PlatformImportProgress({
)}
+ {run.status === "awaiting_cutover" && (
+ <>
+ run.importedProjects?.[service.id])}
+ cutover
+ />
+
+
+ Keep source writers paused until cutover. Retire the old services at the provider
+ after verifying the destination.
+
+
+
+ >
+ )}
{run.deploymentId && (
void;
}) {
const imports = plan.services.filter((s) => choices[s.id]?.data !== "external");
+ const projectCount = plan.projects?.length ?? 1;
return (
@@ -85,6 +87,15 @@ export function PlatformImportReview({
{importDataLabel(service, choice)}
+ {projectCount > 1 && (
+
+ Project:{" "}
+ {
+ plan.projects?.find((project) => project.serviceIds.includes(service.id))
+ ?.name
+ }
+
+ )}
{service.commit
@@ -98,6 +109,12 @@ export function PlatformImportReview({
})}
+ ({
+ ...service,
+ name: choices[service.id].name,
+ }))}
+ />
{(plan.requiresWritePause || plan.requiresWorkerPause) && (
@@ -154,8 +171,15 @@ export function PlatformImportReview({
Review complete
- {imports.length} new {imports.length === 1 ? "project" : "projects"}
+ {projectCount} {projectCount === 1 ? "project" : "projects"} · {imports.length}{" "}
+ {imports.length === 1 ? "service" : "services"}
+ {projectCount > 1 && (
+
+ Separate projects keep each service’s repository and revision. Dependencies use
+ private connections on the destination server.
+
+ )}
- {busy
- ? "Starting import…"
- : `Import ${imports.length} ${imports.length === 1 ? "project" : "projects"}`}
+ {busy ? "Starting import…" : "Import project"}