diff --git a/.changeset/37833-hide-ai-chat-entry-without-agent.md b/.changeset/37833-hide-ai-chat-entry-without-agent.md
new file mode 100644
index 00000000000..f0568e0cba2
--- /dev/null
+++ b/.changeset/37833-hide-ai-chat-entry-without-agent.md
@@ -0,0 +1,20 @@
+---
+'@object-ui/app-shell': patch
+'@object-ui/plugin-chatbot': patch
+---
+
+feat(app-shell): the `ai:chat` menu entry is hidden from a member who cannot get an agent, and the app's home falls to the next entry
+
+Clause-②: no
+Metadata-protocol: none
+
+An app's AI inquiry entry (`type: 'component'`, `componentRef: 'ai:chat'`) is now shown only to a member the access-filtered agent catalog (`GET /api/v1/ai/agents`) serves at least one agent. On a deployment with no AI, or for a member with no AI seat, the entry is left out of the sidebar, the phone's app menu, the command palette and the `nav:menu` block. If it was the app's home, the home is the next entry the member is shown.
+
+- **A declared `landing`** still comes first. A landing entry whose `item` is the `ai:chat` entry is passed over for such a member, like any entry the member is not shown: the next declared entry that holds lands, and with none the first entry shown lands.
+- **While the catalog is loading** the entry is not drawn, and the app root waits on its loading skeleton instead of opening the page or the next entry. It lands once the catalog answers, so the home never opens one page and then jumps to another.
+- **A direct link to the page** is not redirected. The page draws its "AI assistant unavailable" state.
+- The catalog is read only while an app in the list carries an `ai:chat` entry. Apps without one read nothing new.
+- `useAiSurfaceEnabled` takes an optional `{ enabled }` and no longer reports loading for ever when the catalog is empty and is answered from the session cache. Before, a member with no seat who opened the `ai:chat` page after the console had read the catalog saw a blank loading page and never the unavailable state.
+- `@object-ui/plugin-chatbot`: `useAgents` returns `settled`, true once a catalog read for the current `apiBase` has answered or failed. The fields it already returned are unchanged.
+
+Nothing to migrate.
diff --git a/ui/packages/app-shell/src/console/__tests__/AppContent.aiChatEntryGate-37833.test.tsx b/ui/packages/app-shell/src/console/__tests__/AppContent.aiChatEntryGate-37833.test.tsx
new file mode 100644
index 00000000000..09edbee89e4
--- /dev/null
+++ b/ui/packages/app-shell/src/console/__tests__/AppContent.aiChatEntryGate-37833.test.tsx
@@ -0,0 +1,475 @@
+// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
+
+/**
+ * objectstack#37833 — an app's `ai:chat` entry (ui ADR-0057 Amendment A4) is
+ * shown only to a member who can get an agent, and the app's home falls to the
+ * next entry for one who cannot.
+ *
+ * "Can get an agent" is the access-filtered agent catalog
+ * (`useAiSurfaceEnabled`): on a deployment with no AI the catalog route is not
+ * served (Community Edition answers 404), and a member with no AI seat is
+ * served an empty catalog. Both hide the entry.
+ *
+ * ## Real subjects
+ *
+ * The real `AppContent` and its app-root landing, the real `ExpressionProvider`
+ * it mounts, the real `MePermissionsProvider` above it, the real
+ * `useNavMemberGates` / `navEntriesShownToMember` (the gates the sidebar, the
+ * phone's app menu and the landing all read), the real `useAiSurfaceEnabled`
+ * and `useAgents` over a held `apiFetch` on `SchemaRendererContext`, and the
+ * real `AppAskPage` behind the registry's `ai:chat` entry. Stand-ins:
+ * `ConsoleLayout` and the lazily imported pages (as in
+ * `AppContent.landingWaitsReads-13097.test.tsx`), the app metadata, and the
+ * page's two heavy children, `ChatPane` and `AiUnavailable` (the page's job
+ * here is to render the latter, not what it draws).
+ */
+
+import '@testing-library/jest-dom/vitest';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+// The page reaches a dynamic `@objectstack/lint` import; its first load is paid
+// here, at collection, never inside a case's clock (`check:test-source-alias`).
+import '@objectstack/lint';
+import React from 'react';
+import { render, screen, waitFor, act } from '@testing-library/react';
+import { createRoot } from 'react-dom/client';
+import { MemoryRouter, Routes, Route, useLocation } from 'react-router-dom';
+import { AI_CHAT_COMPONENT_REF } from '@objectstack/spec/ui';
+import { MePermissionsProvider, type MePermissionsResponse } from '@object-ui/permissions';
+import { SchemaRendererContext, type ApiFetch } from '@object-ui/react';
+import type { NavigationItem } from '@object-ui/types';
+import { __resetAgentsCatalog } from '../../../../plugin-chatbot/src/useAgents';
+
+// AGENTS.md §测试纪律 — the lazy page modules are stubbed so no unbounded
+// `import()` races a bounded `findBy` window.
+vi.mock('../../views/metadata-admin', () => ({
+ MetadataDirectoryPage: () =>
,
+ MetadataResourceListPage: () => ,
+ MetadataResourceEditPage: () => ,
+ MetadataResourceHistoryPage: () => ,
+ MetadataDiagnosticsPage: () => ,
+}));
+
+vi.mock('@object-ui/plugin-designer', async (importOriginal) => ({
+ ...(await importOriginal()),
+ CreateAppPage: () => ,
+ EditAppPage: () => ,
+ DashboardDesignPage: () => ,
+}));
+
+vi.mock('../../layout/ConsoleLayout', () => ({
+ ConsoleLayout: ({ activeAppName, children }: { activeAppName?: string; children?: React.ReactNode }) => (
+
+ {children}
+
+ ),
+}));
+vi.mock('../../chrome/CommandPalette', () => ({ CommandPalette: () => null }));
+vi.mock('../../chrome/KeyboardShortcutsDialog', () => ({ KeyboardShortcutsDialog: () => null }));
+vi.mock('../../chrome/OnboardingWalkthrough', () => ({ OnboardingWalkthrough: () => null }));
+vi.mock('../../views/ObjectView', () => ({
+ ObjectView: () => ,
+}));
+vi.mock('../ai/AiUnavailable', () => ({ AiUnavailable: () => }));
+vi.mock('../ai/AiChatPage', () => ({ ChatPane: () => }));
+
+vi.mock('@object-ui/i18n', async (importOriginal) => ({
+ ...(await importOriginal>()),
+ useObjectTranslation: () => ({
+ t: (key: string, options?: Record) =>
+ String(options?.defaultValue ?? key).replace(/\{\{(\w+)\}\}/g, (_m, name: string) => String(options?.[name] ?? '')),
+ language: 'en',
+ }),
+ useObjectLabel: () => ({
+ objectLabel: ({ label }: { label?: string }) => label,
+ objectPluralLabel: ({ label }: { label?: string }) => label,
+ appLabel: ({ name, label }: { name: string; label?: string }) => label ?? name,
+ }),
+}));
+
+// One auth value for every render, as the real provider memoises it.
+const authValue = {
+ user: { id: 'u_1', name: 'Member', email: 'member@example.com', role: 'member' },
+ getAuthConfig: async () => ({ features: {} }),
+ activeOrganization: { id: 'org_1', name: 'Org' },
+};
+vi.mock('@object-ui/auth', async (importOriginal) => ({
+ ...(await importOriginal>()),
+ useAuth: () => authValue,
+ useWorkspaceAdminStatus: () => ({ isAdmin: false, isResolved: true }),
+}));
+
+const dataSourceStub = {
+ onConnectionStateChange: () => () => {},
+ getConnectionState: () => 'connected',
+};
+vi.mock('../../providers/AdapterProvider', async (importOriginal) => ({
+ ...(await importOriginal>()),
+ useAdapter: () => dataSourceStub,
+}));
+
+/** The app list as the server hands it to this session. */
+let metadataApps: unknown[] = [];
+vi.mock('../../providers/MetadataProvider', async (importOriginal) => ({
+ ...(await importOriginal>()),
+ useMetadata: () => ({
+ apps: metadataApps,
+ objects: [],
+ loading: false,
+ ensureType: undefined,
+ error: null,
+ refresh: vi.fn(async () => {}),
+ }),
+}));
+
+const actionRunnerStub = { registerHandler: vi.fn(), getContext: () => ({}) };
+vi.mock('@object-ui/react', async (importOriginal) => ({
+ ...(await importOriginal>()),
+ useActionRunner: () => ({ execute: vi.fn(), runner: actionRunnerStub }),
+ useGlobalUndo: () => {},
+ useMutationInvalidationBridge: () => {},
+}));
+
+import { AppContent } from '../AppContent';
+import { AppAskPage } from '../ai/AppAskPage';
+import { registerAppComponent } from '../../services/componentRegistry';
+import { useNavMemberGates, navEntriesShownToMember } from '../../hooks/useNavMemberGates';
+
+// The registry's `ai:chat` entry, with the page module loaded at collection.
+registerAppComponent({ ref: AI_CHAT_COMPONENT_REF, label: 'AI Inquiry', source: '@object-ui/app-shell', component: AppAskPage });
+
+const AGENTS_URL = '/api/v1/ai/agents';
+const SERVED = { success: true, data: { agents: [{ name: 'ask', label: 'Ask' }] } };
+const NO_SEAT = { success: true, data: { agents: [] } };
+
+/** Every pathname the router held, in order. */
+let pathnames: string[] = [];
+function LocationProbe() {
+ const location = useLocation();
+ React.useEffect(() => {
+ if (pathnames[pathnames.length - 1] !== location.pathname) pathnames.push(location.pathname);
+ }, [location.pathname]);
+ return {location.pathname}
;
+}
+
+/** The ids of the entries this member is shown, through the gates the sidebar draws with. */
+function MenuProbe({ app }: { app: { navigation: NavigationItem[] } }) {
+ const gates = useNavMemberGates(app as unknown as Record);
+ const shown = navEntriesShownToMember(app.navigation, gates);
+ return {shown.map((item) => item.id).join(',')}
;
+}
+
+const EVERYTHING_READABLE = {
+ authenticated: true,
+ userId: 'u_1',
+ tenantId: null,
+ positions: [],
+ hasAnyQueue: false,
+ objectsUsingQueues: [],
+ permissionSets: [],
+ objects: { '*': { allowRead: true } },
+ fields: {},
+} as MePermissionsResponse;
+
+/** An `apiFetch` whose answers the test releases, one per URL. */
+function heldApiFetch() {
+ const releases = new Map void>();
+ const apiFetch = vi.fn(
+ (url) =>
+ new Promise((resolve) => {
+ releases.set(String(url), (status, body) =>
+ resolve({ ok: status >= 200 && status < 300, status, json: async () => body } as unknown as Response),
+ );
+ }),
+ );
+ /** Answer `url`, then let the settled read reach the state it sets. */
+ const answer = async (url: string, status: number, body?: unknown) => {
+ await waitFor(() => expect(releases.has(url)).toBe(true));
+ await act(async () => {
+ releases.get(url)!(status, body);
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+ };
+ return { apiFetch, answer };
+}
+
+const askEntry = { id: 'nav_ask', type: 'component', label: 'Ask', componentRef: AI_CHAT_COMPONENT_REF };
+const plainEntry = (id: string, objectName: string) => ({ id, type: 'object', objectName, label: objectName });
+const policyApp = (extra: Record = {}) => ({
+ name: 'policy',
+ label: 'Policy',
+ navigation: [askEntry, plainEntry('nav_cases', 'crm_case'), plainEntry('nav_accounts', 'crm_account')],
+ ...extra,
+});
+
+function withProviders(apiFetch: ApiFetch, children: React.ReactNode) {
+ return (
+
+ {children}
+
+ );
+}
+
+function renderConsoleAt(initialUrl: string, apiFetch: ApiFetch) {
+ return render(
+ withProviders(
+ apiFetch,
+
+
+
+ } />
+
+ ,
+ ),
+ );
+}
+
+function renderMenu(app: { navigation: NavigationItem[] }, apiFetch: ApiFetch) {
+ return render(withProviders(apiFetch, ));
+}
+
+const pathname = () => screen.getByTestId('pathname').textContent;
+
+describe('objectstack#37833 — the ai:chat entry is hidden from a member who cannot get an agent', () => {
+ beforeEach(() => {
+ metadataApps = [];
+ pathnames = [];
+ __resetAgentsCatalog();
+ });
+
+ describe('the menu (the gates the sidebar and the phone app menu draw with)', () => {
+ it('community edition (the catalog route is not served): the entry is absent', async () => {
+ const app = policyApp();
+ metadataApps = [app];
+ const { apiFetch, answer } = heldApiFetch();
+ renderMenu(app as never, apiFetch);
+ // Not shown while the catalog has not answered: it never appears and then leaves.
+ expect(screen.getByTestId('menu').textContent).toBe('nav_cases,nav_accounts');
+ await answer(AGENTS_URL, 404);
+ expect(screen.getByTestId('menu').textContent).toBe('nav_cases,nav_accounts');
+ });
+
+ it('a member with no AI seat (an empty catalog): the entry is absent', async () => {
+ const app = policyApp();
+ metadataApps = [app];
+ const { apiFetch, answer } = heldApiFetch();
+ renderMenu(app as never, apiFetch);
+ await answer(AGENTS_URL, 200, NO_SEAT);
+ expect(screen.getByTestId('menu').textContent).toBe('nav_cases,nav_accounts');
+ });
+
+ it('CONTROL: a member the catalog serves an agent sees the entry', async () => {
+ const app = policyApp();
+ metadataApps = [app];
+ const { apiFetch, answer } = heldApiFetch();
+ renderMenu(app as never, apiFetch);
+ await answer(AGENTS_URL, 200, SERVED);
+ expect(screen.getByTestId('menu').textContent).toBe('nav_ask,nav_cases,nav_accounts');
+ });
+
+ it('CONTROL: an app list with no ai:chat entry never asks the catalog', async () => {
+ const app = { name: 'crm', label: 'CRM', navigation: [plainEntry('nav_cases', 'crm_case')] };
+ metadataApps = [app];
+ const { apiFetch } = heldApiFetch();
+ renderMenu(app as never, apiFetch);
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ });
+ expect(screen.getByTestId('menu').textContent).toBe('nav_cases');
+ expect(apiFetch).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('the app home', () => {
+ it('community edition: the home is the next entry, with no stop on the ai:chat page', async () => {
+ metadataApps = [policyApp()];
+ const { apiFetch, answer } = heldApiFetch();
+ renderConsoleAt('/apps/policy', apiFetch);
+
+ // While the catalog has not answered the root holds: it opens neither entry.
+ await waitFor(() => expect(apiFetch).toHaveBeenCalledWith(AGENTS_URL, expect.objectContaining({ method: 'GET' })));
+ expect(screen.getByTestId('app-landing-pending')).toBeInTheDocument();
+ expect(pathname()).toBe('/apps/policy');
+
+ await answer(AGENTS_URL, 404);
+ expect(await screen.findByTestId('object-view')).toBeInTheDocument();
+ expect(pathname()).toBe('/apps/policy/crm_case');
+ expect(pathnames).toEqual(['/apps/policy', '/apps/policy/crm_case']);
+ });
+
+ it('a member with no AI seat: the home is the next entry, with no stop on the ai:chat page', async () => {
+ metadataApps = [policyApp()];
+ const { apiFetch, answer } = heldApiFetch();
+ renderConsoleAt('/apps/policy', apiFetch);
+
+ await waitFor(() => expect(apiFetch).toHaveBeenCalled());
+ expect(screen.getByTestId('app-landing-pending')).toBeInTheDocument();
+ await answer(AGENTS_URL, 200, NO_SEAT);
+ expect(await screen.findByTestId('object-view')).toBeInTheDocument();
+ expect(pathnames).toEqual(['/apps/policy', '/apps/policy/crm_case']);
+ });
+
+ it('CONTROL: a member the catalog serves an agent lands on the ai:chat page, with no stop on the next entry', async () => {
+ metadataApps = [policyApp()];
+ const { apiFetch, answer } = heldApiFetch();
+ renderConsoleAt('/apps/policy', apiFetch);
+
+ await waitFor(() => expect(apiFetch).toHaveBeenCalled());
+ expect(screen.getByTestId('app-landing-pending')).toBeInTheDocument();
+ await answer(AGENTS_URL, 200, SERVED);
+ expect(await screen.findByTestId('app-ask-home')).toBeInTheDocument();
+ expect(pathnames).toEqual(['/apps/policy', '/apps/policy/component/ai/chat']);
+ });
+
+ it('a declared landing that names the ai:chat entry is passed over for a member with no agent', async () => {
+ // `resolveDeclaredLandingRoute` looks the named entry up among the entries
+ // the member is shown; the gated entry is not one, so the next declared
+ // entry that holds lands.
+ metadataApps = [
+ policyApp({
+ landing: [
+ { item: 'nav_ask', visible: true },
+ { item: 'nav_accounts', visible: true },
+ ],
+ }),
+ ];
+ const { apiFetch, answer } = heldApiFetch();
+ renderConsoleAt('/apps/policy', apiFetch);
+
+ await waitFor(() => expect(apiFetch).toHaveBeenCalled());
+ await answer(AGENTS_URL, 200, NO_SEAT);
+ expect(await screen.findByTestId('object-view')).toBeInTheDocument();
+ expect(pathnames).toEqual(['/apps/policy', '/apps/policy/crm_account']);
+ });
+
+ it('a declared landing that names only the ai:chat entry falls to the first entry the member is shown', async () => {
+ metadataApps = [policyApp({ landing: [{ item: 'nav_ask', visible: true }] })];
+ const { apiFetch, answer } = heldApiFetch();
+ renderConsoleAt('/apps/policy', apiFetch);
+
+ await waitFor(() => expect(apiFetch).toHaveBeenCalled());
+ await answer(AGENTS_URL, 404);
+ expect(await screen.findByTestId('object-view')).toBeInTheDocument();
+ expect(pathnames).toEqual(['/apps/policy', '/apps/policy/crm_case']);
+ });
+ });
+
+ // The console reads the catalog on every open (the top-bar robot), so a
+ // surface that mounts later is usually answered by `useAgents`' module cache.
+ // That answer arrives in the same render that clears the loading flag, so
+ // these cases mount with React's act environment OFF: under `act` every
+ // queued update is flushed one by one and the loading render is seen, which
+ // a browser never does (the cases pass there on a latch that hangs here).
+ describe('a catalog the session already holds, scheduled as a browser schedules it', () => {
+ async function warmTheCatalog(body: unknown) {
+ const { apiFetch, answer } = heldApiFetch();
+ const first = renderMenu(policyApp() as never, apiFetch);
+ await answer(AGENTS_URL, 200, body);
+ first.unmount();
+ return apiFetch;
+ }
+
+ /** Mount the console at `url` outside `act`, as the browser does; returns its unmount. */
+ function mountOutsideAct(url: string, apiFetch: ApiFetch): () => void {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ const actEnv = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean };
+ actEnv.IS_REACT_ACT_ENVIRONMENT = false;
+ root.render(
+ withProviders(
+ apiFetch,
+
+
+
+ } />
+
+ ,
+ ),
+ );
+ return () => {
+ root.unmount();
+ host.remove();
+ actEnv.IS_REACT_ACT_ENVIRONMENT = true;
+ };
+ }
+
+ /** Poll the document, outside `act`, until `testId` is drawn or `ms` passes. */
+ async function drawn(testId: string, ms = 2000): Promise {
+ const until = Date.now() + ms;
+ while (Date.now() < until) {
+ if (document.querySelector(`[data-testid="${testId}"]`)) return true;
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ }
+ return false;
+ }
+
+ it('a member with no AI seat: the home is the next entry, not a hold that never ends', async () => {
+ metadataApps = [policyApp()];
+ const apiFetch = await warmTheCatalog(NO_SEAT);
+ pathnames = [];
+ const unmount = mountOutsideAct('/apps/policy', apiFetch);
+ try {
+ expect(await drawn('object-view')).toBe(true);
+ expect(pathnames).toEqual(['/apps/policy', '/apps/policy/crm_case']);
+ } finally {
+ unmount();
+ }
+ });
+
+ it('a direct link for a member with no AI seat: the page draws AiUnavailable, not its loading state', async () => {
+ metadataApps = [policyApp()];
+ const apiFetch = await warmTheCatalog(NO_SEAT);
+ // The page alone, as the component route mounts it: the console's other
+ // renders in the same window would flush the loading render it must
+ // never depend on.
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ const actEnv = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean };
+ actEnv.IS_REACT_ACT_ENVIRONMENT = false;
+ root.render(
+ withProviders(
+ apiFetch,
+
+
+ } />
+
+ ,
+ ),
+ );
+ try {
+ expect(await drawn('ai-unavailable')).toBe(true);
+ expect(document.querySelector('[data-testid="app-ask-page-loading"]')).toBeNull();
+ } finally {
+ root.unmount();
+ host.remove();
+ actEnv.IS_REACT_ACT_ENVIRONMENT = true;
+ }
+ });
+
+ it('CONTROL: a member the catalog serves an agent lands on the ai:chat page', async () => {
+ metadataApps = [policyApp()];
+ const apiFetch = await warmTheCatalog(SERVED);
+ pathnames = [];
+ const unmount = mountOutsideAct('/apps/policy', apiFetch);
+ try {
+ expect(await drawn('app-ask-home')).toBe(true);
+ expect(pathnames).toEqual(['/apps/policy', '/apps/policy/component/ai/chat']);
+ } finally {
+ unmount();
+ }
+ });
+ });
+
+ describe('a direct link to the page', () => {
+ it('is not redirected: the page draws its own unavailable state for a member with no agent', async () => {
+ metadataApps = [policyApp()];
+ const { apiFetch, answer } = heldApiFetch();
+ renderConsoleAt('/apps/policy/component/ai/chat', apiFetch);
+
+ await answer(AGENTS_URL, 200, NO_SEAT);
+ expect(await screen.findByTestId('ai-unavailable')).toBeInTheDocument();
+ expect(pathnames).toEqual(['/apps/policy/component/ai/chat']);
+ });
+ });
+});
diff --git a/ui/packages/app-shell/src/console/home/__tests__/HomePage.openMarksRead.test.tsx b/ui/packages/app-shell/src/console/home/__tests__/HomePage.openMarksRead.test.tsx
index 9d4b4793d18..b95c35d5a56 100644
--- a/ui/packages/app-shell/src/console/home/__tests__/HomePage.openMarksRead.test.tsx
+++ b/ui/packages/app-shell/src/console/home/__tests__/HomePage.openMarksRead.test.tsx
@@ -82,7 +82,12 @@ vi.mock('../../../context/NavigationContext', () => ({
vi.mock('../../../hooks/useRecentItems', () => ({ useRecentItems: () => ({ recentItems: [] }) }));
vi.mock('../../../hooks/useFavorites', () => ({ useFavorites: () => ({ favorites: [] }) }));
-vi.mock('../../../hooks/useAiSurface', () => ({ resolveAiApiBase: () => '' }));
+// The bell's roster gates navigation through `useNavMemberGates`, which asks
+// the AI surface whether to draw an app's `ai:chat` entry (objectstack#37833).
+vi.mock('../../../hooks/useAiSurface', () => ({
+ resolveAiApiBase: () => '',
+ useAiSurfaceEnabled: () => ({ enabled: false, isLoading: false, buildServed: false, focusServed: false }),
+}));
vi.mock('../../../views/metadata-admin/useMetadata', () => ({
useMetadataClient: () => ({ listDrafts: async () => [] }),
}));
diff --git a/ui/packages/app-shell/src/hooks/__tests__/useAiSurface.test.ts b/ui/packages/app-shell/src/hooks/__tests__/useAiSurface.test.ts
index 5293807ed5f..de38e9a03bc 100644
--- a/ui/packages/app-shell/src/hooks/__tests__/useAiSurface.test.ts
+++ b/ui/packages/app-shell/src/hooks/__tests__/useAiSurface.test.ts
@@ -11,12 +11,13 @@ vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({
}));
const mockAgents = vi.mocked(useAgents);
-function agentsResult(names: string[], isLoading: boolean) {
+function agentsResult(names: string[], isLoading: boolean, settled = false) {
return {
agents: names.map((name) => ({ name, label: name })),
isLoading,
error: undefined,
refetch: vi.fn(),
+ settled,
};
}
@@ -51,12 +52,20 @@ describe('useAiSurfaceEnabled', () => {
const { result, rerender } = renderHook(() => useAiSurfaceEnabled());
expect(result.current.isLoading).toBe(true);
- mockAgents.mockReturnValue(agentsResult([], false));
+ mockAgents.mockReturnValue(agentsResult([], false, true));
rerender();
expect(result.current).toEqual({ enabled: false, isLoading: false, buildServed: false, focusServed: false });
});
});
+describe('useAiSurfaceEnabled — an empty catalog the cache answers (objectstack#37833)', () => {
+ it('is disabled, not loading, on the first render that holds a settled empty answer, never seen loading', () => {
+ mockAgents.mockReturnValue(agentsResult([], false, true));
+ const { result } = renderHook(() => useAiSurfaceEnabled());
+ expect(result.current).toEqual({ enabled: false, isLoading: false, buildServed: false, focusServed: false });
+ });
+});
+
describe('useAiSurfaceEnabled — buildServed reads the build agent itself (objectstack#36969)', () => {
it('in-app building closed (`ask` served, `build` not): AI is on, and building is not served', () => {
mockAgents.mockReturnValue(agentsResult(['ask'], false));
diff --git a/ui/packages/app-shell/src/hooks/__tests__/useAiSurface.warmCatalog-37833.test.tsx b/ui/packages/app-shell/src/hooks/__tests__/useAiSurface.warmCatalog-37833.test.tsx
new file mode 100644
index 00000000000..e176da74eb3
--- /dev/null
+++ b/ui/packages/app-shell/src/hooks/__tests__/useAiSurface.warmCatalog-37833.test.tsx
@@ -0,0 +1,91 @@
+// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
+
+/**
+ * objectstack#37833 — `useAiSurfaceEnabled` leaves its loading state when the
+ * agent catalog is empty and the session cache answers it.
+ *
+ * The console reads the catalog on every open, so a surface that mounts later
+ * (the app root's landing, the `ai:chat` page on a direct link) is answered by
+ * `useAgents`' module cache: `isLoading` goes true and false before React
+ * renders once. Read through a latch that only a render seeing `isLoading`
+ * could set, a member with no AI seat stayed "loading" for ever; it reads
+ * `useAgents`' `settled` now.
+ *
+ * Real `useAgents` (this is why the file is not a `describe` in
+ * `useAiSurface.test.ts`, which mocks it) over a stubbed `apiFetch`, mounted
+ * with `createRoot` and React's act environment OFF, as a browser schedules:
+ * under `act` each queued update is flushed in turn and the loading render is
+ * seen, which hides the defect.
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import React from 'react';
+import { createRoot } from 'react-dom/client';
+import { SchemaRendererContext, type ApiFetch } from '@object-ui/react';
+import { __resetAgentsCatalog } from '../../../../plugin-chatbot/src/useAgents';
+import { useAiSurfaceEnabled } from '../useAiSurface';
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+const actEnv = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean };
+let savedActEnv: boolean | undefined;
+
+function catalogFetch(agents: unknown[]): ApiFetch {
+ return (async () => {
+ await sleep(20);
+ return { ok: true, status: 200, json: async () => ({ success: true, data: { agents } }) } as unknown as Response;
+ }) as ApiFetch;
+}
+
+/** Mount `useAiSurfaceEnabled` outside `act`; every render's `enabled/isLoading` is recorded. */
+function mount(apiFetch: ApiFetch) {
+ const renders: string[] = [];
+ function Probe() {
+ const surface = useAiSurfaceEnabled();
+ renders.push(`${surface.enabled}/${surface.isLoading}`);
+ return null;
+ }
+ const root = createRoot(document.createElement('div'));
+ root.render(
+
+
+ ,
+ );
+ return { renders, unmount: () => root.unmount() };
+}
+
+beforeEach(() => {
+ __resetAgentsCatalog();
+ savedActEnv = actEnv.IS_REACT_ACT_ENVIRONMENT;
+ actEnv.IS_REACT_ACT_ENVIRONMENT = false;
+});
+
+afterEach(() => {
+ actEnv.IS_REACT_ACT_ENVIRONMENT = savedActEnv;
+});
+
+describe('useAiSurfaceEnabled on a catalog the session cache answers (objectstack#37833)', () => {
+ it('an empty catalog: loading on the cold read, then disabled and not loading on the warm one', async () => {
+ const apiFetch = catalogFetch([]);
+ const cold = mount(apiFetch);
+ await sleep(200);
+ expect(cold.renders[0]).toBe('false/true');
+ expect(cold.renders[cold.renders.length - 1]).toBe('false/false');
+ cold.unmount();
+
+ const warm = mount(apiFetch);
+ await sleep(200);
+ expect(warm.renders[0]).toBe('false/true');
+ expect(warm.renders[warm.renders.length - 1]).toBe('false/false');
+ warm.unmount();
+ });
+
+ it('CONTROL: a served catalog is enabled on the warm read', async () => {
+ const apiFetch = catalogFetch([{ name: 'ask', label: 'Ask' }]);
+ const cold = mount(apiFetch);
+ await sleep(200);
+ cold.unmount();
+ const warm = mount(apiFetch);
+ await sleep(200);
+ expect(warm.renders[warm.renders.length - 1]).toBe('true/false');
+ warm.unmount();
+ });
+});
diff --git a/ui/packages/app-shell/src/hooks/useAiSurface.ts b/ui/packages/app-shell/src/hooks/useAiSurface.ts
index 539f4bf3548..116bd6c430e 100644
--- a/ui/packages/app-shell/src/hooks/useAiSurface.ts
+++ b/ui/packages/app-shell/src/hooks/useAiSurface.ts
@@ -40,7 +40,6 @@
* @module
*/
-import { useRef } from 'react';
import { useAgents } from '@object-ui/plugin-chatbot/core';
import { catalogServesBuild, catalogServesFocus } from './surfaceAgent.js';
import { resolveAiApiBase } from './aiApiBase.js';
@@ -75,23 +74,21 @@ export interface AiSurfaceState {
* should be shown FOR THE CURRENT USER, driven off the access-filtered agent
* catalog (empty for seat-less users -> AI hidden; ADR-0068).
*/
-export function useAiSurfaceEnabled(): AiSurfaceState {
- const { agents, isLoading } = useAgents({ apiBase: resolveAiApiBase() });
-
- // useAgents starts `isLoading=false` and only kicks off the fetch in an effect
- // a tick later, so the first render's empty list means "not fetched yet", not
- // "no agents". Latch whether a fetch has actually been in flight so the route
- // guard treats that initial frame as loading (not a definitive empty → redirect).
- const fetchStartedRef = useRef(false);
- if (isLoading) fetchStartedRef.current = true;
+export function useAiSurfaceEnabled(options: { enabled?: boolean } = {}): AiSurfaceState {
+ // `enabled: false` asks nothing (objectstack#37833: the navigation gate asks
+ // only while an app carries an `ai:chat` entry); the answer then reads as
+ // loading, and the caller that turned the read off does not consult it.
+ const { agents, settled } = useAgents({ apiBase: resolveAiApiBase(), enabled: options.enabled ?? true });
const enabled = agents.length > 0;
return {
enabled,
buildServed: catalogServesBuild(agents),
focusServed: catalogServesFocus(agents),
- // Agents present → resolved/available. Otherwise we're loading until a fetch
- // has both started and finished with an empty result.
- isLoading: enabled ? false : isLoading || !fetchStartedRef.current,
+ // Agents present → resolved/available. Otherwise loading until a read has
+ // answered (`settled`): the first render's empty list means "not fetched
+ // yet", and a read the cache answers is never seen loading
+ // (objectstack#37833).
+ isLoading: enabled ? false : !settled,
};
}
diff --git a/ui/packages/app-shell/src/hooks/useNavMemberGates.ts b/ui/packages/app-shell/src/hooks/useNavMemberGates.ts
index 6f5b14da09d..8099e31a709 100644
--- a/ui/packages/app-shell/src/hooks/useNavMemberGates.ts
+++ b/ui/packages/app-shell/src/hooks/useNavMemberGates.ts
@@ -72,6 +72,24 @@
* is hidden. An entry without the key is evaluated exactly as before, with no
* read and no wait.
*
+ * ## An app's AI inquiry entry (objectstack#37833)
+ *
+ * An `ai:chat` entry (`type: 'component'`, `componentRef` `ai:chat`, ui
+ * ADR-0057 Amendment A4) opens a page that runs the platform `ask` agent. It
+ * is shown only to a member who can get an agent: the access-filtered agent
+ * catalog `useAiSurfaceEnabled` reads, which is empty on a deployment with no
+ * AI and for a member with no AI seat. Every surface whose `visible` evaluator
+ * is built here (the sidebar, so the phone's app menu; the landing; the
+ * palette; the `nav:menu` block) hides it the same way, and the landing falls
+ * to the next entry the member is shown. While the catalog has not answered
+ * the entry is hidden and reads as pending (`readEntry`), as an entry whose
+ * API read has not answered does: the landing holds rather than choosing, so
+ * the root neither opens the page and then leaves it, nor opens the next entry
+ * and then the page. The catalog is asked only while an app in the list, or
+ * the app being gated, carries such an entry; with none, nothing is asked and
+ * nothing changes. A direct link to the page is not gated: the page draws its
+ * own unavailable state.
+ *
* Internal module: not re-exported by the package entry.
*/
@@ -89,6 +107,8 @@ import {
type ApiFetch,
} from '@object-ui/react';
import { usePermissions } from '@object-ui/permissions';
+import { AI_CHAT_COMPONENT_REF } from '@objectstack/spec/ui';
+import { useAiSurfaceEnabled } from './useAiSurface.js';
import { useMetadata } from '../providers/MetadataProvider.js';
import {
useExpressionContext,
@@ -236,6 +256,60 @@ function useNavEntryData(app: unknown): (entry: NavigationItem) => NavEntryDataR
);
}
+/** Is `entry` an app's AI inquiry page (`ai:chat`, ui ADR-0057 Amendment A4)? */
+function isAiChatNavEntry(entry: NavigationItem | undefined): boolean {
+ return (
+ !!entry &&
+ entry.type === 'component' &&
+ (entry as { componentRef?: unknown }).componentRef === AI_CHAT_COMPONENT_REF
+ );
+}
+
+/** Does `items` hold an `ai:chat` entry, at any group depth? */
+function treeHasAiChatEntry(items: unknown): boolean {
+ if (!Array.isArray(items)) return false;
+ return items.some(
+ (item) =>
+ !!item &&
+ typeof item === 'object' &&
+ (isAiChatNavEntry(item as NavigationItem) || treeHasAiChatEntry((item as { children?: unknown }).children)),
+ );
+}
+
+/** Does any app of `apps`, or `current`, carry an `ai:chat` entry in its `navigation` or an area's? */
+function appsCarryAiChatEntry(apps: unknown, current: unknown): boolean {
+ const list: unknown[] = Array.isArray(apps) ? [...apps, current] : [current];
+ return list.some((app) => {
+ if (!app || typeof app !== 'object') return false;
+ const { navigation, areas } = app as { navigation?: unknown; areas?: unknown };
+ if (treeHasAiChatEntry(navigation)) return true;
+ return (
+ Array.isArray(areas) &&
+ areas.some((area) => treeHasAiChatEntry(area && typeof area === 'object' ? (area as { navigation?: unknown }).navigation : undefined))
+ );
+ });
+}
+
+/** Where the member's agent stands for an `ai:chat` entry (objectstack#37833). */
+type AiChatEntryGate = 'pending' | 'shown' | 'hidden';
+
+const AI_CHAT_PENDING: NavEntryDataRead = { status: 'pending' };
+
+/**
+ * Whether this member is shown an `ai:chat` entry: `shown` when the
+ * access-filtered agent catalog serves them an agent, `hidden` when it has
+ * answered with none (no AI on the deployment, no AI seat, or the catalog
+ * read failed), `pending` until it answers. The catalog is asked only while
+ * `app` or an app of the list carries such an entry.
+ */
+function useAiChatEntryGate(app: unknown): AiChatEntryGate {
+ const { apps } = useMetadata();
+ const wanted = useMemo(() => appsCarryAiChatEntry(apps, app), [apps, app]);
+ const { enabled, isLoading } = useAiSurfaceEnabled({ enabled: wanted });
+ if (enabled) return 'shown';
+ return isLoading ? 'pending' : 'hidden';
+}
+
/**
* Should this navigation entry be drawn, as far as its `visible` goes? The one
* decision every navigation surface of the shell makes (objectui#13029): an
@@ -284,11 +358,20 @@ function useNavVisibilityAndReads(app: unknown): {
} {
const { evaluator } = useExpressionContext();
const scopeBound = useHasExpressionScope();
- const readEntry = useNavEntryData(app);
+ const readEntryData = useNavEntryData(app);
+ // objectstack#37833 — an `ai:chat` entry is drawn only for a member who can
+ // get an agent, and is pending until the catalog says whether they can.
+ const aiChat = useAiChatEntryGate(app);
const evaluate = useCallback(
(expression: NavigationItem['visible'], entry?: NavigationItem) =>
- navEntryVisible(expression, entry, evaluator, readEntry, scopeBound),
- [evaluator, readEntry, scopeBound],
+ (aiChat === 'shown' || !isAiChatNavEntry(entry)) &&
+ navEntryVisible(expression, entry, evaluator, readEntryData, scopeBound),
+ [evaluator, readEntryData, scopeBound, aiChat],
+ );
+ const readEntry = useCallback(
+ (entry: NavigationItem): NavEntryDataRead =>
+ aiChat === 'pending' && isAiChatNavEntry(entry) ? AI_CHAT_PENDING : readEntryData(entry),
+ [readEntryData, aiChat],
);
return { evaluate, readEntry };
}
@@ -309,7 +392,8 @@ export interface NavMemberGates {
* The member's gates, with where each entry's API binding stands
* (objectui#13097): the read state the `visible` evaluator is built on, so the
* app root's landing can tell an entry that is hidden from one whose read has
- * not answered yet, without a read of its own.
+ * not answered yet, without a read of its own. An `ai:chat` entry reads as
+ * pending while the agent catalog has not answered (objectstack#37833).
*/
export interface NavMemberGatesWithReads extends NavMemberGates {
readEntry: (entry: NavigationItem) => NavEntryDataRead;
diff --git a/ui/packages/plugin-chatbot/src/__tests__/useAgents.settledWarmCache-37833.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/useAgents.settledWarmCache-37833.test.tsx
new file mode 100644
index 00000000000..0aac07c91a5
--- /dev/null
+++ b/ui/packages/plugin-chatbot/src/__tests__/useAgents.settledWarmCache-37833.test.tsx
@@ -0,0 +1,113 @@
+// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
+
+/**
+ * objectstack#37833 — `useAgents` says when a catalog read has answered
+ * (`settled`), and says it on a read the module cache answers too.
+ *
+ * A cache hit resolves in microtasks, so `isLoading` goes true and false
+ * before React renders once: no render ever sees it loading. A caller that
+ * told "not fetched yet" from "fetched, empty" by having seen `isLoading`
+ * (`useAiSurfaceEnabled`, for a member with no AI seat) waited for ever.
+ *
+ * The cases mount with `createRoot` and React's act environment OFF, as a
+ * browser schedules: under `act` each queued update is flushed in turn and
+ * the loading render is seen, which hides the defect.
+ *
+ * (a) cold read over the network: settled once it answers;
+ * (b) a second mount the cache answers (empty catalog): settled, never
+ * having rendered loading;
+ * (c) a failed read: settled, with its error;
+ * (d) disabled: never settled, nothing asked.
+ */
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import React from 'react';
+import { createRoot } from 'react-dom/client';
+import { useAgents, __resetAgentsCatalog, type UseAgentsReturn } from '../useAgents';
+
+const API_BASE = '/api/v1/ai';
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+let fetchMock: ReturnType;
+const actEnv = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean };
+let savedActEnv: boolean | undefined;
+
+function answering(status: number, agents: unknown[]) {
+ return vi.fn(async () => {
+ await sleep(20);
+ return new Response(JSON.stringify({ success: true, data: { agents } }), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ });
+}
+
+/** Mount `useAgents` outside `act`; every render's `{ isLoading, settled }` is recorded. */
+function mount(options: { enabled?: boolean } = {}) {
+ const renders: Array & { error: boolean }> = [];
+ function Probe() {
+ const result = useAgents({ apiBase: API_BASE, ...options });
+ renders.push({ isLoading: result.isLoading, settled: result.settled, error: Boolean(result.error) });
+ return null;
+ }
+ const root = createRoot(document.createElement('div'));
+ root.render();
+ return { renders, unmount: () => root.unmount() };
+}
+
+beforeEach(() => {
+ __resetAgentsCatalog();
+ savedActEnv = actEnv.IS_REACT_ACT_ENVIRONMENT;
+ actEnv.IS_REACT_ACT_ENVIRONMENT = false;
+});
+
+afterEach(() => {
+ actEnv.IS_REACT_ACT_ENVIRONMENT = savedActEnv;
+ vi.unstubAllGlobals();
+});
+
+describe('useAgents reports a settled read (objectstack#37833)', () => {
+ it('(a) a cold read: not settled until the network answers, settled after', async () => {
+ fetchMock = answering(200, []);
+ vi.stubGlobal('fetch', fetchMock);
+ const cold = mount();
+ await sleep(200);
+ expect(cold.renders[0]).toEqual({ isLoading: false, settled: false, error: false });
+ expect(cold.renders.some((r) => r.isLoading && !r.settled)).toBe(true);
+ expect(cold.renders[cold.renders.length - 1]).toEqual({ isLoading: false, settled: true, error: false });
+ cold.unmount();
+ });
+
+ it('(b) a read the cache answers with an empty catalog: settled, though no render saw it loading', async () => {
+ fetchMock = answering(200, []);
+ vi.stubGlobal('fetch', fetchMock);
+ const cold = mount();
+ await sleep(200);
+ cold.unmount();
+
+ const warm = mount();
+ await sleep(200);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(warm.renders.some((r) => r.isLoading)).toBe(false);
+ expect(warm.renders[warm.renders.length - 1]).toEqual({ isLoading: false, settled: true, error: false });
+ warm.unmount();
+ });
+
+ it('(c) a failed read is settled, with its error', async () => {
+ fetchMock = answering(404, []);
+ vi.stubGlobal('fetch', fetchMock);
+ const failed = mount();
+ await sleep(200);
+ expect(failed.renders[failed.renders.length - 1]).toEqual({ isLoading: false, settled: true, error: true });
+ failed.unmount();
+ });
+
+ it('(d) disabled: never settled, and nothing is asked', async () => {
+ fetchMock = answering(200, []);
+ vi.stubGlobal('fetch', fetchMock);
+ const off = mount({ enabled: false });
+ await sleep(200);
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(off.renders.every((r) => !r.settled)).toBe(true);
+ off.unmount();
+ });
+});
diff --git a/ui/packages/plugin-chatbot/src/useAgents.ts b/ui/packages/plugin-chatbot/src/useAgents.ts
index 032e8905704..0679aafa2a7 100644
--- a/ui/packages/plugin-chatbot/src/useAgents.ts
+++ b/ui/packages/plugin-chatbot/src/useAgents.ts
@@ -74,6 +74,14 @@ export interface UseAgentsReturn {
isLoading: boolean;
error: Error | undefined;
refetch: () => void;
+ /**
+ * True once a catalog read for the current `apiBase` has answered or failed,
+ * in this mount; false while disabled and before the first answer. Unlike
+ * `isLoading`, it cannot be missed: a read the module cache answers at once
+ * sets `isLoading` true and false in one render, so no render ever sees it
+ * loading, while `settled` turns true in that same render.
+ */
+ settled: boolean;
}
interface RawAgent {
@@ -357,6 +365,8 @@ export function useAgents(options: UseAgentsOptions = {}): UseAgentsReturn {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(undefined);
const [reloadToken, setReloadToken] = useState(0);
+ // The `apiBase` whose read last answered or failed (`settled`).
+ const [settledFor, setSettledFor] = useState(undefined);
// Stash latest headers in a ref so consumers can pass inline objects without
// triggering a refetch on every render.
@@ -389,7 +399,9 @@ export function useAgents(options: UseAgentsOptions = {}): UseAgentsReturn {
setAgents(fallback);
})
.finally(() => {
- if (!cancelled) setIsLoading(false);
+ if (cancelled) return;
+ setIsLoading(false);
+ setSettledFor(apiBase);
});
});
@@ -403,5 +415,5 @@ export function useAgents(options: UseAgentsOptions = {}): UseAgentsReturn {
const refetch = useCallback(() => setReloadToken((n) => n + 1), []);
- return { agents, isLoading, error, refetch };
+ return { agents, isLoading, error, refetch, settled: enabled && !!apiBase && settledFor === apiBase };
}