diff --git a/ui/src/lib/cloudLinks.test.ts b/ui/src/lib/cloudLinks.test.ts
index 95c0c3303db..7a6a54e2dec 100644
--- a/ui/src/lib/cloudLinks.test.ts
+++ b/ui/src/lib/cloudLinks.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { cloudAppUrl, cloudStackCreateUrl, cloudStackEnterUrl } from "./cloudLinks";
+import { cloudAppUrl, cloudPortfolioManageUrl, cloudStackCreateUrl, cloudStackEnterUrl } from "./cloudLinks";
describe("cloudLinks", () => {
it("resolves stack links against the cloud origin", () => {
@@ -9,6 +9,10 @@ describe("cloudLinks", () => {
expect(cloudStackCreateUrl("https://app.paperclip.app")).toBe(
"https://app.paperclip.app/stacks/new",
);
+ expect(cloudPortfolioManageUrl("https://app.paperclip.app")).toBe(
+ "https://app.paperclip.app/orgs?manage=1",
+ );
+ expect(cloudPortfolioManageUrl(null)).toBeNull();
});
it("drops a control-plane path suffix on the configured origin", () => {
diff --git a/ui/src/lib/cloudLinks.ts b/ui/src/lib/cloudLinks.ts
index 4ec385dc34f..516c61bf7a7 100644
--- a/ui/src/lib/cloudLinks.ts
+++ b/ui/src/lib/cloudLinks.ts
@@ -42,3 +42,14 @@ export function cloudStackEnterUrl(
export function cloudStackCreateUrl(cloudBaseUrl: string | null | undefined): string | null {
return cloudAppUrl(cloudBaseUrl, "/stacks/new");
}
+
+/**
+ * Cloud's organization portfolio in its explicit manage view. `?manage=1`
+ * matters: the plain launchpad auto-forwards a solo user straight back into
+ * their one openable stack, and the caller here has just archived that
+ * stack's only company — bouncing back into it is exactly what the
+ * navigation is escaping.
+ */
+export function cloudPortfolioManageUrl(cloudBaseUrl: string | null | undefined): string | null {
+ return cloudAppUrl(cloudBaseUrl, "/orgs?manage=1");
+}
diff --git a/ui/src/lib/company-selection.test.ts b/ui/src/lib/company-selection.test.ts
index 43f4deb8c50..4eb196be254 100644
--- a/ui/src/lib/company-selection.test.ts
+++ b/ui/src/lib/company-selection.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, it } from "vitest";
-import { resolveArchivedCompanyBounce, shouldSyncCompanySelectionFromRoute } from "./company-selection";
+import {
+ resolveArchivedCompanyBounce,
+ resolveCompanyArchiveDeparture,
+ shouldSyncCompanySelectionFromRoute,
+} from "./company-selection";
describe("shouldSyncCompanySelectionFromRoute", () => {
it("does not resync when selection already matches the route", () => {
@@ -85,3 +89,52 @@ describe("resolveArchivedCompanyBounce", () => {
).toBeNull();
});
});
+
+describe("resolveCompanyArchiveDeparture", () => {
+ const justArchived = { id: "old", name: "Old Co", issuePrefix: "OLD", status: "archived" };
+ const active = { id: "pap", name: "Paperclip", issuePrefix: "PAP", status: "active" };
+ const alsoArchived = { id: "ret", name: "Retail", issuePrefix: "RET", status: "archived" };
+ const portfolioUrl = "https://my.paperclip.app/orgs?manage=1";
+
+ it("switches to another active company when one exists, even on cloud", () => {
+ expect(
+ resolveCompanyArchiveDeparture({
+ archivedCompanyId: "old",
+ companies: [justArchived, alsoArchived, active],
+ cloudPortfolioUrl: portfolioUrl,
+ }),
+ ).toEqual({ kind: "company", company: active });
+ });
+
+ it("never departs into the company that was just archived, whatever its cached status", () => {
+ // The caller's company list is pre-invalidation, so the archived
+ // company can still read "active" there.
+ expect(
+ resolveCompanyArchiveDeparture({
+ archivedCompanyId: "old",
+ companies: [{ ...justArchived, status: "active" }],
+ cloudPortfolioUrl: null,
+ }),
+ ).toEqual({ kind: "companies_list" });
+ });
+
+ it("leaves for the Cloud portfolio when no active company remains", () => {
+ expect(
+ resolveCompanyArchiveDeparture({
+ archivedCompanyId: "old",
+ companies: [justArchived, alsoArchived],
+ cloudPortfolioUrl: portfolioUrl,
+ }),
+ ).toEqual({ kind: "cloud_portfolio", url: portfolioUrl });
+ });
+
+ it("falls back to the companies list on self-hosted instances", () => {
+ expect(
+ resolveCompanyArchiveDeparture({
+ archivedCompanyId: "old",
+ companies: [justArchived],
+ cloudPortfolioUrl: null,
+ }),
+ ).toEqual({ kind: "companies_list" });
+ });
+});
diff --git a/ui/src/lib/company-selection.ts b/ui/src/lib/company-selection.ts
index 43236de27ee..b34e79fb2e6 100644
--- a/ui/src/lib/company-selection.ts
+++ b/ui/src/lib/company-selection.ts
@@ -38,6 +38,38 @@ export function resolveArchivedCompanyBounce(params: {
return selectedActive ?? companies.find((company) => company.status !== "archived") ?? null;
}
+export type CompanyArchiveDeparture =
+ | { kind: "company"; company: BounceCandidateCompany }
+ | { kind: "cloud_portfolio"; url: string }
+ | { kind: "companies_list" };
+
+/**
+ * Decides where the app should take the user after they archive a company
+ * from its own settings page. Staying put is never right: the page they are
+ * on belongs to the company they just archived, and the only visible change
+ * would be the archive button going inert.
+ *
+ * Another active company wins — the user still has somewhere to work, so
+ * switch there (mirroring the cold-arrival bounce above). With no active
+ * company left on a Cloud instance, the whole organization is on its way to
+ * being archived by the control plane, so leave for the Cloud portfolio's
+ * manage view. Self-hosted with nothing active falls back to the companies
+ * list, which shows the archived state and owns the unarchive affordance.
+ */
+export function resolveCompanyArchiveDeparture(params: {
+ archivedCompanyId: string;
+ companies: BounceCandidateCompany[];
+ cloudPortfolioUrl: string | null;
+}): CompanyArchiveDeparture {
+ const { archivedCompanyId, companies, cloudPortfolioUrl } = params;
+ const nextCompany = companies.find(
+ (company) => company.id !== archivedCompanyId && company.status !== "archived",
+ );
+ if (nextCompany) return { kind: "company", company: nextCompany };
+ if (cloudPortfolioUrl) return { kind: "cloud_portfolio", url: cloudPortfolioUrl };
+ return { kind: "companies_list" };
+}
+
export function shouldSyncCompanySelectionFromRoute(params: {
selectionSource: CompanySelectionSource;
selectedCompanyId: string | null;
diff --git a/ui/src/pages/CompanySettings.tsx b/ui/src/pages/CompanySettings.tsx
index 82167d125a7..b095dc1c482 100644
--- a/ui/src/pages/CompanySettings.tsx
+++ b/ui/src/pages/CompanySettings.tsx
@@ -1,4 +1,5 @@
import { ChangeEvent, useEffect, useState } from "react";
+import { useNavigate } from "react-router-dom";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import {
type InteractionResolverGovernance,
@@ -6,7 +7,11 @@ import {
} from "@paperclipai/shared";
import { useCompany } from "../context/CompanyContext";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
+import { useOptionalToastActions } from "../context/ToastContext";
import { useCloudInstance } from "../hooks/useCloudInstance";
+import { resolveCompanyArchiveDeparture } from "../lib/company-selection";
+import { cloudPortfolioManageUrl } from "../lib/cloudLinks";
+import { navigateTopLevel } from "@/lib/browserNavigation";
import { companiesApi } from "../api/companies";
import { assetsApi } from "../api/assets";
import { queryKeys } from "../lib/queryKeys";
@@ -34,9 +39,12 @@ export function CompanySettings() {
} = useCompany();
const { setBreadcrumbs } = useBreadcrumbs();
const queryClient = useQueryClient();
+ const navigate = useNavigate();
+ const toastActions = useOptionalToastActions();
+ const cloud = useCloudInstance();
// Managed instances derive the task ID prefix from the company name, so a
// rename here also renumbers the existing task IDs.
- const isCloudManaged = Boolean(useCloudInstance());
+ const isCloudManaged = Boolean(cloud);
// General settings local state
const [companyName, setCompanyName] = useState("");
const [description, setDescription] = useState("");
@@ -134,16 +142,44 @@ export function CompanySettings() {
}
const archiveMutation = useMutation({
- mutationFn: ({
- companyId,
- nextCompanyId
- }: {
- companyId: string;
- nextCompanyId: string | null;
- }) => companiesApi.archive(companyId).then(() => ({ nextCompanyId })),
- onSuccess: async ({ nextCompanyId }) => {
- if (nextCompanyId) {
- setSelectedCompanyId(nextCompanyId);
+ mutationFn: ({ companyId }: { companyId: string }) =>
+ companiesApi.archive(companyId),
+ onSuccess: async (_result, { companyId }) => {
+ // Never stay on the archived company's settings: the only visible
+ // change would be the archive button going inert. Leave for wherever
+ // still makes sense (another active company, the Cloud portfolio, or
+ // the companies list), with a toast naming what happened.
+ const archived = companies.find((company) => company.id === companyId);
+ const archivedName = archived?.name ?? "Organization";
+ const departure = resolveCompanyArchiveDeparture({
+ archivedCompanyId: companyId,
+ companies,
+ cloudPortfolioUrl: cloudPortfolioManageUrl(cloud?.cloudBaseUrl),
+ });
+ if (departure.kind === "cloud_portfolio") {
+ // The whole organization is on its way to being archived by the
+ // control plane; a full navigation to the Cloud portfolio replaces
+ // this document, so cache invalidation below would never run.
+ navigateTopLevel(departure.url);
+ return;
+ }
+ if (departure.kind === "company") {
+ toastActions?.pushToast({
+ title: `${archivedName} is archived`,
+ body: `Switched to ${departure.company.name}.`,
+ tone: "info",
+ dedupeKey: `company-archive-departure:${companyId}`,
+ });
+ setSelectedCompanyId(departure.company.id);
+ navigate(`/${departure.company.issuePrefix}/dashboard`, { replace: true });
+ } else {
+ toastActions?.pushToast({
+ title: `${archivedName} is archived`,
+ body: "You can unarchive it from this list.",
+ tone: "info",
+ dedupeKey: `company-archive-departure:${companyId}`,
+ });
+ navigate(`/${archived?.issuePrefix ?? ""}/companies`, { replace: true });
}
await queryClient.invalidateQueries({
queryKey: queryKeys.companies.all
@@ -358,16 +394,7 @@ export function CompanySettings() {
`Archive organization "${selectedCompany.name}"? It will be hidden from the sidebar.`
);
if (!confirmed) return;
- const nextCompanyId =
- companies.find(
- (company) =>
- company.id !== selectedCompanyId &&
- company.status !== "archived"
- )?.id ?? null;
- archiveMutation.mutate({
- companyId: selectedCompanyId,
- nextCompanyId
- });
+ archiveMutation.mutate({ companyId: selectedCompanyId });
}}
>
{archiveMutation.isPending
diff --git a/ui/src/pages/CompanySettingsArchive.test.tsx b/ui/src/pages/CompanySettingsArchive.test.tsx
new file mode 100644
index 00000000000..3bac249fd75
--- /dev/null
+++ b/ui/src/pages/CompanySettingsArchive.test.tsx
@@ -0,0 +1,233 @@
+// @vitest-environment jsdom
+
+import { flushSync } from "react-dom";
+import { createRoot } from "react-dom/client";
+import { MemoryRouter, useLocation } from "react-router-dom";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { queryKeys } from "@/lib/queryKeys";
+import { CompanySettings } from "./CompanySettings";
+
+const mockCompaniesApi = vi.hoisted(() => ({
+ update: vi.fn(),
+ archive: vi.fn(),
+}));
+
+const mockAssetsApi = vi.hoisted(() => ({
+ uploadCompanyLogo: vi.fn(),
+}));
+
+const mockSetBreadcrumbs = vi.hoisted(() => vi.fn());
+const mockSetSelectedCompanyId = vi.hoisted(() => vi.fn());
+const mockPushToast = vi.hoisted(() => vi.fn());
+const mockNavigateTopLevel = vi.hoisted(() => vi.fn());
+
+const ARCHIVING_COMPANY = {
+ id: "company-old",
+ name: "Old Co",
+ description: null,
+ status: "active",
+ issuePrefix: "OLD",
+ brandColor: null,
+ logoUrl: null,
+ attachmentMaxBytes: null,
+ requireBoardApprovalForNewAgents: false,
+ interactionResolverGovernance: {},
+};
+
+const SIBLING_COMPANY = {
+ ...ARCHIVING_COMPANY,
+ id: "company-pap",
+ name: "Paperclip",
+ issuePrefix: "PAP",
+};
+
+// Mutable so each test shapes the portfolio the departure resolves against.
+const companyState = vi.hoisted(() => ({
+ companies: [] as unknown[],
+}));
+
+vi.mock("../api/companies", () => ({ companiesApi: mockCompaniesApi }));
+vi.mock("../api/assets", () => ({ assetsApi: mockAssetsApi }));
+
+vi.mock("../context/BreadcrumbContext", () => ({
+ useBreadcrumbs: () => ({ setBreadcrumbs: mockSetBreadcrumbs }),
+}));
+
+vi.mock("../context/ToastContext", () => ({
+ useOptionalToastActions: () => ({ pushToast: mockPushToast }),
+}));
+
+vi.mock("../context/CompanyContext", () => ({
+ useCompany: () => ({
+ companies: companyState.companies,
+ selectedCompany: ARCHIVING_COMPANY,
+ selectedCompanyId: ARCHIVING_COMPANY.id,
+ setSelectedCompanyId: mockSetSelectedCompanyId,
+ }),
+}));
+
+vi.mock("@/lib/browserNavigation", () => ({
+ navigateTopLevel: mockNavigateTopLevel,
+}));
+
+// Both panels below the danger zone own their own queries and are not part
+// of what this test covers.
+vi.mock("../components/InteractionGovernancePanel", () => ({
+ InteractionGovernancePanel: () => null,
+ applyGovernanceChange: (governance: unknown) => governance,
+}));
+
+vi.mock("./InstanceGeneralSettings", () => ({
+ InstanceGeneralSettings: () => null,
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+const CLOUD_HEALTH = {
+ status: "ok" as const,
+ cloud: {
+ managed: true as const,
+ managedBy: "paperclip-cloud" as const,
+ stackSlug: "acme-labs",
+ cloudBaseUrl: "https://cloud.example.test",
+ },
+};
+
+const SELF_HOSTED_HEALTH = { status: "ok" as const, cloud: null };
+
+let observedPath = "";
+
+function LocationProbe() {
+ const location = useLocation();
+ observedPath = `${location.pathname}${location.search}`;
+ return null;
+}
+
+async function flushReact() {
+ await Promise.resolve();
+ await new Promise((resolve) => window.setTimeout(resolve, 0));
+}
+
+async function waitForAssertion(assertion: () => void) {
+ let lastError: unknown;
+ for (let i = 0; i < 20; i += 1) {
+ await flushReact();
+ try {
+ assertion();
+ return;
+ } catch (error) {
+ lastError = error;
+ }
+ }
+ throw lastError;
+}
+
+describe("CompanySettings archive departure", () => {
+ let container: HTMLDivElement;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ mockCompaniesApi.archive.mockResolvedValue({ id: ARCHIVING_COMPANY.id, status: "archived" });
+ vi.spyOn(window, "confirm").mockReturnValue(true);
+ observedPath = "";
+ });
+
+ afterEach(() => {
+ container.remove();
+ document.body.innerHTML = "";
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ function render(health: unknown) {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ // CloudAccessGate owns the health fetch in the app; seeding the cache is
+ // how useCloudInstance sees a managed instance under test.
+ queryClient.setQueryData(queryKeys.health, health);
+ const root = createRoot(container);
+ flushSync(() => {
+ root.render(
+
+
+
+
+
+
+
+ ,
+ );
+ });
+ return root;
+ }
+
+ function clickArchive() {
+ const button = Array.from(container.querySelectorAll("button")).find(
+ (element) => element.textContent?.trim() === "Archive organization",
+ );
+ expect(button).toBeDefined();
+ flushSync(() => {
+ button!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ }
+
+ it("switches to another active company with a toast", async () => {
+ companyState.companies = [ARCHIVING_COMPANY, SIBLING_COMPANY];
+ const root = render(SELF_HOSTED_HEALTH);
+ clickArchive();
+
+ await waitForAssertion(() => {
+ expect(mockCompaniesApi.archive).toHaveBeenCalledWith(ARCHIVING_COMPANY.id);
+ expect(mockSetSelectedCompanyId).toHaveBeenCalledWith(SIBLING_COMPANY.id);
+ expect(observedPath).toBe("/PAP/dashboard");
+ expect(mockPushToast).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: "Old Co is archived",
+ body: "Switched to Paperclip.",
+ }),
+ );
+ expect(mockNavigateTopLevel).not.toHaveBeenCalled();
+ });
+ flushSync(() => root.unmount());
+ });
+
+ it("leaves for the Cloud portfolio's manage view when no active company remains", async () => {
+ companyState.companies = [ARCHIVING_COMPANY];
+ const root = render(CLOUD_HEALTH);
+ clickArchive();
+
+ await waitForAssertion(() => {
+ expect(mockNavigateTopLevel).toHaveBeenCalledWith(
+ "https://cloud.example.test/orgs?manage=1",
+ );
+ // A full navigation replaces the document: no in-app route change and
+ // no company switch.
+ expect(observedPath).toBe("/OLD/company/settings");
+ expect(mockSetSelectedCompanyId).not.toHaveBeenCalled();
+ });
+ flushSync(() => root.unmount());
+ });
+
+ it("falls back to the companies list on self-hosted with nothing active", async () => {
+ companyState.companies = [ARCHIVING_COMPANY];
+ const root = render(SELF_HOSTED_HEALTH);
+ clickArchive();
+
+ await waitForAssertion(() => {
+ expect(observedPath).toBe("/OLD/companies");
+ expect(mockPushToast).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: "Old Co is archived",
+ body: "You can unarchive it from this list.",
+ }),
+ );
+ expect(mockNavigateTopLevel).not.toHaveBeenCalled();
+ });
+ flushSync(() => root.unmount());
+ });
+});
diff --git a/ui/src/pages/CompanySettingsRenameHint.test.tsx b/ui/src/pages/CompanySettingsRenameHint.test.tsx
index 63bdd975681..7fbffec4471 100644
--- a/ui/src/pages/CompanySettingsRenameHint.test.tsx
+++ b/ui/src/pages/CompanySettingsRenameHint.test.tsx
@@ -2,6 +2,7 @@
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
+import { MemoryRouter } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { TooltipProvider } from "@/components/ui/tooltip";
@@ -104,7 +105,9 @@ describe("CompanySettings rename hint", () => {
root.render(
-
+
+
+
,
);