diff --git a/apps/api/test/modules/services/application-identity.test.ts b/apps/api/test/modules/services/application-identity.test.ts new file mode 100644 index 000000000..5cef0a7f7 --- /dev/null +++ b/apps/api/test/modules/services/application-identity.test.ts @@ -0,0 +1,101 @@ +import { beforeEach, expect, it, vi } from "vitest"; +const mocks = vi.hoisted(() => ({ project: vi.fn(), services: vi.fn(), env: vi.fn() })); +vi.mock("@repo/db", async (original) => { + const actual = await original(); + return { + ...actual, + repos: { + ...actual.repos, + project: { ...actual.repos.project, findById: mocks.project, listEnvVars: mocks.env }, + service: { ...actual.repos.service, listByProject: mocks.services }, + }, + }; +}); +import { listServices } from "@repo/platform/engine/modules/services/service.service"; +const project = { + id: "p", + organizationId: "org", + slug: "website", + framework: "nextjs", + rootDirectory: ".", + buildCommand: "bun run build", + port: 3000, + hasServer: true, + workloadType: "web", +}; +const app = { + id: "app", + projectId: "p", + name: "website", + kind: "monorepo", + enabled: true, + sortOrder: -1, + rootDirectory: ".", + environment: {}, + volumes: [], + advanced: {}, + buildArgs: {}, +}; +const database = { + id: "db", + projectId: "p", + name: "postgres", + kind: "compose", + image: "postgres:17", + enabled: true, + sortOrder: 0, + exposed: false, + environment: { PASSWORD: "private-value" }, +}; +const context = { organizationId: "org" } as never; +beforeEach(() => { + mocks.project.mockResolvedValue(project); + mocks.services.mockResolvedValue([app, database]); + mocks.env.mockResolvedValue([]); +}); +it("exposes one stable project application when the first database is added", async () => { + const rows = await listServices(context, "p"); + expect(rows.map((s) => [s.id, s.applicationMode])).toEqual([ + ["app", "project"], + ["db", undefined], + ]); + expect(mocks.env).toHaveBeenCalledWith("p", undefined, "app"); + expect(JSON.stringify(rows)).not.toContain("private-value"); +}); +it("preserves the application identity after removing the last companion", async () => { + mocks.services.mockResolvedValue([app]); + expect((await listServices(context, "p"))[0].applicationMode).toBe("project"); +}); +it.each([ + ["saved runtime override", app, [{ key: "CUSTOM", value: "keep" }]], + ["Compose value", { ...app, environment: { CUSTOM: "keep" } }, []], + ["custom build", { ...app, buildCommand: "custom-build" }, []], + ["renamed app", { ...app, name: "renamed" }, []], + ["disabled app", { ...app, enabled: false }, []], +])("retains service ownership for %s", async (_name, row, env) => { + mocks.services.mockResolvedValue([row, database]); + mocks.env.mockResolvedValue(env); + expect((await listServices(context, "p"))[0].applicationMode).toBe("service"); +}); +it.each([ + { ...project, framework: "docker-compose" }, + { ...project, composePath: "compose.yml" }, +])("does not collapse a real Compose app into the project", async (shape) => { + mocks.project.mockResolvedValue(shape); + expect((await listServices(context, "p")).every((s) => s.applicationMode === undefined)).toBe( + true, + ); +}); +it("does not invent an identity for a regular monorepo application", async () => { + mocks.services.mockResolvedValue([{ ...app, sortOrder: 0 }, database]); + expect((await listServices(context, "p"))[0].applicationMode).toBeUndefined(); +}); + +it.each([ + { workspaceId: "cloud-workspace" }, + { clusterId: "cluster" }, + { workloadType: "static", hasServer: false }, +])("keeps service controls for a runtime outside the primary app pipeline", async (shape) => { + mocks.project.mockResolvedValue({ ...project, ...shape }); + expect((await listServices(context, "p"))[0].applicationMode).toBe("service"); +}); diff --git a/apps/dashboard/scripts/check-i18n.mjs b/apps/dashboard/scripts/check-i18n.mjs index 8eadfab65..7a3f6d701 100644 --- a/apps/dashboard/scripts/check-i18n.mjs +++ b/apps/dashboard/scripts/check-i18n.mjs @@ -14,6 +14,15 @@ import { fileURLToPath } from "node:url"; const SOURCE_LOCALE = "en"; +// These display names intentionally stay English in every locale. +const BRAND_NAMES = new Set([ + "OpenShip", + "OpenShip Cloud", + "OpenShip Desktop", + "OpenShip Manage", + "Ruby on Rails", +]); + /** Absolute path to the locales dir, resolved relative to this script. */ export function defaultLocalesDir() { return fileURLToPath(new URL("../src/i18n/locales", import.meta.url)); @@ -56,7 +65,12 @@ function readJson(file) { * English sentence, so the UI silently renders English and every test stays green. */ function looksTranslatable(value) { - return typeof value === "string" && value.trim().length > 3 && /\s/.test(value.trim()); + return ( + typeof value === "string" && + value.trim().length > 3 && + /\s/.test(value.trim()) && + !BRAND_NAMES.has(value.trim()) + ); } /** @@ -98,7 +112,8 @@ export function checkI18nParity(localesDir = defaultLocalesDir()) { if (fs.existsSync(file)) localeEntries = leafEntries(readJson(file)); const localeKeys = new Set(Object.keys(localeEntries)); for (const k of base) if (!localeKeys.has(k)) missing.push({ locale, namespace: ns, key: k }); - for (const k of localeKeys) if (!baseSet.has(k)) extra.push({ locale, namespace: ns, key: k }); + for (const k of localeKeys) + if (!baseSet.has(k)) extra.push({ locale, namespace: ns, key: k }); // Present, but still the English sentence — invisible to the two checks above. for (const k of localeKeys) { if (!baseSet.has(k)) continue; @@ -189,12 +204,14 @@ if (isMain()) { } if (r.missing.length) { console.log("MISSING (key → locales that lack it):"); - for (const [id, locs] of group(r.missing)) console.log(` ${id} [${[...locs].sort().join(",")}]`); + for (const [id, locs] of group(r.missing)) + console.log(` ${id} [${[...locs].sort().join(",")}]`); console.log(""); } if (r.extra.length) { console.log("EXTRA (stale locale keys not in en):"); - for (const [id, locs] of group(r.extra)) console.log(` ${id} [${[...locs].sort().join(",")}]`); + for (const [id, locs] of group(r.extra)) + console.log(` ${id} [${[...locs].sort().join(",")}]`); console.log(""); } } else { diff --git a/apps/dashboard/src/app/(auth)/login/page.tsx b/apps/dashboard/src/app/(auth)/login/page.tsx index 2cacb7df7..26e819723 100644 --- a/apps/dashboard/src/app/(auth)/login/page.tsx +++ b/apps/dashboard/src/app/(auth)/login/page.tsx @@ -236,7 +236,7 @@ function LoginPageInner() { ); } - /* ── Cloud mode (desktop): redirect to Openship Cloud for all auth ── */ + /* ── Cloud mode (desktop): redirect to OpenShip Cloud for all auth ── */ if (authMode === "cloud") { const apiUrl = getApiOrigin(typeof window !== "undefined" ? window.location.origin : undefined); const callbackUrl = `${apiUrl}/api/auth/cloud-callback`; @@ -251,7 +251,7 @@ function LoginPageInner() { {t.auth.login.title}

- Sign in with your Openship account to continue. + Sign in with your OpenShip account to continue.

@@ -272,7 +272,7 @@ function LoginPageInner() { onClick={() => { void handleCloudSignIn(callbackUrl); }} > {loading ? : } - {loading ? "Opening Openship Cloud..." : "Sign in with Openship"} + {loading ? "Opening OpenShip Cloud..." : "Sign in with OpenShip"} ); diff --git a/apps/dashboard/src/app/(dashboard)/(deployment)/deploy/[slug]/components/CloudWaitlistModal.tsx b/apps/dashboard/src/app/(dashboard)/(deployment)/deploy/[slug]/components/CloudWaitlistModal.tsx index 44e443d2b..797e21a01 100644 --- a/apps/dashboard/src/app/(dashboard)/(deployment)/deploy/[slug]/components/CloudWaitlistModal.tsx +++ b/apps/dashboard/src/app/(dashboard)/(deployment)/deploy/[slug]/components/CloudWaitlistModal.tsx @@ -5,12 +5,12 @@ import { Icon as UiIcon } from "@repo/ui/icons"; // TODO: removed — temporary SaaS "Cloud is almost here" waitlist gate. // Delete this file, the /api/cloud-waitlist route, and the gate in Sidebar's -// handleDeploy when Openship Cloud opens for real deploys. +// handleDeploy when OpenShip Cloud opens for real deploys. import { useState } from "react"; /** - * SaaS-only "Openship Cloud is almost here" gate. Shown instead of running a + * SaaS-only "OpenShip Cloud is almost here" gate. Shown instead of running a * deploy while the managed cloud isn't open yet — captures an email for the * notify-me waitlist. "Notify me" POSTs to `/api/cloud-waitlist`, a thin Next * route handler that forwards to `process.env.MARKETING_API_URL` (no DB / Hono @@ -53,7 +53,7 @@ export function CloudWaitlistModal({ onClose }: { onClose: () => void }) {
-

Openship Cloud is almost here

+

OpenShip Cloud is almost here

Thanks for your interest! We're building a fast, scalable, and efficient managed cloud — one-click deploys with zero infrastructure to run. Launching soon. @@ -64,7 +64,7 @@ export function CloudWaitlistModal({ onClose }: { onClose: () => void }) { {status === "done" ? (

- Thank you — we'll email you the moment Openship Cloud is ready. + Thank you — we'll email you the moment OpenShip Cloud is ready.
) : (
diff --git a/apps/dashboard/src/app/(dashboard)/backups/backups-pages.test.tsx b/apps/dashboard/src/app/(dashboard)/backups/backups-pages.test.tsx index 1bcfca29d..e710363c4 100644 --- a/apps/dashboard/src/app/(dashboard)/backups/backups-pages.test.tsx +++ b/apps/dashboard/src/app/(dashboard)/backups/backups-pages.test.tsx @@ -64,7 +64,7 @@ const row = (id: string, serviceName: string, bytes: number): BackupDestinationR destinationId: "storage", destinationName: "Production backups", projectId: "project", - projectName: "Openship", + projectName: "OpenShip", serviceId: serviceName, serviceName, mailServerId: null, diff --git a/apps/dashboard/src/app/(dashboard)/billing/_components/billing-overview-layout.render.test.tsx b/apps/dashboard/src/app/(dashboard)/billing/_components/billing-overview-layout.render.test.tsx index efc890889..733e1b53d 100644 --- a/apps/dashboard/src/app/(dashboard)/billing/_components/billing-overview-layout.render.test.tsx +++ b/apps/dashboard/src/app/(dashboard)/billing/_components/billing-overview-layout.render.test.tsx @@ -48,7 +48,7 @@ describe("billing sidebar", () => { it("keeps the no-plan promotion visible when the provider has no free product", () => { const out = render(); - expect(text(out)).toContain("Launch on Openship Cloud"); + expect(text(out)).toContain("Launch on OpenShip Cloud"); expect(out).toContain("/billing/plans"); expect(text(out)).not.toContain("Unlimited"); }); diff --git a/apps/dashboard/src/app/(dashboard)/billing/manage/page.test.tsx b/apps/dashboard/src/app/(dashboard)/billing/manage/page.test.tsx index 31f875750..569a0f6de 100644 --- a/apps/dashboard/src/app/(dashboard)/billing/manage/page.test.tsx +++ b/apps/dashboard/src/app/(dashboard)/billing/manage/page.test.tsx @@ -227,7 +227,7 @@ it("adds slots without a plan picker and confirms the exact quoted price only on return state; }); await render(); - expect(host.querySelector("h1")?.textContent).toBe("Openship Manage"); + expect(host.querySelector("h1")?.textContent).toBe("OpenShip Manage"); expect(host.querySelector('a[href="/servers/external"]')?.textContent).toContain( "Production server", ); @@ -270,7 +270,7 @@ it("adds slots without a plan picker and confirms the exact quoted price only on it("keeps an empty paid plan on its detail page and offers the normal server connection form", async () => { activateManagement(0); await render(); - expect(host.querySelector("h1")?.textContent).toBe("Openship Manage"); + expect(host.querySelector("h1")?.textContent).toBe("OpenShip Manage"); expect(host.textContent).toContain(baseDictionary.billing.managementDetail.empty); expect(host.textContent).toContain("0 / 2"); expect(host.querySelector('a[href="/servers/new"]')?.textContent).toContain( @@ -417,7 +417,7 @@ it("keeps the Manage payment controls in its own payments tab", async () => { it("shows an unfinished Manage purchase as a named pending plan with recovery actions", async () => { state.pendingCheckout = true; await render(); - expect(host.querySelector("h1")?.textContent).toBe("Openship Manage"); + expect(host.querySelector("h1")?.textContent).toBe("OpenShip Manage"); expect(host.textContent).toContain(baseDictionary.billing.hub.paymentRequired); expect(button("Resume checkout")).toBeDefined(); expect(host.querySelector('[role="radiogroup"]')).toBeNull(); diff --git a/apps/dashboard/src/app/(dashboard)/emails/_components/setup-error-banner.render.test.tsx b/apps/dashboard/src/app/(dashboard)/emails/_components/setup-error-banner.render.test.tsx index 1f3f83c5a..e4d1a0a25 100644 --- a/apps/dashboard/src/app/(dashboard)/emails/_components/setup-error-banner.render.test.tsx +++ b/apps/dashboard/src/app/(dashboard)/emails/_components/setup-error-banner.render.test.tsx @@ -33,7 +33,7 @@ describe("SetupErrorBanner", () => { render({ title: "Setup couldn't start", message: - "Can't start mail setup: Permission denied (publickey,password). Openship could not run a single command on this server.", + "Can't start mail setup: Permission denied (publickey,password). OpenShip could not run a single command on this server.", }), ); expect(out).toContain("Setup couldn't start"); diff --git a/apps/dashboard/src/app/(dashboard)/library/LibraryContent.tsx b/apps/dashboard/src/app/(dashboard)/library/LibraryContent.tsx new file mode 100644 index 000000000..a7d345baa --- /dev/null +++ b/apps/dashboard/src/app/(dashboard)/library/LibraryContent.tsx @@ -0,0 +1,299 @@ +"use client"; + +import { Icon as UiIcon, type IconName } from "@repo/ui/icons"; + +import React, { useState, useEffect, useCallback, useRef } from "react"; +import { usePathname, useRouter, useSearchParams } from "next/navigation"; +import { migrationHref, parseMigrationSource, type MigrationSourceKind } from "@repo/core"; +import { useGitHub } from "@/context/GitHubContext"; +import { usePlatform } from "@/context/PlatformContext"; +import { useCloud } from "@/context/CloudContext"; +import { ConnectPrompt } from "./components/ConnectPrompt"; +import { LoadingSkeleton } from "./components/LoadingSkeleton"; +import { RepositoryList } from "./components/RepositoryList"; +import { useLibraryRepos } from "./useLibraryRepos"; +import { GhCliConsent } from "./components/GhCliConsent"; +import { LocalProjects } from "./components/LocalProjects"; +import { FolderUpload } from "./components/FolderUpload"; +import { LibrarySidebar } from "./components/LibrarySidebar"; +import { UrlImport } from "./components/UrlImport"; +import { RepositoryAccounts } from "./components/RepositoryAccounts"; +import { PageContainer } from "@/components/ui/PageContainer"; +import { HelpMenu } from "@/components/HelpMenu"; +import { MigrationWizard } from "@/components/migration/MigrationWizard"; +import { useI18n } from "@/components/i18n-provider"; +import { AppCatalog } from "@/components/apps/AppCatalog"; + +type Tab = "folder" | "repositories" | "url" | "server" | "apps"; + +/** One-time gh-CLI repo-read consent flag (per browser — desktop is single-user). */ +const GH_CLI_CONSENT_KEY = "openship.gh-cli-consent"; + +interface TabItem { + key: Tab; + label: string; + icon: IconName; +} + +export function LibraryContent() { + const { t } = useI18n(); + const router = useRouter(); + const pathname = usePathname(); + const searchParams = useSearchParams(); + const migrating = pathname === migrationHref(); + const requestedSource = parseMigrationSource(searchParams.get("from")); + const { + state, + connected, + connecting, + loading, + capabilities, + connect, + cliAction, + accounts, + selectedOwner, + setSelectedOwner, + refresh, + installUrl, + } = useGitHub(); + // Server-paginated repo list for the Library (own hook so the shared + // GitHubContext.repos — used by the GitSettings + migration pickers — stays a + // full-set, client-side list). Fetches a page at a time + authoritative counts. + const libRepos = useLibraryRepos(selectedOwner, connected); + const { selfHosted, deployMode } = usePlatform(); + // Only the desktop app can read the user's folder off disk (native picker + + // co-located API). A remote self-hosted browser uploads it instead. + const isDesktop = deployMode === "desktop"; + const { connected: cloudConnected } = useCloud(); + + // Cloud has a dedicated URL tab. Self-hosted instances keep its shortcut in + // the account row; both use the same selection and public import flow. + const [selectedTab, setActiveTab] = useState("repositories"); + const activeTab = migrating ? "server" : selectedTab; + const appsTabRef = useRef(null); + const importingUrl = activeTab === "url"; + const [showMigrate, setShowMigrate] = useState(migrating); + const [migrationSource, setMigrationSource] = useState( + requestedSource, + ); + // The shared layout keeps an import draft/progress mounted while browsing + // other Library tabs. Browser navigation still selects the source from its URL. + useEffect(() => { + if (!migrating) return; + setShowMigrate(true); + setMigrationSource(requestedSource); + }, [migrating, requestedSource]); + + const importUrl = () => setActiveTab("url"); + const selectOwner = (login: string) => { + setActiveTab("repositories"); + if (login) setSelectedOwner(login); + }; + const addAccount = () => { + setActiveTab("repositories"); + const app = capabilities?.methods.find((method) => method.kind === "app"); + const available = app + ? app.available && (!app.requiresCloud || cloudConnected) + : !selfHosted || !!installUrl; + if (available) void connect("oauth"); + else router.push("/settings?tab=git"); + }; + const sourceHeader = ( +
+ +
+ ); + + // First-run consent before the gh-CLI source lists repos. The gh path runs + // entirely on this machine (nothing to the cloud), but we ask once so the + // Library doesn't silently enumerate the user's repos on first open. + const [ghCliConsent, setGhCliConsent] = useState(true); // optimistic until localStorage reads + useEffect(() => { + setGhCliConsent(localStorage.getItem(GH_CLI_CONSENT_KEY) === "1"); + }, []); + const allowGhCli = useCallback(() => { + localStorage.setItem(GH_CLI_CONSENT_KEY, "1"); + setGhCliConsent(true); + }, []); + // Gate ONLY a credential we found on the host by ourselves. A device sign-in or + // a pasted token was handed over by the operator inside Openship — asking them + // to consent again to the thing they just did is a dead end that made a fresh + // token look broken until the prompt was noticed and accepted. + const needsGhCliConsent = + state.primary === "gh-cli" && + (state.sources.ghCli.method ?? "host-cli") === "host-cli" && + !ghCliConsent; + + // Folder import is available on self-hosted instances. Cloud offers a Git URL tab. + const tabs: TabItem[] = [ + { key: "apps", label: t.dashboard.pages.apps.title, icon: "grid" }, + { key: "repositories", label: t.library.page.tabs.github, icon: "github" }, + ...(selfHosted + ? [{ key: "folder" as const, label: t.library.page.tabs.folder, icon: "folder-out" as const }] + : [{ key: "url" as const, label: t.library.page.tabs.gitUrl, icon: "link" as const }]), + { key: "server", label: t.migration.entry.tab, icon: "migration" }, + ]; + + return ( + + {/* ── Header ───────────────────────────────────────────── */} + {/* No primary action here (the tabs below are the action), so the shared ⋮ + help menu sits alone at the title's trailing edge — level with the + heading, matching the Projects / Apps headers. */} +
+
+

+ {t.library.page.title} +

+

{t.library.page.subtitle}

+
+ +
+ + {/* ── Tabs ─────────────────────────────────────────────── */} +
+ {tabs.map((tab) => { + const Icon = tab.icon; + const selected = + activeTab === tab.key || (selfHosted && importingUrl && tab.key === "repositories"); + return ( + + ); + })} +
+ + {/* ── Main Grid ──────────────────────────────────────────── */} +
+ {/* ── LEFT COLUMN ────────────────────────────────────────── */} +
+ {activeTab === "apps" ? ( + + ) : selfHosted && activeTab === "folder" ? ( + // Desktop reads the folder off disk; remote self-hosted browsers upload it. + isDesktop ? ( + + ) : ( + + ) + ) : importingUrl ? ( + + ) : loading ? ( + + ) : !connected ? ( + { + setActiveTab("apps"); + appsTabRef.current?.focus(); + }} + selfHosted={selfHosted} + /> + ) : needsGhCliConsent ? ( + + ) : ( + + )} +
+ + {/* ── RIGHT COLUMN ───────────────────────────────────────── */} + +
+ + {(migrating || showMigrate) && ( +
+ router.push(migrationHref(source), { scroll: false })} + onClose={() => { + setShowMigrate(false); + setMigrationSource(null); + setActiveTab("repositories"); + router.push("/library", { scroll: false }); + }} + /> +
+ )} +
+ ); +} diff --git a/apps/dashboard/src/app/(dashboard)/library/layout.tsx b/apps/dashboard/src/app/(dashboard)/library/layout.tsx new file mode 100644 index 000000000..c0ceb5ea5 --- /dev/null +++ b/apps/dashboard/src/app/(dashboard)/library/layout.tsx @@ -0,0 +1,13 @@ +import { Suspense, type ReactNode } from "react"; +import { LibraryContent } from "./LibraryContent"; + +export default function LibraryLayout({ children }: { children: ReactNode }) { + return ( + <> + + + + {children} + + ); +} diff --git a/apps/dashboard/src/app/(dashboard)/library/migrate/page.tsx b/apps/dashboard/src/app/(dashboard)/library/migrate/page.tsx new file mode 100644 index 000000000..063704560 --- /dev/null +++ b/apps/dashboard/src/app/(dashboard)/library/migrate/page.tsx @@ -0,0 +1,4 @@ +// A direct entry into the same Library flow, including a source selected by ?from=. +export default function LibraryMigrationPage() { + return null; +} diff --git a/apps/dashboard/src/app/(dashboard)/library/page.test.tsx b/apps/dashboard/src/app/(dashboard)/library/page.test.tsx index 63204a84e..0b0ded45a 100644 --- a/apps/dashboard/src/app/(dashboard)/library/page.test.tsx +++ b/apps/dashboard/src/app/(dashboard)/library/page.test.tsx @@ -2,7 +2,7 @@ import { act } from "react"; import { createRoot, type Root } from "react-dom/client"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import LibraryPage from "./page"; +import { LibraryContent } from "./LibraryContent"; import { decodeSlug } from "@/utils/repoSlug"; const h = vi.hoisted(() => ({ @@ -16,8 +16,13 @@ const h = vi.hoisted(() => ({ appAvailable: true, requiresCloud: false, cloudConnected: true, + href: "/library", +})); +vi.mock("next/navigation", () => ({ + useRouter: () => ({ push: h.push }), + usePathname: () => new URL(h.href, "https://app.test").pathname, + useSearchParams: () => new URL(h.href, "https://app.test").searchParams, })); -vi.mock("next/navigation", () => ({ useRouter: () => ({ push: h.push }) })); vi.mock("@/lib/auth-client", () => ({ useSession: () => ({ data: { user: { id: "user" }, session: { activeOrganizationId: "org" } }, @@ -74,6 +79,14 @@ vi.mock("./components/LibrarySidebar", () => ({ LibrarySidebar: () => null })); vi.mock("./components/LocalProjects", () => ({ LocalProjects: () => null })); vi.mock("./components/FolderUpload", () => ({ FolderUpload: () => null })); vi.mock("@/components/apps/AppCatalog", () => ({ AppCatalog: () =>
App catalog
})); +vi.mock("@/components/migration/PlatformMigrationWizard", () => ({ + PlatformMigrationWizard: ({ provider, onBack }: { provider: string; onBack: () => void }) => ( +
+ + +
+ ), +})); vi.mock("@/components/migration/ServerMigrationWizard", () => ({ ServerMigrationWizard: ({ variant, onClose }: { variant: string; onClose: () => void }) => (
@@ -95,6 +108,13 @@ beforeEach(() => { appAvailable: true, requiresCloud: false, cloudConnected: true, + href: "/library", + }); + h.push.mockImplementation((href: string) => { + if (href.split("?")[0] === "/library" || href.split("?")[0] === "/library/migrate") { + h.href = href; + root.render(); + } }); localStorage.clear(); vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); @@ -107,7 +127,7 @@ afterEach(async () => { container.remove(); vi.unstubAllGlobals(); }); -const render = () => act(async () => root.render()); +const render = () => act(async () => root.render()); function button(label: string) { const result = Array.from(container.querySelectorAll("button")).find( (node) => (node.getAttribute("aria-label") ?? node.textContent?.trim()) === label, @@ -225,20 +245,73 @@ describe("New Project source actions", () => { h.selfHosted = true; await render(); await click("Import existing project"); + expect(h.href).toBe("/library/migrate"); expect(container.textContent).toContain("Where are you moving from?"); const serverSource = Array.from(container.querySelectorAll("button")).find((node) => node.textContent?.includes("Server or Docker"), ); expect(serverSource).toBeDefined(); await act(async () => serverSource!.click()); + expect(h.href).toBe("/library/migrate?from=server"); const wizard = container.querySelector('[aria-label="Migration"]'); expect(wizard?.getAttribute("data-variant")).toBe("tab"); expect(container.querySelector('[role="dialog"]')).toBeNull(); await click("Apps"); + expect(h.href).toBe("/library"); await click("Import existing project"); + expect(h.href).toBe("/library/migrate?from=server"); expect(container.querySelector('[aria-label="Migration"]')).toBe(wizard); await click("Close migration"); + expect(h.href).toBe("/library"); expect(container.querySelector('[aria-label="Migration"]')).toBeNull(); expect(button("GitHub").getAttribute("aria-pressed")).toBe("true"); }); + + it.each(["railway", "vercel"])("opens a direct %s link without GitHub setup", async (provider) => { + h.connected = false; + h.loading = true; + h.href = `/library/migrate?from=${provider}`; + await render(); + expect(button("Import existing project").getAttribute("aria-pressed")).toBe("true"); + expect(container.querySelector(`[aria-label="${provider} import"]`)).not.toBeNull(); + expect(h.connect).not.toHaveBeenCalled(); + const draft = container.querySelector('[aria-label="Connection name"]')!; + draft.value = "My connection"; + await click("Apps"); + await click("Import existing project"); + expect(container.querySelector('[aria-label="Connection name"]')).toBe(draft); + expect(draft.value).toBe("My connection"); + await click("Choose another source"); + expect(h.href).toBe("/library/migrate"); + expect(container.textContent).toContain("Where are you moving from?"); + }); + + it("follows browser source navigation and resets provider-specific drafts", async () => { + h.href = "/library/migrate?from=railway"; + await render(); + const railwayDraft = container.querySelector('[aria-label="Connection name"]')!; + railwayDraft.value = "Railway connection"; + h.href = "/library/migrate?from=vercel"; + await render(); + expect(container.querySelector('[aria-label="railway import"]')).toBeNull(); + expect(container.querySelector('[aria-label="vercel import"]')).not.toBeNull(); + expect(container.querySelector('[aria-label="Connection name"]')!.value).toBe(""); + h.href = "/library/migrate?from=railway"; + await render(); + expect(container.querySelector('[aria-label="railway import"]')).not.toBeNull(); + h.href = "/library/migrate"; + await render(); + expect(container.textContent).toContain("Where are you moving from?"); + }); + + it.each(["", "?from=unknown", "?from=https%3A%2F%2Fevil.test", "?from=Railway"])( + "shows the source chooser for an absent or unsupported hint (%s)", async (query) => { + h.href = `/library/migrate${query}`; + await render(); + expect(container.textContent).toContain("Where are you moving from?"); + expect(container.querySelector('[aria-label="Migration"]')).toBeNull(); + expect(container.querySelector('[aria-label="railway import"]')).toBeNull(); + expect(h.push).not.toHaveBeenCalled(); + }, + ); }); diff --git a/apps/dashboard/src/app/(dashboard)/library/page.tsx b/apps/dashboard/src/app/(dashboard)/library/page.tsx index 3f82d5fc4..9ab8912f8 100644 --- a/apps/dashboard/src/app/(dashboard)/library/page.tsx +++ b/apps/dashboard/src/app/(dashboard)/library/page.tsx @@ -1,262 +1,4 @@ -"use client"; - -import { Icon as UiIcon, type IconName } from "@repo/ui/icons"; - -import React, { useState, useEffect, useCallback, useRef } from "react"; -import { useRouter } from "next/navigation"; -import { useGitHub } from "@/context/GitHubContext"; -import { usePlatform } from "@/context/PlatformContext"; -import { useCloud } from "@/context/CloudContext"; -import { ConnectPrompt } from "./components/ConnectPrompt"; -import { LoadingSkeleton } from "./components/LoadingSkeleton"; -import { RepositoryList } from "./components/RepositoryList"; -import { useLibraryRepos } from "./useLibraryRepos"; -import { GhCliConsent } from "./components/GhCliConsent"; -import { LocalProjects } from "./components/LocalProjects"; -import { FolderUpload } from "./components/FolderUpload"; -import { LibrarySidebar } from "./components/LibrarySidebar"; -import { UrlImport } from "./components/UrlImport"; -import { RepositoryAccounts } from "./components/RepositoryAccounts"; -import { PageContainer } from "@/components/ui/PageContainer"; -import { HelpMenu } from "@/components/HelpMenu"; -import { MigrationWizard } from "@/components/migration/MigrationWizard"; -import { useI18n } from "@/components/i18n-provider"; -import { AppCatalog } from "@/components/apps/AppCatalog"; - -type Tab = "folder" | "repositories" | "url" | "server" | "apps"; - -/** One-time gh-CLI repo-read consent flag (per browser — desktop is single-user). */ -const GH_CLI_CONSENT_KEY = "openship.gh-cli-consent"; - -interface TabItem { - key: Tab; - label: string; - icon: IconName; -} - +// The shared layout owns the Library and retains import progress across its routes. export default function LibraryPage() { - const { t } = useI18n(); - const router = useRouter(); - const { - state, - connected, - connecting, - loading, - capabilities, - connect, - cliAction, - accounts, - selectedOwner, - setSelectedOwner, - refresh, - installUrl, - } = useGitHub(); - // Server-paginated repo list for the Library (own hook so the shared - // GitHubContext.repos — used by the GitSettings + migration pickers — stays a - // full-set, client-side list). Fetches a page at a time + authoritative counts. - const libRepos = useLibraryRepos(selectedOwner, connected); - const { selfHosted, deployMode } = usePlatform(); - // Only the desktop app can read the user's folder off disk (native picker + - // co-located API). A remote self-hosted browser uploads it instead. - const isDesktop = deployMode === "desktop"; - const { connected: cloudConnected } = useCloud(); - - // Cloud has a dedicated URL tab. Self-hosted instances keep its shortcut in - // the account row; both use the same selection and public import flow. - const [activeTab, setActiveTab] = useState("repositories"); - const appsTabRef = useRef(null); - const importingUrl = activeTab === "url"; - const [showMigrate, setShowMigrate] = useState(false); - - const importUrl = () => setActiveTab("url"); - const selectOwner = (login: string) => { - setActiveTab("repositories"); - if (login) setSelectedOwner(login); - }; - const addAccount = () => { - setActiveTab("repositories"); - const app = capabilities?.methods.find((method) => method.kind === "app"); - const available = app - ? app.available && (!app.requiresCloud || cloudConnected) - : !selfHosted || !!installUrl; - if (available) void connect("oauth"); - else router.push("/settings?tab=git"); - }; - const sourceHeader = ( -
- -
- ); - - // First-run consent before the gh-CLI source lists repos. The gh path runs - // entirely on this machine (nothing to the cloud), but we ask once so the - // Library doesn't silently enumerate the user's repos on first open. - const [ghCliConsent, setGhCliConsent] = useState(true); // optimistic until localStorage reads - useEffect(() => { - setGhCliConsent(localStorage.getItem(GH_CLI_CONSENT_KEY) === "1"); - }, []); - const allowGhCli = useCallback(() => { - localStorage.setItem(GH_CLI_CONSENT_KEY, "1"); - setGhCliConsent(true); - }, []); - // Gate ONLY a credential we found on the host by ourselves. A device sign-in or - // a pasted token was handed over by the operator inside Openship — asking them - // to consent again to the thing they just did is a dead end that made a fresh - // token look broken until the prompt was noticed and accepted. - const needsGhCliConsent = - state.primary === "gh-cli" && - (state.sources.ghCli.method ?? "host-cli") === "host-cli" && - !ghCliConsent; - - // Folder import is available on self-hosted instances. Cloud offers a Git URL tab. - const tabs: TabItem[] = [ - { key: "apps", label: t.dashboard.pages.apps.title, icon: "grid" }, - { key: "repositories", label: t.library.page.tabs.github, icon: "github" }, - ...(selfHosted - ? [{ key: "folder" as const, label: t.library.page.tabs.folder, icon: "folder-out" as const }] - : [{ key: "url" as const, label: t.library.page.tabs.gitUrl, icon: "link" as const }]), - { key: "server", label: t.migration.entry.tab, icon: "migration" }, - ]; - - return ( - - {/* ── Header ───────────────────────────────────────────── */} - {/* No primary action here (the tabs below are the action), so the shared ⋮ - help menu sits alone at the title's trailing edge — level with the - heading, matching the Projects / Apps headers. */} -
-
-

- {t.library.page.title} -

-

{t.library.page.subtitle}

-
- -
- - {/* ── Tabs ─────────────────────────────────────────────── */} -
- {tabs.map((tab) => { - const Icon = tab.icon; - const selected = - activeTab === tab.key || (selfHosted && importingUrl && tab.key === "repositories"); - return ( - - ); - })} -
- - {/* ── Main Grid ──────────────────────────────────────────── */} -
- {/* ── LEFT COLUMN ────────────────────────────────────────── */} -
- {activeTab === "apps" ? ( - - ) : selfHosted && activeTab === "folder" ? ( - // Desktop reads the folder off disk; remote self-hosted browsers upload it. - isDesktop ? ( - - ) : ( - - ) - ) : importingUrl ? ( - - ) : loading ? ( - - ) : !connected ? ( - { - setActiveTab("apps"); - appsTabRef.current?.focus(); - }} - selfHosted={selfHosted} - /> - ) : needsGhCliConsent ? ( - - ) : ( - - )} -
- - {/* ── RIGHT COLUMN ───────────────────────────────────────── */} - -
- - {showMigrate && ( -
- { - setShowMigrate(false); - setActiveTab("repositories"); - }} - /> -
- )} -
- ); + return null; } diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/BuildSettings.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/BuildSettings.tsx index d3dfbd688..5cd3d24ee 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/BuildSettings.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/BuildSettings.tsx @@ -12,6 +12,8 @@ import { BuildCacheMigration } from "@/components/project-settings/DeploymentAut import { ResourceSettings } from "./ResourceSettings"; import { CommandEnvironmentNotice } from "@/components/import-project/CommandEnvironmentNotice"; import { RuntimeSourceUpdate } from "@/components/updates/RuntimeSourceUpdate"; +import Link from "next/link"; +import { projectApplication } from "@/lib/project-application"; /** * Configuration cards within project Settings. Build settings link to the deploy wizard; project @@ -50,8 +52,12 @@ function SectionCard({ }) { return (
-
-
+
+
@@ -65,15 +71,7 @@ function SectionCard({ ); } -function Row({ - label, - value, - mono, -}: { - label: string; - value?: React.ReactNode; - mono?: boolean; -}) { +function Row({ label, value, mono }: { label: string; value?: React.ReactNode; mono?: boolean }) { const empty = value === undefined || value === null || value === ""; return (
@@ -87,13 +85,15 @@ function Row({ ); } -export const BuildSettings = () => { - const { buildData, projectData, servicesData, id, updateBuild, refreshEnvironment } = useProjectSettings(); +export const BuildSettings = ({ scope = "project" }: { scope?: "project" | "application" }) => { + const { buildData, projectData, servicesData, id, updateBuild, refreshEnvironment } = + useProjectSettings(); const { t } = useI18n(); const router = useRouter(); const isWebmail = projectData?.framework === "webmail"; const services = servicesData.services; + const application = projectApplication(projectData, services); // SERVICE-FIRST = the project itself is a set of services (a compose-stack // project) or a monorepo of sub-apps — its config genuinely lives per-service. // A single/static APP that merely had a sidecar service ADDED is NOT @@ -101,7 +101,7 @@ export const BuildSettings = () => { // the project's framework, never on "a service row exists" (which conflates // the two — the whole point of this fix). const isServiceFirst = - services.some((service) => service.kind === "monorepo") || + (application?.mode !== "project" && services.some((service) => service.kind === "monorepo")) || isServicesFramework(projectData?.framework); // Edit = the deploy wizard, rehydrated from this project. The single place @@ -146,12 +146,41 @@ export const BuildSettings = () => { // ── Service-first project: config lives per-service in the Services tab. // (A single/static app with an added sidecar service falls through to the // single-app config below — it is NOT service-first.) ── - if (isServiceFirst) { + if (scope === "project" && application) { return (
- {hasRepo && } + + {t.projectDetail.services.detail.tabs.settings} + + + } + /> - + + {services.some((service) => !service.applicationMode) && } +
+ ); + } + if (isServiceFirst && scope === "project") { + return ( +
+ {hasRepo && ( + + )} + +
); @@ -180,76 +209,166 @@ export const BuildSettings = () => { return (
- { updateBuild(commands); await refreshEnvironment(); }} /> + { + updateBuild(commands); + await refreshEnvironment(); + }} + /> - {hasRepo && (projectData?.buildKind === "dockerfile" || projectData?.framework === "docker") && } - -
} + actions={ +
+ {hasRepo && + (projectData?.buildKind === "dockerfile" || projectData?.framework === "docker") && ( + + )} + +
+ } >
- + {/* Resources moved to the editable ResourceSettings card below — one source, and it covers self-hosted (where limits are now a real choice) instead of being cloud-only and read-only. */} - - + + - {getRuntimeVersionPolicy(projectData?.framework) && } - {projectData?.runtimeImage && } - - + {getRuntimeVersionPolicy(projectData?.framework) && ( + + )} + {projectData?.runtimeImage && ( + + )} + + {/* Only when pinned — a blank row would be noise for the vast majority of projects, whose compose file (if any) sits at the root. */} {buildData.composePath && ( - + )}
- - + {scope === "project" && } + {scope === "project" && } {/* Project-wide limits also apply to companion services on a static site. */} - {(workload !== "static" || services.length > 0) && } + {(workload !== "static" || services.length > 0) && + (scope === "project" || !services.some((service) => !service.applicationMode)) && ( + + )} {/* Storage — persistent paths + object storage. Editable in place (see the component's own note on why it doesn't route through the wizard). Only meaningful for a project with a running container. */} - {workload !== "static" && } + {scope === "project" && workload !== "static" && }
); }; /** Shared project inputs remain editable for single apps, Compose and monorepos. */ 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 shared = servicesData.services.some((service) => !service.applicationMode); + if (application && !shared) { + return ( + + {t.projectSettings.build.env.edit} + + + } + /> + ); + } return ( <> - {/* Environment variables — edited in place via a safe per-variable editor - (diff-merge; untouched secrets are never re-sent), NOT the wizard. */} + {/* The same project environment panel also opens from Apps & Services. */} `row-${uidCounter++}`; +import { Button } from "@/components/ui/button"; +import { useI18n } from "@/components/i18n-provider"; +import { ProjectEnvironmentPanel } from "@/components/project-settings/ProjectEnvironmentPanel"; +/** Settings opens the same project environment panel as Apps & Services. */ export function EnvVarsEditor({ projectId, isOpen, @@ -50,425 +16,25 @@ export function EnvVarsEditor({ isOpen: boolean; onClose: () => void; }) { - const { showToast } = useToast(); const { t } = useI18n(); - const { projectData, servicesData } = useProjectSettings(); - const router = useRouter(); - const canRefresh = canRefreshProjectEnvironment(projectData, servicesData.services); - const showCloudPricing = useCloudDeployPricing(projectData.workspaceId); - const showComposeReview = useComposeReview(projectId); - const hasActiveDeployment = Boolean(projectData?.activeDeploymentId); - const [rows, setRows] = useState([]); - const [baseline, setBaseline] = useState(null); - const [loading, setLoading] = useState(false); - const [saving, setSaving] = useState(false); - const [reveal, setReveal] = useState>({}); - // Saving persists the values; applying explicitly updates the active deployment. - const [pendingApply, setPendingApply] = useState(false); - const [applying, setApplying] = useState(false); - // Env keys wired IN by a service connection (keyed by envKey). These render as - // read-only "linked integration" rows — click opens the integration detail. - const [linked, setLinked] = useState>({}); - const [linkDetail, setLinkDetail] = useState(null); - const [unlinking, setUnlinking] = useState(false); - - const load = useCallback(async () => { - setLoading(true); - setRows([]); - setBaseline(null); - setLinked({}); - try { - const res = await projectsApi.getEnv(projectId); - const envState = createProjectEnvEditState(res?.data ?? [], ENVIRONMENT); - const loaded: Row[] = envState.rows.map((row) => ({ - ...row, - uid: nextUid(), - isSecret: row.isSecret ?? false, - })); - setRows(loaded); - setBaseline(envState.baseline); - // Best-effort: which of these keys are managed by a service connection? - const conns = await connectionsApi.list(projectId).catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "dashboard/app/(dashboard)/projects/[id]/components/EnvVarsEditor"); return ({ data: [] }); }); - const map: Record = {}; - for (const cn of conns?.data ?? []) map[cn.envKey] = cn; - setLinked(map); - } catch (err) { - showToast(getApiErrorMessage(err, t.projectSettings.envVars.toast.loadFailed), "error", t.projectSettings.envVars.toast.loadFailedTitle); - } finally { - setLoading(false); - } - }, [projectId, showToast, t]); - - useEffect(() => { - if (isOpen) { - setReveal({}); - setPendingApply(false); - void load(); - } - }, [isOpen, load]); - - const update = (uid: string, patch: Partial) => - setRows((prev) => prev.map((r) => (r.uid === uid ? { ...r, ...patch } : r))); - - const addRow = (atTop = false) => - setRows((prev) => { - const row = { uid: nextUid(), key: "", value: "", visible: true, isSecret: false }; - return atTop ? [row, ...prev] : [...prev, row]; - }); - - const removeRow = (uid: string) => setRows((prev) => prev.filter((r) => r.uid !== uid)); - - const handleSave = async () => { - if (baseline === null) return; - const result = computeProjectEnvDiff(rows, baseline); - if (!result.ok) { - showToast(result.error, "error", t.projectSettings.envVars.toast.validationTitle); - return; - } - const { upserts, deletes } = result.diff; - - if (upserts.length === 0 && deletes.length === 0) { - // Say so, rather than just closing. An untouched masked secret is deliberately - // absent from the diff (we never hold its value), so re-entering the SAME `.env` - // over a set of saved secrets produces an empty diff — and a dialog that shut - // itself with no word read as "Save did nothing", so operators retried and - // concluded env saving was broken (#587). - showToast( - t.projectSettings.envVars.toast.noChanges, - "info", - t.projectSettings.envVars.toast.noChangesTitle, - ); - onClose(); - return; - } - - setSaving(true); - try { - await projectsApi.mergeEnv(projectId, { environment: ENVIRONMENT, upserts, deletes }); - showToast(t.projectSettings.envVars.toast.saved, "success", t.projectSettings.envVars.toast.savedTitle); - // A persisted env change only reaches the RUNNING service on a deploy. - // Offer the deployment mode this project supports; otherwise the saved - // values will take effect on its first deployment. - if (hasActiveDeployment) { - await load(); // re-sync so the diff resets to the saved state - setPendingApply(true); - } else { - onClose(); - } - } catch (err) { - showToast(getApiErrorMessage(err, t.projectSettings.envVars.toast.saveFailed), "error", t.projectSettings.envVars.toast.saveFailedTitle); - } finally { - setSaving(false); - } - }; - - const handleApply = async () => { - setApplying(true); - try { - const res = await deployApi.trigger( - canRefresh ? { projectId, refresh: true } : { projectId, smartRoute: true }, - ); - if (canRefresh) { - showToast(t.projectSettings.envVars.toast.applying, "success", t.projectSettings.envVars.toast.applyingTitle); - } else { - openTriggeredBuild(router, res, projectId); - } - onClose(); - } catch (err) { - if (!showComposeReview(err) && !showCloudPricing(err)) { - showToast( - getApiErrorMessage( - err, - canRefresh - ? t.projectSettings.envVars.toast.applyFailed - : t.projects.redeploy.couldNotRedeploy, - ), - "error", - canRefresh ? t.projectSettings.envVars.toast.applyFailedTitle : t.projects.redeploy.errorTitle, - ); - } - } finally { - setApplying(false); - } - }; - - // Remove a linked connection: drops the injected env var + the link, then - // re-syncs. The connection API already requests a redeploy for a live target. - const handleUnlink = async () => { - if (!linkDetail) return; - setUnlinking(true); - try { - await connectionsApi.remove(projectId, linkDetail.id); - showToast(t.projects.connections.removed, "success"); - setLinkDetail(null); - await load(); - } catch (err) { - showToast(getApiErrorMessage(err, t.projects.connections.failed), "error"); - } finally { - setUnlinking(false); - } - }; - + const [busy, setBusy] = useState(false); return ( - <> - - {pendingApply ? ( - - ) : ( - - )} +
+
} > -
- {pendingApply && ( -
- -
-

- {canRefresh - ? t.projectSettings.envVars.applyTitle - : t.projectSettings.envVars.rebuildTitle} -

-

- {canRefresh ? t.projectSettings.envVars.applyText : t.projectSettings.envVars.rebuildText} -

-
-
- )} -
-
- -
-
-

{t.projectSettings.envVars.title}

-

- {t.projectSettings.envVars.description} -

-
-
- - {loading ? ( -
- -
- ) : ( -
-
- - row.originalKey && linked[row.originalKey]) - .map((row) => row.key)} - disabled={saving || applying || baseline === null} - className="inline-flex h-8 items-center gap-1.5 rounded-lg bg-muted/60 px-3 text-xs font-medium text-foreground hover:bg-muted disabled:opacity-50" - onChange={(next) => - setRows(next.map((row) => ({ - ...row, - uid: rows.find((previous) => previous.key === row.key)?.uid ?? nextUid(), - isSecret: row.isSecret ?? false, - }))) - } - /> -
- {rows.length === 0 ? ( -

- {t.projectSettings.envVars.empty} -

- ) : ( - rows.map((r) => { - // A connection-managed key renders as a read-only integration - // chip — not editable here; click opens the integration detail. - const conn = r.originalKey ? linked[r.originalKey] : undefined; - if (conn) { - return ( - - ); - } - const showValue = reveal[r.uid] || (!r.isSecret && !r.preserveValue); - return ( -
- update(r.uid, { key: e.target.value })} - placeholder={t.projectSettings.envVars.keyPlaceholder} - spellCheck={false} - className="h-9 w-2/5 rounded-lg border border-border/50 bg-muted/20 px-3 font-mono text-[13px] text-foreground outline-none transition-colors focus:border-primary/40" - /> -
- update(r.uid, { value: e.target.value, preserveValue: false })} - placeholder={r.preserveValue ? t.projectSettings.envVars.secretPlaceholder : t.projectSettings.envVars.valuePlaceholder} - spellCheck={false} - className="h-9 w-full rounded-lg border border-border/50 bg-muted/20 px-3 pe-9 font-mono text-[13px] text-foreground outline-none transition-colors focus:border-primary/40" - /> - -
- - -
- ); - }) - )} - - -
- )} -
+ {isOpen && }
- - {/* Linked-integration detail — opens above the env editor when a linked row - is clicked. Shows the source app + reach mode; the value lives in the - connection, so the only action here is removing the link. */} - {linkDetail && ( - setLinkDetail(null)} maxWidth="460px" width="92vw" zIndex={10010} showCloseButton> -
-
-
- -
-
-

- {t.projectSettings.envVars.linkedTitle} -

-

{linkDetail.sourceName}

-
-
- -
-
- {t.projectSettings.envVars.title} - {linkDetail.envKey} -
-
- {t.projects.connections.modeInternalShort}/{t.projects.connections.modePublicShort} - - {linkDetail.mode === "internal" ? : } - {linkDetail.mode === "internal" - ? t.projects.connections.modeInternalShort - : t.projects.connections.modePublicShort} - -
-
- -

- {interpolate(t.projectSettings.envVars.linkedBody, { app: linkDetail.sourceName })} -

- -
- - -
-
-
- )} - ); } diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/LogsSettings.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/LogsSettings.tsx index 1aebaf000..380b2814a 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/LogsSettings.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/LogsSettings.tsx @@ -22,7 +22,7 @@ import { Button } from "@/components/ui/button"; type LogsTab = "terminal" | "server"; -export const LogsSettings = () => { +export const LogsSettings = ({ applicationOnly = false }: { applicationOnly?: boolean }) => { const { projectData, buildData, @@ -52,7 +52,7 @@ export const LogsSettings = () => { }) !== "static"; const searchParams = useSearchParams(); const router = useRouter(); - const serviceIdFromUrl = searchParams.get("service"); + const serviceIdFromUrl = applicationOnly ? null : searchParams.get("service"); const roleFromUrl = searchParams.get("role"); const roleReplicaFromUrl = Number(searchParams.get("replica") ?? 1); const roleDeploymentFromUrl = searchParams.get("deploymentId"); @@ -92,15 +92,15 @@ export const LogsSettings = () => { }, [requestedTarget, urlSelectionChanged]); // Public (exposed) services lead the target picker — the ones users browse to. const services = useMemo( - () => sortServicesByPublicFirst(servicesData.services), - [servicesData.services], + () => applicationOnly ? [] : sortServicesByPublicFirst(servicesData.services), + [servicesData.services, applicationOnly], ); const servicesLoading = servicesData.isLoading; const servicesLoaded = !servicesData.isLoading; const hasServices = services.length > 0; // The shared application model distinguishes companion services from a // Compose/monorepo app whose primary runtime already has a service row. - const hasProjectRuntime = effectiveHasServer && hasSeparateApplication(projectData, services); + const hasProjectRuntime = effectiveHasServer && (applicationOnly || hasSeparateApplication(projectData, services)); // Request logs come from the EDGE, not from a runtime process — so anything // served through an edge has them, whether or not it has a container to stream // stdout from. That's every project with a domain: cloud (Oblien's edge proxy) @@ -188,6 +188,7 @@ export const LogsSettings = () => { // filter is a real, shareable, refresh-safe query param (null = project // runtime → no param). Guarded so we only replace when it actually changed. useEffect(() => { + if (applicationOnly) return; if (servicesLoading || urlSelectionChanged) return; if (roleFromUrl && !urlDeepLinkAppliedRef.current) return; const role = roleTargets.find((target) => target.value === selectedTarget); @@ -210,6 +211,7 @@ export const LogsSettings = () => { roleTargets, roleFromUrl, urlSelectionChanged, + applicationOnly, ]); const switchTab = useCallback( diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/ServicesTab.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/ServicesTab.tsx index 147194d9b..4c3f35dec 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/ServicesTab.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/ServicesTab.tsx @@ -2,14 +2,25 @@ import { serviceRepositorySource } from "./services/repository-source"; -import { observedAllSettled, reportCaughtError as observeCaughtError } from "@repo/core/diagnostics"; +import { + observedAllSettled, + reportCaughtError as observeCaughtError, +} from "@repo/core/diagnostics"; import { Icon as UiIcon } from "@repo/ui/icons"; import React, { useEffect, useState, useCallback, useMemo, useRef } from "react"; import Link from "next/link"; import { useProjectSettings } from "@/context/ProjectSettingsContext"; import { usePlatform } from "@/context/PlatformContext"; -import { serviceKind, serviceCanStartWithoutBuild, servicesApi, sortServicesByPublicFirst, type Service, type ServiceContainer, type ServiceInput } from "@/lib/api/services"; +import { + serviceKind, + serviceCanStartWithoutBuild, + servicesApi, + sortServicesByPublicFirst, + type Service, + type ServiceContainer, + type ServiceInput, +} from "@/lib/api/services"; import { getServiceStatus } from "@/components/services/ServiceStatusBadge"; import { Button } from "@/components/ui/button"; import { ConnectionNotice } from "@/components/shared/ConnectionNotice"; @@ -24,10 +35,17 @@ import { useCloudDeployPricing } from "@/hooks/useCloudDeployPricing"; import { AddServiceModal } from "./services/AddServiceModal"; import { LinkedAppsCard } from "./services/LinkedAppsCard"; import { ServiceListItem } from "./services/ServiceListItem"; -import { hasSeparateApplication } from "@/lib/project-application"; +import { + hasSeparateApplication, + projectApplication, + applicationServiceRoute, +} from "@/lib/project-application"; +import { ServiceIcon } from "@/components/services/ServiceIcon"; +import { canConfigureRuntimeRoles } from "@/lib/runtime-roles"; import { RuntimeRoleConfigurationControl } from "@/components/services/RuntimeRoleConfiguration"; import { RuntimeRolesCard } from "@/components/services/RuntimeRoles"; -import { ProjectApplicationCard } from "./services/ProjectApplicationCard"; +import { ProjectApplicationListItem } from "./services/ProjectApplicationListItem"; +import { ProjectApplicationPanel } from "./services/ProjectApplicationPanel"; /** Render a drift diff value (arrays → csv, objects → keys, scalars → string). */ const fmtDriftVal = (v: unknown): string => { @@ -74,7 +92,8 @@ export const ServicesTab = () => { // the full-tab skeleton on every action and tab switch (#666) — rows render // fine while their runtime status is checked separately. const loading = - servicesData.isLoading || (containersLoading && services.length === 0); + servicesData.isLoading || + (containersLoading && services.length === 0 && !hasSeparateApplication(projectData, services)); const projectSlugBase = projectData.slug || projectData.name || "project"; const selectedId = slug?.[1] ?? null; const hasProjectId = Boolean(id && id !== "undefined"); @@ -98,10 +117,10 @@ export const ServicesTab = () => { // surfaces as a bare runtime error overlay instead of this component's // error state. The container read is also the one that can time out // (it reflects live runtime state), so it must not take the tab down. - const [, containersResult] = await observedAllSettled([ - refreshServices(), - servicesApi.containers(id), - ], "dashboard/app/(dashboard)/projects/[id]/components/ServicesTab"); + const [, containersResult] = await observedAllSettled( + [refreshServices(), servicesApi.containers(id)], + "dashboard/app/(dashboard)/projects/[id]/components/ServicesTab", + ); if (request !== runtimeRequest.current) return; if (containersResult.status === "rejected") throw containersResult.reason; const ctRes = containersResult.value; @@ -121,9 +140,11 @@ export const ServicesTab = () => { projectId: id, // Keep identity/port details, but never present a stale health reading // as current after a failed request. - containers: previous.projectId === id - ? previous.containers?.map((container) => ({ ...container, status: "unknown" })) ?? null - : null, + containers: + previous.projectId === id + ? (previous.containers?.map((container) => ({ ...container, status: "unknown" })) ?? + null) + : null, loading: false, error: !isAbortError(e) && e instanceof Error ? e.message : t.projects.services.failedLoad, })); @@ -139,7 +160,35 @@ export const ServicesTab = () => { const containerFor = (serviceId: string) => containers?.find((c) => c.serviceId === serviceId); - const selectedService = services.find((s) => s.id === selectedId); + const application = + servicesData.error && services.length === 0 ? null : projectApplication(projectData, services); + const hasApplication = application?.mode === "project"; + const selectedApplication = + !!application && (selectedId === "application" || selectedId === application.service?.id); + const selectedService = + selectedApplication && application?.mode === "service" + ? application.service + : services.find((s) => s.id === selectedId); + const listedServices = hasApplication + ? services.filter((s) => s.id !== application?.service?.id) + : services; + const entryCount = listedServices.length + (hasApplication ? 1 : 0); + const choices = [ + ...(hasApplication + ? [ + { + id: application?.service?.id ?? "application", + name: projectData.name, + icon: , + }, + ] + : []), + ...listedServices.map((s) => ({ + id: s.id, + name: s.name, + icon: , + })), + ]; // Null for a service with no route — it is reachable on its port, and linking // to a derived `-` host sent people to a name nobody created. @@ -158,7 +207,7 @@ export const ServicesTab = () => { const handleCreateService = async (data: ServiceInput) => { if (!hasProjectId) return; - const result = await servicesApi.create(id, data).catch(error => { + const result = await servicesApi.create(id, data).catch((error) => { showCloudPricing(error); throw error; }); @@ -181,14 +230,22 @@ export const ServicesTab = () => { if (!shouldLaunch) { // Nothing to launch against yet — keep the row and land on its detail so // the user can deploy/start it when ready. - showToast(interpolate(t.projects.services.toastSavedDeploy, { name: data.name }), "success", t.projects.services.toastServiceTitle); + showToast( + interpolate(t.projects.services.toastSavedDeploy, { name: data.name }), + "success", + t.projects.services.toastServiceTitle, + ); router.push(`/projects/${id}/services/${newServiceId}`); return; } // Start this service on the project's selected server. Keep its saved // configuration on failure so the user can inspect and retry the operation. - showToast(interpolate(t.projects.services.toastAddedDeploying, { name: data.name }), "success", t.projects.services.toastServiceTitle); + showToast( + interpolate(t.projects.services.toastAddedDeploying, { name: data.name }), + "success", + t.projects.services.toastServiceTitle, + ); const showStartFailure = async (message: string) => { await fetchData(); showToast(message, "error", data.name); @@ -201,17 +258,26 @@ export const ServicesTab = () => { await showStartFailure(res?.error || t.projects.services.toastDeployFailed); return; } - showToast(interpolate(t.projects.services.toastStarting, { name: data.name }), "success", t.projects.services.toastServiceTitle); + showToast( + interpolate(t.projects.services.toastStarting, { name: data.name }), + "success", + t.projects.services.toastServiceTitle, + ); await fetchData(); router.push(`/projects/${id}/services/${newServiceId}`); }) .catch(async (err) => { - if (showCloudPricing(err, async () => { - const result = await servicesApi.start(id, newServiceId); - if (result?.success === false) throw new Error(t.projects.services.toastDeployFailed); + if ( + showCloudPricing(err, async () => { + const result = await servicesApi.start(id, newServiceId); + if (result?.success === false) throw new Error(t.projects.services.toastDeployFailed); + await fetchData(); + router.push(`/projects/${id}/services/${newServiceId}`); + }) + ) { await fetchData(); - router.push(`/projects/${id}/services/${newServiceId}`); - })) { await fetchData(); return; } + return; + } await showStartFailure(getApiErrorMessage(err, t.projects.services.toastDeployFailed)); }); }; @@ -236,7 +302,11 @@ export const ServicesTab = () => { await fetchData(); } catch (e) { observeCaughtError(e, "dashboard/app/(dashboard)/projects/[id]/components/ServicesTab"); - showToast(e instanceof Error ? e.message : t.projects.services.failedResolveDrift, "error", name); + showToast( + e instanceof Error ? e.message : t.projects.services.failedResolveDrift, + "error", + name, + ); } finally { setDriftBusy(null); } @@ -245,7 +315,12 @@ export const ServicesTab = () => { ); const driftedServices = services.filter((s) => s.drift && s.drift.changes.length > 0); - const hasApplication = !servicesData.error && hasSeparateApplication(projectData, services); + + // Application variables are control-plane data. Keep them reachable even if + // the live container listing is slow or unavailable (including bare runtimes). + if (selectedApplication && hasApplication && !servicesData.isLoading) { + return ; + } /* ── Loading state ─────────────────────────────────────────────── */ if (loading) { @@ -255,7 +330,10 @@ export const ServicesTab = () => {
-