diff --git a/docs-site/docs/product/settings.mdx b/docs-site/docs/product/settings.mdx
index ce23fe8b..af989451 100644
--- a/docs-site/docs/product/settings.mdx
+++ b/docs-site/docs/product/settings.mdx
@@ -13,7 +13,8 @@ spans the whole organization rather than a single run.
Workspace settings and usage meters, backed by `GET /api/config` and
- `GET /api/settings`.
+ `GET /api/settings`. Owners and admins rename the workspace here; members
+ see its name.
The members of the organization.
diff --git a/frontend/app/(workspace)/settings/general-card.interaction.test.tsx b/frontend/app/(workspace)/settings/general-card.interaction.test.tsx
new file mode 100644
index 00000000..c08ce362
--- /dev/null
+++ b/frontend/app/(workspace)/settings/general-card.interaction.test.tsx
@@ -0,0 +1,214 @@
+// The Workspace name row in Settings, General, mounted under happy-dom beside
+// the user menu, with the real team-api and auth helpers over a stubbed fetch:
+// an owner's Save sends the trimmed name to the organisation update route, the
+// row keeps the new name, and the user menu reads the workspace list again
+// without a reload; a refusal shows the server's own words under the field.
+import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
+import { GlobalRegistrator } from "@happy-dom/global-registrator";
+
+if (typeof window === "undefined") GlobalRegistrator.register();
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+mock.module("next/navigation", () => ({
+ useRouter: () => ({ replace: () => {}, push: () => {}, refresh: () => {} }),
+ usePathname: () => "/settings",
+ useSearchParams: () => new URLSearchParams(),
+}));
+
+const { act } = await import("react");
+const { createRoot } = await import("react-dom/client");
+const { GeneralCard } = await import("./general-card");
+const { UserMenu } = await import("@/components/shell/user-menu");
+
+const originalFetch = globalThis.fetch;
+let calls: { path: string; method: string; body: unknown }[] = [];
+let workspaceName = "Ada's workspace";
+let updateReply: () => Response = () => Response.json({ id: "org-1", name: workspaceName });
+/** Holds the rename's answer until the test lets it go. */
+let updateGate: Promise = Promise.resolve();
+
+let root: ReturnType | null = null;
+let container: HTMLElement | null = null;
+
+async function flush() {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+}
+
+async function mount(role: "owner" | "admin" | "member") {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ await act(async () => {
+ root?.render(
+ <>
+
+
+ >,
+ );
+ });
+ await flush();
+}
+
+function field(): HTMLInputElement {
+ const input = container?.querySelector('input[aria-label="Workspace name"]');
+ if (!input) throw new Error("no Workspace name field");
+ return input;
+}
+
+/** The form's submit button, labelled Save, or Saving... while a rename is in flight. */
+function saveButton(): HTMLButtonElement {
+ const button = container?.querySelector('form button[type="submit"]');
+ if (!button) throw new Error("no Save button");
+ return button;
+}
+
+async function type(value: string) {
+ const input = field();
+ await act(async () => {
+ // React tracks the value it last rendered: go through the native setter so
+ // the input event reads as a change.
+ Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")?.set?.call(
+ input,
+ value,
+ );
+ input.dispatchEvent(new window.Event("input", { bubbles: true }));
+ });
+}
+
+async function save() {
+ await act(async () => {
+ saveButton().dispatchEvent(new window.MouseEvent("click", { bubbles: true }));
+ });
+ await flush();
+}
+
+const workspaceReads = () => calls.filter((call) => call.path === "/api/team/workspaces").length;
+
+beforeEach(() => {
+ calls = [];
+ workspaceName = "Ada's workspace";
+ updateReply = () => Response.json({ id: "org-1", name: workspaceName });
+ updateGate = Promise.resolve();
+ globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
+ const path = String(input);
+ const method = init?.method ?? "GET";
+ const body = typeof init?.body === "string" ? JSON.parse(init.body) : undefined;
+ calls.push({ path, method, body });
+ if (path === "/api/auth/get-session") {
+ return Response.json({
+ user: { id: "u1", name: "Ada", email: "ada@example.test", image: null },
+ session: { activeOrganizationId: "org-1" },
+ });
+ }
+ if (path === "/api/team/workspaces") {
+ return Response.json({
+ activeOrganizationId: "org-1",
+ workspaces: [{ id: "org-1", name: workspaceName, role: "owner", members: 2 }],
+ });
+ }
+ if (path === "/api/auth/organization/update") {
+ await updateGate;
+ const reply = updateReply();
+ if (reply.ok) workspaceName = (body as { data: { name: string } }).data.name;
+ return reply;
+ }
+ return new Response("not found", { status: 404 });
+ }) as typeof fetch;
+});
+
+afterEach(async () => {
+ await act(async () => {
+ root?.unmount();
+ });
+ container?.remove();
+ root = null;
+ container = null;
+ globalThis.fetch = originalFetch;
+});
+
+describe("renaming the workspace from Settings", () => {
+ test("an owner saves the trimmed name, the row keeps it, and the user menu reads the list again", async () => {
+ await mount("owner");
+ expect(field().value).toBe("Ada's workspace");
+ expect(saveButton().textContent).toBe("Save");
+ expect(saveButton().disabled).toBe(true);
+ const readsBefore = workspaceReads();
+ expect(readsBefore).toBeGreaterThan(0);
+
+ await type(" Acme Robotics ");
+ expect(saveButton().disabled).toBe(false);
+ await save();
+
+ const update = calls.find((call) => call.path === "/api/auth/organization/update");
+ expect(update?.method).toBe("POST");
+ expect(update?.body).toEqual({ organizationId: "org-1", data: { name: "Acme Robotics" } });
+ expect(container?.querySelector('[role="status"]')?.textContent).toBe("Saved.");
+ expect(field().value).toBe("Acme Robotics");
+ // The saved name is now the row's own: Save stays off until it changes again.
+ expect(saveButton().disabled).toBe(true);
+ // The user menu asked for the workspace list again, and got the new name.
+ expect(workspaceReads()).toBe(readsBefore + 1);
+ });
+
+ test("an admin who is refused sees the server's reason under the field", async () => {
+ updateReply = () =>
+ Response.json(
+ { message: "You are not allowed to update this organization" },
+ { status: 403 },
+ );
+ await mount("admin");
+ const readsBefore = workspaceReads();
+
+ await type("Acme Robotics");
+ await save();
+
+ const alert = container?.querySelector('[role="alert"]');
+ expect(alert?.textContent).toBe("You are not allowed to update this organization");
+ expect(field().getAttribute("aria-invalid")).toBe("true");
+ expect(field().getAttribute("aria-describedby")).toContain(alert?.id ?? "missing");
+ expect(container?.querySelector('[role="status"]')).toBeNull();
+ expect(field().value).toBe("Acme Robotics");
+ // Nothing changed, so nothing reads the list again.
+ expect(workspaceReads()).toBe(readsBefore);
+ });
+
+ test("text typed while the save is in flight stays in the field, without Saved beside it", async () => {
+ let release = () => {};
+ updateGate = new Promise((resolve) => {
+ release = resolve;
+ });
+ await mount("owner");
+ await type("Acme Robotics");
+ await save();
+ expect(saveButton().textContent).toContain("Saving...");
+
+ await type("Acme Robotics Ltd");
+ await act(async () => {
+ release();
+ });
+ await flush();
+
+ expect(field().value).toBe("Acme Robotics Ltd");
+ expect(container?.querySelector('[role="status"]')).toBeNull();
+ // Measured against the name just saved, the new text can be saved in turn.
+ expect(saveButton().disabled).toBe(false);
+ });
+
+ test("a blank or unchanged name is never sent", async () => {
+ await mount("owner");
+ await type(" ");
+ expect(saveButton().disabled).toBe(true);
+ await type(" Ada's workspace ");
+ expect(saveButton().disabled).toBe(true);
+ expect(calls.some((call) => call.path === "/api/auth/organization/update")).toBe(false);
+ });
+
+ test("a member gets the name as text, with nothing to edit", async () => {
+ await mount("member");
+ expect(container?.querySelector('input[aria-label="Workspace name"]')).toBeNull();
+ expect(container?.textContent).toContain("Ada's workspace");
+ });
+});
diff --git a/frontend/app/(workspace)/settings/general-card.test.tsx b/frontend/app/(workspace)/settings/general-card.test.tsx
index eee899a7..46165856 100644
--- a/frontend/app/(workspace)/settings/general-card.test.tsx
+++ b/frontend/app/(workspace)/settings/general-card.test.tsx
@@ -1,9 +1,11 @@
import { expect, test } from "bun:test";
import { renderToStaticMarkup } from "react-dom/server";
-import { GeneralCard } from "./general-card";
+import { activeWorkspace, GeneralCard } from "./general-card";
+
+const acme = { id: "org-1", name: "Acme Robotics" };
test("the General card shows the workspace's own name, as renamed, not a placeholder", () => {
- const html = renderToStaticMarkup();
+ const html = renderToStaticMarkup();
expect(html).toContain("Workspace name");
expect(html).toContain("Acme Robotics");
expect(html).not.toContain(">UseAgent<");
@@ -14,12 +16,32 @@ test("while the workspace list loads the row shows nothing rather than a wrong n
expect(html).toContain("Workspace name");
expect(html).not.toContain("Not set");
expect(html).not.toContain(">UseAgent<");
+ expect(html).not.toContain(" {
+ const html = renderToStaticMarkup();
+ expect(html).toContain(">Acme Robotics
");
+ expect(html).not.toContain("Save<");
});
-import { activeWorkspaceName } from "./general-card";
+test("an owner or an admin gets the name in a field with Save", () => {
+ for (const role of ["owner", "admin"] as const) {
+ const html = renderToStaticMarkup();
+ expect(html).toContain('aria-label="Workspace name"');
+ expect(html).toContain('value="Acme Robotics"');
+ expect(html).toContain(">Save<");
+ expect(html).not.toContain(">Acme Robotics");
+ }
+});
test("a list without the session's workspace is a failed read, not an unset name", () => {
- expect(activeWorkspaceName([{ active: false, name: "Acme" }])).toBeNull();
- expect(activeWorkspaceName([])).toBeNull();
- expect(activeWorkspaceName([{ active: true, name: "Acme" }])).toBe("Acme");
+ expect(activeWorkspace([{ id: "org-1", name: "Acme", role: "owner", active: false }])).toBeNull();
+ expect(activeWorkspace([])).toBeNull();
+ expect(activeWorkspace([{ id: "org-1", name: "Acme", role: "admin", active: true }])).toEqual({
+ id: "org-1",
+ name: "Acme",
+ role: "admin",
+ });
});
diff --git a/frontend/app/(workspace)/settings/general-card.tsx b/frontend/app/(workspace)/settings/general-card.tsx
index 65ecd16b..aa2e2701 100644
--- a/frontend/app/(workspace)/settings/general-card.tsx
+++ b/frontend/app/(workspace)/settings/general-card.tsx
@@ -1,22 +1,28 @@
"use client";
-import { useEffect, useState } from "react";
-import { listWorkspaces, useSession } from "@/lib/auth";
+import { useEffect, useId, useRef, useState } from "react";
+import { Button } from "@/components/base/buttons/button";
+import { InputBase, TextField } from "@/components/base/input/input";
+import { listWorkspaces, useSession, type Workspace, workspacesChanged } from "@/lib/auth";
import { cx } from "@/utils/cx";
+import { canManageTeam, renameWorkspace } from "./team-api";
import { ThemeToggle } from "./theme-toggle";
import { SettingsCard, SettingsRow } from "./settings-rows";
/**
* General card - profile details read from the live better-auth session and
* the workspace's name from the same workspace list the user menu reads, so a
- * rename (the welcome page) shows here. Nothing here is editable, so the
- * values render as text ("Not set" when there is none) rather than as inputs
- * that ignore typing. Client component because ThemeToggle can't cross the
- * server boundary.
+ * rename on the welcome page shows here. Owners and admins rename the
+ * workspace in place; every other value renders as text ("Not set" when there
+ * is none) rather than as an input that ignores typing. Client component
+ * because ThemeToggle can't cross the server boundary.
*/
export const AVATAR_GRADIENT = "bg-gradient-to-br from-purple-400 to-blue-500 text-white";
+/** What the card needs from the workspace the session is in. */
+export type ActiveWorkspace = Pick;
+
/** A read-only value; `null` while the session is still loading. */
function Value({ value }: { value: string | null }) {
if (value === null) return null;
@@ -27,29 +33,122 @@ function Value({ value }: { value: string | null }) {
);
}
-/** The name of the workspace the session is in; null when the list names none,
- * which the card reports as a failed read rather than an unset name. */
-export function activeWorkspaceName(workspaces: readonly { active: boolean; name: string }[]): string | null {
- return workspaces.find((row) => row.active)?.name ?? null;
+/** The workspace the session is in; null when the list names none, which the
+ * card reports as a failed read rather than an unset name. */
+export function activeWorkspace(
+ workspaces: readonly Pick[],
+): ActiveWorkspace | null {
+ const row = workspaces.find((workspace) => workspace.active);
+ return row ? { id: row.id, name: row.name, role: row.role } : null;
+}
+
+/** The rename an owner or admin gets in place: Save sends the trimmed name,
+ * the server's refusal shows under the field, and a saved name tells every
+ * open workspace list (the user menu) to read again. */
+function WorkspaceNameField({
+ workspace,
+ onRenamed,
+}: {
+ workspace: ActiveWorkspace;
+ onRenamed: (name: string) => void;
+}) {
+ const [draft, setDraft] = useState(workspace.name);
+ const [saving, setSaving] = useState(false);
+ const [saved, setSaved] = useState(false);
+ const [error, setError] = useState(null);
+ const errorId = useId();
+ // The field as typed right now, read when a save settles.
+ const typed = useRef(workspace.name);
+ const trimmed = draft.trim();
+ const canSave = trimmed !== "" && trimmed !== workspace.name && !saving;
+
+ const save = async () => {
+ if (!canSave) return;
+ setSaving(true);
+ setError(null);
+ try {
+ await renameWorkspace(workspace.id, trimmed);
+ onRenamed(trimmed);
+ workspacesChanged();
+ // Typing during the save leaves unsaved text in the field: no "Saved"
+ // beside it. Otherwise the field shows the name exactly as saved.
+ if (typed.current.trim() === trimmed) {
+ typed.current = trimmed;
+ setDraft(trimmed);
+ setSaved(true);
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "Could not rename the workspace.");
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+
+ );
}
-export function GeneralCard({ initialWorkspaceName }: { initialWorkspaceName?: string } = {}) {
+export function GeneralCard({ initialWorkspace }: { initialWorkspace?: ActiveWorkspace } = {}) {
const { session, loading } = useSession();
const name = loading ? null : (session?.user.name?.trim() ?? "");
const email = loading ? null : (session?.user.email ?? "");
- /** The active workspace's name; null while it loads. */
- const [workspaceName, setWorkspaceName] = useState(initialWorkspaceName ?? null);
+ /** The active workspace; null while it loads. */
+ const [workspace, setWorkspace] = useState(initialWorkspace ?? null);
const [workspaceFailed, setWorkspaceFailed] = useState(false);
+ const seeded = initialWorkspace !== undefined;
useEffect(() => {
- if (initialWorkspaceName !== undefined) return;
+ if (seeded) return;
let cancelled = false;
listWorkspaces()
.then((workspaces) => {
if (cancelled) return;
- const active = activeWorkspaceName(workspaces);
+ const active = activeWorkspace(workspaces);
if (active === null) setWorkspaceFailed(true);
- else setWorkspaceName(active);
+ else setWorkspace(active);
})
.catch(() => {
if (!cancelled) setWorkspaceFailed(true);
@@ -57,7 +156,7 @@ export function GeneralCard({ initialWorkspaceName }: { initialWorkspaceName?: s
return () => {
cancelled = true;
};
- }, [initialWorkspaceName]);
+ }, [seeded]);
return (
@@ -70,8 +169,16 @@ export function GeneralCard({ initialWorkspaceName }: { initialWorkspaceName?: s
{workspaceFailed ? (
Could not load the workspace.
+ ) : workspace && canManageTeam(workspace.role) ? (
+
+ setWorkspace((current) => (current ? { ...current, name: renamed } : current))
+ }
+ />
) : (
-
+
)}
diff --git a/frontend/components/shell/user-menu.tsx b/frontend/components/shell/user-menu.tsx
index 122ae849..8965f342 100644
--- a/frontend/components/shell/user-menu.tsx
+++ b/frontend/components/shell/user-menu.tsx
@@ -27,6 +27,7 @@ import {
type Session,
type Workspace,
listWorkspaces,
+ onWorkspacesChanged,
signOut,
switchOrganization,
useSession,
@@ -58,6 +59,10 @@ export function UserMenu(props: UserMenuProps = {}) {
const [workspaces, setWorkspaces] = useState();
const [setupPending, setSetupPending] = useState(false);
const [workspaceSwitchError, setWorkspaceSwitchError] = useState(null);
+ /** Bumped when a page here changes the list (a rename in Settings), so the menu reads it again. */
+ const [workspacesVersion, setWorkspacesVersion] = useState(0);
+
+ useEffect(() => onWorkspacesChanged(() => setWorkspacesVersion((version) => version + 1)), []);
useEffect(() => {
if (loading || !session) {
@@ -79,7 +84,7 @@ export function UserMenu(props: UserMenuProps = {}) {
return () => {
cancelled = true;
};
- }, [loading, session]);
+ }, [loading, session, workspacesVersion]);
const profile = sessionUserProfile(session, loading);
return (
diff --git a/frontend/lib/auth.ts b/frontend/lib/auth.ts
index 8d484dc1..e1c3735e 100644
--- a/frontend/lib/auth.ts
+++ b/frontend/lib/auth.ts
@@ -127,6 +127,22 @@ export async function listWorkspaces(
}));
}
+const workspaceListeners = new Set<() => void>();
+
+/** Something here changed what the workspace list says (a rename): every open
+ * reader of it, such as the user menu, reads it again. */
+export function workspacesChanged(): void {
+ for (const listener of workspaceListeners) listener();
+}
+
+/** Called after each `workspacesChanged`; returns the unsubscribe. */
+export function onWorkspacesChanged(listener: () => void): () => void {
+ workspaceListeners.add(listener);
+ return () => {
+ workspaceListeners.delete(listener);
+ };
+}
+
export async function switchOrganization(
organizationId: string,
fetcher: typeof backendFetch = backendFetch,