Skip to content
This repository was archived by the owner on Nov 4, 2026. It is now read-only.
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
30 changes: 30 additions & 0 deletions .changeset/view-edit-wire-gate-5316.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
---
'@object-ui/app-shell': patch
---

metadata-admin no longer false-rejects a stored `view` that has been pinned or
reordered. The editor's live client-side validation judged BOTH the create and
the edit draft with the AUTHORING schema (`ViewItemSchema` via
`viewSchemaForDraft`). That is right for create and wrong for edit: the editor
opens a body that came back out of `sys_metadata`, and the platform itself
writes keys into stored view bodies — `isPinned` from the view switcher's pin
action, `sortOrder` from the reorder write, and a per-row `id` that the console
filter/sort builders stamp on `config.filter[]` for React. `updateView` GETs the
stored item and PUTs `{ ...current, ...partial }`, and `saveMetaItem` persists
the accepted body verbatim, so those keys are in storage by design.

Before the authoring schemas were tightened these keys were silently stripped
and the draft passed. Once the gate became strict, opening a pinned view in the
editor reported unrecognized keys — while the SERVER accepted the very same body,
because it validates against `ViewMetadataSchema`. The client was strictly
stricter than the server; the direction was inverted.

`validateMetadataDraft` now takes an optional `{ mode: 'create' | 'edit' }`.
Create keeps the authoring gate unchanged. Edit is judged by
`ViewMetadataSchema` — the schema the `view` metadata type registers, i.e. the
same one the server runs — so the client and the server accept the same set by
construction. `mode` defaults to `'create'`, the strict gate, so a caller that
omits it can only ever over-report, never silently widen the door.

The edit gate keeps its teeth: a wrong `config.type` and a container carrying an
unknown key are both still rejected.
16 changes: 14 additions & 2 deletions packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -419,7 +419,19 @@ function MetadataResourceEditPageImpl({
const handle = window.setTimeout(() => {
// Pass the live server schema so the client never flags fields the
// running server now treats as optional (cross-repo spec-skew root-cure).
void validateMetadataDraft(type, draft, entry?.schema as { required?: unknown } | undefined).then((res) => {
//
// `mode` picks the gate (objectstack#5316): a create draft is AUTHORED
// here and judged by the strict authoring schema, while an edit draft is
// a body that came back out of storage and is judged by the same wire
// schema the server runs. Judging a stored body by the authoring schema
// made this editor reject bodies the server accepts — e.g. a view that
// had been pinned or reordered carries `isPinned` / `sortOrder`.
void validateMetadataDraft(
type,
draft,
entry?.schema as { required?: unknown } | undefined,
{ mode: createMode ? 'create' : 'edit' },
).then((res) => {
if (cancelled) return;
setIssues(res.issues);
});
Expand All @@ -428,7 +440,7 @@ function MetadataResourceEditPageImpl({
cancelled = true;
window.clearTimeout(handle);
};
}, [type, draft, entry?.schema]);
}, [type, draft, entry?.schema, createMode]);
// Issues to DISPLAY (banner + inline). Suppressed on a pristine create form
// so a blank new item doesn't open covered in required-field errors.
const displayIssues = React.useMemo(
Expand Down
83 changes: 73 additions & 10 deletions packages/app-shell/src/views/metadata-admin/clientValidation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,24 @@ type ZodLikeSchema = {
};
};

type SchemaLoader = () => Promise<ZodLikeSchema | undefined>;
/**
* Which door a draft came through — the two are validated by different gates
* (objectstack#5316).
*
* - `create` — the draft is being AUTHORED in this admin. It is judged by the
* authoring schema, which is the strict one: a key the authoring contract
* does not declare is a mistake the author should see now.
* - `edit` — the draft is a body that came back OUT of storage. It is judged by
* the same WIRE schema the server's `saveMetaItem` runs, because the platform
* itself writes keys into stored bodies that the authoring contract has no
* reason to declare.
*
* Only `view` currently distinguishes the two; every other loader ignores the
* mode and returns the one schema it has always returned.
*/
export type DraftMode = 'create' | 'edit';

type SchemaLoader = (mode: DraftMode) => Promise<ZodLikeSchema | undefined>;

/**
* The `view` metadata type has TWO spec-declared shapes, and the backend serves
Expand Down Expand Up @@ -98,8 +115,43 @@ const LOADERS: Record<string, SchemaLoader> = {
analytics_cube: async () => (await import('@objectstack/spec/data')).CubeSchema as unknown as ZodLikeSchema,

// ui
view: async () => {
const { ViewItemSchema, ViewSchema } = await import('@objectstack/spec/ui');
//
// `view` is the one type whose two doors need two gates (objectstack#5316).
//
// CREATE — the authoring gate, unchanged: `viewSchemaForDraft` dispatches on
// the record's own `viewKind` discriminant to `ViewItemSchema` (what
// `createBuildBody` emits) or `ViewSchema` (the container). #5074 made these
// strict on purpose and this admin's create path passes them cleanly.
//
// EDIT — the WIRE gate. The editor opens a body that came back out of
// `sys_metadata`, and a stored view body carries keys the PLATFORM wrote:
// `isPinned` (the view switcher's pin action, `ObjectView.tsx:882`),
// `sortOrder` (the reorder write, `ObjectView.tsx:931`), and — nested —
// the console filter/sort builders' per-row `id`. `updateView` GETs the
// stored item and PUTs `{ ...current, ...partial }`; `saveMetaItem` persists
// the accepted body verbatim (ADR-0005 §Validation). So the server ACCEPTS
// this body — it validates against `ViewMetadataSchema` — while the authoring
// gate rejects it. Judging a stored body by the authoring schema made the
// client strictly stricter than the server; that is the inversion #5316 fixes.
//
// Why `ViewMetadataSchema` and not the narrower `ViewItemWireSchema`, which
// also declares `isPinned`/`sortOrder`: two measured reasons.
// 1. It is the schema the `view` metadata type registers, i.e. literally
// the one `saveMetaItem` runs — so client and server accept the same
// set by construction rather than by a maintained resemblance.
// 2. `ViewItemWireSchema` covers only the ViewItem record. It rejects the
// container and the flattened overlay, and — measurably — still rejects
// `config.filter[].id` with `unrecognized_keys`, because that decoration
// is stripped by `ViewMetadataSchema`'s `z.preprocess`, which runs ahead
// of every union member and reaches nested blocks a member-level
// `.strip()` cannot.
//
// NOT a "try both, pass if either passes" fallback: each mode has exactly ONE
// gate and a rejection is final. The last pins in
// `clientValidation.viewShapes.test.ts` guard that.
view: async (mode) => {
const { ViewItemSchema, ViewSchema, ViewMetadataSchema } = await import('@objectstack/spec/ui');
if (mode === 'edit') return ViewMetadataSchema as unknown as ZodLikeSchema;
return viewSchemaForDraft(
ViewItemSchema as unknown as ZodLikeSchema,
ViewSchema as unknown as ZodLikeSchema,
Expand Down Expand Up @@ -247,22 +299,25 @@ async function validateObjectFieldRules(draft: unknown): Promise<SchemaFormIssue
return issues;
}

// Keyed by mode AND type — `view` resolves to a different schema per mode, so
// caching by type alone would hand the create gate whichever mode asked first.
const SCHEMA_CACHE = new Map<string, ZodLikeSchema | null>();

async function getSchemaForType(type: string): Promise<ZodLikeSchema | null> {
if (SCHEMA_CACHE.has(type)) return SCHEMA_CACHE.get(type) ?? null;
async function getSchemaForType(type: string, mode: DraftMode): Promise<ZodLikeSchema | null> {
const key = `${mode}:${type}`;
if (SCHEMA_CACHE.has(key)) return SCHEMA_CACHE.get(key) ?? null;
const loader = LOADERS[type];
if (!loader) {
SCHEMA_CACHE.set(type, null);
SCHEMA_CACHE.set(key, null);
return null;
}
try {
const schema = await loader();
const schema = await loader(mode);
const value = (schema && typeof schema.safeParse === 'function') ? schema : null;
SCHEMA_CACHE.set(type, value);
SCHEMA_CACHE.set(key, value);
return value;
} catch {
SCHEMA_CACHE.set(type, null);
SCHEMA_CACHE.set(key, null);
return null;
}
}
Expand Down Expand Up @@ -301,8 +356,16 @@ export async function validateMetadataDraft(
* per-change shim (cf. `FORWARD_COMPAT_FLOW_NODE_TYPES`).
*/
serverSchema?: { required?: unknown },
/**
* Which door the draft came through (objectstack#5316). Defaults to
* `'create'` — the AUTHORING gate, which is the strict one — so a call site
* that omits it can only ever over-report, never silently widen the door.
* Callers that open a STORED body must say `{ mode: 'edit' }`.
*/
options?: { mode?: DraftMode },
): Promise<ValidateResult> {
const schema = await getSchemaForType(type);
const mode: DraftMode = options?.mode ?? 'create';
const schema = await getSchemaForType(type, mode);
if (!schema) return { ok: true, issues: [] };

// CEL lint for object field conditional rules — additive to the Zod shape
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import { describe, it, expect } from 'vitest';
import { validateMetadataDraft } from './clientValidation';

/** What `anchors.ts`'s `createBuildBody` emits for a default list view. */
const VIEW_ITEM = {
const VIEW_ITEM: Record<string, unknown> = {
name: 'crm_lead.all_leads',
object: 'crm_lead',
viewKind: 'list',
Expand Down Expand Up @@ -79,3 +79,129 @@ describe('validateMetadataDraft("view") — both spec shapes (objectui#3312)', (
expect(res.issues.length).toBeGreaterThan(0);
});
});

/**
* Editing a STORED view body — the wire gate (objectstack#5316).
*
* The four pins above all describe the AUTHORING surface: what
* `createBuildBody` may emit. Editing is a different door. The editor opens a
* body that came back OUT of `sys_metadata`, and a stored body carries keys the
* platform itself wrote there:
*
* - `isPinned` — `ObjectView.tsx:882`, the view-switcher's pin action, via
* `dataSource.updateView(object, vid, { isPinned: true })`.
* - `sortOrder` — `ObjectView.tsx:931`, the reorder write.
* - nested `id` — the console filter/sort builder's stable React key
* (`VIEW_CONSOLE_ROW_DECORATIONS`), on `config.filter[]` rows.
*
* `updateView` GETs the stored item and PUTs `{ ...current, ...partial }`, and
* `saveMetaItem` persists the accepted body verbatim (ADR-0005 §Validation) — so
* these keys are in the stored body by design, not by accident.
*
* Before #5074 `ViewItemSchema` was strip and they were silently dropped. #5074
* tightened it into a real authoring gate, which is correct for CREATE and wrong
* for EDIT: the SERVER validates the very same body against `ViewMetadataSchema`
* and accepts it. The client was strictly stricter than the server — direction
* inverted. These pins fix the direction: create keeps the authoring gate, edit
* is judged by the same wire schema the server runs.
*/
describe('validateMetadataDraft("view") — stored bodies on the EDIT path (objectstack#5316)', () => {
/** A stored ViewItem that has been pinned via the view switcher. */
const PINNED = { ...VIEW_ITEM, isPinned: true };
/** A stored ViewItem that has been dragged into a new position. */
const REORDERED = { ...VIEW_ITEM, sortOrder: 3 };
/** Both round-trip keys, plus the console builder's nested row decoration. */
const PINNED_WITH_BUILDER_ROWS = {
...VIEW_ITEM,
isPinned: true,
sortOrder: 3,
config: {
type: 'grid',
columns: [],
data: { provider: 'object', object: 'crm_lead' },
filter: [{ field: 'status', operator: 'equals', value: 'open', id: 'row-1' }],
},
};

it('accepts a stored view that was PINNED', async () => {
const res = await validateMetadataDraft('view', PINNED, undefined, { mode: 'edit' });
expect(res.issues, JSON.stringify(res.issues)).toEqual([]);
expect(res.ok).toBe(true);
});

it('accepts a stored view that was REORDERED', async () => {
const res = await validateMetadataDraft('view', REORDERED, undefined, { mode: 'edit' });
expect(res.issues, JSON.stringify(res.issues)).toEqual([]);
expect(res.ok).toBe(true);
});

/**
* The nested case is why the gate must be `ViewMetadataSchema` and not the
* bare `ViewItemWireSchema`: the wire member declares `isPinned`/`sortOrder`
* at the TOP level, but only `ViewMetadataSchema`'s
* `z.preprocess(stripViewConsoleDecorations, …)` reaches `config.filter[].id`.
* A member-level `.strip()` cannot — the spec says so at the union's
* definition, and it is measurable: `ViewItemWireSchema` rejects this body
* with `config.filter.0: unrecognized_keys`.
*/
it('accepts a stored view carrying nested console builder row ids', async () => {
const res = await validateMetadataDraft('view', PINNED_WITH_BUILDER_ROWS, undefined, {
mode: 'edit',
});
expect(res.issues, JSON.stringify(res.issues)).toEqual([]);
expect(res.ok).toBe(true);
});

it('accepts the aggregated container on the edit path too', async () => {
const res = await validateMetadataDraft('view', CONTAINER, undefined, { mode: 'edit' });
expect(res.issues, JSON.stringify(res.issues)).toEqual([]);
expect(res.ok).toBe(true);
});

// ── The edit gate still has teeth ────────────────────────────────────────
// Widening the door for keys the platform WRITES must not widen it for a
// body that is actually wrong.

it('still REJECTS a stored view whose config is wrong', async () => {
const res = await validateMetadataDraft(
'view',
{ ...PINNED, config: { type: 'not_a_real_layout', columns: [] } },
undefined,
{ mode: 'edit' },
);
expect(res.ok).toBe(false);
expect(res.issues.length).toBeGreaterThan(0);
});

it('still REJECTS a container carrying an unknown key on the edit path', async () => {
const res = await validateMetadataDraft(
'view',
{ ...CONTAINER, notAContainerKey: true },
undefined,
{ mode: 'edit' },
);
expect(res.ok).toBe(false);
expect(res.issues.length).toBeGreaterThan(0);
});

// ── The CREATE path is untouched ─────────────────────────────────────────

it('keeps REJECTING the same stored keys on the CREATE path', async () => {
// `createBuildBody` has no business emitting `isPinned`: on the authoring
// surface these are still unrecognized, exactly as #5074 made them.
for (const body of [PINNED, REORDERED]) {
const res = await validateMetadataDraft('view', body, undefined, { mode: 'create' });
expect(res.ok, JSON.stringify(res.issues)).toBe(false);
expect(res.issues.length).toBeGreaterThan(0);
}
});

it('defaults to the CREATE gate when no mode is given', async () => {
// Default-strict: a call site that forgets `mode` gets the authoring gate,
// so an omission can only ever over-report — never silently widen the door.
const withMode = await validateMetadataDraft('view', PINNED, undefined, { mode: 'create' });
const withoutMode = await validateMetadataDraft('view', PINNED);
expect(withoutMode.ok).toBe(false);
expect(withoutMode.issues).toEqual(withMode.issues);
});
});
Loading