Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/sidebar-package-app-address.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@object-ui/app-shell': patch
---

fix(app-shell): inside a package's second app, the sidebar and the `nav:menu` block link into that app

Clause-②: no
Metadata-protocol: none

`/apps/SEGMENT` opens a package's first app when SEGMENT is the package id, and a package can ship more than one app. The sidebar built every entry link, and the route its area election reads, on the package id, so inside a package's second app a click on any entry opened the first app. The `nav:menu` page block built its links the same way. Both now build on the app's one address among the metadata app list (`appAddressSegment`, the address the app page resolves its own links with): the package id when it reaches the app, else the app's name. A package's first or only app keeps its package-id links unchanged.
10 changes: 7 additions & 3 deletions ui/packages/app-shell/src/layout/UnifiedSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ import { useNavActionDispatch } from '../hooks/useNavActionDispatch.js';
import { useNavTargetLabel } from '../hooks/useNavTargetLabel.js';
import { useNavDocTargetCheck } from '../hooks/useNavDocTargetCheck.js';
import { useNavMemberGates } from '../hooks/useNavMemberGates.js';
import { matchAppBySegment, appRouteSegment, resolveKeyedI18nLabel } from '../utils/index.js';
import { matchAppBySegment, resolveKeyedI18nLabel } from '../utils/index.js';
import { appAddressSegment } from '../utils/appRoute.js';
import { withoutUnreadableObjectEntries } from '../utils/navObjectReadGate.js';
import { useHomePath } from '../hooks/useHomePath.js';
// Aliased for symmetry with objectui's own `resolveKeyedI18nLabel` above (the
Expand Down Expand Up @@ -341,7 +342,7 @@ export function UnifiedSidebar({ activeAppName, railOverlay = false }: UnifiedSi
? {
pathname: location.pathname,
search: location.search,
basePath: `/apps/${appRouteSegment(activeApp)}`,
basePath: `/apps/${appAddressSegment(apps, activeApp)}`,
templateContext: navTemplateContext,
}
: null;
Expand Down Expand Up @@ -430,7 +431,10 @@ export function UnifiedSidebar({ activeAppName, railOverlay = false }: UnifiedSi

// Determine which navigation to show based on context
const navigationItems = context === 'home' ? homeNavigation : appNavigation;
const basePath = context === 'app' && activeApp ? `/apps/${appRouteSegment(activeApp)}` : '';
// ADR-0048 (A) — the app's one address among the full metadata list, the
// list `/apps/SEGMENT` resolves on: its package id when that reaches this
// app, else its name (a package's second app shares the first app's id).
const basePath = context === 'app' && activeApp ? `/apps/${appAddressSegment(apps, activeApp)}` : '';
const isStudioApp = context === 'app' && activeApp?.name === 'studio';
// Studio's package-management link carries the active package scope. Read
// (and re-emit) it through the SAME per-selector key derivation the selector
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* UnifiedSidebar — inside a package's second app, every link addresses that app.
*
* `/apps/SEGMENT` resolves through `matchAppBySegment` over the metadata app
* list, so a package id opens the package's FIRST app. Two apps shipped by one
* package share that id; the name is the only address that reaches the second.
* The sidebar's links and the route its area election reads are built on
* `appAddressSegment(apps, activeApp)`, the address `AppContent` resolves the
* open app's links with, so a package's first or only app keeps its package-id
* address and its second app is addressed by name.
*
* The route helpers stay REAL (`../../utils` is not mocked), and so do
* `@object-ui/components` and `@object-ui/layout`, so the hrefs asserted below
* are the ones `NavigationRenderer` draws.
*/

import '@testing-library/jest-dom/vitest';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import React from 'react';
import { render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import type { NavigationArea } from '@object-ui/types';

// Partial mock: @object-ui/components also imports from @object-ui/i18n
// (createSafeTranslation), so the rest of the module must stay real.
vi.mock('@object-ui/i18n', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useObjectTranslation: () => ({
t: (key: string, options?: Record<string, unknown>) => String(options?.defaultValue ?? key),
}),
useObjectLabel: () => ({
objectLabel: ({ label }: { label?: string }) => label,
viewLabel: (_o: string, _v: string, fallback?: string) => fallback,
dashboardLabel: ({ label }: { label?: string }) => label,
}),
}));

vi.mock('@object-ui/auth', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useAuth: () => ({ user: null, activeOrganization: null }),
useWorkspaceAdminStatus: () => ({ isAdmin: false, isResolved: true }),
}));

vi.mock('@object-ui/permissions', async (importOriginal) => ({
...(await importOriginal<typeof import('@object-ui/permissions')>()),
usePermissions: () => ({ can: () => true, hasCapabilities: () => true }),
}));

let metadataState: { apps: unknown[]; objects: unknown[] };
vi.mock('../../providers/MetadataProvider', () => ({
useMetadata: () => metadataState,
}));

vi.mock('../../providers/ExpressionProvider', () => ({
useExpressionContext: () => ({ evaluator: null }),
evaluateVisibility: (expr: unknown) => expr !== false && expr !== 'false',
evaluateNavigationVisibility: (expr: unknown) => expr !== false && expr !== 'false',
useHasExpressionScope: () => true,
}));

// Lazy lucide DynamicIcon would suspend mid-test; a null icon is enough here.
vi.mock('../../utils/getIcon', () => ({ getIcon: () => () => null }));

vi.mock('../../hooks/useRecentItems', () => ({ useRecentItems: () => ({ recentItems: [] }) }));
vi.mock('../../hooks/useFavorites', () => ({
useFavorites: () => ({ favorites: [], removeFavorite: vi.fn() }),
}));
vi.mock('../../hooks/useNavPins', () => ({
useNavPins: () => ({ togglePin: vi.fn(), applyPins: (items: unknown) => items }),
}));
vi.mock('../../hooks/useNavActionDispatch', () => ({
useNavActionDispatch: () => vi.fn(),
}));
let currentAppName = '';
vi.mock('../../context/NavigationContext', () => ({
useNavigationContext: () => ({ context: 'app', currentAppName }),
}));
vi.mock('../ContextSelectors', () => ({
useAppContextSelectors: () => ({ contextValues: {}, element: null }),
contextSelectorQueryKey: (id: string) => (id === 'active_package' ? 'package' : id),
STUDIO_PACKAGE_SELECTOR_ID: 'active_package',
}));
vi.mock('../LocalizedSidebarTrigger', () => ({
LocalizedSidebarTrigger: () => null,
}));

import { SidebarProvider } from '@object-ui/components';
import { UnifiedSidebar } from '../UnifiedSidebar';

// ---------------------------------------------------------------------------
// Fixtures — `com.example.crm` ships `crm` (first) and `crm_service`;
// `com.example.hr` ships `hr` alone. Labels are pairwise distinct.
// ---------------------------------------------------------------------------

const queueArea: NavigationArea = {
id: 'area-queue',
label: 'Queue',
navigation: [{ id: 'nav-queue', type: 'object', label: 'Queues', objectName: 'crm_queue' }],
};

const casesArea: NavigationArea = {
id: 'area-cases',
label: 'Casework',
navigation: [
{ id: 'nav-case', type: 'object', label: 'Cases', objectName: 'crm_case' },
{ id: 'nav-board', type: 'dashboard', label: 'Service board', dashboardName: 'service_board' },
],
};

const APPS = [
{
name: 'crm',
label: 'Sales',
_packageId: 'com.example.crm',
active: true,
navigation: [{ id: 'nav-opportunity', type: 'object', label: 'Opportunities', objectName: 'crm_opportunity' }],
},
{
name: 'crm_service',
label: 'Service',
_packageId: 'com.example.crm',
active: true,
areas: [queueArea, casesArea],
},
{
name: 'hr',
label: 'People',
_packageId: 'com.example.hr',
active: true,
navigation: [{ id: 'nav-employee', type: 'object', label: 'Employees', objectName: 'hr_employee' }],
},
];

/** Render the sidebar as `AppContent` does: the app segment the URL carries. */
function renderAt(path: string) {
const segment = decodeURIComponent(path.split('/')[2] ?? '');
currentAppName = segment;
metadataState = { apps: APPS, objects: [] };
return render(
<MemoryRouter initialEntries={[path]}>
<SidebarProvider>
<UnifiedSidebar activeAppName={segment} />
</SidebarProvider>
</MemoryRouter>,
);
}

function href(label: string): string | null {
const link = screen.getByText(label).closest('a');
if (!(link instanceof HTMLAnchorElement)) throw new Error(`no link for ${label}`);
return link.getAttribute('href');
}

function areaButton(label: string): HTMLElement {
const button = screen.getByText(label).closest('[data-sidebar="menu-button"]');
if (!(button instanceof HTMLElement)) throw new Error(`no switcher row for area ${label}`);
return button;
}

beforeEach(() => {
localStorage.clear();
});

describe("UnifiedSidebar addresses a package's second app by its own address", () => {
it("inside the package's second app, every entry links into that app", () => {
renderAt('/apps/crm_service/crm_queue');
expect(href('Queues')).toBe('/apps/crm_service/crm_queue');
});

it('elects the area holding the routed entry of the second app, and its links stay in that app', () => {
renderAt('/apps/crm_service/crm_case');
expect(areaButton('Casework')).toHaveAttribute('data-active', 'true');
expect(areaButton('Queue')).toHaveAttribute('data-active', 'false');
expect(href('Cases')).toBe('/apps/crm_service/crm_case');
expect(href('Service board')).toBe('/apps/crm_service/dashboard/service_board');
});

it("control: the package's first app keeps its package-id address", () => {
renderAt('/apps/com.example.crm/crm_opportunity');
expect(href('Opportunities')).toBe('/apps/com.example.crm/crm_opportunity');
});

it("control: a package's only app keeps its package-id address", () => {
renderAt('/apps/com.example.hr/hr_employee');
expect(href('Employees')).toBe('/apps/com.example.hr/hr_employee');
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/**
* ObjectUI
* Copyright (c) 2024-present ObjectStack Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

/**
* The `nav:menu` page block addresses a package's second app by its own
* address, as the sidebar does (`UnifiedSidebar.packageAppAddress-29328`).
*
* `/apps/SEGMENT` resolves to a package's FIRST app when SEGMENT is the package
* id, so inside the second app the block's links carry the app's name, the
* address `appAddressSegment` answers among the metadata app list. A package's
* first or only app keeps its package-id address.
*/
import '@testing-library/jest-dom/vitest';
import { describe, it, expect } from 'vitest';
import { render, screen, within } from '@testing-library/react';
import React from 'react';
import { MemoryRouter, Routes, Route } from 'react-router-dom';

// Module scope, never a `beforeAll` (AGENTS.md §测试纪律, objectui#3010).
import '@object-ui/components';
import { SchemaRenderer, MetadataCtx } from '@object-ui/react';
import { MePermissionsProvider, type MePermissionsAuthenticatedResponse } from '@object-ui/permissions';
import '../nav-menu-renderer';

const APPS = [
{
name: 'crm',
label: 'Sales',
_packageId: 'com.example.crm',
navigation: [{ id: 'nav_opportunity', type: 'object', objectName: 'crm_opportunity', label: 'Opportunities' }],
},
{
name: 'crm_service',
label: 'Service',
_packageId: 'com.example.crm',
navigation: [
{ id: 'nav_case', type: 'object', objectName: 'crm_case', label: 'Cases' },
{ id: 'nav_board', type: 'dashboard', dashboardName: 'service_board', label: 'Service board' },
],
},
{
name: 'hr',
label: 'People',
_packageId: 'com.example.hr',
navigation: [{ id: 'nav_employee', type: 'object', objectName: 'hr_employee', label: 'Employees' }],
},
];

const ANSWER: MePermissionsAuthenticatedResponse = {
authenticated: true,
userId: 'u_member',
tenantId: null,
positions: [],
hasAnyQueue: false,
permissionSets: ['member'],
systemPermissions: [],
objects: {
crm_opportunity: { allowRead: true },
crm_case: { allowRead: true },
hr_employee: { allowRead: true },
},
fields: {},
};

const METADATA = {
apps: APPS,
objects: [
{ name: 'crm_opportunity', label: 'Opportunities' },
{ name: 'crm_case', label: 'Cases' },
{ name: 'hr_employee', label: 'Employees' },
],
dashboards: [],
reports: [],
pages: [],
loading: false,
error: null,
refresh: async () => {},
invalidate: () => {},
ensureType: async () => [],
getItem: async () => null,
getItemsByType: () => [],
getTypeStatus: () => 'ready',
};

function renderMenuAt(path: string) {
render(
<MePermissionsProvider initialPermissions={ANSWER}>
<MemoryRouter initialEntries={[path]}>
<MetadataCtx.Provider value={METADATA as never}>
<Routes>
<Route
path="/apps/:appName"
element={
<SchemaRenderer
schema={{ type: 'page:section', id: 's1', children: [{ type: 'nav:menu', id: 'blk_nav' }] } as never}
/>
}
/>
</Routes>
</MetadataCtx.Provider>
</MemoryRouter>
</MePermissionsProvider>,
);
return within(screen.getByRole('navigation', { name: 'App navigation' }));
}

describe("`nav:menu` addresses a package's second app by its own address", () => {
it("inside the package's second app, every link stays in that app", () => {
const menu = renderMenuAt('/apps/crm_service');
expect(menu.getByRole('link', { name: 'Cases' })).toHaveAttribute('href', '/apps/crm_service/crm_case');
expect(menu.getByRole('link', { name: 'Service board' })).toHaveAttribute(
'href',
'/apps/crm_service/dashboard/service_board',
);
});

it("control: the package's first app keeps its package-id address", () => {
const menu = renderMenuAt('/apps/com.example.crm');
expect(menu.getByRole('link', { name: 'Opportunities' })).toHaveAttribute(
'href',
'/apps/com.example.crm/crm_opportunity',
);
});

it("control: a package's only app keeps its package-id address", () => {
const menu = renderMenuAt('/apps/com.example.hr');
expect(menu.getByRole('link', { name: 'Employees' })).toHaveAttribute('href', '/apps/com.example.hr/hr_employee');
});
});
7 changes: 5 additions & 2 deletions ui/packages/app-shell/src/views/nav-menu-renderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,8 @@ import { useNavDocTargetCheck } from '../hooks/useNavDocTargetCheck.js';
import { withoutUnreadableObjectEntries } from '../utils/navObjectReadGate.js';
import { useNavigationContext } from '../context/NavigationContext.js';
import { getIcon } from '../utils/getIcon.js';
import { appRouteSegment, matchAppBySegment } from '../utils/index.js';
import { matchAppBySegment } from '../utils/index.js';
import { appAddressSegment } from '../utils/appRoute.js';
import { navigationNames } from '../console/appObjectScope.js';

/** Keep the designer's own data attributes on the wrapper, drop the rest. */
Expand Down Expand Up @@ -293,7 +294,9 @@ export const NavMenuRenderer: React.FC<NavMenuRendererProps> = ({
return readable(activeApp?.navigation as NavigationItem[] | undefined);
}, [activeApp, guards, can]);

const basePath = activeApp ? `/apps/${appRouteSegment(activeApp) ?? activeApp.name}` : '';
// The app's one address among the metadata list `/apps/SEGMENT` resolves on,
// as the sidebar builds it: a package's second app is addressed by name.
const basePath = activeApp ? `/apps/${appAddressSegment(apps, activeApp)}` : '';

const templateContext: NavTemplateContext = useMemo(
() => ({ currentUserId: user?.id ?? null, currentOrgId: activeOrganization?.id ?? null }),
Expand Down
Loading