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
13 changes: 13 additions & 0 deletions .changeset/34860-app-set-default-restore.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
'@object-ui/console': patch
'@object-ui/i18n': patch
---

fix(console): a refused "Set as default" on Setup › Apps no longer leaves the deployment with no default app

Clause-②: no
Metadata-protocol: none

Setting an app as the default first un-sets the current default, then sets the new one. When the second write was refused (for example, the app belongs to a read-only package and the server answers 403), the first write stayed and no app was the default any more. Now, when the server refuses the write (a 4xx answer) or the write fails before it is sent, the page puts each un-set default back, in the package it came from, before it shows the refusal. So a refused set-default leaves the default where it was. If putting it back fails too, a second error names the app that is no longer the default (new key `appManagement.toast.restoreDefaultFailed`, in all eleven console locales). A failure the server did not answer, or a 5xx, may have been written, so it is not undone: the page shows the failure and re-reads the list, which shows the result.

Nothing to migrate.
90 changes: 83 additions & 7 deletions ui/apps/console/src/pages/system/AppManagementPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,18 @@
* row shows the state the server serves. No row is patched locally ahead of
* that read.
*
* ## A refused set-default leaves the default where it was (objectstack#34860)
*
* Set default demotes the outgoing default before it promotes the target.
* When the promote is then refused with a 4xx (a target in a read-only package
* answers 403), or fails before it is sent, it wrote nothing, so each demotion
* that landed is put back in its own package scope before the refusal is
* shown, and the deployment keeps the default it had. A restore that fails too
* gets its own error toast naming the app that is no longer the default. A
* failure the server did not answer (or a 5xx) may have been written, so it is
* not undone: restoring could leave two defaults, and the re-read shows the
* result.
*
* ## A disabled star says why (ux-conventions.disabled-control-reason)
*
* The default app's Set-default star is disabled, and it gives its reason,
Expand Down Expand Up @@ -155,6 +167,31 @@ function owningPackage(app: { _packageId?: unknown }): string | undefined {
: undefined;
}

/**
* The failures `saveApp` raises BEFORE its write is sent: nothing reached the
* server, so nothing was written.
*/
const UNWRITTEN = new WeakSet<object>();

function markUnwritten(e: unknown): Error {
const error = e instanceof Error ? e : new Error(String(e ?? ''));
UNWRITTEN.add(error);
return error;
}

/**
* Whether a failed save is KNOWN to have written nothing: it failed before its
* write was sent, or the server answered it with a 4xx refusal (the client
* puts the status on `httpStatus`). A failure with no answer (a dropped
* connection, a timeout) or a 5xx may have been written anyway, so it is not.
*/
function wroteNothing(e: unknown): boolean {
if (typeof e !== 'object' || e === null) return false;
if (UNWRITTEN.has(e)) return true;
const status = (e as { httpStatus?: unknown }).httpStatus;
return typeof status === 'number' && status >= 400 && status < 500;
}

/**
* Save one app in the scope it is served from (objectui#12300), with the keys
* one control owns changed.
Expand All @@ -180,8 +217,13 @@ async function saveApp(
patch: Record<string, unknown>,
) {
const packageId = owningPackage(app);
const stored = await readAuthored('app', app.name, packageId ? { packageId } : {});
if (!stored) throw new Error();
let stored: Record<string, unknown> | null;
try {
stored = await readAuthored('app', app.name, packageId ? { packageId } : {});
} catch (e: unknown) {
throw markUnwritten(e);
}
if (!stored) throw markUnwritten(new Error());
const body = { ...stored, ...patch };
return packageId
? meta.saveItem('app', app.name, body, { packageId })
Expand Down Expand Up @@ -398,35 +440,69 @@ export function AppManagementPage() {
return;
}
setProcessing(true);
// The outgoing defaults whose demotion the server ACCEPTED, in order — the
// ones a failure further on must put back (objectstack#34860).
const demoted: any[] = [];
try {
// `isDefault` ROUTES (`resolveLandingPath` rule 1 takes the FIRST match),
// so it is single-valued in effect but not by construction: leaving the
// previous holder set would make the landing depend on the order the
// server happens to list apps in. Demote first, promote second — that
// ordering is what makes a failure mid-way leave the deployment with NO
// default (falls through to `/home`, the documented rule-3 answer) rather
// than with two.
// ordering is what makes a failure mid-way never leave the deployment
// with two defaults. A refused write mid-way is then undone below, so it
// does not leave it with NONE either.
const outgoing = (apps || []).filter(
(a: any) => a?.isDefault === true && a.name !== app.name,
);
// Each app is saved in ITS OWN package's scope: the outgoing default and
// the incoming one may belong to different packages, or to none.
for (const prev of outgoing) {
await saveApp(meta, readAuthored, prev, { isDefault: false });
demoted.push(prev);
}
await saveApp(meta, readAuthored, app, { isDefault: true });
toast.success(t('appManagement.toast.setDefaultDone', {
defaultValue: '{{name}} set as default',
name: appTitle(app),
}));
} catch (e: unknown) {
// objectstack#34860 — when the failed write is KNOWN to have written
// nothing (refused with a 4xx, e.g. 403 for a target in a read-only
// package, or failed before it was sent), every demotion that already
// landed is put back, each in the same package scope it was demoted in,
// so a refused set-default leaves the default where it was. The failed
// write changed nothing, so restoring cannot make two defaults.
// Any other failure (no answer, a 5xx) may have been written, so the
// promote may have landed and a restore could make two: nothing is
// undone, and the re-read below shows what the server holds.
const toRestore = wroteNothing(e) ? demoted : [];
const unrestored: any[] = [];
const restoreErrors: unknown[] = [];
for (const prev of toRestore) {
try {
await saveApp(meta, readAuthored, prev, { isDefault: true });
} catch (restoreFailure: unknown) {
unrestored.push(prev);
restoreErrors.push(restoreFailure);
}
}
toast.error(t('appManagement.toast.setDefaultFailed', {
defaultValue: 'Failed to set default app: {{reason}}',
reason: reason(e, unknownError),
}));
if (unrestored.length > 0) {
// The restore failed too: the deployment is left without the default
// it had. Said, never hidden: the operator has to set one. Each app's
// reason is listed once; identical reasons are said once.
toast.error(t('appManagement.toast.restoreDefaultFailed', {
defaultValue: 'Could not restore {{name}} as the default app, so it is no longer the default: {{reason}}',
name: unrestored.map((a) => appTitle(a)).join(', '),
reason: [...new Set(restoreErrors.map((r) => reason(r, unknownError)))].join('; '),
}));
}
} finally {
// Re-read on failure too: a failure after the demotion has already
// changed the server, and the list must show the deployment as it now is.
// Re-read on failure too: the list must show the deployment as it now
// is, restored or not.
await refresh();
setProcessing(false);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -353,11 +353,11 @@ describe('Set default sends each app’s own package (objectui#12300)', () => {
expect(card('lanebapp_app').queryByText('Default')).toBeNull();
});

it('re-reads after a failure too: a demotion that landed is shown, not hidden', async () => {
it('re-reads after a failure too: the restored default is what the list shows', async () => {
const realSave = h.saveItem.getMockImplementation()!;
h.saveItem
.mockImplementationOnce(realSave)
.mockRejectedValueOnce(new Error('forbidden: manage_metadata required'));
.mockRejectedValueOnce(Object.assign(new Error('forbidden: manage_metadata required'), { httpStatus: 403 }));
const user = userEvent.setup();
renderPage();

Expand All @@ -366,8 +366,11 @@ describe('Set default sends each app’s own package (objectui#12300)', () => {
await waitFor(() => expect(h.toastError).toHaveBeenCalled());
expect(h.toastSuccess).not.toHaveBeenCalled();
await waitFor(() => expect(h.refresh).toHaveBeenCalled());
// The demotion landed and the promotion did not: no app is the default.
await waitFor(() => expect(screen.queryByText('Default')).toBeNull());
// The demotion landed and the promotion did not, so the demotion was put
// back (objectstack#34860): the previous default is still the default.
expect(h.saveItem).toHaveBeenCalledTimes(3);
await waitFor(() => expect(card('lanebapp_app').getByText('Default')).toBeInTheDocument());
expect(card('showcase_app').queryByText('Default')).toBeNull();
});
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
* is the pair the stub was able to satisfy before.
*/

import { describe, expect, it, vi, beforeEach } from 'vitest';
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom';
Expand Down Expand Up @@ -182,6 +182,165 @@ describe('Set as default — issues a real mutation', () => {
});
});

/**
* objectstack#34860 — a refused set-default leaves the default where it was.
*
* The outgoing default lives in a writable package; the target lives in a
* read-only one, whose promote the server refuses with 403. Demote-first means
* the demotion has already landed by then, so the page must put it back, in the
* same package scope, or the deployment is left with no default app.
*/
describe('Set as default — a refused promote restores the previous default (objectstack#34860)', () => {
const MTHREE = {
name: 'mthree_app',
label: 'MThree',
isDefault: true,
_packageId: 'com.objectstack.qa.mthree',
};
const SHOWCASE = { name: 'showcase_app', label: 'Showcase', _packageId: 'com.example.showcase' };
const READ_ONLY =
"Cannot overlay 'app' in package 'com.example.showcase': that package is read-only";
/** A refusal the server answered, in the shape the client throws: the status on `httpStatus`. */
const refused = (message: string, httpStatus = 403) => Object.assign(new Error(message), { httpStatus });

/** Every write the page sent, with the package scope it named (the 4th argument). */
const writes = () =>
(saveItem.mock.calls as unknown[][]).map(([, name, body, options]) => [
name,
(body as { isDefault?: boolean }).isDefault,
(options as { packageId?: string } | undefined)?.packageId,
]);

/** The `isDefault` each app holds after the writes that LANDED, over the listed state. */
const landedDefaults = async () => {
const state: Record<string, boolean> = Object.fromEntries(
apps.value.map((a: any) => [a.name, a.isDefault === true]),
);
for (const [i, call] of (saveItem.mock.calls as unknown[][]).entries()) {
const outcome = saveItem.mock.results[i];
// A rejected write is a settled promise that throws; only fulfilled ones landed.
const landed = await Promise.resolve(outcome?.value).then(() => true, () => false);
if (landed) state[call[1] as string] = (call[2] as { isDefault?: boolean }).isDefault === true;
}
return Object.keys(state).filter((name) => state[name]);
};

beforeEach(() => {
apps.value = [MTHREE, SHOWCASE];
});

// `clearAllMocks` keeps an implementation, so the refusals below are undone
// here rather than leaking into the describes that follow.
afterEach(() => {
saveItem.mockImplementation(async () => ({}));
});

it('re-promotes the demoted default in its own package, and the final writes leave the same default', async () => {
saveItem.mockImplementation(async (_type, name, item) => {
if (name === 'showcase_app' && item.isDefault === true) throw refused(READ_ONLY);
return {};
});
const user = userEvent.setup();
renderPage();

await user.click(screen.getByLabelText('Set Showcase as default'));

await waitFor(() => expect(refresh).toHaveBeenCalled());
expect(writes()).toEqual([
['mthree_app', false, 'com.objectstack.qa.mthree'],
['showcase_app', true, 'com.example.showcase'],
['mthree_app', true, 'com.objectstack.qa.mthree'],
]);
expect(await landedDefaults()).toEqual(['mthree_app']);
// The original refusal is what the operator is told, in the server's words.
expect(toastError).toHaveBeenCalledTimes(1);
expect(toastError.mock.calls[0][0]).toContain(READ_ONLY);
expect(toastSuccess).not.toHaveBeenCalled();
});

it('⛔ says so when the restore is refused too — the lost default is never hidden', async () => {
saveItem.mockImplementation(async (_type, name, item) => {
if (name === 'showcase_app' && item.isDefault === true) throw refused(READ_ONLY);
if (name === 'mthree_app' && item.isDefault === true) throw refused('restore refused');
return {};
});
const user = userEvent.setup();
renderPage();

await user.click(screen.getByLabelText('Set Showcase as default'));

await waitFor(() => expect(refresh).toHaveBeenCalled());
expect(writes()).toEqual([
['mthree_app', false, 'com.objectstack.qa.mthree'],
['showcase_app', true, 'com.example.showcase'],
['mthree_app', true, 'com.objectstack.qa.mthree'],
]);
expect(await landedDefaults()).toEqual([]);
expect(toastError).toHaveBeenCalledTimes(2);
expect(toastError.mock.calls[0][0]).toContain(READ_ONLY);
// The second error names the app that is no longer the default, and why.
expect(toastError.mock.calls[1][0]).toContain('MThree');
expect(toastError.mock.calls[1][0]).toContain('restore refused');
expect(toastSuccess).not.toHaveBeenCalled();
});

it('a refused demotion writes nothing more — there is nothing to restore', async () => {
saveItem.mockImplementation(async (_type, name) => {
if (name === 'mthree_app') throw refused('forbidden');
return {};
});
const user = userEvent.setup();
renderPage();

await user.click(screen.getByLabelText('Set Showcase as default'));

await waitFor(() => expect(refresh).toHaveBeenCalled());
expect(writes()).toEqual([['mthree_app', false, 'com.objectstack.qa.mthree']]);
expect(await landedDefaults()).toEqual(['mthree_app']);
expect(toastError).toHaveBeenCalledTimes(1);
});

// A failure the server did not answer, or a 5xx, may have been written: the
// promote may have landed, so a restore could leave TWO defaults. Nothing is
// undone; the re-read shows what the server holds.
it.each([
['no answer (no httpStatus)', () => new TypeError('Failed to fetch')],
['a 5xx', () => refused('upstream timeout', 504)],
])('⛔ a promote failure with %s sends no restore write', async (_label, failure) => {
saveItem.mockImplementation(async (_type, name, item) => {
if (name === 'showcase_app' && item.isDefault === true) throw failure();
return {};
});
const user = userEvent.setup();
renderPage();

await user.click(screen.getByLabelText('Set Showcase as default'));

await waitFor(() => expect(refresh).toHaveBeenCalled());
expect(writes()).toEqual([
['mthree_app', false, 'com.objectstack.qa.mthree'],
['showcase_app', true, 'com.example.showcase'],
]);
expect(toastError).toHaveBeenCalledTimes(1);
expect(toastSuccess).not.toHaveBeenCalled();
});

it('CONTROL: an accepted promote keeps the order demote → promote, with no restore write', async () => {
const user = userEvent.setup();
renderPage();

await user.click(screen.getByLabelText('Set Showcase as default'));

await waitFor(() => expect(toastSuccess).toHaveBeenCalled());
expect(writes()).toEqual([
['mthree_app', false, 'com.objectstack.qa.mthree'],
['showcase_app', true, 'com.example.showcase'],
]);
expect(await landedDefaults()).toEqual(['showcase_app']);
expect(toastError).not.toHaveBeenCalled();
});
});

describe('Disable / Enable — issues a real mutation', () => {
it('PUTs `active: false` when disabling an active app', async () => {
const user = userEvent.setup();
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/ar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6099,6 +6099,7 @@ const ar = {
toggleFailed: "فشل تغيير حالة التطبيق: {{reason}}",
setDefaultDone: "تم تعيين {{name}} كافتراضي",
setDefaultFailed: "فشل تعيين التطبيق الافتراضي: {{reason}}",
restoreDefaultFailed: "تعذرت استعادة {{name}} كتطبيق افتراضي، لذا لم يعد هو الافتراضي: {{reason}}",
appDeleted: "تم حذف {{name}}",
deleteFailed: "فشل حذف التطبيق: {{reason}}",
nothingToDelete: "لا يوجد ما يُحذف لـ {{name}}: {{reason}}",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5492,6 +5492,7 @@ const de = {
toggleFailed: "Ändern des App-Status fehlgeschlagen: {{reason}}",
setDefaultDone: "{{name}} als Standard festgelegt",
setDefaultFailed: "Festlegen der Standard-App fehlgeschlagen: {{reason}}",
restoreDefaultFailed: "{{name}} konnte nicht als Standard-App wiederhergestellt werden und ist daher nicht mehr der Standard: {{reason}}",
appDeleted: "{{name}} gelöscht",
deleteFailed: "Löschen der App fehlgeschlagen: {{reason}}",
nothingToDelete: "Nichts zu löschen für {{name}}: {{reason}}",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6334,6 +6334,7 @@ const en = {
toggleFailed: 'Failed to toggle app status: {{reason}}',
setDefaultDone: '{{name}} set as default',
setDefaultFailed: 'Failed to set default app: {{reason}}',
restoreDefaultFailed: 'Could not restore {{name}} as the default app, so it is no longer the default: {{reason}}',
appDeleted: '{{name}} deleted',
deleteFailed: 'Failed to delete app: {{reason}}',
// A `reset: false` answer: no customization row existed, so nothing was
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5643,6 +5643,7 @@ const es = {
toggleFailed: "Error al cambiar el estado de la aplicación: {{reason}}",
setDefaultDone: "{{name}} establecida como predeterminada",
setDefaultFailed: "Error al establecer la aplicación predeterminada: {{reason}}",
restoreDefaultFailed: "No se pudo restaurar {{name}} como aplicación predeterminada, por lo que ya no es la predeterminada: {{reason}}",
appDeleted: "{{name}} eliminada",
deleteFailed: "Error al eliminar la aplicación: {{reason}}",
nothingToDelete: "Nada que eliminar para {{name}}: {{reason}}",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/fr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5639,6 +5639,7 @@ const fr = {
toggleFailed: "Échec du changement d'état de l'application : {{reason}}",
setDefaultDone: "{{name}} définie par défaut",
setDefaultFailed: "Échec de la définition de l'application par défaut : {{reason}}",
restoreDefaultFailed: "Impossible de rétablir {{name}} comme application par défaut ; elle n'est donc plus l'application par défaut : {{reason}}",
appDeleted: "{{name}} supprimée",
deleteFailed: "Échec de la suppression de l'application : {{reason}}",
nothingToDelete: "Rien à supprimer pour {{name}} : {{reason}}",
Expand Down
Loading
Loading