Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Add account connection settings and SaaS instance management (#7965)

ConnorYohd3687d30cde6
diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/AccountLinkController.java b/app/saas/src/main/java/stirling/software/saas/accountlink/AccountLinkController.java
index 4703c32496..eeb39f107b 100644
--- a/app/saas/src/main/java/stirling/software/saas/accountlink/AccountLinkController.java
+++ b/app/saas/src/main/java/stirling/software/saas/accountlink/AccountLinkController.java
@@ -8,13 +8,18 @@ import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.v3.oas.annotations.Hidden;
+import jakarta.validation.Valid;
+import jakarta.validation.constraints.Size;
+
import lombok.extern.slf4j.Slf4j;
import stirling.software.saas.accountlink.LeaderTeamResolver.LeaderTeam;
@@ -80,4 +85,19 @@ public class AccountLinkController {
boolean ok = service.revoke(lt.teamId(), instanceId);
return ok ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build();
}
+
+ public record RenameRequest(@Size(max = 255) String name) {}
+
+ @PatchMapping("/instances/{instanceId}")
+ public ResponseEntity<Void> rename(
+ @PathVariable Long instanceId,
+ @Valid @RequestBody RenameRequest request,
+ Authentication auth) {
+ LeaderTeam lt = leaderTeams.resolve(auth);
+ if (lt.error() != null) {
+ return ResponseEntity.status(lt.error()).build();
+ }
+ boolean ok = service.rename(lt.teamId(), instanceId, request.name());
+ return ok ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build();
+ }
}
diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/AccountLinkService.java b/app/saas/src/main/java/stirling/software/saas/accountlink/AccountLinkService.java
index fe6a0cc0e6..f9531f170c 100644
--- a/app/saas/src/main/java/stirling/software/saas/accountlink/AccountLinkService.java
+++ b/app/saas/src/main/java/stirling/software/saas/accountlink/AccountLinkService.java
@@ -87,6 +87,14 @@ public class AccountLinkService {
return true;
}
+ /** Updates an owning team's display label; null or blank clears the optional label. */
+ @Transactional
+ public boolean rename(Long teamId, Long instanceId, String name) {
+ return repo.renameForTeam(
+ teamId, instanceId, name == null || name.isBlank() ? null : name.strip())
+ > 0;
+ }
+
/**
* Resolves an active instance from a device credential, or empty if it does not authenticate.
*/
diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstanceRepository.java b/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstanceRepository.java
index dae6a2a69e..384436976d 100644
--- a/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstanceRepository.java
+++ b/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstanceRepository.java
@@ -27,6 +27,16 @@ public interface LinkedInstanceRepository extends JpaRepository<LinkedInstance,
/** Active (non-revoked) linked instances on a team — the orphan guard's count. */
long countByTeamIdAndRevokedAtIsNull(Long teamId);
+ /** Updates only the label so a concurrent credential revocation cannot be overwritten. */
+ @Modifying
+ @Query(
+ "UPDATE LinkedInstance li SET li.name = :name "
+ + "WHERE li.instanceId = :instanceId AND li.teamId = :teamId")
+ int renameForTeam(
+ @Param("teamId") Long teamId,
+ @Param("instanceId") Long instanceId,
+ @Param("name") String name);
+
/**
* Stamps liveness on a single instance. A targeted single-column UPDATE rather than a
* full-entity {@code save}: the auth filter loads the instance outside a transaction, so a full
diff --git a/app/saas/src/test/java/stirling/software/saas/accountlink/AccountLinkControllerTest.java b/app/saas/src/test/java/stirling/software/saas/accountlink/AccountLinkControllerTest.java
index 2a2074b9f0..acc1389385 100644
--- a/app/saas/src/test/java/stirling/software/saas/accountlink/AccountLinkControllerTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/accountlink/AccountLinkControllerTest.java
@@ -108,7 +108,9 @@ class AccountLinkControllerTest {
void list_leader_readsOnlyTheCallersTeam() {
User user = mockUser(42L);
TeamMembership leader = membership(7L, TeamRole.LEADER);
- when(service.list(7L)).thenReturn(List.of());
+ LinkedInstance instance = new LinkedInstance();
+ instance.setName("Production");
+ when(service.list(7L)).thenReturn(List.of(instance));
try (var mocked = org.mockito.Mockito.mockStatic(AuthenticationUtils.class)) {
mocked.when(() -> AuthenticationUtils.getCurrentUser(auth, userRepository))
.thenReturn(user);
@@ -118,6 +120,10 @@ class AccountLinkControllerTest {
ResponseEntity<List<InstanceRow>> resp = controller.list(auth);
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
+ assertThat(resp.getBody())
+ .singleElement()
+ .extracting(InstanceRow::name)
+ .isEqualTo("Production");
// The team comes from the caller's membership, never from the request.
verify(service).list(7L);
}
@@ -157,6 +163,71 @@ class AccountLinkControllerTest {
}
}
+ @Test
+ void rename_nonLeaderReturns403() {
+ User user = mockUser(42L);
+ TeamMembership member = membership(7L, TeamRole.MEMBER);
+ user.setTeam(member.getTeam());
+ when(memberRepo.findByTeamIdAndUserId(7L, 42L)).thenReturn(Optional.of(member));
+ try (var mocked = org.mockito.Mockito.mockStatic(AuthenticationUtils.class)) {
+ mocked.when(() -> AuthenticationUtils.getCurrentUser(auth, userRepository))
+ .thenReturn(user);
+
+ assertThat(
+ controller
+ .rename(
+ 11L,
+ new AccountLinkController.RenameRequest("London"),
+ auth)
+ .getStatusCode())
+ .isEqualTo(HttpStatus.FORBIDDEN);
+ verifyNoInteractions(service);
+ }
+ }
+
+ @Test
+ void rename_usesTheCallersTeamAndReturnsNotFoundForUnownedInstances() {
+ User user = mockUser(42L);
+ TeamMembership leader = membership(7L, TeamRole.LEADER);
+ user.setTeam(leader.getTeam());
+ when(memberRepo.findByTeamIdAndUserId(7L, 42L)).thenReturn(Optional.of(leader));
+ when(service.rename(7L, 11L, "London")).thenReturn(true);
+ try (var mocked = org.mockito.Mockito.mockStatic(AuthenticationUtils.class)) {
+ mocked.when(() -> AuthenticationUtils.getCurrentUser(auth, userRepository))
+ .thenReturn(user);
+
+ assertThat(
+ controller
+ .rename(
+ 11L,
+ new AccountLinkController.RenameRequest("London"),
+ auth)
+ .getStatusCode())
+ .isEqualTo(HttpStatus.NO_CONTENT);
+ assertThat(
+ controller
+ .rename(
+ 99L,
+ new AccountLinkController.RenameRequest("London"),
+ auth)
+ .getStatusCode())
+ .isEqualTo(HttpStatus.NOT_FOUND);
+ verify(service).rename(7L, 11L, "London");
+ }
+ }
+
+ @Test
+ void renameRequest_limitsLabelLengthButAllowsClearingIt() {
+ try (var factory = jakarta.validation.Validation.buildDefaultValidatorFactory()) {
+ var validator = factory.getValidator();
+ assertThat(validator.validate(new AccountLinkController.RenameRequest("a".repeat(256))))
+ .hasSize(1);
+ assertThat(validator.validate(new AccountLinkController.RenameRequest("a".repeat(255))))
+ .isEmpty();
+ assertThat(validator.validate(new AccountLinkController.RenameRequest(null))).isEmpty();
+ }
+ }
+
private static User mockUser(long id) {
User u = new User();
u.setId(id);
diff --git a/app/saas/src/test/java/stirling/software/saas/accountlink/AccountLinkServiceTest.java b/app/saas/src/test/java/stirling/software/saas/accountlink/AccountLinkServiceTest.java
index 3d725b98d6..a8f62db366 100644
--- a/app/saas/src/test/java/stirling/software/saas/accountlink/AccountLinkServiceTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/accountlink/AccountLinkServiceTest.java
@@ -92,6 +92,31 @@ class AccountLinkServiceTest {
verify(repo, never()).save(any());
}
+ @Test
+ void rename_updatesOnlyTheLabelAndAllowsClearingIt() {
+ when(repo.renameForTeam(42L, 11L, "London production")).thenReturn(1);
+ when(repo.renameForTeam(42L, 11L, null)).thenReturn(1);
+
+ assertThat(service.rename(42L, 11L, " London production ")).isTrue();
+ assertThat(service.rename(42L, 11L, " ")).isTrue();
+ verify(repo).renameForTeam(42L, 11L, "London production");
+ verify(repo).renameForTeam(42L, 11L, null);
+ verify(repo, never()).save(any());
+ }
+
+ @Test
+ void rename_cannotChangeAnotherTeamsInstance() {
+ assertThat(service.rename(42L, 11L, "London production")).isFalse();
+ verify(repo).renameForTeam(42L, 11L, "London production");
+ verify(repo, never()).save(any());
+ }
+
+ @Test
+ void rename_unknownInstanceReturnsFalse() {
+ assertThat(service.rename(42L, 404L, "London production")).isFalse();
+ verify(repo, never()).save(any());
+ }
+
private static LinkedInstance instance(Long id, Long teamId, LocalDateTime revokedAt) {
LinkedInstance i = new LinkedInstance();
i.setInstanceId(id);
diff --git a/frontend/editor/.env.proprietary b/frontend/editor/.env.proprietary
index 75ee70ec61..141fe3d4e2 100644
--- a/frontend/editor/.env.proprietary
+++ b/frontend/editor/.env.proprietary
@@ -25,3 +25,6 @@ VITE_SAAS_SUPABASE_ANON_KEY=
# admin's Supabase JWT. Distinct from the local backend (reached same-origin via
# the editor's vite proxy). Absent -> wallet/billing surfaces stay on the mock.
VITE_SAAS_API_URL=https://api2.stirling.com
+
+# Browser destination for cloud account management, including the app base path.
+VITE_SAAS_FRONTEND_URL=https://stirling.com/app
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 529573cbbf..28e32a21a1 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -7254,23 +7254,25 @@ pdfa-2b = "PDF/A-2b"
pdfa-3b = "PDF/A-3b"
[portal.accountLink.card]
-billingNote = "Unattended processing bills against your org wallet."
-eyebrow = "Account link"
-linkButton = "Link your Stirling account"
-linked = "Linked"
-linkedAs = "Linked as {{name}}."
-linkedGeneric = "This instance is linked."
-notLinked = "Not linked"
-title = "Link this org to its Stirling account"
-unlink = "Unlink"
+billingNote = "This server shares your team’s processing allowance in Stirling Cloud."
+connectDescription = "Connect this server to use your team’s processing allowance in Stirling Cloud."
+disconnectBody = "This server will stop using your team’s processing allowance in Stirling Cloud. Your local files stay on this server. To connect again, follow the original connection steps."
+disconnectTitle = "Disconnect this instance?"
+eyebrow = "This instance"
+linkButton = "Connect your Stirling account"
+loading = "Checking account connection"
+notLinked = "Not connected"
+signedInAs = "Signed in to Stirling Cloud as"
+statusError = "Couldn’t check the account connection"
+title = "Stirling Cloud"
+unlink = "Disconnect this instance"
[portal.accountLink.card.error]
-title = "Couldn't link"
+title = "Couldn’t update the connection"
[portal.accountLink.card.loginNotConfigured]
-after = "to enable account linking against the hosted Stirling account. In dev you can simulate sign-in from the link dialog."
-before = "Set"
-title = "SaaS login not configured"
+description = "Ask your server administrator to enable the connection to Stirling Cloud."
+title = "Account connection unavailable"
[portal.accountLink.connect]
close = "Close"
@@ -7331,30 +7333,13 @@ title = "Connecting"
retry = "Try again"
[portal.accountLink.instances]
-active = "Active"
-revoke = "Revoke"
-revoked = "Revoked"
unnamed = "Unnamed instance"
-[portal.accountLink.instances.columns]
-instance = "Instance"
-lastSeen = "Last seen"
-linked = "Linked"
-status = "Status"
-
[portal.accountLink.instances.empty]
-description = "Link this org's account, then register your self-hosted instances to see them here."
-title = "No linked instances"
-
-[portal.accountLink.instances.time]
-daysAgo_one = "{{count}}d ago"
-daysAgo_other = "{{count}}d ago"
-hoursAgo_one = "{{count}}h ago"
-hoursAgo_other = "{{count}}h ago"
-justNow = "just now"
-minutesAgo_one = "{{count}}m ago"
-minutesAgo_other = "{{count}}m ago"
-never = "never"
+description = "Connect a self-hosted server to your team to see it here."
+otherDescription = "This is the only connected instance shown for your team."
+otherTitle = "No other connected instances"
+title = "No connected instances"
[portal.accountLink.modal]
cancel = "Cancel"
@@ -7372,15 +7357,18 @@ before = "Set"
title = "Stirling connection not configured"
[portal.accountLink.panel]
-instancesSub = "Every self-hosted instance registered to this org. Revoke a credential to immediately cut off its unattended access."
-instancesTitle = "Linked instances"
+instancesSub = "Self-hosted servers connected to the same team."
+instancesTitle = "Connected instances"
+manageCloud = "Manage on stirling.com"
+otherInstancesSub = "Other self-hosted servers connected to the same team in Stirling Cloud."
+otherInstancesTitle = "Other connected instances"
revokeError = "Couldn't revoke instance"
-sub = "Link this self-hosted org to its Stirling account so unattended processing bills against your org wallet."
+sub = "Manage this server’s connection to your Stirling Cloud account."
[portal.accountLink.panel.loadError]
-forbidden = "Only the team owner can view the org's linked instances."
-generic = "Couldn't load the team's linked instances. Try again in a moment."
-title = "Couldn't load linked instances"
+forbidden = "Only the team owner can manage connected instances."
+generic = "Your connections could not be checked. Try again."
+title = "Couldn’t load connected instances"
[portal.accountLink.rail]
cta = "Connect"
@@ -9791,7 +9779,7 @@ subtitle = "Anything from your policy runs and your team's editors that needs yo
title = "Review"
[portal.settings.sections]
-account-link = "Account link"
+account-link = "Account connection"
[portal.shell.sidebar]
appEditor = "Editor"
@@ -10870,6 +10858,38 @@ mcp = "MCP Server"
storageSharing = "File Storage & Sharing"
systemSettings = "System Settings"
+[settings.connectedInstances]
+confirmBody = "This revokes the instance’s access to your team in Stirling Cloud. It does not delete local files or remove usage already recorded. To connect again, follow the original connection steps on the instance."
+confirmTitle = "Remove {{name}}?"
+connectedAt = "Connected: {{date}}"
+connectedDate = "Connected"
+connectHelp = "To connect a server, open Settings → Account connection on your self-hosted instance and follow the connection steps."
+copied = "ID copied"
+copyError = "Couldn’t copy the ID. Select it to copy manually."
+copyId = "Copy ID"
+details = "Details"
+displayName = "Display name (optional)"
+editName = "Edit name"
+empty = "No connected instances"
+id = "Instance ID"
+justConnected = "Connected just now"
+lastSeen = "Last seen: {{date}}"
+loadError = "Couldn’t load connected instances"
+loadErrorBody = "Your connections could not be checked. Try again."
+loading = "Loading connected instances"
+ownerOnly = "Only the team owner can manage connected instances."
+remove = "Remove connection"
+removedSuccess = "{{name}} has been disconnected from your team."
+removeError = "Couldn’t remove the connection. Try again."
+renameError = "Couldn’t save the name. Try again."
+retry = "Try again"
+saveName = "Save name"
+subtitle = "Manage the self-hosted servers connected to your team."
+teamNote = "These instances share your team’s processing allowance."
+title = "Connected instances"
+unknown = "Not available"
+yourTeam = "Your team"
+
[settings.connection]
description = "Work locally on this machine or connect the app to a Stirling server."
localDescription = "You are using the local backend without an account. Some tools requiring cloud processing or a self-hosted server are unavailable."
diff --git a/frontend/editor/src/portal-saas/components/settings/accountLinkSettings.test.ts b/frontend/editor/src/portal-saas/components/settings/accountLinkSettings.test.ts
index 5cc64727a1..60d3de1427 100644
--- a/frontend/editor/src/portal-saas/components/settings/accountLinkSettings.test.ts
+++ b/frontend/editor/src/portal-saas/components/settings/accountLinkSettings.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import { accountLinkSettings } from "@portal/components/settings/accountLinkSettings";
describe("accountLinkSettings (SaaS)", () => {
- it("is null — Settings has no account-link section on SaaS", () => {
+ it("omits the self-hosted linking flow on SaaS", () => {
expect(accountLinkSettings).toBeNull();
});
});
diff --git a/frontend/editor/src/portal-saas/components/settings/accountLinkSettings.tsx b/frontend/editor/src/portal-saas/components/settings/accountLinkSettings.tsx
index 556cfe1863..0395510f9a 100644
--- a/frontend/editor/src/portal-saas/components/settings/accountLinkSettings.tsx
+++ b/frontend/editor/src/portal-saas/components/settings/accountLinkSettings.tsx
@@ -2,8 +2,7 @@ import type { AccountLinkSettingsSeam } from "@portal-proprietary/components/set
/**
* SaaS has no account-link concept — the signed-in account IS the SaaS account.
- * Null drops the "Account link" nav item and its panel from the shared settings
- * modal (the portal host treats the seam as optional), so the link-only
- * AccountLinkPanel is never imported into the SaaS bundle.
+ * This seam omits the self-hosted link flow. SaaS settings provide owner-only
+ * connected-instance management through their own navigation and session.
*/
export const accountLinkSettings: AccountLinkSettingsSeam | null = null;
diff --git a/frontend/editor/src/portal/api/link.ts b/frontend/editor/src/portal/api/link.ts
index 0e773f8dc0..12b903c71a 100644
--- a/frontend/editor/src/portal/api/link.ts
+++ b/frontend/editor/src/portal/api/link.ts
@@ -1,10 +1,14 @@
import { apiClient } from "@portal/api/http";
+import type { LinkedInstanceRow } from "@app/types/linkedInstance";
+
+export type { LinkedInstanceRow };
/** Link status for this instance (GET /api/v1/account-link/status). */
export interface LinkStatus {
linked: boolean;
- /** Display name the local backend stored at link time; null when unset. */
- name: string | null;
+ /** Matches the cloud instance row; older status responses may omit it. */
+ deviceId?: string | null;
+ name?: string | null;
}
/** Locally-accrued usage not yet reported to SaaS (GET /api/v1/account-link/usage). */
@@ -30,18 +34,6 @@ export interface FreeTierBalance {
periodEnd: string;
}
-/** A linked instance row (GET /api/v1/account-link/instances). */
-export interface LinkedInstanceRow {
- instanceId: number;
- deviceId: string;
- name: string | null;
- /** ISO timestamp the instance was registered. */
- createdAt: string | null;
- /** ISO timestamp the instance last presented its credential; null if never. */
- lastSeenAt: string | null;
- revoked: boolean;
-}
-
/** Account-link client (combined billing). */
const BASE = "/api/v1/account-link";
diff --git a/frontend/editor/src/portal/components/account-link/AccountLinkPanel.test.tsx b/frontend/editor/src/portal/components/account-link/AccountLinkPanel.test.tsx
new file mode 100644
index 0000000000..9e1a5a6914
--- /dev/null
+++ b/frontend/editor/src/portal/components/account-link/AccountLinkPanel.test.tsx
@@ -0,0 +1,274 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import type { UseAccountLink } from "@portal/hooks/useAccountLink";
+
+const state = vi.hoisted(() => ({
+ fetchInstances: vi.fn(),
+ revokeInstance: vi.fn(),
+ openLinkModal: vi.fn(),
+ refresh: vi.fn(),
+ unlink: vi.fn(),
+ status: { linked: true, name: "Production" } as UseAccountLink["status"],
+ statusError: null as string | null,
+ email: "[email protected]" as string | null,
+}));
+vi.mock("@portal/hooks/useLinkedAccountEmail", () => ({
+ useLinkedAccountEmail: () => state.email,
+}));
+vi.mock("@portal/contexts/AccountLinkContext", () => ({
+ useAccountLinkContext: () => ({
+ loginConfigured: true,
+ status: state.status,
+ statusError: state.statusError,
+ phase: "idle",
+ error: null,
+ unlink: state.unlink,
+ refresh: state.refresh,
+ }),
+}));
+vi.mock("@portal/contexts/UIContext", () => ({
+ useUI: () => ({ openLinkModal: state.openLinkModal }),
+}));
+vi.mock("@portal/api/link", () => ({
+ fetchInstances: state.fetchInstances,
+ revokeInstance: state.revokeInstance,
+}));
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (_key: string, fallback: string, values?: Record<string, unknown>) =>
+ fallback.replace(/\{\{(\w+)\}\}/g, (_, key: string) =>
+ String(values?.[key] ?? ""),
+ ),
+ i18n: { language: "en-US" },
+ }),
+}));
+
+import { AccountLinkPanel } from "@portal/components/account-link/AccountLinkPanel";
+
+const instance = {
+ instanceId: 42,
+ deviceId: "device-42",
+ name: "Production",
+ createdAt: null,
+ lastSeenAt: null,
+ revoked: false,
+};
+function mount() {
+ return render(
+ <MantineProvider>
+ <AccountLinkPanel />
+ </MantineProvider>,
+ );
+}
+
+describe("Self-hosted account connection", () => {
+ beforeEach(() => {
+ vi.stubEnv("VITE_SAAS_FRONTEND_URL", "https://cloud.example/app/");
+ state.fetchInstances.mockReset().mockResolvedValue([instance]);
+ state.revokeInstance.mockReset().mockResolvedValue(undefined);
+ state.openLinkModal.mockReset();
+ state.refresh.mockReset();
+ state.unlink.mockReset();
+ state.status = { linked: true, name: "Production" };
+ state.statusError = null;
+ state.email = "[email protected]";
+ });
+
+ afterEach(() => vi.unstubAllEnvs());
+
+ it("opens cloud management at the configured app path", async () => {
+ await act(async () => {
+ mount();
+ });
+ const manage = screen.getByRole("link", { name: "Manage on stirling.com" });
+ expect(manage).toHaveAttribute(
+ "href",
+ "https://cloud.example/app/settings/account-link",
+ );
+ expect(manage).toHaveAttribute("target", "_blank");
+ expect(manage).toHaveAttribute("rel", "noopener noreferrer");
+ });
+
+ it("identifies this server by device ID while retaining another server with the same name", async () => {
+ state.status = { linked: true, deviceId: "device-42" };
+ state.fetchInstances.mockResolvedValue([
+ instance,
+ { ...instance, instanceId: 43, deviceId: "device-43" },
+ ]);
+ mount();
+ expect(
+ await screen.findByRole("heading", { name: "Production", level: 2 }),
+ ).toBeVisible();
+ expect(
+ screen.getAllByRole("heading", { name: "Production", level: 3 }),
+ ).toHaveLength(1);
+ expect(screen.getByText("device-43")).toBeInTheDocument();
+ expect(screen.queryByText("device-42")).not.toBeInTheDocument();
+ expect(
+ screen.getByRole("heading", { name: "Other connected instances" }),
+ ).toBeVisible();
+ expect(
+ screen.getAllByRole("button", { name: "Remove connection" }),
+ ).toHaveLength(1);
+ });
+
+ it("shows an empty other-instances list when this is the only connected server", async () => {
+ state.status = { linked: true, deviceId: "device-42" };
+ mount();
+ expect(
+ await screen.findByRole("heading", { name: "Production", level: 2 }),
+ ).toBeVisible();
+ expect(screen.getByText("No other connected instances")).toBeVisible();
+ expect(
+ screen.queryByRole("button", { name: "Remove connection" }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Disconnect this instance" }),
+ ).toBeVisible();
+ });
+
+ it("shows instance names and only revokes after confirmation", async () => {
+ state.fetchInstances.mockResolvedValue([
+ instance,
+ { ...instance, instanceId: 99, name: "Old server", revoked: true },
+ ]);
+ mount();
+ expect(
+ await screen.findByRole("heading", { name: "Production", level: 3 }),
+ ).toBeVisible();
+ expect(screen.getByText("device-42")).not.toBeVisible();
+ expect(screen.queryByText("Old server")).not.toBeInTheDocument();
+ expect(screen.queryByText(/Removed connections/)).not.toBeInTheDocument();
+ expect(
+ screen.getByText("Signed in to Stirling Cloud as"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("[email protected]")).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Remove connection" }));
+ const dialog = screen.getByRole("dialog", {
+ name: "Remove Production?",
+ });
+ expect(state.revokeInstance).not.toHaveBeenCalled();
+ fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));
+ expect(state.revokeInstance).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole("button", { name: "Remove connection" }));
+ fireEvent.click(
+ within(screen.getByRole("dialog")).getByRole("button", {
+ name: "Remove connection",
+ }),
+ );
+ await waitFor(() => expect(state.revokeInstance).toHaveBeenCalledWith(42));
+ });
+
+ it("keeps the existing connection flow for a disconnected instance", async () => {
+ state.status = { linked: false, name: null };
+ await act(async () => {
+ mount();
+ });
+ fireEvent.click(
+ screen.getByRole("button", { name: "Connect your Stirling account" }),
+ );
+ expect(state.openLinkModal).toHaveBeenCalledOnce();
+ expect(state.fetchInstances).not.toHaveBeenCalled();
+ });
+
+ it("only disconnects this instance after confirmation", async () => {
+ mount();
+ await screen.findByRole("heading", { name: "Production", level: 3 });
+ fireEvent.click(
+ screen.getByRole("button", { name: "Disconnect this instance" }),
+ );
+ expect(state.unlink).not.toHaveBeenCalled();
+ fireEvent.click(
+ within(screen.getByRole("dialog")).getByRole("button", {
+ name: "Cancel",
+ }),
+ );
+ expect(state.unlink).not.toHaveBeenCalled();
+ fireEvent.click(
+ screen.getByRole("button", { name: "Disconnect this instance" }),
+ );
+ fireEvent.click(
+ within(screen.getByRole("dialog")).getByRole("button", {
+ name: "Disconnect this instance",
+ }),
+ );
+ expect(state.unlink).toHaveBeenCalledOnce();
+ });
+
+ it("shows the connection time until a device has been seen", async () => {
+ state.fetchInstances.mockResolvedValue([
+ { ...instance, createdAt: "2026-09-14T10:00:00Z" },
+ ]);
+ mount();
+ expect(await screen.findByText(/^Connected: /)).toBeVisible();
+ expect(screen.queryByText(/^Last seen:/)).not.toBeInTheDocument();
+ });
+
+ it("shows actual device activity when available", async () => {
+ state.fetchInstances.mockResolvedValue([
+ { ...instance, lastSeenAt: "2026-09-14T10:30:00Z" },
+ ]);
+ mount();
+ expect(await screen.findByText(/^Last seen: /)).toBeVisible();
+ expect(screen.queryByText(/^Connected: /)).not.toBeInTheDocument();
+ });
+
+ it("ages the just-connected label without another request", async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-09-14T10:00:00Z"));
+ state.fetchInstances.mockResolvedValue([
+ { ...instance, createdAt: "2026-09-14T10:00:00Z" },
+ ]);
+ try {
+ await act(async () => {
+ mount();
+ });
+ expect(screen.getByText("Connected just now")).toBeVisible();
+ await act(async () => {
+ vi.advanceTimersByTime(60_000);
+ });
+ expect(screen.queryByText("Connected just now")).not.toBeInTheDocument();
+ expect(screen.getByText(/^Connected: /)).toBeVisible();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("does not offer connection actions before status is known", async () => {
+ state.status = null;
+ await act(async () => {
+ mount();
+ });
+ expect(
+ screen.getByRole("status", { name: "Checking account connection" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /Connect your|Disconnect this/ }),
+ ).not.toBeInTheDocument();
+ expect(state.fetchInstances).not.toHaveBeenCalled();
+ });
+
+ it("offers a status retry without treating a failed read as disconnected", async () => {
+ state.status = null;
+ state.statusError = "Server unavailable";
+ await act(async () => {
+ mount();
+ });
+ expect(
+ screen.getByText("Couldn’t check the account connection"),
+ ).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Try again" }));
+ expect(state.refresh).toHaveBeenCalledOnce();
+ expect(
+ screen.queryByRole("button", { name: "Connect your Stirling account" }),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/editor/src/portal/components/account-link/AccountLinkPanel.tsx b/frontend/editor/src/portal/components/account-link/AccountLinkPanel.tsx
index 48e4a9c562..60eb7cfe4a 100644
--- a/frontend/editor/src/portal/components/account-link/AccountLinkPanel.tsx
+++ b/frontend/editor/src/portal/components/account-link/AccountLinkPanel.tsx
@@ -1,9 +1,10 @@
import { useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
-import { Banner, Skeleton, StatusBadge } from "@app/ui";
+import { Banner, Button, InfoTooltip, Skeleton } from "@app/ui";
+import { Icon } from "@app/ui/Icon";
+import { AccountConnectionLayout } from "@app/components/settings/AccountConnectionLayout";
import { useAsync } from "@portal/hooks/useAsync";
import { useAccountLinkContext } from "@portal/contexts/AccountLinkContext";
-import { useLink, LINK_INFO } from "@portal/contexts/LinkContext";
import { HttpError } from "@portal/api/http";
import {
fetchInstances,
@@ -14,16 +15,10 @@ import { LinkAccountCard } from "@portal/components/account-link/LinkAccountCard
import { LinkedInstancesTable } from "@portal/components/account-link/LinkedInstancesTable";
import "@portal/views/AccountLink.css";
-/**
- * Account-link surface rendered inside the Settings modal (Admin group). Same
- * content as the former /account-link view: the LinkAccountCard for THIS
- * instance + the team-wide LinkedInstancesTable. Lives inline so admins find it
- * intentionally rather than via a top-level sidebar nav entry.
- */
+/** Self-hosted connection status plus the owning team's connected instances. */
export function AccountLinkPanel() {
const { t } = useTranslation();
const link = useAccountLinkContext();
- const { linkState } = useLink();
const linked = link.status?.linked ?? false;
const [reloadKey, setReloadKey] = useState(0);
@@ -38,6 +33,20 @@ export function AccountLinkPanel() {
const [revokingId, setRevokingId] = useState<number | null>(null);
const [revokeError, setRevokeError] = useState<string | null>(null);
+ const deviceId = link.status?.deviceId;
+ const currentInstance = deviceId
+ ? instancesState.data?.find((instance) => instance.deviceId === deviceId)
+ : undefined;
+ const otherInstances = (instancesState.data ?? []).filter(
+ (instance) => !deviceId || instance.deviceId !== deviceId,
+ );
+ const cloudBaseUrl = import.meta.env.VITE_SAAS_FRONTEND_URL?.replace(
+ /\/+$/,
+ "",
+ );
+ const cloudSettingsUrl = cloudBaseUrl
+ ? `${cloudBaseUrl}/settings/account-link`
+ : null;
const revoke = useCallback(async (instance: LinkedInstanceRow) => {
setRevokingId(instance.instanceId);
@@ -53,44 +62,53 @@ export function AccountLinkPanel() {
}, []);
return (
- <div className="portal-link portal-link--in-settings">
- <header className="portal-link__header">
- <div>
- <p className="portal-link__page-sub">
+ <AccountConnectionLayout
+ title={t("portal.settings.sections.account-link", "Account connection")}
+ description={t(
+ "portal.accountLink.panel.sub",
+ "Manage this server’s connection to your Stirling Cloud account.",
+ )}
+ actions={
+ cloudSettingsUrl && (
+ <Button
+ fat
+ as="a"
+ href={cloudSettingsUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ rightSection={<Icon name="external-link" size={20} />}
+ >
{t(
- "portal.accountLink.panel.sub",
- "Link this self-hosted org to its Stirling account so unattended processing bills against your org wallet.",
+ "portal.accountLink.panel.manageCloud",
+ "Manage on stirling.com",
)}
- </p>
- </div>
- <StatusBadge
- tone={
- linkState === "linked-subscribed"
- ? "success"
- : linkState === "linked-free"
- ? "info"
- : "neutral"
- }
- size="md"
- >
- {t(LINK_INFO[linkState].labelKey, LINK_INFO[linkState].labelDefault)}
- </StatusBadge>
- </header>
-
- <LinkAccountCard link={link} />
+ </Button>
+ )
+ }
+ >
+ <LinkAccountCard link={link} instanceName={currentInstance?.name} />
{linked && (
- <section className="portal-link__instances">
+ <section className="account-connection__body">
<div className="portal-link__section-head">
<h2 className="portal-link__section-title">
- {t("portal.accountLink.panel.instancesTitle", "Linked instances")}
- </h2>
- <p className="portal-link__section-sub">
{t(
- "portal.accountLink.panel.instancesSub",
- "Every self-hosted instance registered to this org. Revoke a credential to immediately cut off its unattended access.",
+ deviceId
+ ? "portal.accountLink.panel.otherInstancesTitle"
+ : "portal.accountLink.panel.instancesTitle",
+ deviceId ? "Other connected instances" : "Connected instances",
+ )}
+ </h2>
+ <InfoTooltip
+ label={t(
+ deviceId
+ ? "portal.accountLink.panel.otherInstancesSub"
+ : "portal.accountLink.panel.instancesSub",
+ deviceId
+ ? "Other self-hosted servers connected to the same team in Stirling Cloud."
+ : "Self-hosted servers connected to the same team.",
)}
- </p>
+ />
</div>
{instancesState.loading ? (
<div className="portal-link__skeleton" aria-hidden>
@@ -103,23 +121,33 @@ export function AccountLinkPanel() {
tone="danger"
title={t(
"portal.accountLink.panel.loadError.title",
- "Couldn't load linked instances",
+ "Couldn’t load connected instances",
)}
+ action={
+ <Button
+ variant="secondary"
+ size="sm"
+ onClick={() => setReloadKey((key) => key + 1)}
+ >
+ {t("settings.connectedInstances.retry", "Try again")}
+ </Button>
+ }
>
{instancesState.error instanceof HttpError &&
instancesState.error.status === 403
? t(
"portal.accountLink.panel.loadError.forbidden",
- "Only the team owner can view the org's linked instances.",
+ "Only the team owner can manage connected instances.",
)
: t(
"portal.accountLink.panel.loadError.generic",
- "Couldn't load the team's linked instances. Try again in a moment.",
+ "Your connections could not be checked. Try again.",
)}
</Banner>
) : (
<LinkedInstancesTable
- instances={instancesState.data ?? []}
+ instances={otherInstances}
+ excludingCurrent={Boolean(deviceId)}
onRevoke={revoke}
revokingId={revokingId}
/>
@@ -138,6 +166,6 @@ export function AccountLinkPanel() {
)}
</section>
)}
- </div>
+ </AccountConnectionLayout>
);
}
diff --git a/frontend/editor/src/portal/components/account-link/LinkAccountCard.tsx b/frontend/editor/src/portal/components/account-link/LinkAccountCard.tsx
index af43640905..eb6a88d911 100644
--- a/frontend/editor/src/portal/components/account-link/LinkAccountCard.tsx
+++ b/frontend/editor/src/portal/components/account-link/LinkAccountCard.tsx
@@ -1,58 +1,132 @@
+import { useState } from "react";
+import { Icon } from "@app/ui/Icon";
import { useTranslation } from "react-i18next";
-import { Banner, Button, Card, StatusBadge } from "@app/ui";
+import { Banner, Button, InfoTooltip, Modal, Skeleton } from "@app/ui";
+import "@app/components/settings/AccountConnectionLayout.css";
import type { UseAccountLink } from "@portal/hooks/useAccountLink";
import { useUI } from "@portal/contexts/UIContext";
+import { useLinkedAccountEmail } from "@portal/hooks/useLinkedAccountEmail";
interface Props {
link: UseAccountLink;
+ instanceName?: string | null;
}
-/**
- * Status + actions for THIS instance's account link. The "Link" button opens
- * the single top-level login modal (UIContext.openLinkModal) — never a nested
- * modal. The portal posts the returned JWT to the local backend, which stores
- * the device secret server-side; the secret is never received or rendered here.
- */
-export function LinkAccountCard({ link }: Props) {
+/** Uses the existing top-level connection flow; device credentials stay on the server. */
+export function LinkAccountCard({ link, instanceName }: Props) {
const { t } = useTranslation();
const { openLinkModal } = useUI();
+ const email = useLinkedAccountEmail();
const linking = link.phase === "linking";
const linked = link.status?.linked ?? false;
+ const [confirmDisconnect, setConfirmDisconnect] = useState(false);
+
+ if (link.statusError) {
+ return (
+ <section className="account-connection__team">
+ <Banner
+ tone="danger"
+ title={t(
+ "portal.accountLink.card.statusError",
+ "Couldn’t check the account connection",
+ )}
+ action={
+ <Button
+ variant="secondary"
+ size="sm"
+ onClick={() => void link.refresh()}
+ >
+ {t("settings.connectedInstances.retry", "Try again")}
+ </Button>
+ }
+ >
+ {link.statusError}
+ </Banner>
+ </section>
+ );
+ }
+ if (!link.status) {
+ return (
+ <section
+ className="account-connection__team"
+ role="status"
+ aria-label={t(
+ "portal.accountLink.card.loading",
+ "Checking account connection",
+ )}
+ >
+ <Skeleton height="8rem" />
+ </section>
+ );
+ }
return (
- <Card padding="loose" className="portal-link__card">
+ <section className="account-connection__team portal-link__card">
<div className="portal-link__card-head">
<div>
- <span className="portal-link__eyebrow">
- {t("portal.accountLink.card.eyebrow", "Account link")}
+ <span className="account-connection__eyebrow">
+ {t("portal.accountLink.card.eyebrow", "This instance")}
</span>
- <h2 className="portal-link__title">
- {t(
- "portal.accountLink.card.title",
- "Link this org to its Stirling account",
+ <div className="portal-link__section-head">
+ <h2>
+ {instanceName ??
+ link.status?.name ??
+ t("portal.accountLink.card.title", "Stirling Cloud")}
+ </h2>
+ {linked && (
+ <InfoTooltip
+ label={t(
+ "portal.accountLink.card.billingNote",
+ "This server shares your team’s processing allowance in Stirling Cloud.",
+ )}
+ />
)}
- </h2>
+ </div>
</div>
- <StatusBadge tone={linked ? "success" : "neutral"} size="sm">
- {linked
- ? t("portal.accountLink.card.linked", "Linked")
- : t("portal.accountLink.card.notLinked", "Not linked")}
- </StatusBadge>
+ {!linked && (
+ <span className="portal-link__status">
+ <Icon name="unlink" size={20} />
+ {t("portal.accountLink.card.notLinked", "Not connected")}
+ </span>
+ )}
</div>
- {!link.loginConfigured && (
+ {(email || linked) && (
+ <div className="portal-link__account-row">
+ {email && (
+ <p className="portal-link__account">
+ {t(
+ "portal.accountLink.card.signedInAs",
+ "Signed in to Stirling Cloud as",
+ )}{" "}
+ <strong>{email}</strong>
+ </p>
+ )}
+ {linked && (
+ <Button
+ variant="quiet"
+ accent="neutral"
+ leftSection={<Icon name="unlink" size={20} />}
+ loading={linking}
+ onClick={() => setConfirmDisconnect(true)}
+ >
+ {t("portal.accountLink.card.unlink", "Disconnect this instance")}
+ </Button>
+ )}
+ </div>
+ )}
+
+ {!link.loginConfigured && !linked && (
<Banner
tone="neutral"
title={t(
"portal.accountLink.card.loginNotConfigured.title",
- "SaaS login not configured",
+ "Account connection unavailable",
)}
>
- {t("portal.accountLink.card.loginNotConfigured.before", "Set")}{" "}
- <code>VITE_SUPABASE_URL</code>{" "}
{t(
- "portal.accountLink.card.loginNotConfigured.after",
- "to enable account linking against the hosted Stirling account. In dev you can simulate sign-in from the link dialog.",
+ "portal.accountLink.card.loginNotConfigured.description",
+ "Ask your server administrator to enable the connection to Stirling Cloud.",
)}
</Banner>
)}
@@ -60,47 +134,67 @@ export function LinkAccountCard({ link }: Props) {
{link.error && (
<Banner
tone="danger"
- title={t("portal.accountLink.card.error.title", "Couldn't link")}
+ title={t(
+ "portal.accountLink.card.error.title",
+ "Couldn’t update the connection",
+ )}
>
{link.error}
</Banner>
)}
- {linked ? (
- <div className="portal-link__actions">
- <span className="portal-link__muted">
- {link.status?.name
- ? t("portal.accountLink.card.linkedAs", "Linked as {{name}}.", {
- name: link.status.name,
- })
- : t(
- "portal.accountLink.card.linkedGeneric",
- "This instance is linked.",
- )}{" "}
+ {!linked && (
+ <div className="portal-link__connect">
+ <p>
{t(
- "portal.accountLink.card.billingNote",
- "Unattended processing bills against your org wallet.",
+ "portal.accountLink.card.connectDescription",
+ "Connect this server to use your team’s processing allowance in Stirling Cloud.",
)}
- </span>
- <Button
- variant="secondary"
- accent="danger"
- loading={linking}
- onClick={link.unlink}
- >
- {t("portal.accountLink.card.unlink", "Unlink")}
- </Button>
- </div>
- ) : (
- <div className="portal-link__actions">
+ </p>
<Button loading={linking} onClick={() => openLinkModal()}>
{t(
"portal.accountLink.card.linkButton",
- "Link your Stirling account",
+ "Connect your Stirling account",
)}
</Button>
</div>
)}
- </Card>
+ <Modal
+ open={confirmDisconnect}
+ onClose={() => setConfirmDisconnect(false)}
+ width="sm"
+ title={t(
+ "portal.accountLink.card.disconnectTitle",
+ "Disconnect this instance?",
+ )}
+ footer={
+ <div className="account-connection__actions">
+ <Button
+ variant="secondary"
+ onClick={() => setConfirmDisconnect(false)}
+ data-autofocus
+ >
+ {t("common.cancel", "Cancel")}
+ </Button>
+ <Button
+ accent="danger"
+ onClick={() => {
+ setConfirmDisconnect(false);
+ void link.unlink();
+ }}
+ >
+ {t("portal.accountLink.card.unlink", "Disconnect this instance")}
+ </Button>
+ </div>
+ }
+ >
+ <p>
+ {t(
+ "portal.accountLink.card.disconnectBody",
+ "This server will stop using your team’s processing allowance in Stirling Cloud. Your local files stay on this server. To connect again, follow the original connection steps.",
+ )}
+ </p>
+ </Modal>
+ </section>
);
}
diff --git a/frontend/editor/src/portal/components/account-link/LinkAccountModal.test.tsx b/frontend/editor/src/portal/components/account-link/LinkAccountModal.test.tsx
index 515b740e59..8ed726e3b4 100644
--- a/frontend/editor/src/portal/components/account-link/LinkAccountModal.test.tsx
+++ b/frontend/editor/src/portal/components/account-link/LinkAccountModal.test.tsx
@@ -18,6 +18,9 @@ vi.mock("@portal/auth/saasSupabase", () => ({
// Step 3 reads the connected account's email off this session.
ensureSaasSupabase: () => ({
auth: {
+ onAuthStateChange: () => ({
+ data: { subscription: { unsubscribe: () => {} } },
+ }),
getSession: () =>
Promise.resolve({ data: { session: { user: { email: EMAIL } } } }),
},
@@ -29,6 +32,11 @@ import type { ConnectOutcome } from "@portal/components/account-link/ConnectCall
import { freeWallet } from "@portal/components/billing/walletFixtures";
const AUTHORIZE = "http://localhost:5174/link?request=req-1";
+const deployment = vi.hoisted(() => ({ basePath: "" }));
+vi.mock("@app/constants/app", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@app/constants/app")>()),
+ withBasePath: (path: string) => `${deployment.basePath}${path}`,
+}));
const BENEFITS = "Pipelines, policies, sources and audit";
const GHOST = /Taking you to stirling\.com/;
@@ -68,6 +76,7 @@ describe("LinkAccountModal", () => {
beforeEach(() => {
vi.clearAllMocks();
+ deployment.basePath = "";
fetchWallet.mockResolvedValue(freeWallet);
startConnect.mockResolvedValue({
phase: "PENDING",
@@ -121,7 +130,7 @@ describe("LinkAccountModal", () => {
expect(filledSteps()).toBe(2);
// The backend checks this against the request's Origin header.
expect(startConnect).toHaveBeenCalledWith(
- "localhost",
+ "http://localhost:5173",
"http://localhost:5173/account-link/callback",
);
await waitFor(() => expect(assign).toHaveBeenCalledWith(AUTHORIZE));
@@ -147,6 +156,20 @@ describe("LinkAccountModal", () => {
await waitFor(() => expect(assign).toHaveBeenCalledWith(AUTHORIZE));
});
+ it("names a new connection using its deployment URL without the current route or query", async () => {
+ deployment.basePath = "/pdf";
+ window.location.href =
+ "http://localhost:5173/pdf/settings/account-link?view=account#details";
+ renderModal();
+ click(CONNECT);
+ await waitFor(() =>
+ expect(startConnect).toHaveBeenCalledWith(
+ "http://localhost:5173/pdf",
+ "http://localhost:5173/pdf/account-link/callback",
+ ),
+ );
+ });
+
it("falls back to step 1 with the reason when the handshake cannot start", async () => {
startConnect.mockRejectedValue(new Error("offline"));
diff --git a/frontend/editor/src/portal/components/account-link/LinkedInstancesTable.tsx b/frontend/editor/src/portal/components/account-link/LinkedInstancesTable.tsx
index 910ce957dd..9abc4f7875 100644
--- a/frontend/editor/src/portal/components/account-link/LinkedInstancesTable.tsx
+++ b/frontend/editor/src/portal/components/account-link/LinkedInstancesTable.tsx
@@ -1,116 +1,102 @@
+import { useState } from "react";
import { useTranslation } from "react-i18next";
-import type { TFunction } from "i18next";
-import { column, DataTable, type DataTableColumn, EmptyState } from "@app/ui";
-import type { LinkedInstanceRow } from "@portal/api/link";
+import { Button, EmptyState, Modal } from "@app/ui";
+import { ConnectedInstanceRow } from "@app/components/settings/ConnectedInstanceRow";
+import type { LinkedInstanceRow } from "@app/types/linkedInstance";
interface Props {
instances: LinkedInstanceRow[];
- /** Called when the leader revokes a (non-revoked) instance. */
onRevoke: (instance: LinkedInstanceRow) => void;
- /** instanceId currently being revoked — disables its button + shows progress. */
revokingId?: number | null;
+ excludingCurrent?: boolean;
}
-function relativeTime(iso: string | null, t: TFunction): string {
- if (!iso) return t("portal.accountLink.instances.time.never", "never");
- const diffMs = Date.now() - new Date(iso).getTime();
- const mins = Math.round(diffMs / 60_000);
- if (mins < 1)
- return t("portal.accountLink.instances.time.justNow", "just now");
- if (mins < 60)
- return t("portal.accountLink.instances.time.minutesAgo", "{{count}}m ago", {
- count: mins,
- });
- const hrs = Math.round(mins / 60);
- if (hrs < 24)
- return t("portal.accountLink.instances.time.hoursAgo", "{{count}}h ago", {
- count: hrs,
- });
- return t("portal.accountLink.instances.time.daysAgo", "{{count}}d ago", {
- count: Math.round(hrs / 24),
- });
-}
-
-/** List of linked self-hosted instances with a leader-only revoke action. */
+/** Uses the shared cloud row design while retaining the portal's owner-authorized revoke API. */
export function LinkedInstancesTable({
instances,
onRevoke,
revokingId,
+ excludingCurrent = false,
}: Props) {
const { t } = useTranslation();
- const cols: DataTableColumn<LinkedInstanceRow>[] = [
- column.entity({
- key: "name",
- header: t("portal.accountLink.instances.columns.instance", "Instance"),
- sortable: true,
- primary: (i) =>
- i.name ?? t("portal.accountLink.instances.unnamed", "Unnamed instance"),
- note: (i) => i.deviceId,
- }),
- column.badge({
- key: "status",
- header: t("portal.accountLink.instances.columns.status", "Status"),
- sortable: true,
- get: (i) =>
- i.revoked
- ? {
- tone: "danger",
- label: t("portal.accountLink.instances.revoked", "Revoked"),
- }
- : {
- tone: "success",
- label: t("portal.accountLink.instances.active", "Active"),
- },
- }),
- column.muted({
- key: "lastSeen",
- header: t("portal.accountLink.instances.columns.lastSeen", "Last seen"),
- sortable: true,
- // Sort on the real ISO timestamp, not the "3d ago" label.
- sortBy: (i) => i.lastSeenAt ?? undefined,
- get: (i) => relativeTime(i.lastSeenAt, t),
- }),
- column.muted({
- key: "created",
- header: t("portal.accountLink.instances.columns.linked", "Linked"),
- sortable: true,
- sortBy: (i) => i.createdAt ?? undefined,
- get: (i) => relativeTime(i.createdAt, t),
- }),
- column.actions({
- key: "actions",
- get: (i) =>
- i.revoked
- ? []
- : [
- {
- label: t("portal.accountLink.instances.revoke", "Revoke"),
- tone: "danger",
- loading: revokingId === i.instanceId,
- onClick: () => onRevoke(i),
- },
- ],
- }),
- ];
-
+ const [selected, setSelected] = useState<LinkedInstanceRow | null>(null);
+ const connected = instances.filter((instance) => !instance.revoked);
return (
- <DataTable<LinkedInstanceRow>
- columns={cols}
- rows={instances}
- rowKey={(i) => String(i.instanceId)}
- empty={
+ <>
+ {connected.length > 0 ? (
+ <ul className="account-connection__list">
+ {connected.map((instance) => (
+ <ConnectedInstanceRow
+ key={instance.instanceId}
+ instance={instance}
+ busy={revokingId != null}
+ onRemove={() => setSelected(instance)}
+ />
+ ))}
+ </ul>
+ ) : (
<EmptyState
size="compact"
title={t(
- "portal.accountLink.instances.empty.title",
- "No linked instances",
+ excludingCurrent
+ ? "portal.accountLink.instances.empty.otherTitle"
+ : "portal.accountLink.instances.empty.title",
+ excludingCurrent
+ ? "No other connected instances"
+ : "No connected instances",
)}
description={t(
- "portal.accountLink.instances.empty.description",
- "Link this org's account, then register your self-hosted instances to see them here.",
+ excludingCurrent
+ ? "portal.accountLink.instances.empty.otherDescription"
+ : "portal.accountLink.instances.empty.description",
+ excludingCurrent
+ ? "This is the only connected instance shown for your team."
+ : "Connect a self-hosted server to your team to see it here.",
)}
/>
- }
- />
+ )}
+
+ <Modal
+ open={selected !== null}
+ onClose={() => setSelected(null)}
+ width="sm"
+ title={t(
+ "settings.connectedInstances.confirmTitle",
+ "Remove {{name}}?",
+ {
+ name:
+ selected?.name ??
+ t("portal.accountLink.instances.unnamed", "Unnamed instance"),
+ },
+ )}
+ footer={
+ <div className="account-connection__actions">
+ <Button
+ variant="secondary"
+ onClick={() => setSelected(null)}
+ data-autofocus
+ >
+ {t("common.cancel", "Cancel")}
+ </Button>
+ <Button
+ accent="danger"
+ onClick={() => {
+ if (selected) onRevoke(selected);
+ setSelected(null);
+ }}
+ >
+ {t("settings.connectedInstances.remove", "Remove connection")}
+ </Button>
+ </div>
+ }
+ >
+ <p>
+ {t(
+ "settings.connectedInstances.confirmBody",
+ "This revokes the instance’s access to your team in Stirling Cloud. It does not delete local files or remove usage already recorded. To connect again, follow the original connection steps on the instance.",
+ )}
+ </p>
+ </Modal>
+ </>
);
}
diff --git a/frontend/editor/src/portal/hooks/useConnectHandoff.ts b/frontend/editor/src/portal/hooks/useConnectHandoff.ts
index 1349086085..1b1da16a07 100644
--- a/frontend/editor/src/portal/hooks/useConnectHandoff.ts
+++ b/frontend/editor/src/portal/hooks/useConnectHandoff.ts
@@ -35,7 +35,12 @@ export function useConnectHandoff(reauth: boolean): ConnectHandoff {
).toString();
const status = reauth
? await startReauth(callbackUrl)
- : await startConnect(window.location.hostname, callbackUrl);
+ : await startConnect(
+ new URL(withBasePath("/"), window.location.origin)
+ .toString()
+ .replace(/\/$/, ""),
+ callbackUrl,
+ );
if (status.authorizeUrl) {
window.location.assign(status.authorizeUrl);
return;
diff --git a/frontend/editor/src/portal/hooks/useLinkedAccountEmail.test.ts b/frontend/editor/src/portal/hooks/useLinkedAccountEmail.test.ts
new file mode 100644
index 0000000000..1adac2db84
--- /dev/null
+++ b/frontend/editor/src/portal/hooks/useLinkedAccountEmail.test.ts
@@ -0,0 +1,85 @@
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+type EmailSession = { user: { email: string } } | null;
+const state = vi.hoisted(() => ({
+ configured: true,
+ getSession: vi.fn(),
+ unsubscribe: vi.fn(),
+ listener: null as ((event: string, session: EmailSession) => void) | null,
+}));
+vi.mock("@portal/auth/saasSupabase", () => ({
+ ensureSaasSupabase: () =>
+ state.configured
+ ? {
+ auth: {
+ getSession: state.getSession,
+ onAuthStateChange: (
+ callback: NonNullable<typeof state.listener>,
+ ) => {
+ state.listener = callback;
+ return {
+ data: { subscription: { unsubscribe: state.unsubscribe } },
+ };
+ },
+ },
+ }
+ : null,
+}));
+
+import { useLinkedAccountEmail } from "@portal/hooks/useLinkedAccountEmail";
+
+describe("Current SaaS email", () => {
+ beforeEach(() => {
+ state.configured = true;
+ state.listener = null;
+ state.unsubscribe.mockReset();
+ state.getSession.mockReset().mockResolvedValue({
+ data: { session: { user: { email: "[email protected]" } } },
+ });
+ });
+
+ it("follows account changes and sign-out while the page stays open", async () => {
+ const { result, unmount } = renderHook(useLinkedAccountEmail);
+ await waitFor(() => expect(result.current).toBe("[email protected]"));
+ act(() =>
+ state.listener?.("SIGNED_IN", { user: { email: "[email protected]" } }),
+ );
+ expect(result.current).toBe("[email protected]");
+ act(() => state.listener?.("SIGNED_OUT", null));
+ expect(result.current).toBeNull();
+ unmount();
+ expect(state.unsubscribe).toHaveBeenCalledOnce();
+ });
+
+ it("does not restore an old email when a pending read finishes after sign-out", async () => {
+ let finishRead: (value: {
+ data: { session: EmailSession };
+ }) => void = () => {};
+ state.getSession.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finishRead = resolve;
+ }),
+ );
+ const { result } = renderHook(useLinkedAccountEmail);
+ act(() => state.listener?.("SIGNED_OUT", null));
+ await act(async () =>
+ finishRead({ data: { session: { user: { email: "[email protected]" } } } }),
+ );
+ expect(result.current).toBeNull();
+ });
+
+ it("leaves the email unavailable if the session read fails", async () => {
+ state.getSession.mockRejectedValue(new Error("Session unavailable"));
+ const { result } = await act(async () => renderHook(useLinkedAccountEmail));
+ expect(result.current).toBeNull();
+ });
+
+ it("does not query an unconfigured SaaS client", () => {
+ state.configured = false;
+ const { result } = renderHook(useLinkedAccountEmail);
+ expect(result.current).toBeNull();
+ expect(state.getSession).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/editor/src/portal/hooks/useLinkedAccountEmail.ts b/frontend/editor/src/portal/hooks/useLinkedAccountEmail.ts
index 9ec193e844..6a220fd2d2 100644
--- a/frontend/editor/src/portal/hooks/useLinkedAccountEmail.ts
+++ b/frontend/editor/src/portal/hooks/useLinkedAccountEmail.ts
@@ -2,31 +2,38 @@ import { useEffect, useState } from "react";
import { ensureSaasSupabase } from "@portal/auth/saasSupabase";
/**
- * The email of the linked SaaS account, read from the in-app SaaS Supabase
- * session (the same session the account-link flow establishes). Null when there
- * is no SaaS session — not linked, SaaS Supabase unconfigured, or the attended
- * session has expired — in which case callers treat it as "prefill unavailable"
- * and degrade gracefully.
- *
- * Deliberately does NOT depend on LinkContext: the SaaS flavor has no
- * LinkProvider (see usePortalLinked's SaaS shadow), and this hook is reached from
- * shared procurement code compiled into every flavor.
+ * Current browser SaaS identity, independent of the local server login or connection owner.
+ * Null means no email is available. Tracks sign-in and sign-out without depending on LinkContext.
*/
export function useLinkedAccountEmail(): string | null {
const [email, setEmail] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
+ let sessionChanged = false;
const supabase = ensureSaasSupabase();
if (!supabase) {
setEmail(null);
return;
}
- void supabase.auth.getSession().then(({ data }) => {
- if (!cancelled) setEmail(data.session?.user?.email ?? null);
+ const {
+ data: { subscription },
+ } = supabase.auth.onAuthStateChange((_event, session) => {
+ sessionChanged = true;
+ if (!cancelled) setEmail(session?.user?.email ?? null);
});
+ void supabase.auth
+ .getSession()
+ .then(({ data }) => {
+ if (!cancelled && !sessionChanged)
+ setEmail(data.session?.user?.email ?? null);
+ })
+ .catch(() => {
+ if (!cancelled && !sessionChanged) setEmail(null);
+ });
return () => {
cancelled = true;
+ subscription.unsubscribe();
};
}, []);
diff --git a/frontend/editor/src/portal/views/AccountLink.css b/frontend/editor/src/portal/views/AccountLink.css
index 34afe4d7af..5aed7bb440 100644
--- a/frontend/editor/src/portal/views/AccountLink.css
+++ b/frontend/editor/src/portal/views/AccountLink.css
@@ -1,84 +1,57 @@
-.portal-link {
+.portal-link__card {
display: flex;
flex-direction: column;
- gap: 1.25rem;
- padding: 1.5rem;
- max-width: 72rem;
- margin: 0 auto;
+ gap: 0.875rem;
}
-/* Header */
-.portal-link__header {
+.portal-link__card-head,
+.portal-link__account-row {
display: flex;
- align-items: flex-start;
+ align-items: center;
justify-content: space-between;
gap: 1rem;
+ flex-wrap: wrap;
}
-.portal-link__page-title {
- margin: 0;
- font-size: 1.375rem;
- font-weight: 600;
- color: var(--c-text);
-}
-
-.portal-link__page-sub {
- margin: 0.25rem 0 0;
- font-size: 0.8125rem;
- color: var(--c-text-subtle);
- max-width: 44rem;
-}
-
-/* Link account card */
-.portal-link__card {
+.portal-link__connect {
display: flex;
flex-direction: column;
- gap: 0.875rem;
-}
-
-.portal-link__card-head {
- display: flex;
align-items: flex-start;
- justify-content: space-between;
- gap: 0.75rem;
+ gap: 1rem;
}
-.portal-link__eyebrow {
- display: block;
- font-size: 0.6875rem;
- font-weight: 600;
- text-transform: uppercase;
- letter-spacing: 0.04em;
- color: var(--c-text-subtle);
+.portal-link__account-row > button {
+ margin-left: auto;
}
-.portal-link__title {
- margin: 0.125rem 0 0;
- font-size: 1.125rem;
- font-weight: 600;
- color: var(--c-text);
+.portal-link__account-row p {
+ margin: 0;
+ min-width: 0;
+ flex: 1 1 18rem;
}
-.portal-link__form,
-.portal-link__register {
+.portal-link__section-head {
display: flex;
- flex-direction: column;
- gap: 0.75rem;
+ align-items: center;
+ gap: 0.5rem;
}
-.portal-link__form-actions,
-.portal-link__actions {
- display: flex;
+.portal-link__account {
+ overflow-wrap: anywhere;
+}
+
+.portal-link__status {
+ display: inline-flex;
align-items: center;
- gap: 0.625rem;
- flex-wrap: wrap;
+ gap: 0.375rem;
+ color: var(--c-text-subtle);
+ font-size: 0.75rem;
+ white-space: nowrap;
}
-/* Instances section */
-.portal-link__instances {
- display: flex;
- flex-direction: column;
- gap: 0.875rem;
+.portal-link__account strong {
+ color: var(--c-text);
+ font-weight: 600;
}
.portal-link__section-title {
@@ -88,38 +61,8 @@
color: var(--c-text);
}
-.portal-link__section-sub {
- margin: 0.25rem 0 0;
- font-size: 0.75rem;
- color: var(--c-text-subtle);
- max-width: 44rem;
-}
-
.portal-link__skeleton {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
-
-/* Table cells */
-.portal-link__cell-stack {
- display: flex;
- flex-direction: column;
- gap: 0.125rem;
-}
-
-.portal-link__cell-strong {
- font-weight: 600;
- color: var(--c-text);
-}
-
-.portal-link__device-id {
- font-size: 0.6875rem;
- color: var(--c-text-subtle);
- font-variant-numeric: tabular-nums;
-}
-
-.portal-link__muted {
- color: var(--c-text-subtle);
- font-size: 0.8125rem;
-}
diff --git a/frontend/editor/src/portal/vite-env.d.ts b/frontend/editor/src/portal/vite-env.d.ts
index 894d70ddb3..15ef296ba5 100644
--- a/frontend/editor/src/portal/vite-env.d.ts
+++ b/frontend/editor/src/portal/vite-env.d.ts
@@ -7,6 +7,8 @@ interface ImportMetaEnv {
readonly VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY: string;
/** Hosted SaaS Java backend base URL — attended portal→SaaS reads (wallet, invoices, …) via apiClient.saas with the admin's JWT. */
readonly VITE_SAAS_API_URL: string;
+ /** Hosted web app base URL, including its deployment path. */
+ readonly VITE_SAAS_FRONTEND_URL: string;
/** Stripe publishable key (pk_live_… / pk_test_…) used by embedded Checkout. */
readonly VITE_STRIPE_PUBLISHABLE_KEY: string;
/** URL of the editor app (app switcher + non-admin redirect). See editor/.env.proprietary. */
diff --git a/frontend/editor/src/proprietary/components/settings/AccountConnectionLayout.css b/frontend/editor/src/proprietary/components/settings/AccountConnectionLayout.css
new file mode 100644
index 0000000000..b56df4ee35
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/settings/AccountConnectionLayout.css
@@ -0,0 +1,164 @@
+.account-connection {
+ padding: 1.75rem 2.5rem;
+ color: var(--c-text);
+}
+
+.account-connection__header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ flex-wrap: wrap;
+ gap: 1rem;
+ margin-bottom: 1.5rem;
+}
+
+.account-connection__header h1 {
+ margin: 0;
+ font-size: 1.75rem;
+ font-weight: 700;
+ letter-spacing: -0.01em;
+}
+
+.account-connection__header p,
+.account-connection__team p {
+ margin: 0.25rem 0 0;
+ font-size: 0.875rem;
+ color: var(--c-text-subtle);
+}
+
+.account-connection__sheet {
+ background: var(--c-surface);
+ border: 1px solid var(--c-border-subtle);
+ border-radius: 0.75rem;
+ overflow: hidden;
+}
+
+.account-connection__team,
+.account-connection__body {
+ padding: 1.25rem 1.625rem;
+}
+
+.account-connection__team {
+ border-bottom: 1px solid var(--c-border-subtle);
+}
+
+.account-connection__team h2 {
+ margin: 0;
+ font-size: 1.375rem;
+ font-weight: 700;
+ overflow-wrap: anywhere;
+}
+
+.account-connection__eyebrow {
+ display: block;
+ margin-bottom: 0.625rem;
+ font-size: 0.6875rem;
+ font-weight: 700;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ color: var(--c-text-subtle);
+}
+
+.account-connection__body {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+}
+
+.account-connection__list {
+ list-style: none;
+ padding: 0;
+ margin: 0;
+}
+
+.account-connection__row {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 1rem;
+ padding: 1rem 0;
+}
+
+.account-connection__row + .account-connection__row {
+ border-top: 1px solid var(--c-border-subtle);
+}
+
+.account-connection__identity {
+ min-width: 0;
+ overflow-wrap: anywhere;
+}
+
+.account-connection__identity h3 {
+ margin: 0;
+ font-size: 0.875rem;
+ font-weight: 600;
+}
+
+.account-connection__identity p {
+ margin: 0.25rem 0 0;
+ font-size: 0.75rem;
+ color: var(--c-text-subtle);
+}
+
+.account-connection__name {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 0.5rem;
+ font-size: 0.8125rem;
+}
+
+.account-connection__details {
+ margin-top: 0.5rem;
+ font-size: 0.75rem;
+ color: var(--c-text-subtle);
+}
+
+.account-connection__details summary {
+ cursor: pointer;
+}
+
+.account-connection__details dl {
+ margin: 0.5rem 0 0;
+}
+
+.account-connection__details dl > div {
+ display: flex;
+ align-items: baseline;
+ flex-wrap: wrap;
+ gap: 0.5rem;
+}
+
+.account-connection__details dd {
+ margin: 0;
+ color: var(--c-text);
+}
+
+.account-connection__name-form {
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+ margin-bottom: 1rem;
+}
+
+.account-connection__actions {
+ display: flex;
+ justify-content: flex-end;
+ flex-wrap: wrap;
+ gap: 0.75rem;
+}
+
+@media (max-width: 48rem) {
+ .account-connection {
+ padding: 1.5rem 1rem;
+ }
+
+ .account-connection__team,
+ .account-connection__body {
+ padding: 1.25rem 1rem;
+ }
+
+ .account-connection__row {
+ flex-wrap: wrap;
+ }
+}
diff --git a/frontend/editor/src/proprietary/components/settings/AccountConnectionLayout.tsx b/frontend/editor/src/proprietary/components/settings/AccountConnectionLayout.tsx
new file mode 100644
index 0000000000..a889d99100
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/settings/AccountConnectionLayout.tsx
@@ -0,0 +1,28 @@
+import type { ReactNode } from "react";
+import "@app/components/settings/AccountConnectionLayout.css";
+
+/** Shared settings surface for an instance's account connection and its team's instance list. */
+export function AccountConnectionLayout({
+ title,
+ description,
+ actions,
+ children,
+}: {
+ title: string;
+ description: string;
+ actions?: ReactNode;
+ children: ReactNode;
+}) {
+ return (
+ <div className="account-connection">
+ <header className="account-connection__header">
+ <div>
+ <h1>{title}</h1>
+ <p>{description}</p>
+ </div>
+ {actions}
+ </header>
+ <div className="account-connection__sheet">{children}</div>
+ </div>
+ );
+}
diff --git a/frontend/editor/src/proprietary/components/settings/ConnectedInstanceRow.tsx b/frontend/editor/src/proprietary/components/settings/ConnectedInstanceRow.tsx
new file mode 100644
index 0000000000..a2f82d6bac
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/settings/ConnectedInstanceRow.tsx
@@ -0,0 +1,147 @@
+import { useEffect, useState } from "react";
+import { Icon } from "@app/ui/Icon";
+import { useTranslation } from "react-i18next";
+import { Button } from "@app/ui/Button";
+import type { LinkedInstanceRow } from "@app/types/linkedInstance";
+import "@app/components/settings/AccountConnectionLayout.css";
+
+interface Props {
+ instance: LinkedInstanceRow;
+ busy?: boolean;
+ onRename?: () => void;
+ onRemove: () => void;
+}
+
+/** Active connection identity with optional name editing and collapsed technical details. */
+export function ConnectedInstanceRow({
+ instance,
+ busy,
+ onRename,
+ onRemove,
+}: Props) {
+ const { t, i18n } = useTranslation();
+ const [copyState, setCopyState] = useState<"idle" | "copied" | "error">(
+ "idle",
+ );
+ const [now, setNow] = useState(Date.now);
+ const connectedAt = instance.createdAt
+ ? new Date(instance.createdAt).getTime()
+ : Number.NaN;
+ const justConnected = now >= connectedAt && now - connectedAt < 60_000;
+
+ useEffect(() => {
+ if (instance.lastSeenAt || !justConnected) return;
+ const timeout = window.setTimeout(
+ () => setNow(Date.now()),
+ Math.max(0, connectedAt + 60_000 - Date.now()),
+ );
+ return () => window.clearTimeout(timeout);
+ }, [connectedAt, instance.lastSeenAt, justConnected]);
+ const formatDate = (value: string | null) => {
+ const date = value ? new Date(value) : null;
+ return !date || Number.isNaN(date.getTime())
+ ? t("settings.connectedInstances.unknown", "Not available")
+ : new Intl.DateTimeFormat(i18n.language, {
+ dateStyle: "medium",
+ timeStyle: "short",
+ }).format(date);
+ };
+
+ const copyId = async () => {
+ try {
+ await navigator.clipboard.writeText(instance.deviceId);
+ setCopyState("copied");
+ } catch {
+ setCopyState("error");
+ }
+ };
+
+ return (
+ <li className="account-connection__row">
+ <div className="account-connection__identity">
+ <div className="account-connection__name">
+ <h3>
+ {instance.name ??
+ t("portal.accountLink.instances.unnamed", "Unnamed instance")}
+ </h3>
+ {onRename && (
+ <Button
+ variant="quiet"
+ size="sm"
+ disabled={busy}
+ onClick={onRename}
+ >
+ {t("settings.connectedInstances.editName", "Edit name")}
+ </Button>
+ )}
+ </div>
+ {!instance.revoked && (
+ <p>
+ {instance.lastSeenAt
+ ? t(
+ "settings.connectedInstances.lastSeen",
+ "Last seen: {{date}}",
+ {
+ date: formatDate(instance.lastSeenAt),
+ },
+ )
+ : justConnected
+ ? t(
+ "settings.connectedInstances.justConnected",
+ "Connected just now",
+ )
+ : t(
+ "settings.connectedInstances.connectedAt",
+ "Connected: {{date}}",
+ {
+ date: formatDate(instance.createdAt),
+ },
+ )}
+ </p>
+ )}
+ <details className="account-connection__details">
+ <summary>
+ {t("settings.connectedInstances.details", "Details")}
+ </summary>
+ <dl>
+ <div>
+ <dt>{t("settings.connectedInstances.id", "Instance ID")}</dt>
+ <dd>
+ <code>{instance.deviceId}</code>{" "}
+ <Button variant="quiet" size="sm" onClick={() => void copyId()}>
+ {t("settings.connectedInstances.copyId", "Copy ID")}
+ </Button>
+ </dd>
+ </div>
+ <div>
+ <dt>
+ {t("settings.connectedInstances.connectedDate", "Connected")}
+ </dt>
+ <dd>{formatDate(instance.createdAt)}</dd>
+ </div>
+ </dl>
+ <span role="status">
+ {copyState === "copied"
+ ? t("settings.connectedInstances.copied", "ID copied")
+ : copyState === "error"
+ ? t(
+ "settings.connectedInstances.copyError",
+ "Couldn’t copy the ID. Select it to copy manually.",
+ )
+ : ""}
+ </span>
+ </details>
+ </div>
+ <Button
+ variant="quiet"
+ accent="neutral"
+ leftSection={<Icon name="unlink" size={20} />}
+ size="sm"
+ disabled={busy}
+ onClick={onRemove}
+ >
+ {t("settings.connectedInstances.remove", "Remove connection")}
+ </Button>
+ </li>
+ );
+}
diff --git a/frontend/editor/src/proprietary/components/settings/portalSettingsNav.tsx b/frontend/editor/src/proprietary/components/settings/portalSettingsNav.tsx
index 5b7fedc63a..4fb35f5748 100644
--- a/frontend/editor/src/proprietary/components/settings/portalSettingsNav.tsx
+++ b/frontend/editor/src/proprietary/components/settings/portalSettingsNav.tsx
@@ -102,13 +102,14 @@ export function buildPortalSettingsSections(
if (includeAccountLink && AccountLinkSection) {
workspace.push({
key: "account-link",
- label: t("portal.settings.sections.account-link", "Account link"),
+ label: t("portal.settings.sections.account-link", "Account connection"),
description: t(
"portal.accountLink.panel.sub",
- "Link this self-hosted org to its Stirling account so unattended processing bills against your org wallet.",
+ "Manage this server’s connection to your Stirling Cloud account.",
),
icon: "link-rounded",
component: <AccountLinkSection />,
+ fullBleed: true,
});
}
const groups: ConfigNavSection[] = [
diff --git a/frontend/editor/src/proprietary/types/linkedInstance.ts b/frontend/editor/src/proprietary/types/linkedInstance.ts
new file mode 100644
index 0000000000..813d85cee7
--- /dev/null
+++ b/frontend/editor/src/proprietary/types/linkedInstance.ts
@@ -0,0 +1,10 @@
+/** Team-owned instance returned by GET /api/v1/account-link/instances, including revoked credentials. */
+export interface LinkedInstanceRow {
+ instanceId: number;
+ deviceId: string;
+ name: string | null;
+ createdAt: string | null;
+ /** Last credential-authenticated contact with Stirling; not a heartbeat or online status. */
+ lastSeenAt: string | null;
+ revoked: boolean;
+}
diff --git a/frontend/editor/src/saas/components/settings/ConnectedInstancesSection.test.tsx b/frontend/editor/src/saas/components/settings/ConnectedInstancesSection.test.tsx
new file mode 100644
index 0000000000..121fb115b1
--- /dev/null
+++ b/frontend/editor/src/saas/components/settings/ConnectedInstancesSection.test.tsx
@@ -0,0 +1,277 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { MantineProvider } from "@mantine/core";
+import type { LinkedInstanceRow } from "@app/types/linkedInstance";
+
+const state = vi.hoisted(() => ({
+ get: vi.fn(),
+ post: vi.fn(),
+ patch: vi.fn(),
+ owner: true,
+ loading: false,
+}));
+
+vi.mock("@app/services/apiClient", () => ({
+ default: { get: state.get, post: state.post, patch: state.patch },
+}));
+vi.mock("@app/auth/UseSession", () => ({
+ useAuth: () => ({ user: { id: "owner-1" } }),
+}));
+vi.mock("@app/contexts/SaaSTeamContext", () => ({
+ useSaaSTeam: () => ({
+ currentTeam: { teamId: 7, name: "Northstar Studio" },
+ isTeamLeader: state.owner,
+ loading: state.loading,
+ }),
+}));
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (_key: string, fallback: string, values?: Record<string, unknown>) =>
+ fallback.replace(/\{\{(\w+)\}\}/g, (_, key: string) =>
+ String(values?.[key] ?? ""),
+ ),
+ i18n: { language: "en-US" },
+ }),
+}));
+
+import ConnectedInstancesSection from "@app/components/settings/ConnectedInstancesSection";
+
+const instance: LinkedInstanceRow = {
+ instanceId: 42,
+ deviceId: "server-42",
+ name: "Old office server",
+ createdAt: "2026-06-12T12:00:00Z",
+ lastSeenAt: null,
+ revoked: false,
+};
+
+function mount() {
+ const client = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false, gcTime: 0 },
+ mutations: { retry: false },
+ },
+ });
+ return render(
+ <MantineProvider>
+ <QueryClientProvider client={client}>
+ <ConnectedInstancesSection />
+ </QueryClientProvider>
+ </MantineProvider>,
+ );
+}
+
+describe("Connected instances", () => {
+ beforeEach(() => {
+ state.get.mockReset().mockResolvedValue({ data: [instance] });
+ state.post.mockReset().mockResolvedValue({});
+ state.patch.mockReset().mockResolvedValue({});
+ state.owner = true;
+ state.loading = false;
+ });
+
+ it("lists instances without calling local connection status", async () => {
+ mount();
+ expect(await screen.findByText("Old office server")).toBeInTheDocument();
+ expect(state.get).toHaveBeenCalledTimes(1);
+ expect(state.get).toHaveBeenCalledWith(
+ "/api/v1/account-link/instances",
+ expect.objectContaining({ signal: expect.any(AbortSignal) }),
+ );
+ });
+
+ it("makes no instance requests for members or while ownership is loading", () => {
+ state.owner = false;
+ const { unmount } = mount();
+ expect(
+ screen.getByText("Only the team owner can manage connected instances."),
+ ).toBeInTheDocument();
+ expect(state.get).not.toHaveBeenCalled();
+ unmount();
+ state.owner = true;
+ state.loading = true;
+ mount();
+ expect(state.get).not.toHaveBeenCalled();
+ });
+
+ it("requires confirmation, permits cancellation, and hides removed connections", async () => {
+ mount();
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Remove connection" }),
+ );
+ expect(state.post).not.toHaveBeenCalled();
+ fireEvent.click(
+ within(screen.getByRole("dialog")).getByRole("button", {
+ name: "Cancel",
+ }),
+ );
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ expect(state.post).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole("button", { name: "Remove connection" }));
+ state.get.mockResolvedValue({ data: [{ ...instance, revoked: true }] });
+ fireEvent.click(
+ within(screen.getByRole("dialog")).getByRole("button", {
+ name: "Remove connection",
+ }),
+ );
+ await waitFor(() =>
+ expect(state.post).toHaveBeenCalledWith(
+ "/api/v1/account-link/instances/42/revoke",
+ undefined,
+ { suppressErrorToast: true },
+ ),
+ );
+ expect(
+ await screen.findByText("No connected instances"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText("Removed connections (1)"),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByText("server-42")).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Remove connection" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("keeps a failed removal actionable without marking the instance removed", async () => {
+ state.post.mockRejectedValueOnce(new Error("Unavailable"));
+ mount();
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Remove connection" }),
+ );
+ fireEvent.click(
+ within(screen.getByRole("dialog")).getByRole("button", {
+ name: "Remove connection",
+ }),
+ );
+ expect(
+ await screen.findByText("Couldn’t remove the connection. Try again."),
+ ).toBeInTheDocument();
+ expect(screen.getByText("Old office server")).toBeInTheDocument();
+ expect(
+ screen.queryByText("Removed connections (1)"),
+ ).not.toBeInTheDocument();
+ expect(
+ within(screen.getByRole("dialog")).getByRole("button", {
+ name: "Remove connection",
+ }),
+ ).toBeEnabled();
+ });
+
+ it("shows load failure separately from an empty list and allows retry", async () => {
+ state.get.mockRejectedValueOnce(new Error("Unavailable"));
+ mount();
+ expect(
+ await screen.findByText("Couldn’t load connected instances"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText("No connected instances"),
+ ).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Try again" }));
+ expect(await screen.findByText("Old office server")).toBeInTheDocument();
+ });
+
+ it("respects a server-side ownership denial", async () => {
+ state.get.mockRejectedValue({
+ isAxiosError: true,
+ response: { status: 403 },
+ });
+ mount();
+ expect(
+ await screen.findByText(
+ "Only the team owner can manage connected instances.",
+ ),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Remove connection" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("leads with the name and hides the ID in Details", async () => {
+ mount();
+ expect(
+ await screen.findByRole("heading", { name: "Old office server" }),
+ ).toBeVisible();
+ expect(screen.getByText("server-42")).not.toBeVisible();
+ fireEvent.click(screen.getByText("Details"));
+ expect(screen.getByText("server-42")).toBeVisible();
+ fireEvent.click(screen.getByRole("button", { name: "Remove connection" }));
+ expect(
+ screen.getByRole("dialog", {
+ name: "Remove Old office server?",
+ }),
+ ).toBeInTheDocument();
+ });
+
+ it("edits the instance name", async () => {
+ mount();
+ fireEvent.click(await screen.findByRole("button", { name: "Edit name" }));
+ fireEvent.change(screen.getByLabelText("Display name (optional)"), {
+ target: { value: " London production " },
+ });
+ state.get.mockResolvedValue({
+ data: [{ ...instance, name: "London production" }],
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Save name" }));
+ await waitFor(() =>
+ expect(state.patch).toHaveBeenCalledWith(
+ "/api/v1/account-link/instances/42",
+ { name: "London production" },
+ { suppressErrorToast: true },
+ ),
+ );
+ expect(await screen.findByText("London production")).toBeVisible();
+ expect(
+ screen.getByRole("heading", { name: "London production" }),
+ ).toBeVisible();
+ });
+
+ it("retains a failed name edit for retry", async () => {
+ state.patch.mockRejectedValueOnce(new Error("Unavailable"));
+ mount();
+ fireEvent.click(await screen.findByRole("button", { name: "Edit name" }));
+ fireEvent.change(screen.getByLabelText("Display name (optional)"), {
+ target: { value: "London" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Save name" }));
+ expect(
+ await screen.findByText("Couldn’t save the name. Try again."),
+ ).toBeInTheDocument();
+ expect(screen.getByLabelText("Display name (optional)")).toHaveValue(
+ "London",
+ );
+ expect(screen.getByText("Old office server")).toBeVisible();
+ });
+
+ it("can clear an optional name", async () => {
+ mount();
+ fireEvent.click(await screen.findByRole("button", { name: "Edit name" }));
+ fireEvent.change(screen.getByLabelText("Display name (optional)"), {
+ target: { value: " " },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Save name" }));
+ await waitFor(() =>
+ expect(state.patch).toHaveBeenCalledWith(
+ "/api/v1/account-link/instances/42",
+ { name: null },
+ { suppressErrorToast: true },
+ ),
+ );
+ });
+
+ it("keeps hostname names as plain labels", async () => {
+ state.get.mockResolvedValue({
+ data: [{ ...instance, name: "pdf.example.com" }],
+ });
+ mount();
+ expect(await screen.findByText("pdf.example.com")).toBeVisible();
+ expect(screen.queryByRole("link")).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/editor/src/saas/components/settings/ConnectedInstancesSection.tsx b/frontend/editor/src/saas/components/settings/ConnectedInstancesSection.tsx
new file mode 100644
index 0000000000..3a40fd73c0
--- /dev/null
+++ b/frontend/editor/src/saas/components/settings/ConnectedInstancesSection.tsx
@@ -0,0 +1,371 @@
+import { useId, useState } from "react";
+import { isAxiosError } from "axios";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useTranslation } from "react-i18next";
+import { useAuth } from "@app/auth/UseSession";
+import { useSaaSTeam } from "@app/contexts/SaaSTeamContext";
+import apiClient from "@app/services/apiClient";
+import type { LinkedInstanceRow } from "@app/types/linkedInstance";
+import { Banner, Button, EmptyState, Input, Modal, Skeleton } from "@app/ui";
+import { ConnectedInstanceRow } from "@app/components/settings/ConnectedInstanceRow";
+import { AccountConnectionLayout } from "@app/components/settings/AccountConnectionLayout";
+
+const BASE = "/api/v1/account-link/instances";
+
+function InstanceList({ userId, teamId }: { userId: string; teamId: number }) {
+ const { t } = useTranslation();
+ const queryClient = useQueryClient();
+ const queryKey = ["connected-instances", userId, teamId];
+ const [selected, setSelected] = useState<LinkedInstanceRow | null>(null);
+ const [removedName, setRemovedName] = useState<string | null>(null);
+ const [editing, setEditing] = useState<LinkedInstanceRow | null>(null);
+ const [name, setName] = useState("");
+ const nameFormId = useId();
+ const instances = useQuery({
+ queryKey,
+ queryFn: async ({ signal }) => {
+ const response = await apiClient.get<LinkedInstanceRow[]>(BASE, {
+ signal,
+ suppressErrorToast: true,
+ });
+ return response.data;
+ },
+ retry: false,
+ });
+ const removal = useMutation({
+ mutationFn: async (instance: LinkedInstanceRow) => {
+ await apiClient.post(`${BASE}/${instance.instanceId}/revoke`, undefined, {
+ suppressErrorToast: true,
+ });
+ },
+ onSuccess: async (_, instance) => {
+ await queryClient.cancelQueries({ queryKey });
+ queryClient.setQueryData<LinkedInstanceRow[]>(queryKey, (rows) =>
+ rows?.map((row) =>
+ row.instanceId === instance.instanceId
+ ? { ...row, revoked: true }
+ : row,
+ ),
+ );
+ setSelected(null);
+ setRemovedName(
+ instance.name ??
+ t("portal.accountLink.instances.unnamed", "Unnamed instance"),
+ );
+ void queryClient.invalidateQueries({ queryKey });
+ },
+ });
+
+ const rename = useMutation({
+ mutationFn: async ({
+ instance,
+ name,
+ }: {
+ instance: LinkedInstanceRow;
+ name: string | null;
+ }) => {
+ await apiClient.patch(
+ `${BASE}/${instance.instanceId}`,
+ { name },
+ { suppressErrorToast: true },
+ );
+ },
+ onSuccess: async (_, { instance, name }) => {
+ await queryClient.cancelQueries({ queryKey });
+ queryClient.setQueryData<LinkedInstanceRow[]>(queryKey, (rows) =>
+ rows?.map((row) =>
+ row.instanceId === instance.instanceId ? { ...row, name } : row,
+ ),
+ );
+ setEditing(null);
+ void queryClient.invalidateQueries({ queryKey });
+ },
+ });
+
+ const connected =
+ instances.data?.filter((instance) => !instance.revoked) ?? [];
+ const forbidden =
+ isAxiosError(instances.error) && instances.error.response?.status === 403;
+ const removalForbidden =
+ isAxiosError(removal.error) && removal.error.response?.status === 403;
+ const renameForbidden =
+ isAxiosError(rename.error) && rename.error.response?.status === 403;
+ const closeRename = () => {
+ if (rename.isPending) return;
+ setEditing(null);
+ rename.reset();
+ };
+
+ const close = () => {
+ if (removal.isPending) return;
+ setSelected(null);
+ removal.reset();
+ };
+
+ return (
+ <>
+ {removedName && (
+ <Banner tone="success">
+ {t(
+ "settings.connectedInstances.removedSuccess",
+ "{{name}} has been disconnected from your team.",
+ { name: removedName },
+ )}
+ </Banner>
+ )}
+ {instances.isPending ? (
+ <div
+ role="status"
+ aria-label={t(
+ "settings.connectedInstances.loading",
+ "Loading connected instances",
+ )}
+ >
+ <Skeleton height="8rem" />
+ </div>
+ ) : instances.isError ? (
+ <Banner
+ tone="danger"
+ title={t(
+ "settings.connectedInstances.loadError",
+ "Couldn’t load connected instances",
+ )}
+ action={
+ <Button
+ variant="secondary"
+ size="sm"
+ onClick={() => void instances.refetch()}
+ loading={instances.isFetching}
+ >
+ {t("settings.connectedInstances.retry", "Try again")}
+ </Button>
+ }
+ >
+ {forbidden
+ ? t(
+ "settings.connectedInstances.ownerOnly",
+ "Only the team owner can manage connected instances.",
+ )
+ : t(
+ "settings.connectedInstances.loadErrorBody",
+ "Your connections could not be checked. Try again.",
+ )}
+ </Banner>
+ ) : (
+ <>
+ {connected.length === 0 ? (
+ <EmptyState
+ size="compact"
+ title={t(
+ "settings.connectedInstances.empty",
+ "No connected instances",
+ )}
+ description={t(
+ "settings.connectedInstances.connectHelp",
+ "To connect a server, open Settings → Account connection on your self-hosted instance and follow the connection steps.",
+ )}
+ />
+ ) : (
+ <ul className="account-connection__list">
+ {connected.map((instance) => (
+ <ConnectedInstanceRow
+ key={instance.instanceId}
+ instance={instance}
+ busy={removal.isPending || rename.isPending}
+ onRemove={() => {
+ removal.reset();
+ setSelected(instance);
+ }}
+ onRename={() => {
+ rename.reset();
+ setEditing(instance);
+ setName(instance.name ?? "");
+ }}
+ />
+ ))}
+ </ul>
+ )}
+ </>
+ )}
+ <Modal
+ open={selected !== null}
+ onClose={close}
+ width="sm"
+ title={t(
+ "settings.connectedInstances.confirmTitle",
+ "Remove {{name}}?",
+ {
+ name:
+ selected?.name ??
+ t("portal.accountLink.instances.unnamed", "Unnamed instance"),
+ },
+ )}
+ disableBackdropClose={removal.isPending}
+ disableEscapeClose={removal.isPending}
+ footer={
+ <div className="account-connection__actions">
+ <Button
+ variant="secondary"
+ onClick={close}
+ disabled={removal.isPending}
+ data-autofocus
+ >
+ {t("common.cancel", "Cancel")}
+ </Button>
+ <Button
+ accent="danger"
+ loading={removal.isPending}
+ onClick={() => {
+ if (selected && !removal.isPending) removal.mutate(selected);
+ }}
+ >
+ {t("settings.connectedInstances.remove", "Remove connection")}
+ </Button>
+ </div>
+ }
+ >
+ <p>
+ {t(
+ "settings.connectedInstances.confirmBody",
+ "This revokes the instance’s access to your team in Stirling Cloud. It does not delete local files or remove usage already recorded. To connect again, follow the original connection steps on the instance.",
+ )}
+ </p>
+ {removal.isError && (
+ <Banner tone="danger">
+ {removalForbidden
+ ? t(
+ "settings.connectedInstances.ownerOnly",
+ "Only the team owner can manage connected instances.",
+ )
+ : t(
+ "settings.connectedInstances.removeError",
+ "Couldn’t remove the connection. Try again.",
+ )}
+ </Banner>
+ )}
+ </Modal>
+ <Modal
+ open={editing !== null}
+ onClose={closeRename}
+ width="sm"
+ title={t("settings.connectedInstances.editName", "Edit name")}
+ disableBackdropClose={rename.isPending}
+ disableEscapeClose={rename.isPending}
+ footer={
+ <div className="account-connection__actions">
+ <Button
+ variant="secondary"
+ onClick={closeRename}
+ disabled={rename.isPending}
+ >
+ {t("common.cancel", "Cancel")}
+ </Button>
+ <Button
+ type="submit"
+ form={nameFormId}
+ loading={rename.isPending}
+ disabled={name.trim() === (editing?.name ?? "")}
+ >
+ {t("settings.connectedInstances.saveName", "Save name")}
+ </Button>
+ </div>
+ }
+ >
+ <form
+ id={nameFormId}
+ onSubmit={(event) => {
+ event.preventDefault();
+ if (editing && !rename.isPending)
+ rename.mutate({ instance: editing, name: name.trim() || null });
+ }}
+ className="account-connection__name-form"
+ >
+ <label htmlFor={`${nameFormId}-input`}>
+ {t(
+ "settings.connectedInstances.displayName",
+ "Display name (optional)",
+ )}
+ </label>
+ <Input
+ id={`${nameFormId}-input`}
+ value={name}
+ maxLength={255}
+ onChange={(event) => setName(event.target.value)}
+ disabled={rename.isPending}
+ data-autofocus
+ />
+ </form>
+ {rename.isError && (
+ <Banner tone="danger">
+ {renameForbidden
+ ? t(
+ "settings.connectedInstances.ownerOnly",
+ "Only the team owner can manage connected instances.",
+ )
+ : t(
+ "settings.connectedInstances.renameError",
+ "Couldn’t save the name. Try again.",
+ )}
+ </Banner>
+ )}
+ </Modal>
+ </>
+ );
+}
+
+/** Owner-only cloud management; no access to a linked self-hosted server is required. */
+export default function ConnectedInstancesSection() {
+ const { t } = useTranslation();
+ const { user } = useAuth();
+ const { currentTeam, isTeamLeader, loading } = useSaaSTeam();
+
+ return (
+ <AccountConnectionLayout
+ title={t("settings.connectedInstances.title", "Connected instances")}
+ description={t(
+ "settings.connectedInstances.subtitle",
+ "Manage the self-hosted servers connected to your team.",
+ )}
+ >
+ {loading ? (
+ <Skeleton height="8rem" />
+ ) : !user || !isTeamLeader || !currentTeam ? (
+ <EmptyState
+ size="compact"
+ title={t(
+ "settings.connectedInstances.ownerOnly",
+ "Only the team owner can manage connected instances.",
+ )}
+ />
+ ) : (
+ <>
+ <section className="account-connection__team">
+ <span className="account-connection__eyebrow">
+ {t("settings.connectedInstances.yourTeam", "Your team")}
+ </span>
+ <h2>{currentTeam.name}</h2>
+ <p>
+ {t(
+ "settings.connectedInstances.teamNote",
+ "These instances share your team’s processing allowance.",
+ )}
+ </p>
+ </section>
+ <section
+ className="account-connection__body"
+ aria-label={t(
+ "settings.connectedInstances.title",
+ "Connected instances",
+ )}
+ >
+ <InstanceList
+ key={`${user.id}:${currentTeam.teamId}`}
+ userId={user.id}
+ teamId={currentTeam.teamId}
+ />
+ </section>
+ </>
+ )}
+ </AccountConnectionLayout>
+ );
+}
diff --git a/frontend/editor/src/saas/components/settings/useSettingsNav.test.tsx b/frontend/editor/src/saas/components/settings/useSettingsNav.test.tsx
new file mode 100644
index 0000000000..7ec450f296
--- /dev/null
+++ b/frontend/editor/src/saas/components/settings/useSettingsNav.test.tsx
@@ -0,0 +1,83 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { renderHook } from "@testing-library/react";
+
+const state = vi.hoisted(() => ({
+ owner: true,
+ loading: false,
+ portalAccess: false,
+}));
+
+vi.mock("@app/auth/UseSession", () => ({
+ useAuth: () => ({ user: { id: "owner-1" }, signOut: vi.fn() }),
+}));
+vi.mock("@app/contexts/SaaSTeamContext", () => ({
+ useSaaSTeam: () => ({ isTeamLeader: state.owner, loading: state.loading }),
+}));
+vi.mock("@app/hooks/usePortalAccess", () => ({
+ usePortalAccessState: () => ({ granted: state.portalAccess, settled: true }),
+}));
+vi.mock("@app/auth/supabase", () => ({ isUserAnonymous: () => false }));
+vi.mock("@app/components/shared/config/configSections/Overview", () => ({
+ default: () => null,
+}));
+vi.mock("@app/components/shared/config/saasConfigNavSections", () => ({
+ createSaasConfigNavSections: () => [],
+}));
+vi.mock("@app/components/settings/portalSettingsNav", () => ({
+ buildPortalSettingsSections: () => [
+ {
+ id: "workspace",
+ title: "Workspace",
+ items: [
+ {
+ key: "billing",
+ label: "Billing",
+ icon: "payments-rounded",
+ component: null,
+ },
+ ],
+ },
+ ],
+ PORTAL_SECTION_ALIASES: {},
+ PORTAL_SUPERSEDED_SECTION_KEYS: [],
+}));
+
+import { useSettingsNav } from "@app/components/settings/useSettingsNav";
+
+describe("Connected instances settings navigation", () => {
+ beforeEach(() => {
+ state.owner = true;
+ state.loading = false;
+ state.portalAccess = false;
+ });
+
+ it.each([false, true])(
+ "offers management to owners with Processor access = %s",
+ (portalAccess) => {
+ state.portalAccess = portalAccess;
+ const { result } = renderHook(() => useSettingsNav(vi.fn()));
+ expect(
+ result.current.sections
+ .flatMap((section) => section.items)
+ .filter((item) => item.key === "account-link"),
+ ).toHaveLength(1);
+ },
+ );
+
+ it.each([
+ { owner: false, loading: false },
+ { owner: true, loading: true },
+ ])(
+ "hides management until ownership is established: %o",
+ ({ owner, loading }) => {
+ state.owner = owner;
+ state.loading = loading;
+ const { result } = renderHook(() => useSettingsNav(vi.fn()));
+ expect(
+ result.current.sections
+ .flatMap((section) => section.items)
+ .some((item) => item.key === "account-link"),
+ ).toBe(false);
+ },
+ );
+});
diff --git a/frontend/editor/src/saas/components/settings/useSettingsNav.tsx b/frontend/editor/src/saas/components/settings/useSettingsNav.tsx
index 58f54aed96..1a5e48b2af 100644
--- a/frontend/editor/src/saas/components/settings/useSettingsNav.tsx
+++ b/frontend/editor/src/saas/components/settings/useSettingsNav.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useMemo, useState } from "react";
+import { Suspense, lazy, useCallback, useMemo, useState } from "react";
import { Modal, Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Button } from "@app/ui/Button";
@@ -16,6 +16,12 @@ import {
PORTAL_SUPERSEDED_SECTION_KEYS,
} from "@app/components/settings/portalSettingsNav";
import { mergeSettingsGroups } from "@app/components/settings/mergeSettingsGroups";
+import { useSaaSTeam } from "@app/contexts/SaaSTeamContext";
+import { LoadingFallback } from "@app/components/shared/LoadingFallback";
+
+const ConnectedInstancesSection = lazy(
+ () => import("@app/components/settings/ConnectedInstancesSection"),
+);
export type { SettingsNav };
@@ -29,6 +35,7 @@ export type { SettingsNav };
export function useSettingsNav(onLeave: () => void): SettingsNav {
const { t } = useTranslation();
const { signOut, user } = useAuth();
+ const { isTeamLeader, loading: teamLoading } = useSaaSTeam();
// Not from useAuth: the editor's Supabase context never carries permission
// flags, so only this seam knows. The processor has its own auth context.
const { granted: portalAccess, settled: accessSettled } =
@@ -38,11 +45,40 @@ export function useSettingsNav(onLeave: () => void): SettingsNav {
const isAnonymous = user ? isUserAnonymous(user) : false;
const sections = useMemo(() => {
- const own = createSaasConfigNavSections(Overview, openLogoutConfirm, {
+ let own = createSaasConfigNavSections(Overview, openLogoutConfirm, {
isAnonymous,
t,
onRequestClose: onLeave,
});
+ if (isTeamLeader && !teamLoading && !isAnonymous) {
+ own = mergeSettingsGroups(
+ own,
+ [
+ {
+ id: "workspace",
+ title: t("settings.workspace.title", "Workspace"),
+ mergeAt: "append",
+ items: [
+ {
+ key: "account-link",
+ label: t(
+ "settings.connectedInstances.title",
+ "Connected instances",
+ ),
+ icon: "link-rounded",
+ fullBleed: true,
+ component: (
+ <Suspense fallback={<LoadingFallback />}>
+ <ConnectedInstancesSection />
+ </Suspense>
+ ),
+ },
+ ],
+ },
+ ],
+ [],
+ );
+ }
if (!portalAccess) return own;
const portal = buildPortalSettingsSections(t, {
includeAccountLink: false,
@@ -50,7 +86,15 @@ export function useSettingsNav(onLeave: () => void): SettingsNav {
});
if (portal.length === 0) return own;
return mergeSettingsGroups(own, portal, PORTAL_SUPERSEDED_SECTION_KEYS);
- }, [openLogoutConfirm, isAnonymous, t, onLeave, portalAccess]);
+ }, [
+ openLogoutConfirm,
+ isAnonymous,
+ t,
+ onLeave,
+ portalAccess,
+ isTeamLeader,
+ teamLoading,
+ ]);
const overlay = (
<Modal
@@ -90,6 +134,6 @@ export function useSettingsNav(onLeave: () => void): SettingsNav {
sections,
overlay,
aliases: portalAccess ? PORTAL_SECTION_ALIASES : undefined,
- pending: !accessSettled,
+ pending: !accessSettled || teamLoading,
};
}