diff --git a/.changeset/34591-org-menu-posture.md b/.changeset/34591-org-menu-posture.md new file mode 100644 index 00000000000..9c3a1810f0b --- /dev/null +++ b/.changeset/34591-org-menu-posture.md @@ -0,0 +1,20 @@ +--- +'@object-ui/app-shell': patch +--- + +feat(app-shell): the avatar menu's organization entries follow the deployment posture, and the organization switcher moves into the avatar menu + +Clause-②: no +Metadata-protocol: none + +The avatar menu reads the deployment signals the server already serves on `GET /api/v1/auth/config` (`features.multiOrgEnabled`, `features.cloudManaged`, `features.tenancyPosture`) and offers organization entries by them: + +- **Single-tenant** (`multiOrgEnabled` false, the `single` posture): no organization entry at all, and no organization switcher. Member management for the one organization stays at Setup → Organization. +- **Multi-organization**: "My Organizations" and "Create organization"; "Switch organization" joins them only when the member belongs to two or more organizations. +- **Cloud-managed** (`cloudManaged` true): no "Create organization"; organizations are created on the cloud there. + +A server that serves none of these flags reads the spec's defaults (multi-organization on, not managed), which is the menu as it was. + +The organization switcher no longer sits at the left of the top bar, which now holds only the product mark and the app switcher. It is the avatar menu's "Switch organization" submenu. Under the `group` posture it still names the working organization (the write target) and says that views show data from every organization the member belongs to (ADR-0105). On a walled posture (`group` or `isolated`) the top bar still names the active organization, read-only, now at any membership count (before, only at exactly one), so a member of two or more organizations still sees which organization lists are scoped to; the name is also shown under "My Organizations". The switcher's own "Manage members" and "Create organization" items are gone: "My Organizations" and the menu's own create entry lead to the same pages. Inside the ObjectStack mobile shell, the top-bar button that opens the shell's native connection switcher is unchanged. + +There is no Setup setting for this menu. diff --git a/ui/packages/app-shell/src/hooks/useOrgMenuPosture.ts b/ui/packages/app-shell/src/hooks/useOrgMenuPosture.ts new file mode 100644 index 00000000000..4cd0c977163 --- /dev/null +++ b/ui/packages/app-shell/src/hooks/useOrgMenuPosture.ts @@ -0,0 +1,115 @@ +/** + * useOrgMenuPosture — which organization entries the avatar menu offers, read + * from the deployment signals the server already serves on `GET /auth/config` + * (objectstack-ai/objectstack#34591, ruling 6937513776): + * + * - `features.multiOrgEnabled` — the multi-organization capability flag. The + * server derives it from the effective tenancy posture (`false` on `single`, + * and on a degraded deployment that asked for isolation but has none), and + * the spec says the console offers creating, switching and leaving + * organizations only when it is on. It is default-on: absent reads as on. + * - `features.cloudManaged` — the cloud's control plane runs this environment. + * Organizations are created on the cloud there, so the console offers no + * create entry; the cloud adds its own entries through the existing + * `manifest.navigationContributions` path, never through this menu. Absent + * reads as not managed. + * - `features.tenancyPosture` — how to render organization context (ADR-0105 + * D1): under `group` the switcher picks the WRITE target, so it says so. + * + * There is no Setup override: the menu follows the served signals alone (the + * ruling drops the card's settings key). Single-organization member + * management stays reachable at Setup → Organization (ruling 6384629949), so a + * single-tenant menu without organization entries closes no door. + * + * Until the config resolves the defaults are the spec's absent readings + * (multi-organization on, not managed), which is today's rendering. + */ + +import { useEffect, useState } from 'react'; +import { useAuth } from '@object-ui/auth'; +import type { AuthPublicConfig, TenancyPosture } from '@object-ui/auth'; + +const POSTURES: readonly TenancyPosture[] = ['single', 'group', 'isolated']; + +export interface OrgMenuPosture { + /** `features.multiOrgEnabled !== false` — the spec's default-on reading. */ + multiOrgEnabled: boolean; + /** `features.cloudManaged === true`. */ + cloudManaged: boolean; + /** `features.tenancyPosture` when it is a recognised posture, else `undefined`. */ + tenancyPosture: TenancyPosture | undefined; +} + +const UNRESOLVED: OrgMenuPosture = { + multiOrgEnabled: true, + cloudManaged: false, + tenancyPosture: undefined, +}; + +/** The served `features` object, read into the three answers above. */ +export function readOrgMenuPosture(features: AuthPublicConfig['features'] | null | undefined): OrgMenuPosture { + const posture: unknown = features?.tenancyPosture; + return { + multiOrgEnabled: features?.multiOrgEnabled !== false, + cloudManaged: features?.cloudManaged === true, + tenancyPosture: + typeof posture === 'string' && (POSTURES as readonly string[]).includes(posture) + ? (posture as TenancyPosture) + : undefined, + }; +} + +export interface OrgMenuEntries { + /** "My Organizations" → `/organizations?manage=1`. */ + myOrganizations: boolean; + /** "Switch organization" — the organization switcher, inside the avatar menu. */ + switchOrganization: boolean; + /** "Create organization" → `/organizations?create=1`. */ + createOrganization: boolean; +} + +/** + * The avatar menu's organization entries for one deployment and one member. + * + * - single-tenant (`multiOrgEnabled` off) ⇒ none; + * - multi-organization ⇒ My Organizations and Create organization, plus Switch + * organization only at two or more memberships (one has nothing to switch to); + * - cloud-managed ⇒ no Create organization. + * + * `hasOrgSection` is the member's own organization context (memberships still + * loading, any membership, or an active organization): with none there is + * nothing to manage or switch, as before. + */ +export function orgMenuEntries(input: { + posture: Pick; + hasOrgSection: boolean; + membershipCount: number; +}): OrgMenuEntries { + const offered = input.posture.multiOrgEnabled && input.hasOrgSection; + return { + myOrganizations: offered, + switchOrganization: offered && input.membershipCount > 1, + createOrganization: offered && !input.posture.cloudManaged, + }; +} + +export function useOrgMenuPosture(): OrgMenuPosture { + const { getAuthConfig } = useAuth(); + const [posture, setPosture] = useState(UNRESOLVED); + + useEffect(() => { + let cancelled = false; + getAuthConfig?.() + .then((cfg) => { + if (!cancelled) setPosture(readOrgMenuPosture(cfg?.features)); + }) + .catch(() => { + /* config unavailable — keep the absent readings; the server still enforces */ + }); + return () => { + cancelled = true; + }; + }, [getAuthConfig]); + + return posture; +} diff --git a/ui/packages/app-shell/src/layout/AppHeader.tsx b/ui/packages/app-shell/src/layout/AppHeader.tsx index 699412eb12f..9bd459deff6 100644 --- a/ui/packages/app-shell/src/layout/AppHeader.tsx +++ b/ui/packages/app-shell/src/layout/AppHeader.tsx @@ -76,7 +76,7 @@ import { useState, useEffect, useLayoutEffect, useCallback, useRef, type RefObje import { useOffline } from '@object-ui/react'; import { PresenceAvatars, useTenantPresence, type PresenceUser } from '@object-ui/collaboration'; import { ModeToggle } from './ModeToggle.js'; -import { WorkspaceSwitcher } from './WorkspaceSwitcher.js'; +import { WorkspaceSwitcher, WorkspaceSwitcherMenu } from './WorkspaceSwitcher.js'; import { CurrentOrganizationIndicator } from './CurrentOrganizationIndicator.js'; import { LocaleSwitcher } from './LocaleSwitcher.js'; import { NotificationPreferencesMenu } from './NotificationPreferencesMenu.js'; @@ -107,6 +107,8 @@ import { useStudioEntryGate } from '../hooks/useStudioDesignGate.js'; import { useSharedActivityFeed, type ActivityFeedReading } from '../hooks/sharedUserFeeds.js'; import { useInboxBell } from '../hooks/useInboxBell.js'; import { useHomePath } from '../hooks/useHomePath.js'; +import { orgMenuEntries, useOrgMenuPosture } from '../hooks/useOrgMenuPosture.js'; +import { postureHasOrgWall } from '../hooks/useTenancyPosture.js'; import { useServedViewItems } from '../hooks/useServedViewItems.js'; import { viewTabLabel } from '../views/viewTabLabel.js'; import { resolveViewId } from '../utils/resolveViewId.js'; @@ -475,7 +477,6 @@ export function AppHeader({ organizations, activeOrganization, isOrganizationsLoading, - getAuthConfig, } = useAuth(); const dataSource = useAdapter(); // Runtime AI gating: hide the top-bar AI entry point when the server serves @@ -611,24 +612,17 @@ export function AppHeader({ : apiActivity; const orgList = organizations ?? []; const hasOrgSection = isOrganizationsLoading || orgList.length > 0 || !!activeOrganization; - // Mirror the server's `beforeCreateOrganization` gate so the "Create - // workspace" entry only shows where multi-org self-service is enabled. - // Default to allowed until the config resolves (avoids hiding it on slow - // networks); the server still enforces. - const [multiOrgDisabled, setMultiOrgDisabled] = useState(false); - useEffect(() => { - let cancelled = false; - getAuthConfig?.() - .then((cfg) => { - if (!cancelled) setMultiOrgDisabled(cfg?.features?.multiOrgEnabled === false); - }) - .catch(() => { - /* leave default — server still enforces */ - }); - return () => { - cancelled = true; - }; - }, [getAuthConfig]); + // The avatar menu's organization entries follow the served deployment + // signals (objectstack-ai/objectstack#34591): none on a single-tenant + // deployment, no create entry on a cloud-managed one, and the switcher only + // at two or more memberships. Until the config resolves, the spec's absent + // readings keep today's rendering; the server still enforces. + const orgMenuPosture = useOrgMenuPosture(); + const orgMenu = orgMenuEntries({ + posture: orgMenuPosture, + hasOrgSection, + membershipCount: orgList.length, + }); // Build path segments (only used in `app` variant) const pathParts = location.pathname.split('/').filter(Boolean); @@ -948,12 +942,13 @@ export function AppHeader({ reports GA. */} {!isApp && } - {/* Organization context — "which org am I in", right after the brand and - before the app/section breadcrumb. Two mutually exclusive renderers: - the switcher for multi-membership users (name + switch dropdown), - and the read-only indicator for the single-membership case the - switcher declines to render, on walled deployments only - (objectui#5287 — the switcher's own visibility rule is unchanged). */} + {/* Organization context, right after the brand. The web organization + switcher lives in the avatar menu (objectstack-ai/objectstack#34591): + the left of the bar is the product mark and the app switcher. What + stays here: the mobile shell's own connection-switcher button + (renders only inside a shell that announces it), and the read-only + organization name on a walled deployment, at any membership count + (objectui#5287). */} @@ -1306,34 +1301,50 @@ export function AppHeader({ )} {/* - * Workspace entries. The header-left WorkspaceSwitcher carries - * the same destinations, but it renders NOTHING below two orgs - * (`orgList.length <= 1` → null) — so for the single-org majority - * the avatar menu is the ONLY door to workspace management. - * Leaving just the create shortcut here is what shut every path - * to Members / Invitations / Organization settings for them - * (objectstack#8096): the picker at `/organizations` auto-skips - * with one org, and the switcher never appears. + * Organization entries, by deployment posture (`orgMenuEntries`, + * objectstack-ai/objectstack#34591, ruling 6937513776). + * + * Single-tenant (`multiOrgEnabled` off): none. Member management + * for the one organization is Setup → Organization (ruling + * 6384629949), so dropping these closes no door. * - * "My Organizations" → `?manage=1`, which OrganizationsPage reads as - * "the user came here to MANAGE": multi-org users get the picker, - * a single-org user is deep-linked straight to that org's members - * page (there is no choice worth showing them). Deliberately NOT - * gated on `multiOrgDisabled` — that flag governs CREATING orgs; - * where self-service creation is off this entry is the only way - * in, so gating it there would re-close the door. + * Multi-organization: "My Organizations" → `?manage=1`, which + * OrganizationsPage reads as "came here to MANAGE" — a member of + * one organization is deep-linked to its members page, since the + * picker auto-skips at one organization (objectstack#8096: this + * entry is that member's door, as the switcher is not offered at + * one membership). Then the switcher, at two or more memberships, + * and "Create organization" unless the cloud manages this + * environment (organizations are created on the cloud there). + * + * On a walled posture the active organization's name also rides + * under "My Organizations", beside the entries that act on it; the + * bar names it read-only (`CurrentOrganizationIndicator`). */} - {hasOrgSection && ( + {orgMenu.myOrganizations && ( leaveTo('/organizations?manage=1')} className="cursor-pointer" data-testid="header-my-organizations" > - {t('organizations.mine', { defaultValue: 'My Organizations' })} + + {t('organizations.mine', { defaultValue: 'My Organizations' })} + {activeOrganization && postureHasOrgWall(orgMenuPosture.tenancyPosture) && ( + + {activeOrganization.name} + + )} + )} - {hasOrgSection && !multiOrgDisabled && ( + {orgMenu.switchOrganization && ( + + )} + {orgMenu.createOrganization && ( leaveTo('/organizations?create=1')} className="cursor-pointer" diff --git a/ui/packages/app-shell/src/layout/CurrentOrganizationIndicator.tsx b/ui/packages/app-shell/src/layout/CurrentOrganizationIndicator.tsx index a89e9b98187..3dfcfaac1c8 100644 --- a/ui/packages/app-shell/src/layout/CurrentOrganizationIndicator.tsx +++ b/ui/packages/app-shell/src/layout/CurrentOrganizationIndicator.tsx @@ -1,24 +1,22 @@ /** - * CurrentOrganizationIndicator — read-only "which organization am I in" for - * users who have exactly ONE membership (objectui#5287). + * CurrentOrganizationIndicator — read-only "which organization am I in" on a + * walled deployment, at any membership count (objectui#5287). * - * `WorkspaceSwitcher` is a multi-membership affordance: with one organization - * there is nothing to switch to, so it renders nothing — and it is also the - * only place the console ever showed the organization name. On a walled - * deployment that left a single-membership business user with no indication - * anywhere of which organization they were looking at, while every list on the - * page was silently scoped to it. Found in a downstream multi-tenant - * acceptance run (case S20-001). + * On a walled posture every list on the page is silently scoped to the active + * organization, so the top bar must say which one without the user opening + * anything. Found in a downstream multi-tenant acceptance run (case S20-001) + * for a single-membership user, who had no organization name anywhere. * - * This is the other half of that surface, deliberately a SEPARATE component: + * The organization switcher is not in the top bar: the left of the bar is the + * product mark and the app switcher, and switching lives in the avatar menu + * (`WorkspaceSwitcherMenu`, objectstack-ai/objectstack#34591). So this + * indicator is the bar's only organization name, at one membership and at two + * or more alike (seat ruling repo:objectstack#3 on that card). * - * - the switcher's visibility rule is unchanged (`orgList.length <= 1` still - * renders nothing — a one-entry dropdown was the rejected option); - * - this renders in exactly the case the switcher declines, and renders no - * control at all: no trigger, no menu, no click target. The name is - * context, not navigation. Members / workspace management stay reachable - * from the avatar menu's "My Workspaces" entry (objectstack#8096), which - * is what covers this configuration. + * It renders no control at all: no trigger, no menu, no click target. The name + * is context, not navigation; a read-only name is not a switcher. Switching and + * members / workspace management stay in the avatar menu ("Switch + * organization", "My Organizations"). * * ## Why it is gated on the tenancy posture, not on "an org exists" * @@ -35,7 +33,8 @@ * * Inside the mobile shell, when it announces `showConnectionSwitcher`, this * renders nothing: `WorkspaceSwitcher` then draws the same badge and name, at - * the same widths, as the button that opens the shell's native switcher. + * the same widths, as the top-bar button that opens the shell's native + * switcher. * * An absent or unrecognized posture (older server, config fetch still in * flight or failed) renders nothing, matching how every other posture-keyed @@ -61,11 +60,10 @@ export function CurrentOrganizationIndicator() { // exactly as it is today. Also covers the not-yet-resolved config. if (!postureHasOrgWall(posture)) return null; - const orgList = organizations ?? []; - - // Exactly one membership. Two or more is the switcher's case and it must - // stay the only affordance there; zero means no organization context at all. - if (orgList.length !== 1) return null; + // Any membership count names the organization: the switcher is in the + // avatar menu, so this is the bar's only organization name. Zero memberships + // means no organization context at all. + if ((organizations ?? []).length === 0) return null; // The organization the SERVER reports as active, never a guess from the // membership list (objectui#12698): a session with no active organization — diff --git a/ui/packages/app-shell/src/layout/WorkspaceSwitcher.tsx b/ui/packages/app-shell/src/layout/WorkspaceSwitcher.tsx index f9e435e4b40..20192e47e87 100644 --- a/ui/packages/app-shell/src/layout/WorkspaceSwitcher.tsx +++ b/ui/packages/app-shell/src/layout/WorkspaceSwitcher.tsx @@ -1,141 +1,124 @@ /** - * WorkspaceSwitcher + * WorkspaceSwitcher — the organization switcher, in two places. * - * Header-left organization (workspace) switcher — the standard place users - * expect "which org am I in / switch org" to live (Linear/Vercel/GitHub style). + * ## `WorkspaceSwitcherMenu` — inside the avatar menu (the web switcher) * - * - Single-org users (the vast majority): render NOTHING on the web. With one - * org there is nothing to switch to, so a dropdown here would control - * nothing. The web switcher is a multi-org affordance (the mobile shell's - * native switcher, below, is not). Where a tenancy wall IS in force the - * org name still matters at one membership — `CurrentOrganizationIndicator` - * renders it read-only there (objectui#5287), without a control. - * - Multi-org users: the active org name + a dropdown to switch orgs inline - * (full-page reload so the active-org context refreshes app-wide, mirroring - * OrganizationsPage), plus shortcuts to manage members / create a workspace. - * - No org context at all: renders nothing. + * The top bar's left side is the product mark and the app switcher; switching + * organization is rare, so the switcher lives in the avatar menu as a + * "Switch organization" submenu (objectstack-ai/objectstack#34591). + * The avatar menu decides WHETHER it is offered from the served deployment + * signals (`orgMenuEntries` in `hooks/useOrgMenuPosture.ts`: a multi-organization + * deployment and two or more memberships). This component renders nothing + * without an active organization, at one membership, or inside a mobile shell + * that carries its own switcher (below). + * + * Under `group` tenancy posture (ADR-0105) the active organization is only the + * WRITE target — reads span every organization the member belongs to — so the + * submenu labels it as the working organization and says so. ADR-0105 requires + * that write-context switcher to stay reachable in group posture; the avatar + * menu is where it is reached. + * + * Below the phone breakpoint (`usePhoneViewport`) the rows render inline in the + * avatar menu under a "Switch organization" label instead of in a submenu: a + * submenu opens beside the menu, and at phone width the menu already spans the + * screen, so neither side has room and the rows would open off the screen. + * + * Switching does a full-page reload to the console root so the active-org + * context refreshes app-wide, mirroring OrganizationsPage. + * + * ## `WorkspaceSwitcher` — the mobile shell's button in the top bar * * Inside the ObjectStack mobile shell (`@object-ui/mobile`), when the shell - * announces `showConnectionSwitcher`, the button opens the shell's native - * switcher instead of the dropdown, and it renders whenever there is an active + * announces `showConnectionSwitcher`, the top bar keeps a button that opens the + * shell's native switcher. It renders whenever there is an active * organization, at any membership count: the sheet lists the connections the * shell holds across company servers, which this server's membership list - * cannot count. In a plain browser, or a shell without the capability, the - * rules above apply unchanged. - * - * Under `group` tenancy posture (ADR-0105) the switcher's meaning changes: - * the active organization is only the WRITE target — reads span every - * organization the member belongs to — so the dropdown labels it as the - * working organization instead of implying it bounds what the user sees. + * cannot count — it is the shell's control, not this server's organization + * menu. In a plain browser, or a shell without the capability, it renders + * nothing; the web switcher is the avatar menu's. */ -import { useEffect, useState } from 'react'; -import { useNavigate } from 'react-router-dom'; import { useAuth } from '@object-ui/auth'; import type { AuthOrganization } from '@object-ui/auth'; import { useObjectTranslation } from '@object-ui/i18n'; import { nativeHostCan, nativeShowConnectionSwitcher, useNativeHost } from '@object-ui/mobile'; import { - DropdownMenu, - DropdownMenuTrigger, - DropdownMenuContent, + DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, } from '@object-ui/components'; -import { ChevronsUpDown, Check, Plus, Users } from 'lucide-react'; +import { ArrowLeftRight, Check, ChevronsUpDown } from 'lucide-react'; import { resolveRootUrl } from '../console/organizations/resolveHomeUrl.js'; -import { useTenancyPosture } from '../hooks/useTenancyPosture.js'; import { confirmUnsavedLeave } from '../chrome/unsavedEdits.js'; +import { usePhoneViewport } from '../hooks/usePhoneViewport.js'; import { OrgBadge } from './OrgBadge.js'; +/** The top bar's mobile-shell button; nothing in a plain browser. */ export function WorkspaceSwitcher() { - const { t } = useObjectTranslation(); - const navigate = useNavigate(); - const { organizations, activeOrganization, switchOrganization, getAuthConfig } = useAuth(); - const [multiOrgDisabled, setMultiOrgDisabled] = useState(false); - const isGroupPosture = useTenancyPosture() === 'group'; + const { activeOrganization } = useAuth(); const nativeSwitcher = nativeHostCan(useNativeHost(), 'showConnectionSwitcher'); - useEffect(() => { - let cancelled = false; - getAuthConfig?.() - .then((cfg) => { - if (!cancelled) setMultiOrgDisabled(cfg?.features?.multiOrgEnabled === false); - }) - .catch(() => { - /* leave default — create entry stays available */ - }); - return () => { - cancelled = true; - }; - }, [getAuthConfig]); - - const orgList = organizations ?? []; - // The organization the SERVER reports as active, never `orgList[0]` - // (objectui#12698): that guess named an organization the session did not - // hold — e.g. after a refused `set-active`. + // The organization the SERVER reports as active, never a membership-list + // guess (objectui#12698); none ⇒ nothing to name. const current = activeOrganization; + if (!nativeSwitcher || !current) return null; - // No organization context (e.g. a brand-new user before provisioning, or a - // session the server reports no active organization for) — show nothing - // rather than an empty switcher or a guessed name. - if (!current) return null; - - const triggerClassName = - 'ml-2 inline-flex max-w-[14rem] items-center gap-1.5 rounded-md px-1.5 py-1 text-sm font-medium text-foreground/80 transition-colors hover:bg-accent hover:text-foreground'; - const triggerContent = ( - <> + // The shell's sheet is the switcher; switching there is the shell's own + // flow, so nothing is sent from here. + return ( + ); +} - // The shell's sheet replaces the web menu; switching there is the shell's - // own flow, so nothing is sent from here. - if (nativeSwitcher) { - return ( - - ); - } +/** The avatar menu's "Switch organization" submenu (inline rows on a phone). Render it inside a `DropdownMenuContent`. */ +export function WorkspaceSwitcherMenu({ isGroupPosture }: { isGroupPosture: boolean }) { + const { t } = useObjectTranslation(); + const { organizations, activeOrganization, switchOrganization } = useAuth(); + const nativeSwitcher = nativeHostCan(useNativeHost(), 'showConnectionSwitcher'); + const phone = usePhoneViewport(); + + // The shell's button in the top bar replaces the web switcher there. + if (nativeSwitcher) return null; + + const current = activeOrganization; + if (!current) return null; - // Single-org: render nothing. With only one org there's nothing to switch to, - // so a dropdown here would be a control that controls nothing. The switcher - // appears only once a second org exists. On a walled deployment the org NAME - // is still load-bearing context at one membership — `CurrentOrganizationIndicator` - // renders it read-only for exactly this case (objectui#5287); this rule is - // unchanged. + // One membership: nothing to switch to, so no control that controls nothing. + const orgList = organizations ?? []; if (orgList.length <= 1) return null; const handleSwitch = (org: AuthOrganization) => { if (org.id === current.id) return; - // objectui#13231 — ask BEFORE `set-active` is sent. Asking at the reload - // would be too late: the server has already switched, and the page holding - // the edits reloads itself for the new organization (dropping them, and its - // leave prompt with them) before the document load starts. On Cancel - // nothing is sent: the organization, the URL and the edits stay. + // objectui#13231 — ask BEFORE `set-active` is sent: once the server has + // switched, the page holding the edits reloads itself for the new + // organization before any leave prompt could run. On Cancel nothing is + // sent: the organization, the URL and the edits stay. confirmUnsavedLeave(async () => { try { await switchOrganization(org.id); - // switchOrganization only updates state; reload to the console root so the - // new active org propagates to every data scope app-wide AND - // RootLandingRedirect resolves the right landing (single-app workspace → - // that app, not the redundant launcher). Same as OrganizationsPage. + // Reload to the console root so the new active org reaches every data + // scope and RootLandingRedirect resolves the right landing. Same as + // OrganizationsPage. window.location.href = resolveRootUrl(); } catch (err) { console.error('[WorkspaceSwitcher] switch failed', err); @@ -143,59 +126,68 @@ export function WorkspaceSwitcher() { }); }; - return ( - - - {triggerContent} - - - - {isGroupPosture - ? t('organization.switcher.groupLabel', { defaultValue: 'Working organization' }) - : t('organization.switcher.label', { defaultValue: 'Switch organization' })} - - {isGroupPosture && ( -

- {t('organization.switcher.groupHint', { - defaultValue: - 'New records are created here. Views show data from all your organizations.', - })} -

- )} - {orgList.map((org) => ( - handleSwitch(org)} - className="cursor-pointer gap-2" - > - - {org.name} - {org.id === current.id && } - - ))} + const groupHint = isGroupPosture ? ( + <> + + {t('organization.switcher.groupLabel', { defaultValue: 'Working organization' })} + + {/* Bounded width: the menu sizes to its content, so an unbounded line + widens it past a phone screen instead of wrapping. */} +

+ {t('organization.switcher.groupHint', { + defaultValue: 'New records are created here. Views show data from all your organizations.', + })} +

+ + ) : null; + const rows = orgList.map((org) => ( + handleSwitch(org)} + className="cursor-pointer gap-2" + data-testid={`workspace-switcher-org-${org.id}`} + > + + {org.name} + {org.id === current.id && } + + )); + const label = t('organization.switcher.label', { defaultValue: 'Switch organization' }); + + // Phone: inline rows under a label — a submenu has no side with room there. + if (phone) { + return ( + <> - confirmUnsavedLeave(() => navigate(`/organizations/${current.slug}/members`))} - className="cursor-pointer gap-2" - data-testid="workspace-manage-members" - > - - {t('organization.switcher.manageMembers', { defaultValue: 'Manage members' })} - - {!multiOrgDisabled && ( - confirmUnsavedLeave(() => navigate('/organizations?create=1'))} - className="cursor-pointer gap-2" - data-testid="workspace-create" + + - - {t('organizations.create', { defaultValue: 'Create organization' })} - - )} -
-
+ + {label} + + {groupHint} + {rows} + + + + ); + } + + return ( + + + + {label} + + + {groupHint} + {rows} + + ); } diff --git a/ui/packages/app-shell/src/layout/__tests__/AppHeader.myOrganizations.test.tsx b/ui/packages/app-shell/src/layout/__tests__/AppHeader.myOrganizations.test.tsx index d96de7313f9..15942c6fbbd 100644 --- a/ui/packages/app-shell/src/layout/__tests__/AppHeader.myOrganizations.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/AppHeader.myOrganizations.test.tsx @@ -25,7 +25,7 @@ */ import '@testing-library/jest-dom/vitest'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, screen } from '@testing-library/react'; +import { render, screen, act } from '@testing-library/react'; const navigate = vi.fn(); @@ -81,6 +81,9 @@ vi.mock('@object-ui/components', async (importOriginal) => { DropdownMenuLabel: Pass, DropdownMenuSeparator: () => null, DropdownMenuGroup: Pass, + DropdownMenuSub: Pass, + DropdownMenuSubTrigger: Pass, + DropdownMenuSubContent: Pass, Avatar: Pass, AvatarImage: () => null, AvatarFallback: Pass, @@ -127,10 +130,11 @@ vi.mock('../LocalizedSidebarTrigger', () => ({ LocalizedSidebarTrigger: () => nu vi.mock('../PreviewBadge', () => ({ PreviewBadge: () => null })); /** - * The REAL WorkspaceSwitcher, deliberately — mocking it away would erase the - * precondition under test. Its `orgList.length <= 1` early return is what - * leaves the avatar menu as the only door, so the cases below get to assert - * that it renders nothing while the avatar entry is present. + * The REAL WorkspaceSwitcher and WorkspaceSwitcherMenu, deliberately — mocking + * them away would erase the preconditions under test: the switcher's + * one-membership early return is what leaves "My Organizations" as the only + * door, and the top bar's switcher drawing nothing in a browser is what the + * deployment-posture cases below assert. */ vi.mock('../../providers/MetadataProvider', () => ({ useMetadata: () => ({ apps: [], dashboards: [], pages: [], reports: [] }), @@ -140,8 +144,8 @@ const ONE_ORG = { id: 'org_1', name: 'Acme', slug: 'acme' }; /** Orgs the mocked `useAuth` reports for the current case. */ let organizations: Array> = [ONE_ORG]; -/** `features.multiOrgEnabled` the mocked auth config resolves with. */ -let multiOrgEnabled = true; +/** The served `features` the mocked auth config resolves with. */ +let features: Record = { multiOrgEnabled: true }; vi.mock('@object-ui/auth', async (importOriginal) => { /** @@ -153,7 +157,7 @@ vi.mock('@object-ui/auth', async (importOriginal) => { * V8 OOM during collection, not a test assertion). Reading the `let` at CALL * time keeps per-case control without touching identity. */ - const getAuthConfig = () => Promise.resolve({ features: { multiOrgEnabled } }); + const getAuthConfig = () => Promise.resolve({ features }); return { ...(await importOriginal>()), useAuth: () => ({ @@ -190,7 +194,7 @@ import { AppHeader } from '../AppHeader'; beforeEach(() => { navigate.mockClear(); organizations = [ONE_ORG]; - multiOrgEnabled = true; + features = { multiOrgEnabled: true }; vi.stubGlobal('fetch', vi.fn(() => Promise.resolve(new Response('{}', { status: 404 })))); }); @@ -224,19 +228,6 @@ describe('AppHeader avatar menu — the single-org door to workspace management expect(screen.getByTestId('header-my-organizations')).toBeInTheDocument(); }); - it('survives multi-org self-service being disabled — that flag governs CREATE only', async () => { - multiOrgEnabled = false; - render(); - - // Where creation is off this entry is the only way into the manage pages, - // so gating it on the same flag as "Create workspace" would re-close the - // door. Await a tick so the async `getAuthConfig` gate has resolved. - await vi.waitFor(() => - expect(screen.queryByTestId('header-create-workspace')).not.toBeInTheDocument(), - ); - expect(screen.getByTestId('header-my-organizations')).toBeInTheDocument(); - }); - it('still offers it to a multi-org user (the switcher is a duplicate, not a replacement)', () => { organizations = [ONE_ORG, { id: 'org_2', name: 'Globex', slug: 'globex' }]; render(); @@ -253,3 +244,140 @@ describe('AppHeader avatar menu trigger — an accessible name (objectui#13461)' expect(trigger).toHaveTextContent('ZS'); }); }); + +/** Lets the async config read resolve and React flush before reading an absence. */ +async function settle() { + await act(() => new Promise((resolve) => setTimeout(resolve, 0))); +} + +const TWO_ORGS = [ONE_ORG, { id: 'org_2', name: 'Globex', slug: 'globex' }]; + +/** Which of the avatar menu's organization entries render, and whether the top bar draws a switcher. */ +function orgEntries() { + return { + myOrganizations: !!screen.queryByTestId('header-my-organizations'), + switchOrganization: !!screen.queryByTestId('header-switch-organization'), + createOrganization: !!screen.queryByTestId('header-create-workspace'), + topBarSwitcher: !!screen.queryByTestId('workspace-switcher'), + }; +} + +/* + * objectstack-ai/objectstack#34591, ruling 6937513776: the avatar menu's + * organization entries follow the served deployment signals + * (`features.multiOrgEnabled`, `features.cloudManaged`, + * `features.tenancyPosture`), with no Setup override; the web switcher moves + * from the top bar into the avatar menu. + */ +describe('AppHeader avatar menu — organization entries follow the deployment posture (#34591)', () => { + it('single-tenant: no organization entry and no top-bar switcher', async () => { + features = { multiOrgEnabled: false, tenancyPosture: 'single' }; + organizations = TWO_ORGS; + render(); + await settle(); + + // Member management for the one organization is Setup → Organization + // (ruling 6384629949), so the avatar menu closes no door here. + expect(orgEntries()).toEqual({ + myOrganizations: false, + switchOrganization: false, + createOrganization: false, + topBarSwitcher: false, + }); + // Counter-probe: the menu itself rendered. + expect(screen.getByRole('button', { name: 'Log out' })).toBeInTheDocument(); + }); + + it('multi-organization, one membership: My Organizations and Create, no Switch organization', async () => { + features = { multiOrgEnabled: true, tenancyPosture: 'isolated' }; + render(); + await settle(); + + expect(orgEntries()).toEqual({ + myOrganizations: true, + switchOrganization: false, + createOrganization: true, + topBarSwitcher: false, + }); + }); + + it('multi-organization, two memberships: Switch organization joins the menu; the top bar draws none', async () => { + features = { multiOrgEnabled: true, tenancyPosture: 'isolated' }; + organizations = TWO_ORGS; + render(); + await settle(); + + expect(orgEntries()).toEqual({ + myOrganizations: true, + switchOrganization: true, + createOrganization: true, + topBarSwitcher: false, + }); + expect(screen.getByTestId('workspace-switcher-org-org_2')).toHaveTextContent('Globex'); + }); + + it('cloud-managed: no Create organization (organizations are created on the cloud)', async () => { + features = { multiOrgEnabled: true, tenancyPosture: 'isolated', cloudManaged: true }; + organizations = TWO_ORGS; + render(); + await settle(); + + expect(orgEntries()).toEqual({ + myOrganizations: true, + switchOrganization: true, + createOrganization: false, + topBarSwitcher: false, + }); + }); + + it('cloud-managed single-tenant: nothing', async () => { + features = { multiOrgEnabled: false, tenancyPosture: 'single', cloudManaged: true }; + render(); + await settle(); + + expect(orgEntries()).toEqual({ + myOrganizations: false, + switchOrganization: false, + createOrganization: false, + topBarSwitcher: false, + }); + }); + + it('a server that serves no flags reads the spec defaults: multi-organization on, not managed', async () => { + features = {}; + render(); + await settle(); + + expect(orgEntries()).toEqual({ + myOrganizations: true, + switchOrganization: false, + createOrganization: true, + topBarSwitcher: false, + }); + }); + + it('group posture: the switcher stays reachable as the write context (ADR-0105) and says so', async () => { + features = { multiOrgEnabled: true, tenancyPosture: 'group' }; + organizations = TWO_ORGS; + render(); + await settle(); + + expect(screen.getByTestId('header-switch-organization')).toBeInTheDocument(); + expect(screen.getByTestId('workspace-switcher-group-hint')).toBeInTheDocument(); + }); + + it('walled posture: the active organization is named under My Organizations; not on a posture-less server', async () => { + features = { multiOrgEnabled: true, tenancyPosture: 'isolated' }; + organizations = TWO_ORGS; + const walled = render(); + await settle(); + expect(screen.getByTestId('header-my-organizations-current')).toHaveTextContent('Acme'); + walled.unmount(); + + features = { multiOrgEnabled: true }; + render(); + await settle(); + expect(screen.getByTestId('header-my-organizations')).toBeInTheDocument(); + expect(screen.queryByTestId('header-my-organizations-current')).not.toBeInTheDocument(); + }); +}); diff --git a/ui/packages/app-shell/src/layout/__tests__/AppHeader.organizationNoun-12851.test.tsx b/ui/packages/app-shell/src/layout/__tests__/AppHeader.organizationNoun-12851.test.tsx index e360e02fbc0..46d5c093f4c 100644 --- a/ui/packages/app-shell/src/layout/__tests__/AppHeader.organizationNoun-12851.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/AppHeader.organizationNoun-12851.test.tsx @@ -52,6 +52,9 @@ vi.mock('@object-ui/components', async (importOriginal) => { DropdownMenuLabel: Pass, DropdownMenuSeparator: () => null, DropdownMenuGroup: Pass, + DropdownMenuSub: Pass, + DropdownMenuSubTrigger: Pass, + DropdownMenuSubContent: Pass, Avatar: Pass, AvatarImage: () => null, AvatarFallback: Pass, diff --git a/ui/packages/app-shell/src/layout/__tests__/AppHeader.singleMembershipOrg.test.tsx b/ui/packages/app-shell/src/layout/__tests__/AppHeader.singleMembershipOrg.test.tsx index 46a4c75d361..6dcc517bc05 100644 --- a/ui/packages/app-shell/src/layout/__tests__/AppHeader.singleMembershipOrg.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/AppHeader.singleMembershipOrg.test.tsx @@ -26,7 +26,7 @@ import '@testing-library/jest-dom/vitest'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, screen, waitFor, act } from '@testing-library/react'; +import { render, screen, act, within } from '@testing-library/react'; const navigate = vi.fn(); vi.mock('react-router-dom', () => ({ @@ -76,6 +76,9 @@ vi.mock('@object-ui/components', async (importOriginal) => { DropdownMenuLabel: Pass, DropdownMenuSeparator: () => null, DropdownMenuGroup: Pass, + DropdownMenuSub: Pass, + DropdownMenuSubTrigger: Pass, + DropdownMenuSubContent: Pass, Avatar: Pass, AvatarImage: () => null, AvatarFallback: Pass, @@ -160,12 +163,14 @@ vi.mock('../../providers/AdapterProvider', () => ({ useAdapter: () => fakeAdapte import { AppHeader } from '../AppHeader'; -/** Lets the async posture/config gates resolve and React flush before reading an absence. */ +/** + * Lets the async posture/config gates resolve and React flush before reading an + * absence. A macrotask, not an element to wait on: on a single-tenant + * deployment the resolved config REMOVES the avatar menu's organization + * entries, so no element marks "resolved" in every case. + */ async function settle() { - await waitFor(() => expect(screen.getByTestId('header-my-organizations')).toBeInTheDocument()); - await act(async () => { - await Promise.resolve(); - }); + await act(() => new Promise((resolve) => setTimeout(resolve, 0))); } beforeEach(() => { @@ -183,8 +188,8 @@ describe('AppHeader — organization context at one membership (#5287)', () => { it('isolated posture: names the organization read-only, with no switcher', async () => { render(); - expect(await screen.findByTestId('current-organization-indicator')).toBeInTheDocument(); - expect(screen.getByText('Titanwind EHR')).toBeInTheDocument(); + const indicator = await screen.findByTestId('current-organization-indicator'); + expect(within(indicator).getByText('Titanwind EHR')).toBeInTheDocument(); // The counter-probe that keeps the pre-fix zero honest: this bar renders // session data. Before the fix, this line passed and the two above did not. @@ -196,12 +201,14 @@ describe('AppHeader — organization context at one membership (#5287)', () => { expect(screen.queryByText('Switch organization')).not.toBeInTheDocument(); }); - it('multiple memberships: unchanged — the switcher renders and the indicator stands down', async () => { + it('multiple memberships: the switcher is the avatar menu\'s, the bar draws none, and the indicator still names the organization', async () => { organizations = [SOLO, SECOND]; render(); - expect(await screen.findByTestId('workspace-switcher')).toBeInTheDocument(); - expect(screen.queryByTestId('current-organization-indicator')).not.toBeInTheDocument(); + const indicator = await screen.findByTestId('current-organization-indicator'); + expect(within(indicator).getByText('Titanwind EHR')).toBeInTheDocument(); + expect(screen.getByTestId('header-switch-organization')).toBeInTheDocument(); + expect(screen.queryByTestId('workspace-switcher')).not.toBeInTheDocument(); }); it('single-tenant posture: nothing new renders — no organization name anywhere', async () => { diff --git a/ui/packages/app-shell/src/layout/__tests__/AppHeader.unsavedEditsLeave-13231.test.tsx b/ui/packages/app-shell/src/layout/__tests__/AppHeader.unsavedEditsLeave-13231.test.tsx index ad6fbf0ed05..412f70041e3 100644 --- a/ui/packages/app-shell/src/layout/__tests__/AppHeader.unsavedEditsLeave-13231.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/AppHeader.unsavedEditsLeave-13231.test.tsx @@ -18,8 +18,9 @@ * * ## What is driven here * - * The real `AppHeader` in its `app` variant, with the real `WorkspaceSwitcher` - * inside it (two organizations, so it renders), under a real `MemoryRouter`. + * The real `AppHeader` in its `app` variant, with the real organization + * switcher inside its avatar menu (two organizations on a multi-organization + * deployment, so it renders), under a real `MemoryRouter`. * Only `navigate` is a spy, so each case reads where the header sent the user. * A page's unsaved edits are registered with the seam directly * (`registerUnsavedEdits`), the way a page's hook does; the pages' own @@ -88,6 +89,9 @@ vi.mock('@object-ui/components', async (importOriginal) => { DropdownMenuLabel: Pass, DropdownMenuSeparator: () => null, DropdownMenuGroup: Pass, + DropdownMenuSub: Pass, + DropdownMenuSubTrigger: Pass, + DropdownMenuSubContent: Pass, Avatar: Pass, AvatarImage: () => null, AvatarFallback: Pass, @@ -213,12 +217,10 @@ const MENU_DEPARTURES: Array<{ entry: string; click: () => void; to: string }> = { entry: 'avatar › My Organizations', click: () => fireEvent.click(screen.getByTestId('header-my-organizations')), to: '/organizations?manage=1' }, { entry: 'avatar › Create organization', click: () => fireEvent.click(screen.getByTestId('header-create-workspace')), to: '/organizations?create=1' }, { entry: 'avatar › a hidden app', click: () => fireEvent.click(screen.getByRole('button', { name: 'Personal Settings' })), to: '/apps/personal_settings' }, - { entry: 'workspace › Manage members', click: () => fireEvent.click(screen.getByTestId('workspace-manage-members')), to: '/organizations/acme/members' }, - { entry: 'workspace › Create organization', click: () => fireEvent.click(screen.getByTestId('workspace-create')), to: '/organizations?create=1' }, ]; -/** The workspace switcher's row for the other organization. */ -const globexRow = () => screen.getAllByRole('button').find((b) => b.textContent?.trim().endsWith('Globex') && !b.hasAttribute('data-testid'))!; +/** The avatar menu switcher's row for the other organization. */ +const globexRow = () => screen.getByTestId('workspace-switcher-org-org_globex'); beforeEach(() => { navigate.mockReset(); @@ -257,7 +259,7 @@ describe('the header menus ask before leaving unsaved edits (objectui#13231)', ( }); } - it('workspace › another organization asks BEFORE set-active; Cancel sends nothing and keeps the organization', async () => { + it('avatar › Switch organization › another organization asks BEFORE set-active; Cancel sends nothing and keeps the organization', async () => { holdUnsavedEdit(); await renderHeader(); @@ -268,7 +270,7 @@ describe('the header menus ask before leaving unsaved edits (objectui#13231)', ( expect(window.location.hash).toBe(''); }); - it('workspace › another organization: OK switches, then reloads, with no second prompt from the tab-close guard', async () => { + it('avatar › Switch organization › another organization: OK switches, then reloads, with no second prompt from the tab-close guard', async () => { holdUnsavedEdit(); confirmSpy.mockReturnValue(true); let unloadHeldDuringSwitch: boolean | undefined; diff --git a/ui/packages/app-shell/src/layout/__tests__/CurrentOrganizationIndicator.test.tsx b/ui/packages/app-shell/src/layout/__tests__/CurrentOrganizationIndicator.test.tsx index 655d0fd595b..66587061924 100644 --- a/ui/packages/app-shell/src/layout/__tests__/CurrentOrganizationIndicator.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/CurrentOrganizationIndicator.test.tsx @@ -3,14 +3,14 @@ /** * CurrentOrganizationIndicator — objectui#5287. * - * A single-membership user on a walled (isolated / group) deployment gets the - * active organization name read-only; every other configuration renders - * nothing. The two halves are equally load-bearing and fail in opposite - * directions: + * A user on a walled (isolated / group) deployment gets the active organization + * name read-only, at one membership and at two or more alike (the switcher is + * in the avatar menu, objectstack-ai/objectstack#34591, so this is the bar's + * only organization name); every other configuration renders nothing. The two + * halves are equally load-bearing and fail in opposite directions: * - * - miss the render and the reported defect survives — with the switcher - * hidden by design at one membership, there is no second surface that - * would show the miss; + * - miss the render and the reported defect survives — no other top-bar + * surface names the organization, so nothing else would show the miss; * - miss the GATE and every existing single-tenant console grows an * organization name in its top bar, which is a visible regression for * users who have no organization context at all. @@ -92,7 +92,7 @@ beforeEach(() => { features = { multiOrgEnabled: true, tenancyPosture: 'isolated' }; }); -describe('CurrentOrganizationIndicator — renders (walled posture, one membership)', () => { +describe('CurrentOrganizationIndicator — renders (walled posture, any membership count)', () => { it('isolated posture: shows the active organization name', async () => { mount(); @@ -108,6 +108,31 @@ describe('CurrentOrganizationIndicator — renders (walled posture, one membersh expect(screen.getByText('Titanwind EHR')).toBeInTheDocument(); }); + it('two or more memberships, isolated posture: names the ACTIVE organization, read-only', async () => { + // The harness's active organization is the first membership: Globex here. + organizations = [SECOND, SOLO]; + mount(); + + const indicator = await screen.findByTestId('current-organization-indicator'); + expect(indicator).toHaveAttribute('title', 'Current organization: Globex'); + expect(screen.getByText('Globex')).toBeInTheDocument(); + expect(screen.queryByText('Titanwind EHR')).not.toBeInTheDocument(); + // Still a name, not a switcher, at two memberships. + expect(indicator.querySelector('button, a, [role="button"], [role="menuitem"]')).toBeNull(); + expect(screen.queryByRole('menu')).not.toBeInTheDocument(); + }); + + it('two or more memberships, group posture: the write-target organization is named', async () => { + organizations = [SECOND, SOLO]; + features = { multiOrgEnabled: true, tenancyPosture: 'group' }; + mount(); + + expect(await screen.findByTestId('current-organization-indicator')).toHaveAttribute( + 'title', + 'Current organization: Globex', + ); + }); + it('is genuinely read-only — no control, no menu, no click target', async () => { mount(); @@ -172,15 +197,6 @@ describe('CurrentOrganizationIndicator — renders nothing (the regression guard expect(screen.queryByTestId('current-organization-indicator')).not.toBeInTheDocument(); }); - it('multiple memberships: that is the switcher’s case, not this one', async () => { - organizations = [SOLO, SECOND]; - mount(); - - await waitFor(() => expect(screen.getByTestId('posture')).toHaveTextContent('isolated')); - expect(screen.queryByTestId('current-organization-indicator')).not.toBeInTheDocument(); - expect(screen.queryByText('Titanwind EHR')).not.toBeInTheDocument(); - }); - it('no memberships at all: no organization context to name', async () => { organizations = []; mount(); diff --git a/ui/packages/app-shell/src/layout/__tests__/WorkspaceSwitcher.nativeConnectionSwitcher.test.tsx b/ui/packages/app-shell/src/layout/__tests__/WorkspaceSwitcher.nativeConnectionSwitcher.test.tsx index 5e16af21092..ace576bde2b 100644 --- a/ui/packages/app-shell/src/layout/__tests__/WorkspaceSwitcher.nativeConnectionSwitcher.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/WorkspaceSwitcher.nativeConnectionSwitcher.test.tsx @@ -4,11 +4,12 @@ * WorkspaceSwitcher inside the ObjectStack mobile shell. * * When the shell's bridge (`window.ObjectStackNative`, read through - * `@object-ui/mobile`) announces `showConnectionSwitcher`, the header's - * organization button opens the shell's native switcher and the web menu does - * not open. With no bridge, or a bridge without that capability, the web menu - * opens exactly as before. The dropdown is the real one, opened by a real - * click, so "the web menu opens" is observed, not assumed. + * `@object-ui/mobile`) announces `showConnectionSwitcher`, the top bar keeps an + * organization button that opens the shell's native switcher, and no web menu + * opens. With no bridge, or a bridge without that capability, the top bar + * draws no organization button at all: the web switcher is the avatar menu's + * (objectstack-ai/objectstack#34591, pinned in `WorkspaceSwitcher.test.tsx` + * and the AppHeader harness). * * In the shell the button renders at ONE membership too: the sheet lists the * shell's connections across servers, which this server's membership count @@ -105,30 +106,18 @@ describe('WorkspaceSwitcher in the mobile shell', () => { expect(authState.switchOrganization).not.toHaveBeenCalled(); }); - it('control: with no bridge, the button opens the web organization menu', async () => { + it('control: with no bridge, the top bar draws no organization button (the switcher is in the avatar menu)', () => { render(); - const button = screen.getByTestId('workspace-switcher'); - expect(button).not.toHaveAttribute('data-native-switcher'); - - await userEvent.click(button); - - expect(await screen.findByRole('menu')).toBeInTheDocument(); - expect(screen.getByText('Switch organization')).toBeInTheDocument(); - expect(screen.getByText('Plant B')).toBeInTheDocument(); + expect(screen.queryByTestId('workspace-switcher')).not.toBeInTheDocument(); + expect(screen.queryByText('Plant A')).not.toBeInTheDocument(); }); - it('control: a shell without the capability keeps the web menu and never calls the native switcher', async () => { + it('control: a shell without the capability draws no button and never calls the native switcher', () => { const showConnectionSwitcher = installBridge(BASE_METHODS); render(); - const button = screen.getByTestId('workspace-switcher'); - expect(button).not.toHaveAttribute('data-native-switcher'); - - await userEvent.click(button); - - expect(await screen.findByRole('menu')).toBeInTheDocument(); - expect(screen.getByText('Plant B')).toBeInTheDocument(); + expect(screen.queryByTestId('workspace-switcher')).not.toBeInTheDocument(); expect(showConnectionSwitcher).not.toHaveBeenCalled(); }); }); diff --git a/ui/packages/app-shell/src/layout/__tests__/WorkspaceSwitcher.noActiveOrg-12698.test.tsx b/ui/packages/app-shell/src/layout/__tests__/WorkspaceSwitcher.noActiveOrg-12698.test.tsx index e8b79c7fd50..59e6ee98f54 100644 --- a/ui/packages/app-shell/src/layout/__tests__/WorkspaceSwitcher.noActiveOrg-12698.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/WorkspaceSwitcher.noActiveOrg-12698.test.tsx @@ -4,12 +4,13 @@ * objectui#12698 — the header names the organization the SERVER reports as * active, never `orgList[0]`. * - * Real `AuthProvider` over a mocked auth server, real `WorkspaceSwitcher`. When - * the server holds no active organization (a refused `set-active` nulls it), - * the provider holds `activeOrganization = null`; the component used to fill - * that with the first membership and name an organization the session did not - * hold. The control case uses the identical harness, which is what proves the - * query can see the component when an organization is active. + * Real `AuthProvider` over a mocked auth server, real `WorkspaceSwitcherMenu` + * (the avatar menu's switcher; its submenu primitives pass through so the rows + * render inline). When the server holds no active organization (a refused + * `set-active` nulls it), the provider holds `activeOrganization = null`, and + * the switcher names no organization. The control case uses the identical + * harness, which is what proves the query can see the component when an + * organization is active. */ import '@testing-library/jest-dom/vitest'; @@ -18,7 +19,20 @@ import { describe, it, expect, vi, afterEach } from 'vitest'; import { cleanup, render, screen, waitFor } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; import { AuthProvider, useAuth, type AuthClient, type AuthOrganization } from '@object-ui/auth'; -import { WorkspaceSwitcher } from '../WorkspaceSwitcher'; + +vi.mock('@object-ui/components', async (importOriginal) => { + const Pass = ({ children, ...p }: any) =>
{children}
; + return { + ...(await importOriginal>()), + DropdownMenuSub: Pass, + DropdownMenuSubTrigger: Pass, + DropdownMenuSubContent: Pass, + DropdownMenuItem: Pass, + DropdownMenuLabel: Pass, + }; +}); + +import { WorkspaceSwitcherMenu } from '../WorkspaceSwitcher'; const PREV = { id: 'org_prev', name: 'Previous Org', slug: 'prev' } as AuthOrganization; const OTHER = { id: 'org_other', name: 'Other Org', slug: 'other' } as AuthOrganization; @@ -52,7 +66,7 @@ async function boot(active: AuthOrganization | null) { - + , ); @@ -64,20 +78,20 @@ afterEach(() => { localStorage.clear(); }); -describe('WorkspaceSwitcher names only the server-active organization (objectui#12698)', () => { +describe('WorkspaceSwitcherMenu names only the server-active organization (objectui#12698)', () => { it('(a) two memberships, server reports no active organization: no organization is named', async () => { await boot(null); // Let the tenancy-posture config fetch land too, so "nothing rendered" is not "not yet rendered". await new Promise((r) => setTimeout(r, 20)); - expect(screen.queryByTestId('workspace-switcher')).toBeNull(); + expect(screen.queryByTestId('header-switch-organization')).toBeNull(); for (const org of MEMBERSHIPS) expect(screen.queryByText(org.name)).toBeNull(); }); it('(b) control: the server-active organization is named as before', async () => { await boot(PREV); - const el = await screen.findByTestId('workspace-switcher'); - expect(el).toHaveTextContent(PREV.name); + expect(await screen.findByTestId('header-switch-organization')).toBeInTheDocument(); + expect(screen.getByTestId(`workspace-switcher-org-${PREV.id}`)).toHaveTextContent(PREV.name); }); }); diff --git a/ui/packages/app-shell/src/layout/__tests__/WorkspaceSwitcher.organizationNoun-12851.test.tsx b/ui/packages/app-shell/src/layout/__tests__/WorkspaceSwitcher.organizationNoun-12851.test.tsx index cb1830ffaf5..9b33228612d 100644 --- a/ui/packages/app-shell/src/layout/__tests__/WorkspaceSwitcher.organizationNoun-12851.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/WorkspaceSwitcher.organizationNoun-12851.test.tsx @@ -1,76 +1,69 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. /** - * objectui#12851 — the header-left switcher names the organisation 「组织」 / + * objectui#12851 — the organization switcher names the organisation 「组织」 / * "Organization" (the maintainer's ruling on objectstack-ai/cloud#2939, * letter A). Rendered through the REAL locale packs in zh-CN with en as the * control; the sibling `WorkspaceSwitcher.test.tsx` stubs `t()` to its inline - * default and cannot see a pack value. + * default and cannot see a pack value. The switcher is the avatar menu's + * submenu (objectstack-ai/objectstack#34591); the menu's own create entry is + * pinned by `AppHeader.organizationNoun-12851.test.tsx`. */ import '@testing-library/jest-dom/vitest'; -import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { describe, it, expect, vi } from 'vitest'; import { render, screen } from '@testing-library/react'; -const navigate = vi.fn(); -vi.mock('react-router-dom', () => ({ - useNavigate: () => navigate, -})); - const ORGS = [ { id: 'org_a', name: 'Plant A', slug: 'plant-a' }, { id: 'org_b', name: 'Plant B', slug: 'plant-b' }, ]; -const getAuthConfig = vi.fn().mockResolvedValue({ features: { multiOrgEnabled: true } }); vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), useAuth: () => ({ organizations: ORGS, activeOrganization: ORGS[0], switchOrganization: vi.fn(), - getAuthConfig, }), })); vi.mock('../../console/organizations/resolveHomeUrl', () => ({ resolveRootUrl: () => '/root' })); -// Passthrough dropdown primitives: the open menu's content renders inline. -vi.mock('@object-ui/components', async (importOriginal) => ({ - ...(await importOriginal>()), - DropdownMenu: (p: any) =>
{p.children}
, - DropdownMenuTrigger: (p: any) => + ), + DropdownMenuLabel: Pass, + }; +}); -import { WorkspaceSwitcher } from '../WorkspaceSwitcher'; +import { NATIVE_HOST_GLOBAL } from '@object-ui/mobile'; +import { WorkspaceSwitcherMenu } from '../WorkspaceSwitcher'; const ORGS = [ { id: 'org_a', name: 'Plant A', slug: 'plant-a' }, { id: 'org_b', name: 'Plant B', slug: 'plant-b' }, ]; -function setAuthConfig(features: Record) { +beforeEach(() => { + delete (window as unknown as Record)[NATIVE_HOST_GLOBAL]; authState = { organizations: ORGS, activeOrganization: ORGS[0], - switchOrganization: vi.fn(), - getAuthConfig: vi.fn().mockResolvedValue({ features }), + switchOrganization: vi.fn(async () => undefined), }; -} + window.history.replaceState(null, '', '/'); +}); -beforeEach(() => { - vi.clearAllMocks(); +afterEach(() => { + delete (window as unknown as Record)[NATIVE_HOST_GLOBAL]; + window.history.replaceState(null, '', '/'); }); -describe('WorkspaceSwitcher (ADR-0105 tenancy posture)', () => { - it('group posture: labels the active org as the working organization and explains the read/write split', async () => { - setAuthConfig({ multiOrgEnabled: true, tenancyPosture: 'group' }); - render(); - await waitFor(() => { - expect(screen.getByText('Working organization')).toBeInTheDocument(); - }); +describe('WorkspaceSwitcherMenu (ADR-0105 tenancy posture)', () => { + it('group posture: labels the active org as the working organization and explains the read/write split', () => { + render(); + expect(screen.getByText('Working organization')).toBeInTheDocument(); expect(screen.getByTestId('workspace-switcher-group-hint')).toHaveTextContent( 'New records are created here. Views show data from all your organizations.', ); - expect(screen.queryByText('Switch organization')).not.toBeInTheDocument(); + // The submenu is still reached by its plain entry in the avatar menu. + expect(screen.getByTestId('header-switch-organization')).toHaveTextContent('Switch organization'); }); - it('isolated posture: keeps the plain switch label with no group hint', async () => { - setAuthConfig({ multiOrgEnabled: true, tenancyPosture: 'isolated' }); - render(); - // The posture fetch resolves async — assert the steady state. - await waitFor(() => { - expect((authState.getAuthConfig as ReturnType).mock.calls.length).toBeGreaterThan(0); - }); - expect(screen.getByText('Switch organization')).toBeInTheDocument(); + it('any other posture: the plain switch entry, with no group hint', () => { + render(); + expect(screen.getByTestId('header-switch-organization')).toHaveTextContent('Switch organization'); + expect(screen.queryByText('Working organization')).not.toBeInTheDocument(); expect(screen.queryByTestId('workspace-switcher-group-hint')).not.toBeInTheDocument(); }); +}); - it('absent or unrecognized posture fails toward today\'s rendering', async () => { - setAuthConfig({ multiOrgEnabled: true, tenancyPosture: 'weird-future-value' }); - render(); - await waitFor(() => { - expect((authState.getAuthConfig as ReturnType).mock.calls.length).toBeGreaterThan(0); - }); - expect(screen.getByText('Switch organization')).toBeInTheDocument(); - expect(screen.queryByTestId('workspace-switcher-group-hint')).not.toBeInTheDocument(); +describe('WorkspaceSwitcherMenu — rows and switching', () => { + it('lists every membership; picking another one switches and reloads to the console root', async () => { + render(); + expect(screen.getByTestId('workspace-switcher-org-org_a')).toHaveTextContent('Plant A'); + + fireEvent.click(screen.getByTestId('workspace-switcher-org-org_b')); + await act(() => new Promise((resolve) => setTimeout(resolve, 0))); + + expect(authState.switchOrganization).toHaveBeenCalledWith('org_b'); + expect(window.location.hash).toBe('#switched'); + }); + + it('picking the active organization sends nothing', async () => { + render(); + fireEvent.click(screen.getByTestId('workspace-switcher-org-org_a')); + await act(() => new Promise((resolve) => setTimeout(resolve, 0))); + + expect(authState.switchOrganization).not.toHaveBeenCalled(); + expect(window.location.hash).toBe(''); + }); +}); + +describe('WorkspaceSwitcherMenu — renders nothing', () => { + it('at one membership: nothing to switch to', () => { + authState = { ...authState, organizations: [ORGS[0]] }; + render(); + expect(screen.queryByTestId('header-switch-organization')).not.toBeInTheDocument(); + }); + + it('without a server-active organization (objectui#12698)', () => { + authState = { ...authState, activeOrganization: null }; + render(); + expect(screen.queryByTestId('header-switch-organization')).not.toBeInTheDocument(); + for (const org of ORGS) expect(screen.queryByText(org.name)).not.toBeInTheDocument(); + }); + + it('inside a mobile shell that announces its own switcher', () => { + const capabilities = ['showConnectionSwitcher']; + (window as unknown as Record)[NATIVE_HOST_GLOBAL] = { + version: 1, + platform: 'ios', + appVersion: '2.1.0', + capabilities, + safeArea: { top: 0, bottom: 0, left: 0, right: 0 }, + has: (capability: string) => capabilities.includes(capability), + showConnectionSwitcher: vi.fn(async () => null), + ready: vi.fn(), + routeChanged: vi.fn(), + }; + render(); + expect(screen.queryByTestId('header-switch-organization')).not.toBeInTheDocument(); + }); + + it('control: the same harness with no shell renders the entry', () => { + render(); + expect(screen.getByTestId('header-switch-organization')).toBeInTheDocument(); + }); +}); + +describe('WorkspaceSwitcherMenu — phone width: inline rows, no submenu', () => { + // A submenu opens beside the avatar menu; at phone width the menu already + // spans the screen, so a submenu would open off the screen. Below the phone + // breakpoint the rows render inline under a label instead. + const realWidth = window.innerWidth; + const setWidth = (w: number) => + Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: w }); + afterEach(() => setWidth(realWidth)); + + it('at 375 px: no sub-trigger; the label and every row render inline, and a row still switches', async () => { + setWidth(375); + render(); + expect(screen.queryByTestId('header-switch-organization')).not.toBeInTheDocument(); + expect(screen.getByTestId('header-switch-organization-label')).toHaveTextContent('Switch organization'); + const group = screen.getByTestId('workspace-switcher-menu'); + for (const org of ORGS) expect(group).toContainElement(screen.getByTestId(`workspace-switcher-org-${org.id}`)); + + fireEvent.click(screen.getByTestId('workspace-switcher-org-org_b')); + await act(() => new Promise((resolve) => setTimeout(resolve, 0))); + expect(authState.switchOrganization).toHaveBeenCalledWith('org_b'); + }); + + it('at 375 px under group posture: the working-organization hint stays, width-bounded so it wraps', () => { + setWidth(375); + render(); + // The menu sizes to its content: an unbounded hint line widened it to 442 px on a 375 px screen. + expect(screen.getByTestId('workspace-switcher-group-hint')).toHaveClass('max-w-60'); + }); + + it('control: at 1024 px the submenu trigger renders and the inline label does not', () => { + setWidth(1024); + render(); + expect(screen.getByTestId('header-switch-organization')).toBeInTheDocument(); + expect(screen.queryByTestId('header-switch-organization-label')).not.toBeInTheDocument(); }); });