Skip to content

Commit 92a9daa

Browse files
committed
fix(app-shell): the edit page shows a pending draft's own server verdict
The edit page read `_diagnostics` from the layered read alone, which judges the published body, so a pending draft the publish refuses reached the canvas Problems panel and the diagnostics banner as valid. The draft read's `_diagnostics` now carries the publish's verdict on the draft; the page takes it whenever it holds a draft, and merges its server-only errors with the live client parse. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5oVR19x7NPLf4YzCzj
1 parent b74652f commit 92a9daa

4 files changed

Lines changed: 346 additions & 28 deletions

File tree

Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#26707 — while a draft is pending, the editor shows the DRAFT's
5+
* server verdict, which carries what its publish would refuse.
6+
*
7+
* ## The defect this file keeps fixed
8+
*
9+
* The edit page read `_diagnostics` from the layered read alone. That verdict
10+
* judges the PUBLISHED body (`getMetaItemLayered` composes `effective` from the
11+
* active rows and never reads a draft), so a pending draft the publish refuses
12+
* — a flow edge whose CEL does not parse, a summary field with no operations —
13+
* reached the canvas Problems panel and the diagnostics banner as "valid", and
14+
* the refusal arrived only at Publish. Since objectstack#26707 the draft read's
15+
* `_diagnostics` is the publish's own verdict on the draft; this page now takes
16+
* it whenever it holds a draft.
17+
*
18+
* The server double below serves that verdict the way the real draft read
19+
* does — computed from the stored draft body, with the rule id as `code` — and
20+
* a layered verdict that says `valid: true`, as the published body is clean.
21+
* Red on base: the canvas never receives the draft's error.
22+
*/
23+
24+
import '@testing-library/jest-dom/vitest';
25+
import * as React from 'react';
26+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
27+
import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react';
28+
import { MemoryRouter } from 'react-router-dom';
29+
30+
type Row = Record<string, unknown>;
31+
32+
const REFUSAL = {
33+
path: 'regions.0',
34+
message: 'region "main" names a component this deployment does not have',
35+
code: 'page-component-unknown',
36+
};
37+
38+
const server = vi.hoisted(() => ({
39+
active: new Map<string, Record<string, unknown>>(),
40+
drafts: new Map<string, Record<string, unknown>>(),
41+
saves: 0,
42+
}));
43+
44+
const mockClient = vi.hoisted(() => {
45+
const k = (type: string, name: string) => `${type}/${name}`;
46+
/** The publish's verdict on a body: this double refuses a body labelled `broken`. */
47+
const verdictOf = (body: Record<string, unknown>) =>
48+
body.label === 'broken'
49+
? {
50+
valid: false,
51+
errors: [{
52+
path: 'regions.0',
53+
message: 'region "main" names a component this deployment does not have',
54+
code: 'page-component-unknown',
55+
}],
56+
}
57+
: { valid: true };
58+
return {
59+
list: vi.fn(async () => []),
60+
listDrafts: vi.fn(async () => []),
61+
get: vi.fn(async () => null),
62+
references: vi.fn(async () => []),
63+
layered: vi.fn(async (type: string, name: string) => {
64+
const eff = server.active.get(k(type, name)) ?? null;
65+
return {
66+
code: null,
67+
overlay: eff,
68+
overlayScope: eff ? 'env' : null,
69+
effective: eff,
70+
// The PUBLISHED body's verdict — clean.
71+
...(eff ? { _diagnostics: { valid: true } } : {}),
72+
editable: true,
73+
deletable: true,
74+
resettable: false,
75+
lock: 'none',
76+
};
77+
}),
78+
getDraft: vi.fn(async (type: string, name: string) => {
79+
const row = server.drafts.get(k(type, name));
80+
if (!row) {
81+
throw Object.assign(new Error(`No pending draft exists for ${type}/${name}.`), { code: 'NO_DRAFT', status: 404 });
82+
}
83+
return { type, name, item: { ...row, _draft: true, _diagnostics: verdictOf(row) } };
84+
}),
85+
save: vi.fn(async (type: string, name: string, item: unknown, opts?: Record<string, unknown>) => {
86+
const body = JSON.parse(JSON.stringify(item)) as Record<string, unknown>;
87+
server.saves += 1;
88+
if (opts?.mode === 'draft') server.drafts.set(k(type, name), body);
89+
else server.active.set(k(type, name), body);
90+
return { type, name, item: body };
91+
}),
92+
publish: vi.fn(async () => ({ success: true })),
93+
reset: vi.fn(async () => ({})),
94+
};
95+
});
96+
97+
vi.mock('./useMetadata', async (importOriginal) => {
98+
const mod = await importOriginal<typeof import('./useMetadata')>();
99+
return {
100+
...mod,
101+
useMetadataClient: () => mockClient,
102+
useMetadataTypes: () => ({
103+
entries: [{ type: 'page', name: 'page', label: 'Page', allowEnvironmentOverlay: true, schema: { required: [] } }],
104+
}),
105+
};
106+
});
107+
108+
import { MetadataResourceEditPage } from './ResourceEditPage';
109+
import { registerMetadataPreview, getMetadataPreview } from './preview-registry';
110+
111+
/** Canvas stand-in: prints the server diagnostics the page hands a preview, and dirties the draft on demand. */
112+
function StubCanvas({
113+
diagnostics,
114+
onPatch,
115+
}: {
116+
diagnostics?: Array<{ path?: string; message: string; severity?: string }>;
117+
onPatch?: (patch: Record<string, unknown>) => void;
118+
}) {
119+
return (
120+
<>
121+
<pre data-testid="canvas-diagnostics">{JSON.stringify(diagnostics ?? [])}</pre>
122+
<button type="button" onClick={() => onPatch?.({ label: 'fixed' })}>fix the draft</button>
123+
</>
124+
);
125+
}
126+
127+
const realPage = getMetadataPreview('page');
128+
129+
const PAGE: Row = {
130+
name: 'home',
131+
label: 'Home',
132+
type: 'home',
133+
template: 'default',
134+
regions: [{ name: 'main', components: [{ type: 'text', id: 'b1' }] }],
135+
};
136+
137+
beforeEach(() => {
138+
server.active.clear();
139+
server.drafts.clear();
140+
server.saves = 0;
141+
for (const fn of Object.values(mockClient)) (fn as unknown as { mockClear: () => void }).mockClear();
142+
registerMetadataPreview('page', StubCanvas as never);
143+
});
144+
145+
afterEach(() => {
146+
cleanup();
147+
if (realPage) registerMetadataPreview('page', realPage);
148+
window.history.replaceState(null, '', '/');
149+
});
150+
151+
function renderEditor() {
152+
window.history.replaceState(null, '', '/metadata/page/home');
153+
render(
154+
<MemoryRouter initialEntries={['/metadata/page/home']}>
155+
<MetadataResourceEditPage type="page" name="home" />
156+
</MemoryRouter>,
157+
);
158+
}
159+
160+
const canvasDiagnostics = () =>
161+
JSON.parse(screen.getByTestId('canvas-diagnostics').textContent ?? '[]') as Array<{ message: string; severity?: string }>;
162+
163+
describe('MetadataResourceEditPage — a pending draft is judged by its own server verdict (objectstack#26707)', () => {
164+
it('the canvas receives the draft read\'s refusal although the published body is clean', async () => {
165+
server.active.set('page/home', PAGE);
166+
server.drafts.set('page/home', { ...PAGE, label: 'broken' });
167+
renderEditor();
168+
169+
await waitFor(
170+
() => expect(canvasDiagnostics()).toContainEqual(expect.objectContaining({ message: REFUSAL.message, severity: 'error' })),
171+
{ timeout: 8000 },
172+
);
173+
});
174+
175+
it('the verdict follows the draft: the refresh after an autosave of a fixed draft clears it', async () => {
176+
server.active.set('page/home', PAGE);
177+
server.drafts.set('page/home', { ...PAGE, label: 'broken' });
178+
renderEditor();
179+
await waitFor(() => expect(canvasDiagnostics().map((d) => d.message)).toContain(REFUSAL.message), { timeout: 8000 });
180+
181+
fireEvent.click(screen.getByRole('button', { name: 'fix the draft' }));
182+
183+
await waitFor(() => expect(server.saves).toBe(1), { timeout: 8000 });
184+
await waitFor(() => expect(canvasDiagnostics().map((d) => d.message)).not.toContain(REFUSAL.message), { timeout: 8000 });
185+
});
186+
187+
it('control: with no pending draft the published verdict stands', async () => {
188+
server.active.set('page/home', PAGE);
189+
renderEditor();
190+
191+
await waitFor(() => expect(mockClient.layered).toHaveBeenCalled(), { timeout: 8000 });
192+
await screen.findByTestId('canvas-diagnostics', undefined, { timeout: 8000 });
193+
expect(canvasDiagnostics().map((d) => d.message)).not.toContain(REFUSAL.message);
194+
});
195+
});

‎ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx‎

Lines changed: 43 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,12 @@ import { useRegisteredMetadataDefaultInspector } from './default-inspector-regis
146146
import { useMetadataLocale, t, tFormat, translateMetadataType, translateValidationMessage } from './i18n.js';
147147
import { JsonSourceEditor } from './JsonSourceEditor.js';
148148
import { validateMetadataDraft, hasClientValidator, type DraftMode } from './clientValidation.js';
149+
import {
150+
draftEnvelopeDiagnostics,
151+
editedItemDiagnostics,
152+
withServerOnlyErrors,
153+
type ServerDiagnostics,
154+
} from './draftVerdict.js';
149155
import { describeIssuePath, issueSlicePath, issueSliceFingerprint } from './issuePath.js';
150156
import { buildCreateModeBody, seedStructuralDefaults, unsetSeedPlaceholders } from './createBody.js';
151157
import { errorCodeIs, errorCodeIsAnyOf } from '@object-ui/types';
@@ -750,6 +756,18 @@ function MetadataResourceEditPageImpl({
750756
() => (createMode && !createDirty ? [] : issues),
751757
[createMode, createDirty, issues],
752758
);
759+
// Per-item draft pending publish (mode=draft saves land here).
760+
// When non-null, the editor is "viewing the draft" and we surface
761+
// Publish / Discard-draft actions.
762+
const [hasDraft, setHasDraft] = React.useState(false);
763+
// objectstack#26707 — the pending draft's own `_diagnostics`, kept from each
764+
// draft read (load, save, publish) before its decorations are stripped.
765+
const [draftDiagnostics, setDraftDiagnostics] = React.useState<ServerDiagnostics | undefined>(undefined);
766+
// The server verdict on the body on screen (see `draftVerdict.ts`).
767+
const serverDiagnostics = React.useMemo(
768+
() => editedItemDiagnostics({ hasDraft, draftDiagnostics, layered }),
769+
[hasDraft, draftDiagnostics, layered],
770+
);
753771
// Server-computed diagnostics handed to a canvas Preview (e.g. the flow
754772
// Problems panel + on-canvas badges). Errors prefer the live client-side Zod
755773
// issues when a client validator exists (so they track every keystroke);
@@ -758,12 +776,13 @@ function MetadataResourceEditPageImpl({
758776
const previewDiagnostics = React.useMemo<
759777
Array<{ path?: string; message: string; severity: 'error' | 'warning' }>
760778
>(() => {
761-
const diag = (layered as any)?._diagnostics as
762-
| { errors?: Array<{ path: string; message: string }>; warnings?: Array<{ path: string; message: string }> }
763-
| undefined;
764-
const errs = hasClientValidator(type, draftMode)
765-
? displayIssues.map((i) => ({ path: i.path, message: translateValidationMessage(i.message, locale) }))
766-
: (diag?.errors ?? []).map((i) => ({ path: i.path, message: translateValidationMessage(i.message, locale) }));
779+
// objectstack#26707 — the verdict on the body on screen: the pending
780+
// draft's (which carries what its publish would refuse) while one is held.
781+
const diag = serverDiagnostics;
782+
const errs = (hasClientValidator(type, draftMode)
783+
? withServerOnlyErrors(displayIssues, diag?.errors)
784+
: (diag?.errors ?? [])
785+
).map((i) => ({ path: i.path, message: translateValidationMessage(i.message, locale) }));
767786
const warns = (diag?.warnings ?? []).map((i) => ({
768787
path: i.path,
769788
message: translateValidationMessage(i.message, locale),
@@ -772,11 +791,7 @@ function MetadataResourceEditPageImpl({
772791
...errs.map((e) => ({ path: e.path || undefined, message: e.message, severity: 'error' as const })),
773792
...warns.map((w) => ({ path: w.path || undefined, message: w.message, severity: 'warning' as const })),
774793
];
775-
}, [layered, displayIssues, type, locale, draftMode]);
776-
// Per-item draft pending publish (mode=draft saves land here).
777-
// When non-null, the editor is "viewing the draft" and we surface
778-
// Publish / Discard-draft actions.
779-
const [hasDraft, setHasDraft] = React.useState(false);
794+
}, [serverDiagnostics, displayIssues, type, locale, draftMode]);
780795
const [publishing, setPublishing] = React.useState(false);
781796
// Bumped by destructive operations (rollback / discard-draft) to
782797
// force the load effect to refetch layered + draft state.
@@ -1166,10 +1181,14 @@ function MetadataResourceEditPageImpl({
11661181
if (cancelled) return;
11671182
const draftResp = draftRead.answer;
11681183
setLayered(lay);
1184+
// objectstack#26707 — a pending draft is judged by its own read, whose
1185+
// verdict carries what its publish would refuse.
1186+
const loadDraftDiagnostics = extractDraftBody(draftResp) ? draftEnvelopeDiagnostics(draftResp) : undefined;
1187+
setDraftDiagnostics(loadDraftDiagnostics);
11691188
// Surface server-computed load-time validation errors as inline
11701189
// SchemaForm issues — operators see what's wrong with the
11711190
// saved metadata immediately, not just on the next Save round-trip.
1172-
const loadDiag = (lay as any)?._diagnostics as
1191+
const loadDiag = loadDraftDiagnostics ?? (lay as any)?._diagnostics as
11731192
| { valid: boolean; errors?: Array<{ path: string; message: string }> }
11741193
| undefined;
11751194
if (loadDiag && loadDiag.valid === false && Array.isArray(loadDiag.errors)) {
@@ -1781,6 +1800,7 @@ function MetadataResourceEditPageImpl({
17811800
if (!layerless) setLayered(lay);
17821801
const draftReal = extractDraftBody(draftResp);
17831802
setHasDraft(!!draftReal);
1803+
setDraftDiagnostics(draftReal ? draftEnvelopeDiagnostics(draftResp) : undefined);
17841804
// The served draft is the whole document the save just stored (see the
17851805
// load effect, objectui#10765): take it as-is. ⛔ Not spread over
17861806
// `effective` — that is the PUBLISHED layer, and a spread would bring a
@@ -2015,6 +2035,7 @@ function MetadataResourceEditPageImpl({
20152035
setLayered(lay);
20162036
const draftReal = extractDraftBody(draftResp);
20172037
setHasDraft(!!draftReal);
2038+
setDraftDiagnostics(draftReal ? draftEnvelopeDiagnostics(draftResp) : undefined);
20182039
// After a publish the promoted body IS `effective` and the draft row is
20192040
// normally gone; a draft that does remain is a whole document and is
20202041
// taken as-is (objectui#10765). ⛔ Not spread over `effective`: the
@@ -2077,6 +2098,7 @@ function MetadataResourceEditPageImpl({
20772098
setDraft(fresh);
20782099
draftSnapshotRef.current = fresh;
20792100
setHasDraft(false);
2101+
setDraftDiagnostics(undefined);
20802102
// objectui#12303 — the discard is said, naming what it discarded, through
20812103
// the console's shared toast (`sonner`, the one Studio's publish uses).
20822104
// Only here, after the DELETE and the re-read landed: a refused discard
@@ -2847,27 +2869,20 @@ function MetadataResourceEditPageImpl({
28472869
// a structural problem without saving first. The same
28482870
// errors are also threaded into SchemaForm as `issues`
28492871
// and rendered inline next to each broken field.
2850-
const diag = (layered as any)?._diagnostics as
2851-
| {
2852-
valid: boolean;
2853-
errors?: Array<{ path: string; message: string }>;
2854-
warnings?: Array<{ path: string; message: string }>;
2855-
}
2856-
| undefined;
2872+
// objectstack#26707 — the pending draft's verdict while one is held.
2873+
const diag = serverDiagnostics;
28572874
// When client-side Zod validation is available for this
28582875
// type, drive the error portion of the banner from the
28592876
// live `issues` state instead of the stale load-time
28602877
// diagnostics, so it stays in sync with every keystroke.
28612878
// Warnings remain server-sourced (Zod doesn't model them).
2862-
const liveErrors = hasClientValidator(type, draftMode)
2863-
? issues.map((i) => ({
2864-
path: i.path,
2865-
message: translateValidationMessage(i.message, locale),
2866-
}))
2867-
: (diag?.errors ?? []).map((i) => ({
2868-
...i,
2869-
message: translateValidationMessage(i.message, locale),
2870-
}));
2879+
const liveErrors = (hasClientValidator(type, draftMode)
2880+
? withServerOnlyErrors(issues, diag?.errors)
2881+
: (diag?.errors ?? [])
2882+
).map((i) => ({
2883+
path: i.path,
2884+
message: translateValidationMessage(i.message, locale),
2885+
}));
28712886
const liveValid = hasClientValidator(type, draftMode)
28722887
? liveErrors.length === 0
28732888
: diag?.valid !== false;
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { describe, it, expect } from 'vitest';
4+
import { draftEnvelopeDiagnostics, editedItemDiagnostics, withServerOnlyErrors } from './draftVerdict';
5+
6+
const refused = {
7+
valid: false,
8+
errors: [{ path: 'edges.1.condition', message: 'invalid CEL predicate', code: 'expression-invalid' }],
9+
};
10+
11+
describe('draftVerdict (objectstack#26707)', () => {
12+
it('reads `_diagnostics` off a served draft envelope, before the strip', () => {
13+
expect(draftEnvelopeDiagnostics({ type: 'flow', name: 'f', item: { name: 'f', _draft: true, _diagnostics: refused } })).toBe(refused);
14+
expect(draftEnvelopeDiagnostics({ type: 'flow', name: 'f', item: { name: 'f' } })).toBeUndefined();
15+
expect(draftEnvelopeDiagnostics(null)).toBeUndefined();
16+
});
17+
18+
it('a pending draft is judged by its own verdict; without one the layered verdict stands', () => {
19+
const layered = { _diagnostics: { valid: true } };
20+
expect(editedItemDiagnostics({ hasDraft: true, draftDiagnostics: refused, layered })).toBe(refused);
21+
expect(editedItemDiagnostics({ hasDraft: false, draftDiagnostics: refused, layered })).toEqual({ valid: true });
22+
expect(editedItemDiagnostics({ hasDraft: true, draftDiagnostics: undefined, layered })).toEqual({ valid: true });
23+
});
24+
25+
it('adds the server errors the client parse did not raise, once', () => {
26+
const client = [{ path: 'label', message: 'Required' }];
27+
const server = [{ path: 'label', message: 'Required' }, ...refused.errors];
28+
expect(withServerOnlyErrors(client, server)).toEqual([client[0], refused.errors[0]]);
29+
expect(withServerOnlyErrors(client, undefined)).toEqual(client);
30+
});
31+
});

0 commit comments

Comments
 (0)