Skip to content
20 changes: 20 additions & 0 deletions .changeset/37833-hide-ai-chat-entry-without-agent.md
Original file line number Diff line number Diff line change
@@ -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.

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -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 () => [] }),
}));
Expand Down
13 changes: 11 additions & 2 deletions ui/packages/app-shell/src/hooks/__tests__/useAiSurface.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
}

Expand Down Expand Up @@ -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));
Expand Down
Original file line number Diff line number Diff line change
@@ -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<void>((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(
<SchemaRendererContext.Provider value={{ dataSource: null, apiFetch } as never}>
<Probe />
</SchemaRendererContext.Provider>,
);
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();
});
});
23 changes: 10 additions & 13 deletions ui/packages/app-shell/src/hooks/useAiSurface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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,
};
}
92 changes: 88 additions & 4 deletions ui/packages/app-shell/src/hooks/useNavMemberGates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/

Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 };
}
Expand All @@ -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;
Expand Down
Loading
Loading