Skip to content

Commit 531e55b

Browse files
feat(app-shell): hide the ai:chat menu entry from a member who cannot get an agent; the home falls to the next entry (#37960)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9D3PqTGGb1rgoRqKj4rT4Xjk)_ Fixes #37833 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:部署没开 AI、或本人没有 AI 席位的人,在应用菜单(电脑侧栏、手机应用菜单、命令面板、页面里的菜单块)里不再看到「AI 问询」项;它原本是首页时,打开应用直接进入下一个菜单项,加载期间只显示骨架、不会先闪进问询页再跳走。 - 为什么做:这是「AI 问询首页」专区的收尾一项,替拿不到 AI 的成员挡掉一个点开就是「不可用」的入口。 - 出错会怎样:最坏是有 AI 的人看不到这个入口或首页落到下一项,数据不受影响;直接撤回本 PR 即恢复原状。 - 要你做什么:无。 ## What changes - **The gate** (`useNavMemberGates.ts`, `useNavVisibilityAndReads`): every navigation surface builds its `visible` evaluator here: the sidebar (and so the phone's app menu it draws), the app-root landing, the command palette and the `nav:menu` block. An `ai:chat` entry (`type: 'component'`, `componentRef: AI_CHAT_COMPONENT_REF`) is drawn only when `useAiSurfaceEnabled` answers `enabled`, the access-filtered agent catalog, which is empty on a deployment with no AI and for a member with no AI seat. - **Loading phase, chosen and pinned:** until the catalog answers, the entry is hidden and `readEntry` reports it as `pending`. That reuses the landing's existing pending-read hold (objectui#13097), so the app root shows its skeleton and lands once, either on the page or on the next entry. It never opens one and then jumps to the other. The sidebar never draws the entry and then removes it. - **Declared `landing`** (ruling record 6545223246, letter A) is unchanged. `resolveDeclaredLandingRoute` looks the named entry up among the entries the member is shown, so a landing entry whose `item` is the gated `ai:chat` entry is passed over: the next declared entry that holds lands, and with none, the first entry shown lands. Both are pinned. - **A direct link** to `component/ai/chat` is not gated. The page draws `AiUnavailable`. - **Asked only when needed:** the catalog is read only while an app in the list (or the gated app) carries an `ai:chat` entry, through a new optional `useAiSurfaceEnabled({ enabled })`. Apps without one read nothing new (pinned: no request). - **Prerequisite fix, latch:** `useAgents` (`@object-ui/plugin-chatbot`) now returns `settled`, true once a catalog read for the current `apiBase` has answered or failed. It is additive, and the fields it already returned are unchanged. `useAiSurfaceEnabled` reads it instead of `fetchStartedRef`. See Acceptance notes. - Changeset: `.changeset/37833-hide-ai-chat-entry-without-agent.md` (patch, `@object-ui/app-shell` and `@object-ui/plugin-chatbot`). ### Read first (by risk) 1. `ui/packages/app-shell/src/hooks/useAiSurface.ts`: the latch now reads `settled`. Every `useAiSurfaceEnabled` consumer reads its `isLoading` through this line. 2. `ui/packages/app-shell/src/hooks/useNavMemberGates.ts`: `useNavVisibilityAndReads`, the `aiChat` term in `evaluate` and in `readEntry`. 3. `ui/packages/plugin-chatbot/src/useAgents.ts`: `settledFor` set in the read's `.finally`. ### Two-minute verification `pnpm --dir ui exec vitest run packages/app-shell/src/console/__tests__/AppContent.aiChatEntryGate-37833.test.tsx`: expect 13 passed, including the community-edition and no-seat home cases whose router pathname log is exactly `/apps/policy`, `/apps/policy/crm_case`. ## Tests - `AppContent.aiChatEntryGate-37833.test.tsx` (new): real `AppContent` landing, real `ExpressionProvider`, `MePermissionsProvider`, `useNavMemberGates`, `useAiSurfaceEnabled`, `useAgents` over a held `apiFetch`, and the real `AppAskPage`. The cases: - the menu leaves the entry out on community edition (agents route 404) and with no seat (empty catalog); - CONTROLs: a member with an agent sees the entry, and an app list with no `ai:chat` entry fetches nothing; - the home is the next entry on both, with no stop on the page, and with an agent the home is the page with no stop on the next entry; - the two declared-landing cases; - the direct link draws `AiUnavailable`; - three warm-cache cases mounted with React's act environment off. - `useAiSurface.warmCatalog-37833.test.tsx` (new): the hook on a cold read, then on a warm one, with act off. - `useAgents.settledWarmCache-37833.test.tsx` (new): `settled` on a cold read, a warm read, a failed read and a disabled read, with act off. - `useAiSurface.test.ts`: its mocked `useAgents` result now carries `settled`, plus one case for a settled empty answer. - `HomePage.openMarksRead.test.tsx`: its `useAiSurface` mock now also answers `useAiSurfaceEnabled`. The Home bell's roster gates navigation through `useNavMemberGates`, so the old mock went red here (a stale fixture caused by this change; it was the only red in the wide run below). ## Acceptance notes - **Latch defect, fixed here (not filed):** with an empty catalog answered from `useAgents`' module cache (30 s TTL), `isLoading` went true and false within one render. `useAiSurfaceEnabled`'s `fetchStartedRef` latch was never set, so it reported loading for ever. Two effects for a member with no seat after the console's first catalog read: the `ai:chat` page on a direct link stayed on its blank loading state instead of `AiUnavailable` (a defect on `main` since the page landed), and this PR's gate would have held the app-root landing for good. Measured outside act; the pins below fail on the pre-fix code and pass after. - The app-root warm-cache landing case passes on the pre-fix code too, in this harness: the console's other renders in that window flush the loading render. The hook-level and page-level pins are the discriminating ones. - A catalog that serves agents but not `ask` still shows the entry. The gate follows `enabled`, the same value the page's own unavailable check reads, and the page's `AiUnavailable` covers it. - An app whose only entry is `ai:chat` shows a member with no agent the existing no-access empty state, the landing's rule for an app that shows them nothing. - `useAiSurface.ts` is also edited by #37924 (draft); the two merge cleanly, and this edit is kept to the latch and the `enabled` option. ## Verification All runs are on head `4ca23ec3` unless noted. The `check:*` list ran at `ce385345`; the one later commit changes only a test mock, and the four gates that read test files were re-run on `4ca23ec3`. <details><summary>New and touched pins: 19 passed, and 5 of them red on the pre-fix code</summary> - `vitest run` over `useAgents.settledWarmCache-37833`, `useAiSurface.warmCatalog-37833` and `AppContent.aiChatEntryGate-37833` (`ce385345`): Test Files 3 passed (3), Tests 19 passed (19). - **Reverse check.** `useAgents.ts` and `useAiSurface.ts` were put back to their `868742bf` content in the working tree only (`settled` hits 0/0, latch hits 3). Result: Tests 5 failed, 14 passed (19). The five red cases are useAgents (a), (b) and (c), the hook's warm-catalog case, and the page's warm direct link. Restored with `git checkout HEAD`; `git diff HEAD` empty; both blobs equal to HEAD. - **Gate ablation** (`node scripts/ablation-replace.mjs` at `868742bf`; anchor hits 1 to 0): the `aiChat` term of `evaluate` was replaced by `true`. Result: Tests 8 failed, 4 passed (12). Restored blob equal to HEAD, `git diff HEAD` empty. </details> <details><summary>Wide run and type-check</summary> - `vitest run` over `packages/plugin-chatbot/` and app-shell's `hooks/`, `console/`, `layout/`, `chrome/`, `views/__tests__/` and `providers/` (`ce385345`): Test Files 1 failed, 807 passed (808); Tests 3 failed, 7025 passed (7028). The failing file was `HomePage.openMarksRead` (`No "useAiSurfaceEnabled" export is defined on the mock`), repaired in `4ca23ec3`, where it shows Tests 3 passed (3). - This run is a declared narrowing of app-shell's suite; `Test UI` runs all of it in CI. - `pnpm --filter @object-ui/app-shell --filter @object-ui/plugin-chatbot run type-check`: both Done, and `pnpm --dir ui exec vitest run scripts/` gave Test Files 172 passed, 2 skipped. Lock VERDICT command-exit 0. </details> <details><summary>Derived gates (dispatch-gates --commands, 39 families)</summary> - 38 `check:*` and script families: every one ended with exit 0, except `check:type-check-debt`. Its first run exited 3 while it was queued behind the verification lock; the re-run exited 0 (`--re-measure: OK`, surplus none). - `pnpm --dir ui exec vitest run scripts/`: passed (above). - Reconciliation: `dispatch-gates --ran` printed 39 derived, 39 run, 0 NOT-MEASURED, 0 UNRUN. - Re-run on `4ca23ec3`: `check:nul-bytes`, `check:test-source-alias`, `check:cross-package-test-inputs` and `check:undeclared-dep-imports` all exit 0. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_016WV4cwGVgec21LwQTtRY85 --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent b316afa commit 531e55b

9 files changed

Lines changed: 828 additions & 22 deletions

File tree

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
'@object-ui/plugin-chatbot': patch
4+
---
5+
6+
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
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
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.
12+
13+
- **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.
14+
- **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.
15+
- **A direct link to the page** is not redirected. The page draws its "AI assistant unavailable" state.
16+
- The catalog is read only while an app in the list carries an `ai:chat` entry. Apps without one read nothing new.
17+
- `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.
18+
- `@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.
19+
20+
Nothing to migrate.

‎ui/packages/app-shell/src/console/__tests__/AppContent.aiChatEntryGate-37833.test.tsx‎

Lines changed: 475 additions & 0 deletions
Large diffs are not rendered by default.

‎ui/packages/app-shell/src/console/home/__tests__/HomePage.openMarksRead.test.tsx‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,12 @@ vi.mock('../../../context/NavigationContext', () => ({
8282

8383
vi.mock('../../../hooks/useRecentItems', () => ({ useRecentItems: () => ({ recentItems: [] }) }));
8484
vi.mock('../../../hooks/useFavorites', () => ({ useFavorites: () => ({ favorites: [] }) }));
85-
vi.mock('../../../hooks/useAiSurface', () => ({ resolveAiApiBase: () => '' }));
85+
// The bell's roster gates navigation through `useNavMemberGates`, which asks
86+
// the AI surface whether to draw an app's `ai:chat` entry (objectstack#37833).
87+
vi.mock('../../../hooks/useAiSurface', () => ({
88+
resolveAiApiBase: () => '',
89+
useAiSurfaceEnabled: () => ({ enabled: false, isLoading: false, buildServed: false, focusServed: false }),
90+
}));
8691
vi.mock('../../../views/metadata-admin/useMetadata', () => ({
8792
useMetadataClient: () => ({ listDrafts: async () => [] }),
8893
}));

‎ui/packages/app-shell/src/hooks/__tests__/useAiSurface.test.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,13 @@ vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({
1111
}));
1212
const mockAgents = vi.mocked(useAgents);
1313

14-
function agentsResult(names: string[], isLoading: boolean) {
14+
function agentsResult(names: string[], isLoading: boolean, settled = false) {
1515
return {
1616
agents: names.map((name) => ({ name, label: name })),
1717
isLoading,
1818
error: undefined,
1919
refetch: vi.fn(),
20+
settled,
2021
};
2122
}
2223

@@ -51,12 +52,20 @@ describe('useAiSurfaceEnabled', () => {
5152
const { result, rerender } = renderHook(() => useAiSurfaceEnabled());
5253
expect(result.current.isLoading).toBe(true);
5354

54-
mockAgents.mockReturnValue(agentsResult([], false));
55+
mockAgents.mockReturnValue(agentsResult([], false, true));
5556
rerender();
5657
expect(result.current).toEqual({ enabled: false, isLoading: false, buildServed: false, focusServed: false });
5758
});
5859
});
5960

61+
describe('useAiSurfaceEnabled — an empty catalog the cache answers (objectstack#37833)', () => {
62+
it('is disabled, not loading, on the first render that holds a settled empty answer, never seen loading', () => {
63+
mockAgents.mockReturnValue(agentsResult([], false, true));
64+
const { result } = renderHook(() => useAiSurfaceEnabled());
65+
expect(result.current).toEqual({ enabled: false, isLoading: false, buildServed: false, focusServed: false });
66+
});
67+
});
68+
6069
describe('useAiSurfaceEnabled — buildServed reads the build agent itself (objectstack#36969)', () => {
6170
it('in-app building closed (`ask` served, `build` not): AI is on, and building is not served', () => {
6271
mockAgents.mockReturnValue(agentsResult(['ask'], false));
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#37833 — `useAiSurfaceEnabled` leaves its loading state when the
5+
* agent catalog is empty and the session cache answers it.
6+
*
7+
* The console reads the catalog on every open, so a surface that mounts later
8+
* (the app root's landing, the `ai:chat` page on a direct link) is answered by
9+
* `useAgents`' module cache: `isLoading` goes true and false before React
10+
* renders once. Read through a latch that only a render seeing `isLoading`
11+
* could set, a member with no AI seat stayed "loading" for ever; it reads
12+
* `useAgents`' `settled` now.
13+
*
14+
* Real `useAgents` (this is why the file is not a `describe` in
15+
* `useAiSurface.test.ts`, which mocks it) over a stubbed `apiFetch`, mounted
16+
* with `createRoot` and React's act environment OFF, as a browser schedules:
17+
* under `act` each queued update is flushed in turn and the loading render is
18+
* seen, which hides the defect.
19+
*/
20+
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
21+
import React from 'react';
22+
import { createRoot } from 'react-dom/client';
23+
import { SchemaRendererContext, type ApiFetch } from '@object-ui/react';
24+
import { __resetAgentsCatalog } from '../../../../plugin-chatbot/src/useAgents';
25+
import { useAiSurfaceEnabled } from '../useAiSurface';
26+
27+
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
28+
const actEnv = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean };
29+
let savedActEnv: boolean | undefined;
30+
31+
function catalogFetch(agents: unknown[]): ApiFetch {
32+
return (async () => {
33+
await sleep(20);
34+
return { ok: true, status: 200, json: async () => ({ success: true, data: { agents } }) } as unknown as Response;
35+
}) as ApiFetch;
36+
}
37+
38+
/** Mount `useAiSurfaceEnabled` outside `act`; every render's `enabled/isLoading` is recorded. */
39+
function mount(apiFetch: ApiFetch) {
40+
const renders: string[] = [];
41+
function Probe() {
42+
const surface = useAiSurfaceEnabled();
43+
renders.push(`${surface.enabled}/${surface.isLoading}`);
44+
return null;
45+
}
46+
const root = createRoot(document.createElement('div'));
47+
root.render(
48+
<SchemaRendererContext.Provider value={{ dataSource: null, apiFetch } as never}>
49+
<Probe />
50+
</SchemaRendererContext.Provider>,
51+
);
52+
return { renders, unmount: () => root.unmount() };
53+
}
54+
55+
beforeEach(() => {
56+
__resetAgentsCatalog();
57+
savedActEnv = actEnv.IS_REACT_ACT_ENVIRONMENT;
58+
actEnv.IS_REACT_ACT_ENVIRONMENT = false;
59+
});
60+
61+
afterEach(() => {
62+
actEnv.IS_REACT_ACT_ENVIRONMENT = savedActEnv;
63+
});
64+
65+
describe('useAiSurfaceEnabled on a catalog the session cache answers (objectstack#37833)', () => {
66+
it('an empty catalog: loading on the cold read, then disabled and not loading on the warm one', async () => {
67+
const apiFetch = catalogFetch([]);
68+
const cold = mount(apiFetch);
69+
await sleep(200);
70+
expect(cold.renders[0]).toBe('false/true');
71+
expect(cold.renders[cold.renders.length - 1]).toBe('false/false');
72+
cold.unmount();
73+
74+
const warm = mount(apiFetch);
75+
await sleep(200);
76+
expect(warm.renders[0]).toBe('false/true');
77+
expect(warm.renders[warm.renders.length - 1]).toBe('false/false');
78+
warm.unmount();
79+
});
80+
81+
it('CONTROL: a served catalog is enabled on the warm read', async () => {
82+
const apiFetch = catalogFetch([{ name: 'ask', label: 'Ask' }]);
83+
const cold = mount(apiFetch);
84+
await sleep(200);
85+
cold.unmount();
86+
const warm = mount(apiFetch);
87+
await sleep(200);
88+
expect(warm.renders[warm.renders.length - 1]).toBe('true/false');
89+
warm.unmount();
90+
});
91+
});

‎ui/packages/app-shell/src/hooks/useAiSurface.ts‎

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,6 @@
4040
* @module
4141
*/
4242

43-
import { useRef } from 'react';
4443
import { useAgents } from '@object-ui/plugin-chatbot/core';
4544
import { catalogServesBuild, catalogServesFocus } from './surfaceAgent.js';
4645
import { resolveAiApiBase } from './aiApiBase.js';
@@ -75,23 +74,21 @@ export interface AiSurfaceState {
7574
* should be shown FOR THE CURRENT USER, driven off the access-filtered agent
7675
* catalog (empty for seat-less users -> AI hidden; ADR-0068).
7776
*/
78-
export function useAiSurfaceEnabled(): AiSurfaceState {
79-
const { agents, isLoading } = useAgents({ apiBase: resolveAiApiBase() });
80-
81-
// useAgents starts `isLoading=false` and only kicks off the fetch in an effect
82-
// a tick later, so the first render's empty list means "not fetched yet", not
83-
// "no agents". Latch whether a fetch has actually been in flight so the route
84-
// guard treats that initial frame as loading (not a definitive empty → redirect).
85-
const fetchStartedRef = useRef(false);
86-
if (isLoading) fetchStartedRef.current = true;
77+
export function useAiSurfaceEnabled(options: { enabled?: boolean } = {}): AiSurfaceState {
78+
// `enabled: false` asks nothing (objectstack#37833: the navigation gate asks
79+
// only while an app carries an `ai:chat` entry); the answer then reads as
80+
// loading, and the caller that turned the read off does not consult it.
81+
const { agents, settled } = useAgents({ apiBase: resolveAiApiBase(), enabled: options.enabled ?? true });
8782

8883
const enabled = agents.length > 0;
8984
return {
9085
enabled,
9186
buildServed: catalogServesBuild(agents),
9287
focusServed: catalogServesFocus(agents),
93-
// Agents present → resolved/available. Otherwise we're loading until a fetch
94-
// has both started and finished with an empty result.
95-
isLoading: enabled ? false : isLoading || !fetchStartedRef.current,
88+
// Agents present → resolved/available. Otherwise loading until a read has
89+
// answered (`settled`): the first render's empty list means "not fetched
90+
// yet", and a read the cache answers is never seen loading
91+
// (objectstack#37833).
92+
isLoading: enabled ? false : !settled,
9693
};
9794
}

‎ui/packages/app-shell/src/hooks/useNavMemberGates.ts‎

Lines changed: 88 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,24 @@
7272
* is hidden. An entry without the key is evaluated exactly as before, with no
7373
* read and no wait.
7474
*
75+
* ## An app's AI inquiry entry (objectstack#37833)
76+
*
77+
* An `ai:chat` entry (`type: 'component'`, `componentRef` `ai:chat`, ui
78+
* ADR-0057 Amendment A4) opens a page that runs the platform `ask` agent. It
79+
* is shown only to a member who can get an agent: the access-filtered agent
80+
* catalog `useAiSurfaceEnabled` reads, which is empty on a deployment with no
81+
* AI and for a member with no AI seat. Every surface whose `visible` evaluator
82+
* is built here (the sidebar, so the phone's app menu; the landing; the
83+
* palette; the `nav:menu` block) hides it the same way, and the landing falls
84+
* to the next entry the member is shown. While the catalog has not answered
85+
* the entry is hidden and reads as pending (`readEntry`), as an entry whose
86+
* API read has not answered does: the landing holds rather than choosing, so
87+
* the root neither opens the page and then leaves it, nor opens the next entry
88+
* and then the page. The catalog is asked only while an app in the list, or
89+
* the app being gated, carries such an entry; with none, nothing is asked and
90+
* nothing changes. A direct link to the page is not gated: the page draws its
91+
* own unavailable state.
92+
*
7593
* Internal module: not re-exported by the package entry.
7694
*/
7795

@@ -89,6 +107,8 @@ import {
89107
type ApiFetch,
90108
} from '@object-ui/react';
91109
import { usePermissions } from '@object-ui/permissions';
110+
import { AI_CHAT_COMPONENT_REF } from '@objectstack/spec/ui';
111+
import { useAiSurfaceEnabled } from './useAiSurface.js';
92112
import { useMetadata } from '../providers/MetadataProvider.js';
93113
import {
94114
useExpressionContext,
@@ -236,6 +256,60 @@ function useNavEntryData(app: unknown): (entry: NavigationItem) => NavEntryDataR
236256
);
237257
}
238258

259+
/** Is `entry` an app's AI inquiry page (`ai:chat`, ui ADR-0057 Amendment A4)? */
260+
function isAiChatNavEntry(entry: NavigationItem | undefined): boolean {
261+
return (
262+
!!entry &&
263+
entry.type === 'component' &&
264+
(entry as { componentRef?: unknown }).componentRef === AI_CHAT_COMPONENT_REF
265+
);
266+
}
267+
268+
/** Does `items` hold an `ai:chat` entry, at any group depth? */
269+
function treeHasAiChatEntry(items: unknown): boolean {
270+
if (!Array.isArray(items)) return false;
271+
return items.some(
272+
(item) =>
273+
!!item &&
274+
typeof item === 'object' &&
275+
(isAiChatNavEntry(item as NavigationItem) || treeHasAiChatEntry((item as { children?: unknown }).children)),
276+
);
277+
}
278+
279+
/** Does any app of `apps`, or `current`, carry an `ai:chat` entry in its `navigation` or an area's? */
280+
function appsCarryAiChatEntry(apps: unknown, current: unknown): boolean {
281+
const list: unknown[] = Array.isArray(apps) ? [...apps, current] : [current];
282+
return list.some((app) => {
283+
if (!app || typeof app !== 'object') return false;
284+
const { navigation, areas } = app as { navigation?: unknown; areas?: unknown };
285+
if (treeHasAiChatEntry(navigation)) return true;
286+
return (
287+
Array.isArray(areas) &&
288+
areas.some((area) => treeHasAiChatEntry(area && typeof area === 'object' ? (area as { navigation?: unknown }).navigation : undefined))
289+
);
290+
});
291+
}
292+
293+
/** Where the member's agent stands for an `ai:chat` entry (objectstack#37833). */
294+
type AiChatEntryGate = 'pending' | 'shown' | 'hidden';
295+
296+
const AI_CHAT_PENDING: NavEntryDataRead = { status: 'pending' };
297+
298+
/**
299+
* Whether this member is shown an `ai:chat` entry: `shown` when the
300+
* access-filtered agent catalog serves them an agent, `hidden` when it has
301+
* answered with none (no AI on the deployment, no AI seat, or the catalog
302+
* read failed), `pending` until it answers. The catalog is asked only while
303+
* `app` or an app of the list carries such an entry.
304+
*/
305+
function useAiChatEntryGate(app: unknown): AiChatEntryGate {
306+
const { apps } = useMetadata();
307+
const wanted = useMemo(() => appsCarryAiChatEntry(apps, app), [apps, app]);
308+
const { enabled, isLoading } = useAiSurfaceEnabled({ enabled: wanted });
309+
if (enabled) return 'shown';
310+
return isLoading ? 'pending' : 'hidden';
311+
}
312+
239313
/**
240314
* Should this navigation entry be drawn, as far as its `visible` goes? The one
241315
* decision every navigation surface of the shell makes (objectui#13029): an
@@ -284,11 +358,20 @@ function useNavVisibilityAndReads(app: unknown): {
284358
} {
285359
const { evaluator } = useExpressionContext();
286360
const scopeBound = useHasExpressionScope();
287-
const readEntry = useNavEntryData(app);
361+
const readEntryData = useNavEntryData(app);
362+
// objectstack#37833 — an `ai:chat` entry is drawn only for a member who can
363+
// get an agent, and is pending until the catalog says whether they can.
364+
const aiChat = useAiChatEntryGate(app);
288365
const evaluate = useCallback(
289366
(expression: NavigationItem['visible'], entry?: NavigationItem) =>
290-
navEntryVisible(expression, entry, evaluator, readEntry, scopeBound),
291-
[evaluator, readEntry, scopeBound],
367+
(aiChat === 'shown' || !isAiChatNavEntry(entry)) &&
368+
navEntryVisible(expression, entry, evaluator, readEntryData, scopeBound),
369+
[evaluator, readEntryData, scopeBound, aiChat],
370+
);
371+
const readEntry = useCallback(
372+
(entry: NavigationItem): NavEntryDataRead =>
373+
aiChat === 'pending' && isAiChatNavEntry(entry) ? AI_CHAT_PENDING : readEntryData(entry),
374+
[readEntryData, aiChat],
292375
);
293376
return { evaluate, readEntry };
294377
}
@@ -309,7 +392,8 @@ export interface NavMemberGates {
309392
* The member's gates, with where each entry's API binding stands
310393
* (objectui#13097): the read state the `visible` evaluator is built on, so the
311394
* app root's landing can tell an entry that is hidden from one whose read has
312-
* not answered yet, without a read of its own.
395+
* not answered yet, without a read of its own. An `ai:chat` entry reads as
396+
* pending while the agent catalog has not answered (objectstack#37833).
313397
*/
314398
export interface NavMemberGatesWithReads extends NavMemberGates {
315399
readEntry: (entry: NavigationItem) => NavEntryDataRead;

0 commit comments

Comments
 (0)