Skip to content

Commit 71e02ff

Browse files
fix(studio): the CEL condition builder offers membership, not equals, on a list field (#36185)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XP3RHGWUG7UH3fNa4tBa9UC)_ Part of #36167 — the builder half. The card's Done-when also names `validateExpression` refusing a list compared with a scalar; that half narrows an accept set and is not built here: the seat picked option A on the card (7068927390), and area a4-C claimed it (7068951634) under its own `Part of #36167`. Clause-②: no Metadata-protocol: none ## 维护者速读 - 在 Studio 里给多值字段(多选、标签、多选人员或多选关联)写条件时,操作符从「等于 / 不等于」换成「包含 / 不包含 / 为空 / 不为空」;单值字段不变。 - 属于 Studio 条件编辑器:多值字段上的「等于」永远不成立、作者毫无提示,这次让编辑器只给出能真正命中的写法。 - 已保存的「多值字段 等于 某值」条件会改为在表达式框里原样打开,不会被改写;若有问题,作者看到的是表达式框而非行编辑器,可直接撤回本改动。 - 要你做的:决定是否另做「保存时拒绝多值字段与单值比较」的那一半(见卡片报告里的待决问题)。 ## What changes - `ConditionBuilder` (the Studio CEL condition builder behind hook, validation-rule, action visibility, page-block and flow entry conditions) now offers a **list subject** (a `multiselect` / `checkboxes` / `tags`, or a `select` / `lookup` / `user` declared `multiple: true`) exactly what the shared filter builder offers it: contains, does not contain, is empty, is not empty. `==` / `!=` / ordering are no longer offered there. Which operators a list takes is read from `jsonColumnFilterOperators` (through the new `listSubjectOperators`), not restated; a small table only translates those names onto the builder's own operator values. - Contains writes `S != null && V in S`, does not contain writes `S == null || !(V in S)`. That is the spelling the flow edge's rows shipped; it now lives in one module, `inspectors/cel-list-membership.ts` (`listMembershipCel` / `readListMembership` / `listSubjectOperators`), and `flow-edge-condition-rows.ts` writes through it too (its output is byte-for-byte unchanged; its existing pins hold). - A row moved onto a list subject leaves `equals` for `contains`; moved off a list, membership becomes `equals`. An operator offered on both sides (is empty / is not empty) stays, re-spelled for the new field. - A stored condition whose row uses an operator its subject is not offered (for example `record.labels == 'frontend'` on a list, or membership on a single-value field) opens in the raw expression editor exactly as stored: never rewritten, nothing emitted. - New studio locale key `engine.inspector.condition.op.notContains` (en, zh). ## Tests - New pin `ConditionBuilder.listSubject-36167.test.tsx` (27 tests): each of six list subjects offers the shared builder's list set and nothing else; three single-value controls keep equals / not equals and get no membership; the written CEL equals what the flow edge's `rowsToCel` writes for the same row and is evaluated by `celEngine` (member true, non-member false, `[]` and `null` null-safe both ways); stored membership round-trips; stored `==` / `!=` on a list and membership on a single-value field open raw and verbatim; an instrument control shows the replaced `==` answering a constant. - Fixture triage: three existing pins (`ConditionBuilder.typedEmptyOps-11894`, two cases; `ObjectValidationsPanel.typedEmptyOps-11894`, one case) seeded a list subject's row as `S == 'x'` only to reach its operator dropdown. That seed now opens in the raw editor, so it became the membership row; what each case pins (the empty check on a list, and that `multiple` reaches the builder) is unchanged and still needs the flag to reach the builder. ## Acceptance notes - Re-measured under `celEngine` (objectstack tree at this branch): `'a' in S` with `S = null` faults (no such overload for `string in` a null dyn), with `S = []` answers false; `S == 'a'` is false for `['a','b']` and for `null`; `S.contains('a')` faults on a list. Hence the null guard on both membership spellings. - A stored `S == null` / `S != null` on a list subject also opens raw now (the builder's own spelling for it is is empty / is not empty). Unchanged bytes, by the round-trip rule. - The schema-driven condition widget's catalog (`ResourceEditPage`'s object fetch) dropped `multiple` on this branch's base. #36182 (merged to `main` as 865df27) closes it: the fetch now goes through `objectCatalogOf`, which carries `multiple: true`, and the condition widget hands that catalog to `ConditionBuilder` unprojected, so after this PR lands a `select` / `lookup` / `user` declared `multiple: true` is a list subject at that mount too. `multiselect` / `checkboxes` / `tags` are lists by type alone. The hook, page-block, action, flow-entry and validation-panel mounts carry `multiple`. - `node scripts/pm/overlap-check.mjs` reports a textual overlap with draft PR #35923 on the studio en / zh catalogues (different keys). Not merged around. ## Verification Read first (risk order): 1. `ui/packages/app-shell/src/views/metadata-admin/inspectors/ConditionBuilder.tsx`: `initFrom` (the new offered-operator check that sends a stored row to the raw editor) and `withOfferedOp` on a subject change. 2. `ui/packages/app-shell/src/views/metadata-admin/inspectors/cel-list-membership.ts`: the shared spelling and reader. 3. `ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-edge-condition-rows.ts`: now writes through the shared module. Two-minute check: `pnpm --dir ui exec vitest run packages/app-shell/src/views/metadata-admin/inspectors/ConditionBuilder.listSubject-36167.test.tsx` — expect 27 passed. Local readings at `ef21bbcb31` (objectstack tree): <details><summary>Tests, type-check, ablation</summary> - `ConditionBuilder.listSubject-36167.test.tsx`: 27 passed. All `inspectors/ConditionBuilder*`, `flow-edge-condition-rows*`, `FlowEdgeInspector*` suites: 22 files, 262 tests passed (two locked runs; five suites first failed to collect on an unbuilt `@objectstack/client`, passed once it was built). - Mount-site suites (`ObjectValidationsPanel*`, `FlowNodeConfigField*`, `HookDefaultInspector*`, `ActionDefaultInspector*`, `PageBlockInspector.visibleWhen*`, `FlowNodeInspector.entryCondition*`, `widgets*ondition*`): 33 files, 323 passed, 1 failed before triage (the `ObjectValidationsPanel.typedEmptyOps-11894` list seed); after triage that file passes, run with `packages/i18n/` (106 files, 1967 passed) and with `ui/scripts/` (175 files, 5126 passed). - `pnpm --filter @object-ui/app-shell type-check` and `pnpm --filter @object-ui/i18n type-check`: exit 0 (lock VERDICT command-exit 0). - Ablation (one-off, restored byte-identical to the HEAD blob): deleting the list branch of `opChoicesFor` through `scripts/ablation-replace.mjs` (anchor 1 to 0) turns the new pin 19 failed / 8 passed of 27; the 8 are the single-value controls, the instrument control and the raw-open cases. </details> <details><summary>Gates</summary> `node scripts/pm/dispatch-gates.mjs --commands` (diff-derived, 38 families) all exit 0 at `ef21bbcb31`; `--ran` reconciliation: 38 derived, 38 run, 0 NOT-MEASURED (a derived zero). `pnpm --dir ui check:new-line-citations`: 0 new. ESLint on the changed files: 0 errors (warnings pre-existing). CI runs the full farm. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5okniknzVVR3KTSVr1)_ <!-- signed: repo:objectstack#4 · os-project-manager · session_01FEkQ5okniknzVVR3KTSVr1 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 1d06026 commit 71e02ff

9 files changed

Lines changed: 470 additions & 27 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
'@object-ui/console': patch
4+
'@object-ui/i18n': patch
5+
---
6+
7+
fix(studio): the CEL condition builder offers membership, not equals, on a list field
8+
9+
Clause-②: no
10+
Metadata-protocol: none
11+
12+
On a field that holds a list (a `multiselect`, `checkboxes` or `tags` field, or a `select` / `lookup` / `user` field declared `multiple: true`), Studio's condition builder (hook, validation-rule, action-visibility, page-block and flow entry conditions) offered equals / not equals and the ordering operators. CEL compares the whole list with one value there, so `record.labels == 'frontend'` was false for every record (and `!=` true for every record), and the author got no signal.
13+
14+
Such a field is now offered what the list toolbar's filter builder offers it: contains, does not contain, is empty and is not empty. Contains writes `S != null && V in S` and does not contain writes `S == null || !(V in S)`, the same spelling a flow edge's condition rows write; both are null-safe. A row moved onto a list field leaves equals for contains, and a row moved off one leaves membership for equals. A stored condition that compares a list field with `==` / `!=` now opens in the expression editor exactly as stored, never rewritten. A single-value field is offered what it was before.
15+
16+
New locale key: `engine.inspector.condition.op.notContains` in the studio catalogue (en, zh). No props or exports change.
Lines changed: 252 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,252 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#36167 — `ConditionBuilder` on a LIST subject (a `multiselect` /
5+
* `checkboxes` / `tags`, or a `select` / `lookup` / `user` declared
6+
* `multiple: true`).
7+
*
8+
* Under `@objectstack/formula`'s `celEngine`, `S == V` compares the whole list
9+
* with one value, so it answers a constant. The builder therefore offers a
10+
* list subject what the shared filter builder offers it (membership and the
11+
* empty checks), writes membership in the one spelling the flow edge's rows
12+
* write (`cel-list-membership.ts`), and opens a stored `==` on a list in the
13+
* raw editor unchanged. Every emitted condition is evaluated by the engine
14+
* beside its spelling, and a single-value field keeps `==`.
15+
*/
16+
17+
// The builder reaches a dynamic `import()` of each module below: its first load
18+
// is paid here, at collection, never inside a case's clocked window
19+
// (`check:test-source-alias`).
20+
import '@objectstack/lint';
21+
import '@object-ui/core';
22+
import * as React from 'react';
23+
import { describe, it, expect, afterEach, beforeAll, vi } from 'vitest';
24+
import { render, screen, cleanup, fireEvent } from '@testing-library/react';
25+
import userEvent from '@testing-library/user-event';
26+
import { celEngine } from '@objectstack/formula';
27+
import { jsonColumnFilterOperators } from '@object-ui/components';
28+
29+
// ConditionBuilder calls useObjectFields(objectName) even when `fields` is
30+
// supplied; stub the shared client so the mount-time fetch stays off the network.
31+
const state = vi.hoisted(() => ({
32+
metadataClient: {
33+
get: vi.fn(async (): Promise<unknown> => undefined),
34+
list: vi.fn(async () => [] as unknown[]),
35+
withPreviewDrafts() { return this; },
36+
},
37+
}));
38+
vi.mock('../useMetadata', () => ({
39+
useMetadataClient: () => state.metadataClient,
40+
}));
41+
42+
import { ConditionBuilder } from './ConditionBuilder';
43+
import { listSubjectOperators } from './cel-list-membership';
44+
import { rowsToCel } from './flow-edge-condition-rows';
45+
46+
afterEach(() => cleanup());
47+
48+
beforeAll(() => {
49+
// Radix Select probes pointer-capture APIs the test DOM lacks.
50+
for (const m of ['hasPointerCapture', 'setPointerCapture', 'releasePointerCapture'] as const) {
51+
if (!Element.prototype[m]) {
52+
// @ts-expect-error test shim
53+
Element.prototype[m] = m === 'hasPointerCapture' ? () => false : () => {};
54+
}
55+
}
56+
});
57+
58+
type CatalogRow = { name: string; label?: string; type?: string; multiple?: boolean };
59+
60+
const FIELDS: CatalogRow[] = [
61+
{ name: 'labels', label: 'Labels', type: 'multiselect' },
62+
{ name: 'tags', label: 'Tags', type: 'tags' },
63+
{ name: 'channels', label: 'Channels', type: 'checkboxes' },
64+
{ name: 'regions', label: 'Regions', type: 'select', multiple: true },
65+
{ name: 'watchers', label: 'Watchers', type: 'lookup', multiple: true },
66+
{ name: 'reviewers', label: 'Reviewers', type: 'user', multiple: true },
67+
{ name: 'status', label: 'Status', type: 'select' },
68+
{ name: 'owner', label: 'Owner', type: 'lookup' },
69+
{ name: 'address', label: 'Address', type: 'address' },
70+
];
71+
const LIST_FIELDS = FIELDS.slice(0, 6);
72+
const SCALAR_FIELDS = FIELDS.slice(6);
73+
74+
/** The words the builder shows for the shared builder's list operators. */
75+
const LIST_OP_WORDS: Record<string, string> = {
76+
contains: 'contains',
77+
not_contains: 'does not contain',
78+
is_empty: 'is empty',
79+
is_not_empty: 'is not empty',
80+
};
81+
82+
function Harness({ initial }: { initial: string }) {
83+
const [v, setV] = React.useState(initial);
84+
return (
85+
<div>
86+
<ConditionBuilder label="Condition" value={v} onCommit={setV} fields={FIELDS} />
87+
<pre data-testid="committed">{v}</pre>
88+
</div>
89+
);
90+
}
91+
92+
const committed = () => screen.getByTestId('committed').textContent ?? '';
93+
const comboboxes = (c: HTMLElement) => Array.from(c.querySelectorAll('[role="combobox"]')) as HTMLElement[];
94+
const lastOpTrigger = (c: HTMLElement) => comboboxes(c).at(-1)!;
95+
const rawEditor = (c: HTMLElement) => c.querySelector('textarea');
96+
97+
async function offeredOps(c: HTMLElement): Promise<string[]> {
98+
await userEvent.click(lastOpTrigger(c));
99+
const ops = (await screen.findAllByRole('option')).map((o) => o.textContent ?? '');
100+
await userEvent.keyboard('{Escape}');
101+
return ops;
102+
}
103+
104+
async function pickOp(c: HTMLElement, label: string) {
105+
await userEvent.click(lastOpTrigger(c));
106+
await userEvent.click(await screen.findByRole('option', { name: label }));
107+
}
108+
109+
/** Add a row and pick `field` as its subject. */
110+
async function addRowOn(c: HTMLElement, field: CatalogRow) {
111+
fireEvent.click(screen.getByText('Add condition'));
112+
const subjects = comboboxes(c);
113+
await userEvent.click(subjects[subjects.length - 2]);
114+
await userEvent.click(await screen.findByRole('option', { name: `${field.label} record.${field.name}` }));
115+
}
116+
117+
const typeValue = (c: HTMLElement, value: string) => {
118+
const boxes = c.querySelectorAll('input');
119+
fireEvent.change(boxes[boxes.length - 1], { target: { value } });
120+
};
121+
122+
const evaluate = (cel: string, record: Record<string, unknown>) => {
123+
const r = celEngine.evaluate({ dialect: 'cel', source: cel }, { record });
124+
if (!r.ok) throw new Error(JSON.stringify(r.error));
125+
return r.value;
126+
};
127+
128+
describe('a list subject is offered the shared builder’s list operators, and nothing else', () => {
129+
it.each(LIST_FIELDS)('$label ($type) offers membership and the empty checks — never == / != / ordering', async (field) => {
130+
const shared = jsonColumnFilterOperators({ type: field.type, multiple: field.multiple === true })!;
131+
expect(listSubjectOperators(field)).toEqual(shared);
132+
const { container } = render(<Harness initial="" />);
133+
await addRowOn(container, field);
134+
expect(await offeredOps(container)).toEqual(shared.map((op) => LIST_OP_WORDS[op]));
135+
});
136+
137+
it.each(SCALAR_FIELDS)('CONTROL — $label ($type) keeps equals / not equals and is offered no membership', async (field) => {
138+
expect(listSubjectOperators(field)).toBeUndefined();
139+
const { container } = render(<Harness initial="" />);
140+
await addRowOn(container, field);
141+
const ops = await offeredOps(container);
142+
expect(ops).toEqual(expect.arrayContaining(['equals', 'not equals', 'is empty', 'is not empty']));
143+
expect(ops).not.toContain('contains');
144+
expect(ops).not.toContain('does not contain');
145+
});
146+
});
147+
148+
describe('membership is written null-safe, in the flow edge’s spelling, and the engine answers it as membership', () => {
149+
it('picking a list subject moves a new row off `equals` onto `contains`', async () => {
150+
const { container } = render(<Harness initial="" />);
151+
await addRowOn(container, FIELDS[0]);
152+
expect(lastOpTrigger(container).textContent).toBe('contains');
153+
typeValue(container, 'frontend');
154+
expect(committed()).toBe("record.labels != null && 'frontend' in record.labels");
155+
});
156+
157+
it.each(LIST_FIELDS)('$label: contains / does not contain', async (field) => {
158+
const s = `record.${field.name}`;
159+
const { container } = render(<Harness initial="" />);
160+
await addRowOn(container, field);
161+
typeValue(container, 'u1');
162+
const contains = committed();
163+
await pickOp(container, 'does not contain');
164+
const notContains = committed();
165+
166+
expect(contains).toBe(`${s} != null && 'u1' in ${s}`);
167+
expect(notContains).toBe(`${s} == null || !('u1' in ${s})`);
168+
// The same row through the flow edge's writer: one spelling.
169+
const edgeField = { value: s, label: field.label!, type: field.type, multiple: field.multiple };
170+
expect(rowsToCel({ logic: 'and', conditions: [{ field: s, operator: 'contains', value: 'u1' }] }, [edgeField]))
171+
.toEqual({ ok: true, cel: contains });
172+
expect(rowsToCel({ logic: 'and', conditions: [{ field: s, operator: 'not_contains', value: 'u1' }] }, [edgeField]))
173+
.toEqual({ ok: true, cel: notContains });
174+
175+
expect(evaluate(contains, { [field.name]: ['u1', 'u2'] })).toBe(true);
176+
expect(evaluate(contains, { [field.name]: ['u2'] })).toBe(false);
177+
expect(evaluate(contains, { [field.name]: [] })).toBe(false);
178+
expect(evaluate(contains, { [field.name]: null })).toBe(false);
179+
expect(evaluate(notContains, { [field.name]: ['u2'] })).toBe(true);
180+
expect(evaluate(notContains, { [field.name]: ['u1', 'u2'] })).toBe(false);
181+
expect(evaluate(notContains, { [field.name]: [] })).toBe(true);
182+
expect(evaluate(notContains, { [field.name]: null })).toBe(true);
183+
});
184+
185+
it('the empty checks on a list keep their null-or-empty-list spelling', async () => {
186+
const { container } = render(<Harness initial="" />);
187+
await addRowOn(container, FIELDS[0]);
188+
await pickOp(container, 'is empty');
189+
const cel = committed();
190+
expect(cel).toBe('record.labels == null || size(record.labels) == 0');
191+
expect(evaluate(cel, { labels: [] })).toBe(true);
192+
expect(evaluate(cel, { labels: null })).toBe(true);
193+
expect(evaluate(cel, { labels: ['qa'] })).toBe(false);
194+
});
195+
196+
it('INSTRUMENT CONTROL — the equality this replaces answers a constant on a list', () => {
197+
expect(evaluate("record.labels == 'frontend'", { labels: ['frontend', 'qa'] })).toBe(false);
198+
expect(evaluate("record.labels == 'frontend'", { labels: ['qa'] })).toBe(false);
199+
expect(evaluate("record.labels != 'frontend'", { labels: ['frontend', 'qa'] })).toBe(true);
200+
expect(evaluate("record.labels != 'frontend'", { labels: ['qa'] })).toBe(true);
201+
});
202+
});
203+
204+
describe('a stored condition on a list reads back exactly, or opens in the raw editor unchanged', () => {
205+
it.each([
206+
['contains, alone', "record.labels != null && 'frontend' in record.labels"],
207+
['does not contain, alone', "record.labels == null || !('frontend' in record.labels)"],
208+
['contains, joined', "record.status == 'done' && (record.watchers != null && 'u1' in record.watchers)"],
209+
])('%s: reopens as rows, and an edit re-emits it unchanged', (_name, cel) => {
210+
const { container } = render(<Harness initial={cel} />);
211+
expect(rawEditor(container), 'opened in the raw editor — it did not round-trip').toBeNull();
212+
if (cel.startsWith("record.status == 'done'")) {
213+
fireEvent.change(container.querySelector('input')!, { target: { value: 'closed' } });
214+
expect(committed()).toBe(cel.replace("'done'", "'closed'"));
215+
}
216+
});
217+
218+
it.each([
219+
['== on a list', "record.labels == 'frontend'"],
220+
['!= on a list, joined', "record.status == 'done' && record.regions != 'emea'"],
221+
['membership on a single-value field', "record.owner != null && 'u1' in record.owner"],
222+
])('%s: opens in the raw editor verbatim, and nothing is emitted', (_name, stored) => {
223+
const { container } = render(<Harness initial={stored} />);
224+
expect(rawEditor(container), 'expected the raw CEL editor').not.toBeNull();
225+
expect(rawEditor(container)!.value).toBe(stored);
226+
expect(committed()).toBe(stored);
227+
});
228+
229+
it('CONTROL — equality on a single-value field still opens as rows', () => {
230+
const { container } = render(<Harness initial="record.status == 'done'" />);
231+
expect(rawEditor(container)).toBeNull();
232+
expect(lastOpTrigger(container).textContent).toBe('equals');
233+
});
234+
});
235+
236+
describe('moving a row between a list and a single-value field keeps an offered operator', () => {
237+
it('list → single value: membership becomes equals, the value kept', async () => {
238+
const { container } = render(<Harness initial="record.labels != null && 'frontend' in record.labels" />);
239+
await userEvent.click(comboboxes(container)[0]);
240+
await userEvent.click(await screen.findByRole('option', { name: 'Status record.status' }));
241+
expect(lastOpTrigger(container).textContent).toBe('equals');
242+
expect(committed()).toBe("record.status == 'frontend'");
243+
});
244+
245+
it('an empty check survives the move, re-spelled for the new field', async () => {
246+
const { container } = render(<Harness initial="record.labels == null || size(record.labels) == 0" />);
247+
await userEvent.click(comboboxes(container)[0]);
248+
await userEvent.click(await screen.findByRole('option', { name: 'Owner record.owner' }));
249+
expect(lastOpTrigger(container).textContent).toBe('is empty');
250+
expect(committed()).toBe('record.owner == null');
251+
});
252+
});

0 commit comments

Comments
 (0)