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
12 changes: 12 additions & 0 deletions .changeset/35115-app-writes-package-scope.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@object-ui/plugin-designer': patch
'@object-ui/app-shell': patch
'@object-ui/console': patch
---

fix(plugin-designer, app-shell): a packaged app is saved at its package, not at the package-less address

Clause-②: no
Metadata-protocol: none

The Edit app wizard read a packaged app at its package but saved it with no package, and the navigation sync that adds or removes an entry when a page or dashboard is created or deleted read and saved every app with no package. Both now read and save an app a package owns with `{ packageId }` (sent as `?package=`), the row the console serves, the way App management already saves it. An app no package owns, including one served with the `sys_metadata` sentinel, keeps the package-less address. A managed package's sealed app is still refused by the server at either address, and the navigation sync still skips it.
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,8 @@ describe('a navigation write sends the authored app (objectstack#35054)', () =>
const getAuthoredItem = vi.fn(async () => SOURCE);
const saveItem = await addPage(getAuthoredItem);

expect(getAuthoredItem).toHaveBeenCalledWith('app', 'qatr_app');
// Read at the app's package (objectstack#35115), the address the save names.
expect(getAuthoredItem).toHaveBeenCalledWith('app', 'qatr_app', { packageId: 'com.qa.tr' });
expect(saveItem).toHaveBeenCalledTimes(1);
const [type, name, body] = saveItem.mock.calls[0] as [string, string, any];
expect([type, name]).toEqual(['app', 'qatr_app']);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* objectstack#35115 — a navigation write reads and saves a packaged app at its
* package.
*
* `useNavigationSync` read the stored app (`getAuthoredItem('app', name)`) and
* saved it (`client.meta.saveItem('app', name, body)`) with no package, so a
* navigation write into an app a package owns went to the package-less
* address (no `?package=`). The read, the save and the Undo now name the
* served app's package (`{ packageId }`, sent as `?package=`); a package-less
* app, and an app served with the server's `sys_metadata` sentinel, keep the
* package-less address.
*
* Direction, written before the run: with the hook left package-less (the
* unmodified tree) the packaged case goes RED on the read's and the save's
* package while the package-less case stays GREEN.
*/

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import React, { useEffect } from 'react';
import { render, waitFor, cleanup } from '@testing-library/react';
import { MetadataCtx, AdapterCtx, type MetadataContextValue } from '@object-ui/react';
import { toast } from 'sonner';
import { useNavigationSync } from '../useNavigationSync';

vi.mock('sonner', () => ({
toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn(), info: vi.fn() }),
}));

/** The app as its author stored it. */
const STORED = {
name: 'qa_scope_app',
label: 'QA Scope App',
navigation: [{ id: 'nav_home', type: 'page', label: 'Home', pageName: 'qa_scope_home' }],
};

function metaValue(apps: Record<string, unknown>[]): MetadataContextValue {
return {
apps,
objects: [],
dashboards: [],
reports: [],
pages: [],
loading: false,
error: null,
refresh: async () => {},
invalidate: () => {},
ensureType: async () => [],
getItem: async () => null,
getItemsByType: () => [],
getTypeStatus: () => 'ready',
} as unknown as MetadataContextValue;
}

/** Add a page to the navigation of every app, the way a page publish does. */
async function addPage(served: Record<string, unknown>) {
const saveItem = vi.fn().mockResolvedValue({});
const getAuthoredItem = vi.fn(async () => STORED);
let done = false;
function Site() {
const { syncPageCreatedAllApps } = useNavigationSync();
useEffect(() => {
void syncPageCreatedAllApps('qa_scope_new_page').then(() => { done = true; });
// Once, on mount: the write is the case.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return null;
}
const adapter = { getClient: () => ({ meta: { saveItem } }), getAuthoredItem } as unknown as React.ComponentProps<
typeof AdapterCtx.Provider
>['value'];
render(
<AdapterCtx.Provider value={adapter}>
<MetadataCtx.Provider value={metaValue([served])}>
<Site />
</MetadataCtx.Provider>
</AdapterCtx.Provider>,
);
await waitFor(() => expect(done).toBe(true));
return { saveItem, getAuthoredItem };
}

/** Press the success toast's Undo, and wait for its save. */
async function undo(saveItem: ReturnType<typeof vi.fn>) {
const options = vi.mocked(toast.success).mock.calls[0]?.[1] as unknown as { action: { onClick: () => Promise<void> } };
await options.action.onClick();
await waitFor(() => expect(saveItem).toHaveBeenCalledTimes(2));
}

beforeEach(() => vi.clearAllMocks());
afterEach(() => cleanup());

describe('a navigation write addresses the app at its package (objectstack#35115)', () => {
it('a packaged app is read, saved and undone at its package', async () => {
const { saveItem, getAuthoredItem } = await addPage({ ...STORED, _packageId: 'com.qa.scope' });

expect(getAuthoredItem).toHaveBeenCalledWith('app', 'qa_scope_app', { packageId: 'com.qa.scope' });
expect(saveItem).toHaveBeenCalledTimes(1);
const [type, name, body, options] = saveItem.mock.calls[0] as [string, string, any, unknown];
expect([type, name, options]).toEqual(['app', 'qa_scope_app', { packageId: 'com.qa.scope' }]);
// Control: the write's own change is what it carries.
expect(body.navigation).toHaveLength(2);

await undo(saveItem);
expect(saveItem.mock.calls[1]?.[3]).toEqual({ packageId: 'com.qa.scope' });
expect((saveItem.mock.calls[1]?.[2] as any).navigation).toHaveLength(1);
});

it('a package-less app is read, saved and undone with no package', async () => {
const { saveItem, getAuthoredItem } = await addPage({ ...STORED });

expect(getAuthoredItem).toHaveBeenCalledWith('app', 'qa_scope_app');
expect(saveItem).toHaveBeenCalledTimes(1);
expect(saveItem.mock.calls[0]).toHaveLength(3);
expect(saveItem.mock.calls[0]?.slice(0, 2)).toEqual(['app', 'qa_scope_app']);

await undo(saveItem);
expect(saveItem.mock.calls[1]).toHaveLength(3);
});

it('an app served with the sys_metadata sentinel names no package on the read or the save', async () => {
const { saveItem, getAuthoredItem } = await addPage({ ...STORED, _packageId: 'sys_metadata' });

expect(getAuthoredItem).toHaveBeenCalledWith('app', 'qa_scope_app');
expect(saveItem).toHaveBeenCalledTimes(1);
expect(saveItem.mock.calls[0]).toHaveLength(3);
});
});
66 changes: 49 additions & 17 deletions ui/packages/app-shell/src/hooks/useNavigationSync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { useObjectTranslation } from '@object-ui/i18n';
import { useAdapter } from '../providers/AdapterProvider.js';
import { useMetadata } from '../providers/MetadataProvider.js';
import { matchAppBySegment } from '../utils/appRoute.js';
import { isPackageLessItem } from '../views/studio-design/studioScope.js';
import { usePreviewDrafts } from '../preview/PreviewModeContext.js';

// ============================================================================
Expand Down Expand Up @@ -274,23 +275,51 @@ export function useNavigationSync(): UseNavigationSyncReturn {
const refreshRef = useRef(refresh);
refreshRef.current = refresh;

/** Persist an updated app schema and refresh metadata. */
/** Find the current app schema from metadata by name. */
const findApp = useCallback(
(appName: string): AppComponentSchema | undefined =>
matchAppBySegment(apps, appName) as AppComponentSchema | undefined,
[apps],
);

/**
* objectstack#35115 — the one address a navigation write reads the app at
* and saves it to: the served app's name, and the package that owns it.
*
* A packaged app is read and saved with `{ packageId }` (`?package=`), the
* row it is served from, the way the console's other app writers name it
* (App management's `saveApp`, objectui#12300). A package-less app (no
* `_packageId`, or the server's `sys_metadata` sentinel) keeps the
* package-less address. A managed package's sealed app (ADR-0131 D6) is
* never targeted by the all-apps writes ({@link isNavigationSyncableApp}),
* and the server refuses a write onto it at either address.
*/
const appAddress = useCallback(
(appName: string): { name: string; packageId?: string } | undefined => {
const served = findApp(appName);
if (!served) return undefined;
const name = typeof served.name === 'string' && served.name ? served.name : appName;
const packageId = (served as { _packageId?: unknown })._packageId;
return !isPackageLessItem(served as { _packageId?: unknown }) && typeof packageId === 'string'
? { name, packageId }
: { name };
},
[findApp],
);

/** Persist an updated app schema at the app's address and refresh metadata. */
const saveApp = useCallback(
async (appName: string, schema: AppComponentSchema) => {
const client = adapterRef.current?.getClient();
if (client) {
await client.meta.saveItem('app', appName, schema);
const address = appAddress(appName) ?? { name: appName };
await (address.packageId
? client.meta.saveItem('app', address.name, schema, { packageId: address.packageId })
: client.meta.saveItem('app', address.name, schema));
}
await refreshRef.current?.();
},
[],
);

/** Find the current app schema from metadata by name. */
const findApp = useCallback(
(appName: string): AppComponentSchema | undefined =>
matchAppBySegment(apps, appName) as AppComponentSchema | undefined,
[apps],
[appAddress],
);

/**
Expand All @@ -303,25 +332,28 @@ export function useNavigationSync(): UseNavigationSyncReturn {
* stored the translations as source text, into every app a new page joined.
* The served list only finds the app here; its body comes from the
* untranslated layers (`getAuthoredItem`), read at the address `saveApp`
* writes (no package). An app with nothing stored to read is not written,
* and the failure is said once.
* writes ({@link appAddress}: its package, when it has one). An app with
* nothing stored to read is not written, and the failure is said once.
*/
const storedApp = useCallback(
async (appName: string): Promise<AppComponentSchema | undefined> => {
const served = findApp(appName);
if (!served) return undefined;
const name = typeof served.name === 'string' && served.name ? served.name : appName;
const address = appAddress(appName);
if (!address) return undefined;
try {
const read = adapterRef.current?.getAuthoredItem;
const stored = read ? await read.call(adapterRef.current, 'app', name) : null;
const stored = read
? await (address.packageId
? read.call(adapterRef.current, 'app', address.name, { packageId: address.packageId })
: read.call(adapterRef.current, 'app', address.name))
: null;
if (stored) return stored as unknown as AppComponentSchema;
} catch {
// Said below, as an absent body is.
}
toast.error(t('navigationSync.updateFailed'));
return undefined;
},
[findApp, t],
[appAddress, t],
);

// ------------------------------------------------------------------
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* objectstack#35115 — the app wizard saves a packaged app at its package.
*
* `EditAppPage` reads the stored app at the package the served app came from
* (`getAuthoredItem('app', name, { packageId })`, objectstack#35054), but its
* save called `client.meta.saveItem('app', name, body)` with no package, so
* the write went to the package-less address (no `?package=`) while the row it
* edited belongs to a package. The save now names the same package
* (`{ packageId }`, sent as `?package=`); a package-less app, and an app
* served with the server's `sys_metadata` sentinel, keep the package-less
* address for both the read and the save.
*
* Direction, written before the run: with the save left package-less (the
* unmodified tree) the packaged case goes RED on the save's options while the
* package-less case stays GREEN.
*/

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import React from 'react';
import { render, screen, cleanup, fireEvent, waitFor } from '@testing-library/react';

const saveItem = vi.fn().mockResolvedValue({});
const getAuthoredItem = vi.fn();
const apps: Record<string, unknown>[] = [];

vi.mock('react-router-dom', () => ({
useParams: () => ({ editAppName: 'qa_scope_app' }),
useNavigate: () => vi.fn(),
}));

vi.mock('@object-ui/react', async (importOriginal) => {
const actual = await importOriginal<Record<string, unknown>>();
return {
...actual,
useAdapter: () => ({ getClient: () => ({ meta: { saveItem } }), getAuthoredItem }),
useMetadata: () => ({ apps, objects: [], refresh: () => Promise.resolve() }),
};
});

vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn() } }));

import { EditAppPage } from '../pages/EditAppPage';

/** The app as its author stored it. */
const STORED = { name: 'qa_scope_app', label: 'QA Scope App', icon: 'sparkles', navigation: [] };

const next = () => fireEvent.click(screen.getByTestId('wizard-next'));

/** Open the wizard on the served app, edit the description and complete it. */
async function editAndSave(served: Record<string, unknown>) {
apps.push(served);
getAuthoredItem.mockResolvedValue(STORED);
render(<EditAppPage />);
await screen.findByTestId('edit-app-page');
fireEvent.change(screen.getByTestId('app-description-input'), { target: { value: 'Edited description' } });
next(); // → objects
next(); // → navigation
next(); // → branding
fireEvent.click(screen.getByTestId('wizard-complete'));
await waitFor(() => expect(saveItem).toHaveBeenCalledTimes(1));
return saveItem.mock.calls[0] as unknown[];
}

beforeEach(() => {
saveItem.mockClear();
getAuthoredItem.mockReset();
apps.length = 0;
});
afterEach(() => cleanup());

describe('EditAppPage saves the app at its package (objectstack#35115)', () => {
it('a packaged app is read and saved at its package', async () => {
const call = await editAndSave({ ...STORED, _packageId: 'com.qa.scope' });
expect(getAuthoredItem).toHaveBeenCalledWith('app', 'qa_scope_app', { packageId: 'com.qa.scope' });
expect(call[3]).toEqual({ packageId: 'com.qa.scope' });
// Control: the save is the app, with the edit.
expect(call.slice(0, 2)).toEqual(['app', 'qa_scope_app']);
expect((call[2] as Record<string, unknown>).description).toBe('Edited description');
});

it('a package-less app is read and saved with no package', async () => {
const call = await editAndSave({ ...STORED });
expect(getAuthoredItem).toHaveBeenCalledWith('app', 'qa_scope_app', {});
expect(call).toHaveLength(3);
expect(call.slice(0, 2)).toEqual(['app', 'qa_scope_app']);
});

it('an app served with the sys_metadata sentinel names no package on the read or the save', async () => {
const call = await editAndSave({ ...STORED, _packageId: 'sys_metadata' });
expect(getAuthoredItem).toHaveBeenCalledWith('app', 'qa_scope_app', {});
expect(call).toHaveLength(3);
});
});
Loading
Loading