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
10 changes: 10 additions & 0 deletions .changeset/bulk-action-capability-gate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@object-ui/types': patch
'@object-ui/plugin-grid': patch
---

The bulk selection bar now applies the ADR-0066 D4 `requiredPermissions` capability gate, and short-circuits a boolean `visible` instead of treating it as a broken expression (#3492).

Two independent gaps put the selection bar out of step with the other three action surfaces. **First**, the capability gate: `action-bar.tsx` (list toolbar), `containers.tsx` (record header) and `RowActionMenu.tsx` (row kebab) all call `useCapabilityGate`, but `resolveBulkActions` dropped `requiredPermissions` when promoting an object action into a `BulkActionDef` and `BulkActionBar` never read it — so the same action was hidden from an unentitled user in the row kebab and offered to them in the selection bar the moment they ticked a checkbox. For a `type: 'api'` action pointed at a custom endpoint nothing behind it was guaranteed to say no. `BulkActionDef` now carries `requiredPermissions?: string[]`, the fold forwards it, and the bar filters on it with the engine's rule verbatim (empty declaration passes, several are AND-ed, unknown capabilities fail OPEN).

**Second**, boolean `visible`: `partitionBulkRows` handed it straight to the CEL engine, producing `{ dialect: 'cel', source: undefined }` — a fault, which on this fail-closed path disqualified every selected record. So `visible: true` hid the button from everyone, the exact inverse of what it says; and `visible: false` rendered the button anyway, because the render guard tested `def.visible &&` for truthiness and read a declared `false` as "ungated". Booleans now short-circuit the way `useCondition` / `useRowPredicate` always have, and "is this def gated" is one shared predicate (`hasVisibilityGate`) rather than a truthiness test. `BulkActionDefSchema.visible` is `ExpressionInputSchema`, so `objectstack build` never emitted this shape — hand-written view JSON and in-process callers did.
14 changes: 14 additions & 0 deletions .changeset/lookup-fields-in-predicates.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@object-ui/core': patch
'@object-ui/react': patch
'@object-ui/components': patch
'@object-ui/plugin-grid': patch
'@object-ui/plugin-list': patch
'@object-ui/plugin-kanban': patch
---

Relation fields (`lookup` / `master_detail` / `user` / `tree`) are now usable in action and conditional-formatting predicates: they bind as the stored foreign key on every surface, and the fields a predicate reads are included in the query projection (#3501).

Before this, one predicate over one relation field had four different fates, decided by things its author does not control. `$expand` **replaces** the id in place with the whole related record, and a view expands exactly the relations it shows as COLUMNS — so `record.owner == "U1"` was **true** where the column was absent, **false** where it was displayed, and a **fault** where the field was neither displayed nor projected (a list's `$select` was built from its columns alone, and CEL treats an absent key as a fault, not as null). A fault is fail-CLOSED on the row kebab and the selection bar and fail-OPEN on the lenient paths, so the same authoring mistake hid the button from everyone on one surface and showed it to everyone on the next, with nothing on screen to point at either. The server, meanwhile, only ever sees the id — so client and server could not agree, which is the one thing ADR-0036 / ADR-0058 exist to guarantee.

Two changes close it. `toPredicateRecord` (new, `@object-ui/core`) collapses expanded relation values back to their ids when a record is bound for evaluation — driven by the object's own field types, not by sniffing for an `id` key, so a `json` field that happens to carry one is untouched. It is threaded through `evalRowPredicate` / `resolveConditionalFormatting` (via a new `fields` option), `useRowPredicate`, `partitionBulkRows`, and both `page:header` evaluators, with the object schema supplied by `ObjectGrid` / `ListView` / `ObjectKanban` / the record context. Kanban card formatting is threaded the same way, so a rule cannot match on the grid view of a list and silently never match on its board. Display is unaffected — a detail-page title still renders the related record's name, and the schema-only `kanban-ui` entry point (which has no object schema to offer) keeps using the payload verbatim. `collectPredicateFieldRefs` / `listViewPredicates` (new) harvest the `record.x` / `data.x` references out of a view's conditional formatting, row-action defs, bulk-action defs, promoted object actions and `userActions` overrides, and add them to `$select` — intersected with the object's declared fields plus the platform columns every object carries (`isProjectableField`), because an unknown key is not ignored by every backend. No `$expand` is added: a predicate wants the foreign key, which is what an unexpanded relation already is.
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
/**
* 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.
*/

/**
* `page:header` — relation fields in a header action's `visible` / `disabled`
* (objectui#3501).
*
* The record-header surface is where the reported symptom was seen. The detail
* fetch expands every relation it can, so `ctx.data.owner` arrives as the whole
* related record rather than the id it stands for. Evaluated as delivered, that
* makes the two natural spellings fail in opposite directions on the LEGACY JS
* evaluator this surface uses:
*
* `os.user.id == record.owner` → `'U1' == {…}` → a clean, silent FALSE,
* even on the caller's own record
* `os.user.id == record.owner.id` → throws the moment `owner` is empty
*
* Binding the record the way the server does — relation ⇒ foreign key — is what
* makes the first spelling (the one that also works in a bare list and in a
* server-side rule) the right one everywhere.
*/

import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { ComponentRegistry } from '@object-ui/core';
import { ActionProvider, RecordContextProvider, PredicateScopeProvider } from '@object-ui/react';

function PageHeader({ schema }: { schema: any }) {
const Component = ComponentRegistry.get('page:header');
if (!Component) throw new Error('page:header not registered');
// eslint-disable-next-line react-hooks/static-components -- registry component is stable
return <Component schema={schema} />;
}

const OBJECT_SCHEMA = {
name: 'showcase_task',
label: 'Task',
fields: {
title: { type: 'text' },
owner: { type: 'user' },
project: { type: 'master_detail', reference: 'showcase_project' },
},
};

const schema = (visible: string) => ({
type: 'page:header',
title: 'Task',
actions: [{ name: 'reassign', locations: ['record_header'], label: 'Reassign', type: 'api', visible }],
});

function renderHeader(record: any, visible: string) {
return render(
<PredicateScopeProvider scope={{ user: { id: 'U1' }, os: { user: { id: 'U1' } } }}>
<ActionProvider>
<RecordContextProvider
objectName="showcase_task"
recordId={record?.id ?? null}
data={record}
objectSchema={OBJECT_SCHEMA}
>
<PageHeader schema={schema(visible)} />
</RecordContextProvider>
</ActionProvider>
</PredicateScopeProvider>,
);
}

const shown = () => !!screen.queryByRole('button', { name: /Reassign/i });

const EXPANDED = {
id: 'r1',
title: 'SEO migration plan',
owner: { id: 'U1', name: 'Ada Lovelace' },
project: { id: 'P1', name: 'Website Relaunch' },
};

describe('page:header — relation fields in `visible` (#3501)', () => {
it('shows the action on the caller’s own record, with `owner` expanded', () => {
renderHeader(EXPANDED, 'os.user.id == record.owner');
expect(shown()).toBe(true);
});

it('reaches the same verdict when the record arrived UNexpanded', () => {
renderHeader({ ...EXPANDED, owner: 'U1' }, 'os.user.id == record.owner');
expect(shown()).toBe(true);
});

it('still hides it on someone else’s record', () => {
renderHeader({ ...EXPANDED, owner: { id: 'U2', name: 'Grace' } }, 'os.user.id == record.owner');
expect(shown()).toBe(false);
});

it('hides it cleanly when the relation is empty — no throw to fall back on', () => {
renderHeader({ ...EXPANDED, owner: null }, 'os.user.id == record.owner');
expect(shown()).toBe(false);
});

it('compares a master_detail relation against a literal id', () => {
renderHeader(EXPANDED, 'record.project == "P1"');
expect(shown()).toBe(true);
});

it('leaves the record’s own display data expanded — the title still reads the NAME', () => {
// The normalization is scoped to predicate evaluation; `interpolate` keeps
// reading `ctx.data`, so a `{project.name}` title is unaffected.
render(
<PredicateScopeProvider scope={{ user: { id: 'U1' }, os: { user: { id: 'U1' } } }}>
<ActionProvider>
<RecordContextProvider
objectName="showcase_task"
recordId="r1"
data={EXPANDED}
objectSchema={OBJECT_SCHEMA}
>
<PageHeader schema={{ type: 'page:header', title: '{project.name}' }} />
</RecordContextProvider>
</ActionProvider>
</PredicateScopeProvider>,
);

expect(screen.getByText('Website Relaunch')).toBeTruthy();
});
});
28 changes: 21 additions & 7 deletions packages/components/src/renderers/layout/containers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
*/

import React from 'react';
import { ComponentRegistry, ExpressionEvaluator, getRecordDisplayName } from '@object-ui/core';
import { ComponentRegistry, ExpressionEvaluator, getRecordDisplayName, toPredicateRecord } from '@object-ui/core';
import { actionRendersAt } from '@object-ui/types';
import { useRecordContext, useAction, useCapabilityGate, usePredicateScope, usePageVariables, useInlineEdit } from '@object-ui/react';
import { renderChildren, cn } from '../../lib/utils';
Expand Down Expand Up @@ -968,19 +968,30 @@ const PageHeaderRenderer: React.FC<any> = ({ schema, className, ...props }) => {
// predicates resolve — alongside the record fields spread for bare
// `status`/`is_default` CEL.
const scopeUser = (predicateScope as any)?.user;
// Relation fields bind as the FOREIGN KEY the server stores, not as the
// record `$expand` substituted for them: the detail fetch expands every
// relation it can, so `record.owner == os.user.id` — the spelling that
// works server-side and in a bare list — could only ever be false here,
// while `record.owner.id` throws on any record whose lookup is empty. See
// `toPredicateRecord`. Display (`interpolate` above) still reads the raw
// `ctx.data`, which is what renders the related record's NAME.
// `toPredicateRecord` passes a null/undefined record straight through, so
// "no record loaded yet" stays distinguishable from "an empty record" —
// spreading either into `evalCtx` is a no-op.
const predicateRecord = toPredicateRecord(recordData, headerObjectSchema?.fields);
const evalCtx = {
...(recordData && typeof recordData === 'object' ? recordData : {}),
record: recordData,
data: recordData,
...predicateRecord,
record: predicateRecord,
data: predicateRecord,
user: scopeUser,
// Server-CEL-parity identity alias (#2358 trap 1): the spec's canonical
// CEL identity scope is `os.user.*`, so a predicate authored against the
// server dialect resolves here too instead of throwing (fail-closed).
os: (predicateScope as any)?.os ?? { user: scopeUser },
ctx: {
user: scopeUser,
record: recordData,
data: recordData,
record: predicateRecord,
data: predicateRecord,
app: (predicateScope as any)?.app,
features: (predicateScope as any)?.features,
},
Expand Down Expand Up @@ -1197,7 +1208,10 @@ const PageHeaderRenderer: React.FC<any> = ({ schema, className, ...props }) => {
// evaluation above — a boolean OR a CEL expression (`'record.status == …'`
// or the `{ dialect, source }` envelope). Without this a CEL `disabled`
// silently did nothing (only boolean was honoured).
const dRecord: any = ctx?.data;
// Same relation normalization the `visible` evaluation above applies, so a
// `disabled` predicate over a lookup reaches the same verdict (and the same
// one the server would) instead of throwing on `record.owner.id`.
const dRecord: any = toPredicateRecord(ctx?.data, headerObjectSchema?.fields);
const dScopeUser = (predicateScope as any)?.user;
const dEvaluator = new ExpressionEvaluator({
...(dRecord && typeof dRecord === 'object' ? dRecord : {}),
Expand Down
69 changes: 69 additions & 0 deletions packages/core/src/evaluator/__tests__/listConditional.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,3 +225,72 @@ describe('resolveConditionalFormatting', () => {
).toEqual({});
});
});

/**
* The relation binding (objectui#3501): with the payload as delivered, whether
* `record.<lookup>` is an id or a whole record is decided by whether THIS
* surface happened to expand that column — a display decision no predicate
* author participates in. Supplying the object's fields collapses the expanded
* form back to the id, which is what the server's CEL engine sees.
*/
describe('evalRowPredicate — relation fields', () => {
const FIELDS = {
title: { type: 'text' },
owner: { type: 'user' },
account: { type: 'lookup', reference: 'accounts' },
config: { type: 'json' },
};
const SCOPE = { os: { user: { id: 'U1' } } };

it('an EXPANDED relation compares equal to the id it stands for', () => {
const expanded = { owner: { id: 'U1', name: 'Ada' } };

// Without the schema this is the reported bug: false for the very user the
// record belongs to, with no error to notice.
expect(evalRowPredicate('record.owner == os.user.id', expanded, { scope: SCOPE })).toBe(false);
expect(
evalRowPredicate('record.owner == os.user.id', expanded, { scope: SCOPE, fields: FIELDS }),
).toBe(true);
});

it('an UNEXPANDED relation reaches the same verdict — one predicate, one answer', () => {
const plain = { owner: 'U1' };

expect(evalRowPredicate('record.owner == os.user.id', plain, { scope: SCOPE, fields: FIELDS })).toBe(true);
expect(evalRowPredicate('record.owner == os.user.id', plain, { scope: SCOPE })).toBe(true);
});

it('an EMPTY relation is a clean false, not a fault', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});

expect(
evalRowPredicate('record.owner == os.user.id', { owner: null }, {
scope: SCOPE, fields: FIELDS, warnOnError: true,
}),
).toBe(false);
expect(warn).not.toHaveBeenCalled();
warn.mockRestore();
});

it('binds the collapsed value under the bare and `data.` spellings too', () => {
const expanded = { account: { id: 'A1', name: 'Acme' } };

expect(evalRowPredicate('account == "A1"', expanded, { fields: FIELDS })).toBe(true);
expect(evalRowPredicate('data.account == "A1"', expanded, { fields: FIELDS })).toBe(true);
});

it('leaves a non-relational object field addressable as an object', () => {
expect(
evalRowPredicate('record.config.retries == 3', { config: { retries: 3 } }, { fields: FIELDS }),
).toBe(true);
});

it('applies to conditional formatting through the same option', () => {
const rules = [{ condition: 'record.owner == os.user.id', backgroundColor: 'mine' }];

expect(resolveConditionalFormatting({ owner: { id: 'U1' } }, rules, SCOPE)).toEqual({});
expect(resolveConditionalFormatting({ owner: { id: 'U1' } }, rules, SCOPE, FIELDS)).toEqual({
backgroundColor: 'mine',
});
});
});
19 changes: 18 additions & 1 deletion packages/core/src/evaluator/listConditional.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
*/
import { evalFieldPredicate, type FieldRulePredicate } from './fieldRules.js';
import { ExpressionEvaluator } from './ExpressionEvaluator.js';
import { toPredicateRecord, type FieldContainerLike } from '../utils/predicate-record.js';

/**
* Syntax that only the legacy JS-dialect evaluator understands and that is NOT
Expand Down Expand Up @@ -127,6 +128,14 @@ export interface RowPredicateOptions {
warnOnError?: boolean;
/** Label used in warning messages (e.g. an action name or rule index). */
label?: string;
/**
* The object's field definitions (`objectSchema.fields`). Supplying them lets
* a relation field be bound as the FOREIGN KEY the server stores, rather than
* as whatever `$expand` happened to substitute for it on this surface — see
* {@link toPredicateRecord}. Omitting them keeps the payload verbatim, so a
* caller with no schema at hand never guesses which fields are relations.
*/
fields?: FieldContainerLike;
}

/**
Expand All @@ -147,7 +156,10 @@ export function evalRowPredicate(
const source = typeof pred === 'string' ? pred : undefined;
if (source !== undefined && !source.trim()) return fallback;

const rowObj = row && typeof row === 'object' ? row : {};
// Relations collapse to the foreign key the server stores, so `record.owner`
// means one thing whether or not this surface expanded the column
// (objectui#3501). Returned by reference when there is nothing to collapse.
const rowObj = toPredicateRecord(row && typeof row === 'object' ? row : {}, opts.fields);
// Bare fields + `data.*` + the host scope, all top-level; `record` is bound
// by the engine call itself (evalCel / the legacy evaluator below).
const scope = { ...(opts.scope ?? {}), ...rowObj, data: rowObj };
Expand Down Expand Up @@ -272,11 +284,15 @@ function ruleToStyle(rule: ConditionalFormattingRuleLike): Record<string, string
*
* @param scope Extra top-level scope (host predicate scope) bound alongside
* the row, so `features.*` predicates keep resolving.
* @param fields The object's field definitions, so a rule comparing a relation
* field sees the stored foreign key rather than the expanded
* record (see {@link RowPredicateOptions.fields}).
*/
export function resolveConditionalFormatting(
record: Record<string, unknown> | null | undefined,
rules?: readonly ConditionalFormattingRuleLike[] | null,
scope?: Record<string, unknown>,
fields?: FieldContainerLike,
): Record<string, string> {
if (!rules || rules.length === 0) return {};
const row = record && typeof record === 'object' ? record : {};
Expand All @@ -288,6 +304,7 @@ export function resolveConditionalFormatting(
const matched = evalRowPredicate(pred, row, {
fallback: false,
scope,
fields,
label: `conditionalFormatting[${i}]`,
});
if (matched) return ruleToStyle(rule);
Expand Down
8 changes: 8 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,12 @@ export * from './utils/dataset-pivot.js';
export * from './utils/record-title.js';
export * from './utils/export-filename.js';
export * from './utils/reference-keys.js';
// Binds a fetched record into an expression scope the way the SERVER binds it
// (a relation is its foreign key, never the expanded record) — see
// `toPredicateRecord` for why an unnormalized one gives the same predicate
// different verdicts on different surfaces.
export * from './utils/predicate-record.js';
// The other half of a view's field appetite: the fields its PREDICATES read,
// which the column-derived `$select` never asked the server for.
export * from './utils/predicate-fields.js';
export * from './utils/normalize-list-view.js';
Loading
Loading