Skip to content

Commit bb175bf

Browse files
committed
fix(app-shell): the command palette and the default-app fallback skip an app /me/apps hides
The palette's "Switch app" group (Home and in-app) narrows its active apps by the same /me/apps answer through a new useServedApps, keeping its own rule that lists hidden apps; AppContent's default-app fallback for an unresolved segment reads useLauncherApps. One test and one ablation each. Claude-Session: https://claude.ai/code/session_01JQwxbYwBbR8jCpWPE5Kosz Co-authored-by: Claude <noreply@anthropic.com>
1 parent cbe8d37 commit bb175bf

7 files changed

Lines changed: 353 additions & 11 deletions

File tree

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#26838 — the ⌘K palette's "Switch app" group offers no app the
5+
* user's permission sets hide (`tabPermissions: hidden`): it is narrowed by
6+
* the same `GET /me/apps` answer as Home's tiles and the app switcher. The
7+
* palette keeps its own rule otherwise — every active app, a `hidden` one
8+
* (the avatar-menu kind) included.
9+
*
10+
* Under the real `LauncherAppsProvider` fed a `/me/apps` double, the real
11+
* `CommandPaletteProvider` opened by its `?palette=1` deep link, and a real
12+
* `I18nProvider` in `en` — the `CommandPalette.navMatch-11812` harness.
13+
*/
14+
15+
import * as React from 'react';
16+
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
17+
import { render, waitFor, cleanup } from '@testing-library/react';
18+
import { MemoryRouter } from 'react-router-dom';
19+
import { createI18n, I18nProvider } from '@object-ui/i18n';
20+
21+
const state = vi.hoisted(() => ({ apps: [] as Array<Record<string, unknown>> }));
22+
23+
vi.mock('@object-ui/auth', async (importOriginal) => ({
24+
...(await importOriginal<Record<string, unknown>>()),
25+
useAuth: () => ({ user: { id: 'u1' }, activeOrganization: null }),
26+
}));
27+
// The provider reads the app list from the metadata cache; the rest of the
28+
// cache is the real (empty) one the palette's other groups read.
29+
vi.mock('../providers/MetadataProvider', async (importOriginal) => {
30+
const actual = await importOriginal<typeof import('../providers/MetadataProvider')>();
31+
return {
32+
...actual,
33+
useMetadata: () => ({ ...actual.useMetadata(), apps: state.apps, loading: false }),
34+
};
35+
});
36+
37+
import { CommandPalette } from './CommandPalette';
38+
import { CommandPaletteProvider } from '../context/CommandPaletteProvider';
39+
import { LauncherAppsProvider } from '../hooks/useLauncherApps';
40+
41+
const SHOWCASE = { name: 'showcase_app', label: 'Showcase', navigation: [] };
42+
const CRM = { name: 'crm_app', label: 'CRM', navigation: [] };
43+
const OPS = { name: 'ops_app', label: 'Ops', navigation: [] };
44+
const ACCOUNT = { name: 'account', label: 'Account', hidden: true, navigation: [] };
45+
46+
/** A `/me/apps` double: the listed names, or a bare status. */
47+
function meApps(answer: string[] | number) {
48+
return vi.fn(async (_url: unknown) =>
49+
typeof answer === 'number'
50+
? new Response('{}', { status: answer })
51+
: new Response(JSON.stringify({ apps: answer.map((name) => ({ name })) }), { status: 200 }),
52+
);
53+
}
54+
55+
function mount(fetcher: ReturnType<typeof meApps>) {
56+
render(
57+
<I18nProvider instance={createI18n({ defaultLanguage: 'en', detectBrowserLanguage: false })} persistLanguage={false}>
58+
<MemoryRouter initialEntries={['/apps/showcase_app?palette=1']}>
59+
<LauncherAppsProvider endpoint="/me-apps-double" fetcher={fetcher as unknown as typeof fetch}>
60+
<CommandPaletteProvider>
61+
<CommandPalette
62+
apps={state.apps}
63+
activeApp={SHOWCASE}
64+
objects={[]}
65+
onAppChange={() => {}}
66+
dataSource={{ find: vi.fn(async () => ({ data: [] })), searchAll: vi.fn(async () => ({ hits: [] })) }}
67+
/>
68+
</CommandPaletteProvider>
69+
</LauncherAppsProvider>
70+
</MemoryRouter>
71+
</I18nProvider>,
72+
);
73+
if (!document.querySelector('[cmdk-input]')) throw new Error('the palette did not open');
74+
}
75+
76+
/** The visible text of every app item cmdk rendered. */
77+
function shownApps(): string[] {
78+
return Array.from(document.querySelectorAll('[cmdk-item][data-value^="app "]')).map((el) =>
79+
(el.textContent ?? '').replace(/Current$/, '').trim(),
80+
);
81+
}
82+
83+
beforeEach(() => {
84+
state.apps = [SHOWCASE, CRM, OPS, ACCOUNT];
85+
});
86+
87+
afterEach(() => cleanup());
88+
89+
describe('objectstack#26838 — the palette offers no app a permission set hides', () => {
90+
it('an app /me/apps does not list is not a "Switch app" item', async () => {
91+
const fetcher = meApps(['showcase_app', 'crm_app', 'account']);
92+
mount(fetcher);
93+
await waitFor(() => expect(shownApps()).toEqual(['Showcase', 'CRM', 'Account']));
94+
expect(fetcher).toHaveBeenCalledTimes(1);
95+
});
96+
97+
it('CONTROL — a 404 (no security plugin) offers every active app, as before', async () => {
98+
const fetcher = meApps(404);
99+
mount(fetcher);
100+
await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1));
101+
await waitFor(() => expect(shownApps()).toEqual(['Showcase', 'CRM', 'Ops', 'Account']));
102+
});
103+
});

‎ui/packages/app-shell/src/chrome/CommandPalette.tsx‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ import { fetchPackages, type PkgEntry } from '../views/studio-design/packages-io
7373
import { isPackageLessItem, studioOrgScopePath } from '../views/studio-design/studioScope.js';
7474
import { DESIGNER_SURFACE_PARAM, formatSurfaceParam } from '../views/metadata-admin/nav-selection.js';
7575
import { flattenNavigation, useAppReportEntries } from '../views/appReportIndex.js';
76+
import { useServedApps } from '../hooks/useLauncherApps.js';
7677

7778
/** The palette of the active app: the frame `ConsoleLayout` draws for `/apps/APP`. */
7879
interface AppCommandPaletteProps {
@@ -235,7 +236,10 @@ function CommandPaletteBody(props: CommandPaletteProps) {
235236
const appReports = useAppReportEntries(activeApp, open && !inStudio).entries.filter(
236237
(entry) => !navReportNames.has(entry.name) && matches(entry.label, entry.name),
237238
);
238-
const switchableApps = apps.filter((a) => a.active !== false);
239+
// Every active app, `hidden` ones included, minus an app the user's
240+
// permission sets hide: the palette offers none that Home's tiles and the
241+
// switcher withhold for that reason (objectstack#26838).
242+
const switchableApps = useServedApps(apps.filter((a) => a.active !== false));
239243
const appItems =
240244
switchableApps.length > 1
241245
? switchableApps.filter((app) => matches(resolveKeyedI18nLabel(app.label, t), app.name))

‎ui/packages/app-shell/src/console/AppContent.tsx‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import {
3333
import { buildExpressionUser } from '../providers/expressionUser.js';
3434
import { useTrackRouteAsRecent } from '../hooks/useTrackRouteAsRecent.js';
3535
import { useHomePath } from '../hooks/useHomePath.js';
36+
import { useLauncherApps } from '../hooks/useLauncherApps.js';
3637
import { useSignedInUserLocale } from '../hooks/useUserLocale.js';
3738
import { resolveRecordFormTarget, resolveRecordFormModalLayout, resolveNavigateCreateUrl, resolveNavigateEditUrl, resolvePostCreateTarget, recordFormCreateValues, readRecordFormCreateValues, RECORD_FORM_CREATE_VALUES_STATE } from '../utils/recordFormNavigation.js';
3839
import { deriveRecordSurface, deriveRecordFlowSurface } from '@object-ui/plugin-view';
@@ -336,8 +337,11 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps =
336337
// ⛔ `hidden` only — never `_unpublished` (objectstack#6955 / objectstack-ai/objectstack#4829 A1). The
337338
// publish gate is enforced server-side; duplicating it here would strand a
338339
// builder on their own unpublished app.
339-
const activeApps = apps.filter((a: any) => a.active !== false);
340-
const launcherApps = activeApps.filter((a: any) => a.hidden !== true);
340+
//
341+
// objectstack#26838 — and, like Home's tiles and the switcher, never on an
342+
// app the user's permission sets hide (`tabPermissions: hidden`, the
343+
// `/me/apps` answer); the route lookup below still finds such an app.
344+
const { apps: launcherApps } = useLauncherApps(apps);
341345
// ADR-0048 (A) — the route segment is the package id; resolve by it,
342346
// falling back to the app name (legacy/alias URL).
343347
// Built-in pseudo-routes under /apps/* that are NOT metadata apps (create-app,
Lines changed: 215 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,215 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#26838 — when a URL names no app the shell can resolve (a
5+
* pseudo-route such as `/apps/ghost/system/marketplace`), `AppContent` falls
6+
* back to the default launcher app. That fallback never lands on an app the
7+
* user's permission sets hide (`tabPermissions: hidden`): its list is the one
8+
* Home's tiles and the switcher offer, narrowed by the `GET /me/apps` answer.
9+
*
10+
* Under the real `LauncherAppsProvider` fed a `/me/apps` double; the routing
11+
* harness (stubs, `ConsoleLayout` probe echoing `activeAppName`) is
12+
* `AppContent.pseudoRouteSegments.test.tsx`'s.
13+
*/
14+
15+
import '@testing-library/jest-dom/vitest';
16+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
17+
import React from 'react';
18+
import { cleanup, render, screen, waitFor } from '@testing-library/react';
19+
import {
20+
MemoryRouter,
21+
Routes,
22+
Route,
23+
Navigate,
24+
useParams,
25+
} from 'react-router-dom';
26+
27+
// ---------------------------------------------------------------------------
28+
// Mocks — everything that takes part in the routing decision (AppContent's
29+
// guards, its nested <Routes>, react-router's matching) stays real.
30+
// ---------------------------------------------------------------------------
31+
32+
// AGENTS.md §测试纪律 — the lazy page modules are stubbed so no unbounded
33+
// `import()` races a bounded `findBy` window.
34+
vi.mock('../../views/metadata-admin', () => ({
35+
MetadataDirectoryPage: () => <div data-testid="metadata-directory-page">directory</div>,
36+
MetadataResourceListPage: () => {
37+
const { type } = useParams<{ type?: string }>();
38+
return <div data-testid="metadata-resource-list-page">{type}</div>;
39+
},
40+
MetadataResourceEditPage: () => <div data-testid="metadata-resource-edit-page" />,
41+
MetadataResourceHistoryPage: () => <div data-testid="metadata-resource-history-page" />,
42+
MetadataDiagnosticsPage: () => <div data-testid="metadata-diagnostics-page" />,
43+
}));
44+
45+
vi.mock('../marketplace/MarketplacePage', () => ({
46+
MarketplacePage: () => <div data-testid="marketplace-page">marketplace</div>,
47+
}));
48+
vi.mock('../marketplace/MarketplacePackagePage', () => ({
49+
MarketplacePackagePage: () => <div data-testid="marketplace-package-page" />,
50+
}));
51+
52+
vi.mock('@object-ui/plugin-designer', async (importOriginal) => ({
53+
...(await importOriginal<typeof import('@object-ui/plugin-designer')>()),
54+
CreateAppPage: () => <div data-testid="create-app-page">create app</div>,
55+
EditAppPage: () => <div data-testid="edit-app-page" />,
56+
DashboardDesignPage: () => <div data-testid="dashboard-design-page" />,
57+
}));
58+
59+
// Pay the real designer barrel's load in the IMPORT phase, where no timeout
60+
// applies. `AppContent` reaches `CreateAppPage` only through
61+
// `React.lazy(() => import('@object-ui/plugin-designer'))`, so the factory
62+
// above -- which now awaits the real module -- first runs when that lazy
63+
// boundary resolves, i.e. INSIDE the `findByTestId` budget of the two cases
64+
// below that assert on `create-app-page`. Under a saturated transform pipeline
65+
// the barrel's graph does not fit in that budget and the file goes red on LOAD
66+
// rather than on behaviour (AGENTS.md, the flaky-test discipline: an unbounded
67+
// module load counted against a bounded window). The specifier is byte-
68+
// identical to the component's own, so ESM hands the lazy factory this
69+
// already-resolved module.
70+
import '@object-ui/plugin-designer';
71+
72+
/**
73+
* The probe that makes the bug visible: it reports WHICH app's shell rendered.
74+
* The real `ConsoleLayout` drags in the whole console chrome (sidebar, header,
75+
* chat dock) — none of it part of this question.
76+
*/
77+
vi.mock('../../layout/ConsoleLayout', () => ({
78+
ConsoleLayout: ({ activeAppName, children }: { activeAppName?: string; children?: React.ReactNode }) => (
79+
<div data-testid="console-layout" data-active-app={activeAppName}>
80+
{children}
81+
</div>
82+
),
83+
}));
84+
vi.mock('../../chrome/CommandPalette', () => ({ CommandPalette: () => null }));
85+
vi.mock('../../chrome/KeyboardShortcutsDialog', () => ({ KeyboardShortcutsDialog: () => null }));
86+
vi.mock('../../chrome/OnboardingWalkthrough', () => ({ OnboardingWalkthrough: () => null }));
87+
88+
/** Echoes `:objectName` — the near-miss segment is taken as an object name. */
89+
vi.mock('../../views/ObjectView', () => ({
90+
ObjectView: () => {
91+
const { objectName } = useParams<{ objectName?: string }>();
92+
return <div data-testid="object-view">{objectName}</div>;
93+
},
94+
}));
95+
96+
vi.mock('@object-ui/i18n', async (importOriginal) => ({
97+
...(await importOriginal<Record<string, unknown>>()),
98+
useObjectTranslation: () => ({
99+
t: (key: string, options?: Record<string, unknown>) => String(options?.defaultValue ?? key),
100+
}),
101+
useObjectLabel: () => ({
102+
objectLabel: ({ label }: { label?: string }) => label,
103+
}),
104+
}));
105+
106+
// A workspace admin: the zero-app cases below land on the "no apps configured"
107+
// empty state, which since objectui#4473 renders for admins only — a viewer who
108+
// cannot act on its CTAs is bounced to `/home` with the shell chrome instead of
109+
// being stranded there (`AppContent.inaccessibleAppStrand.test.tsx`). Which
110+
// BRANCH a segment reaches — the question this file measures — does not depend
111+
// on the viewer.
112+
vi.mock('@object-ui/auth', async (importOriginal) => ({
113+
...(await importOriginal<Record<string, unknown>>()),
114+
// A signed-in user: the `/me/apps` read is asked per user.
115+
useAuth: () => ({
116+
user: { id: 'u1' },
117+
getAuthConfig: async () => ({ features: {} }),
118+
activeOrganization: null,
119+
}),
120+
useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }),
121+
}));
122+
123+
const dataSourceStub = {
124+
onConnectionStateChange: () => () => {},
125+
getConnectionState: () => 'connected',
126+
};
127+
vi.mock('../../providers/AdapterProvider', async (importOriginal) => ({
128+
...(await importOriginal<Record<string, unknown>>()),
129+
useAdapter: () => dataSourceStub,
130+
}));
131+
132+
/**
133+
* Two published apps, one of them the default. The default is what a broken
134+
* `requestedAppMissing` falls back to, so `crm` is the app that must NEVER
135+
* appear for a `/apps/<mistyped>/…` URL.
136+
*/
137+
const APPS = [
138+
{ name: 'crm', label: 'CRM', isDefault: true, navigation: [] },
139+
{ name: 'sales', label: 'Sales', navigation: [] },
140+
];
141+
142+
const refreshMetadata = vi.fn(async () => {});
143+
let metadataApps: unknown[] = APPS;
144+
vi.mock('../../providers/MetadataProvider', async (importOriginal) => ({
145+
...(await importOriginal<Record<string, unknown>>()),
146+
useMetadata: () => ({
147+
apps: metadataApps,
148+
objects: [],
149+
loading: false,
150+
// `undefined` — no bucket preloading to await, so the shell is ready on
151+
// first render (mirrors a host that ships metadata eagerly).
152+
ensureType: undefined,
153+
error: null,
154+
refresh: refreshMetadata,
155+
}),
156+
}));
157+
158+
import { AppContent } from '../AppContent';
159+
import { LauncherAppsProvider } from '../../hooks/useLauncherApps';
160+
161+
/** A `/me/apps` double: the listed names, or a bare status. */
162+
function meApps(answer: string[] | number) {
163+
return vi.fn(async (_url: unknown) =>
164+
typeof answer === 'number'
165+
? new Response('{}', { status: answer })
166+
: new Response(JSON.stringify({ apps: answer.map((name) => ({ name })) }), { status: 200 }),
167+
);
168+
}
169+
170+
function renderAt(url: string, fetcher: ReturnType<typeof meApps>) {
171+
render(
172+
<MemoryRouter initialEntries={[url]}>
173+
<LauncherAppsProvider endpoint="/me-apps-double" fetcher={fetcher as unknown as typeof fetch}>
174+
<Routes>
175+
<Route path="/apps/:appName/*" element={<AppContent />} />
176+
<Route path="/home" element={<div data-testid="home-launcher">home</div>} />
177+
<Route path="*" element={<Navigate to="/home" replace />} />
178+
</Routes>
179+
</LauncherAppsProvider>
180+
</MemoryRouter>,
181+
);
182+
}
183+
184+
beforeEach(() => {
185+
vi.clearAllMocks();
186+
metadataApps = APPS;
187+
});
188+
189+
afterEach(() => cleanup());
190+
191+
describe('the default-app fallback skips an app a permission set hides (objectstack#26838)', () => {
192+
it('the default app hidden by /me/apps: the fallback lands on the next launcher app', async () => {
193+
const fetcher = meApps(['sales']);
194+
renderAt('/apps/ghost/system/marketplace', fetcher);
195+
expect(await screen.findByTestId('marketplace-page')).toBeInTheDocument();
196+
await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1));
197+
await waitFor(() =>
198+
expect(screen.getByTestId('console-layout')).toHaveAttribute('data-active-app', 'sales'),
199+
);
200+
});
201+
202+
it('CONTROL — a 404 (no security plugin) keeps the declared default', async () => {
203+
const fetcher = meApps(404);
204+
renderAt('/apps/ghost/system/marketplace', fetcher);
205+
expect(await screen.findByTestId('marketplace-page')).toBeInTheDocument();
206+
await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1));
207+
expect(screen.getByTestId('console-layout')).toHaveAttribute('data-active-app', 'crm');
208+
});
209+
210+
it('a URL that names the hidden app still opens it', async () => {
211+
renderAt('/apps/crm/system/marketplace', meApps(['sales']));
212+
expect(await screen.findByTestId('marketplace-page')).toBeInTheDocument();
213+
expect(screen.getByTestId('console-layout')).toHaveAttribute('data-active-app', 'crm');
214+
});
215+
});

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ export { useHomePath } from './useHomePath.js';
6666
export {
6767
LauncherAppsProvider,
6868
useLauncherApps,
69+
useServedApps,
6970
type LauncherApps,
7071
type LauncherAppsProviderProps,
7172
} from './useLauncherApps.js';

0 commit comments

Comments
 (0)