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
16 changes: 16 additions & 0 deletions .changeset/37867-declarative-update-action-warnings.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@objectstack/runtime': patch
'@object-ui/core': patch
'@object-ui/app-shell': patch
---

Clause-②: yes (widening)
Metadata-protocol: none

A declarative `operation: 'update'` action now tells the person about the validation warnings its write raised.
A `severity: 'warning'` rule lets the save through and answers `warnings`, and the edit form shows them; the
button that performs the same write answered only its success. The action's answer
(`POST /api/v1/actions/:object/:action`, and MCP `run_action`) now carries the write's `warnings`, in the data
door's own element shape, present only when the write raised one. The console's action runner raises the
success toast on its warning variant with the rule's words under the title, and keeps the Undo button; an action
whose success toast is turned off still shows the warning. `ToastHandler` options gain an optional `description`.
123 changes: 123 additions & 0 deletions packages/runtime/src/action-declarative-update.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@
import { describe, it, expect, vi } from 'vitest';

import { assertEngineUpdateDispatch } from '@objectstack/metadata-core';
// Paid at collection, not inside a case's clocked window: the dispatcher's reach
// loads it lazily (check:test-source-alias).
import '@objectstack/metadata';

import { HttpDispatcher } from './http-dispatcher.js';
import {
Expand Down Expand Up @@ -770,3 +773,123 @@ describe('#15079 reverse pin — a handler-less `type: script` action WITHOUT `o
expect(rig.row.status).toBe('open');
});
});

// ───────────────────────────────────────────────────────────────────────────
// [#37867] The write's advisory `warnings` ride the action's answer
// ───────────────────────────────────────────────────────────────────────────

/**
* A warning rule lets the write through and answers `warnings`
* (`protocol.updateData`, #22726). The button that performs the same write
* answers the same warnings, at both doors, or the rule warns only the people
* who edit the form.
*
* The rig above reaches the ObjectQL fallback of `callData`, which answers no
* warnings by construction, so this block puts a `protocol` slot in front of it:
* a double whose `updateData` writes through the rig's caller-honouring
* `ql.update` and answers the protocol's shape, `warnings` set only when the
* write tripped the stand-in rule (`status` set to `closed` while
* `priority` is `low`).
*/
describe('#37867 — a declarative update answers the `warnings` its data-plane write raised', () => {
const EARLY_CLOSE_WARNING = {
field: 'status',
code: 'rule_violation',
message: 'A low-priority case closed this early skips the review queue.',
rule: 'early_close_review',
severity: 'warning',
};

function protocolRig() {
const rig = makeRig();
const protocol: any = {
updateData: vi.fn(async (req: any) => {
await rig.ql.update(req.object, { ...req.data, id: req.id }, { where: { id: req.id }, context: req.context });
const trips = rig.row.status === 'closed' && rig.row.priority === 'low';
return {
object: req.object,
id: req.id,
record: { ...rig.row },
...(trips ? { warnings: [{ ...EARLY_CLOSE_WARNING }] } : {}),
};
}),
};
return { rig, protocol };
}

async function restVia(userId: string, rig: Rig, protocol: any, path: string, body: any = {}) {
const metadata: any = {
load: vi.fn(async () => null),
loadDiagnosed: vi.fn(async () => ({ data: null, degraded: false, errors: [] })),
listObjects: vi.fn(async () => [OBJECT_DEF]),
getObject: vi.fn(async (n: string) => (n === OBJECT_DEF.name ? OBJECT_DEF : undefined)),
};
const kernel: any = {
context: {
getService: (n: string) =>
n === 'objectql' || n === 'data' ? rig.ql
: n === 'metadata' ? metadata
: n === 'protocol' ? protocol
: null,
},
};
const context: any = { request: {}, environmentId: 'platform', executionContext: ec(userId) };
const res: any = await (new HttpDispatcher(kernel) as any).handleActions(path, 'POST', body, context);
return res.response;
}

async function mcpVia(userId: string, rig: Rig, protocol: any, name: string, input: Record<string, unknown>) {
const deps: any = {
resolveService: async (_ctx: unknown, n: string) => (n === 'protocol' ? protocol : undefined),
getObjectQL: async () => rig.ql,
};
const requestContext: any = { request: {}, environmentId: 'platform' };
return await invokeBusinessAction(deps, requestContext, name, input as any, {
driver: undefined,
envId: 'platform',
ec: ec(userId),
getMeta: () => ({ listObjects: async () => [OBJECT_DEF] }),
callData: (action, params, dataDriver, scopeId, execCtx) =>
callData(deps, requestContext, action, params, dataDriver, scopeId, execCtx),
});
}

it('REST: the 200 answer carries the write\'s warnings, element for element, beside the written record', async () => {
const { rig, protocol } = protocolRig();
const res = await restVia(OWNER, rig, protocol, `/${OBJECT}/close_case/${RECORD_ID}`);

expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
// The write went through the protocol, once, as the caller.
expect(protocol.updateData).toHaveBeenCalledTimes(1);
expect(protocol.updateData.mock.calls[0][0].context?.userId).toBe(OWNER);
expect(rig.row.status).toBe('closed');
expect(res.body.data.warnings).toEqual([EARLY_CLOSE_WARNING]);
expect(res.body.data).toMatchObject({ operation: DECLARATIVE_UPDATE_OPERATION, object: OBJECT, id: RECORD_ID });
expect(res.body.data.record).toMatchObject({ id: RECORD_ID, status: 'closed' });
// The undo anchor still rides beside them.
expect(res.body.data.undo).toMatchObject({ undoData: { status: 'open' }, redoData: { status: 'closed' } });
});

it('MCP `run_action`: the same write answers the same warnings', async () => {
const { rig, protocol } = protocolRig();
const out: any = await mcpVia(OWNER, rig, protocol, 'close_case', { recordId: RECORD_ID });

expect(out.ok).toBe(true);
expect(protocol.updateData).toHaveBeenCalledTimes(1);
expect(out.result.warnings).toEqual([EARLY_CLOSE_WARNING]);
});

it('a write that trips no rule carries no `warnings` key at all', async () => {
// The same action through the same protocol, on a row the rule does not
// fire for. ABSENT, never `[]` — the data door's own shape; the firing
// positive control is the REST case above, same rig.
const { rig, protocol } = protocolRig();
rig.row.priority = 'high';
const res = await restVia(OWNER, rig, protocol, `/${OBJECT}/close_case/${RECORD_ID}`);

expect(res.status).toBe(200);
expect(protocol.updateData).toHaveBeenCalledTimes(1);
expect('warnings' in res.body.data).toBe(false);
});
});
29 changes: 28 additions & 1 deletion packages/runtime/src/action-execution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { EngineQueryOptionsSchema, DATA_ACTION_TO_API_OPERATION } from '@objects
import type { ExecutionContext } from '@objectstack/spec/kernel';
import { isStoredMetadataBodyObject } from '@objectstack/spec/kernel';
import type { IHttpServer, IObjectQLEngine, InternalFieldEvaluationQuery, QueryEvaluationGate, ServiceSlotContract, ServiceSlotContracts } from '@objectstack/spec/contracts';
import { standardErrorCodeForHttpStatus, type MetadataProtocol } from '@objectstack/spec/api';
import { standardErrorCodeForHttpStatus, type MetadataProtocol, type ValidateDataIssue } from '@objectstack/spec/api';
import { renderOperationMessage } from '@objectstack/spec/system';
// [#15942 / #16293] The confirmation member's SPELLING is the contract, so it
// is imported, never hand-spelled: the door that refuses and the client that
Expand Down Expand Up @@ -4985,6 +4985,26 @@ export interface DeclarativeUpdateResult {
record: Record<string, unknown>;
/** Present only when the action declares `undoable: true`. */
undo?: DeclarativeUpdateUndo;
/**
* [#37867] The advisory validation-rule hits (`severity: 'warning' | 'info'`)
* of THIS write, exactly as the data-plane update answered them — the
* element is `ValidateDataIssue`, the data door's own `warnings` vocabulary.
* Present only when the write raised one: the same rule on the same write
* answers the same warnings whichever door the person used.
*/
warnings?: ValidateDataIssue[];
}

/**
* [#37867] The `warnings` a data-plane write answer carries, or `undefined`
* when it carries none. The protocol's `updateData` sets the member only when
* the write raised an advisory rule hit, so an empty or absent member answers
* the same: no warnings. Only the protocol arm of `callData` produces it; the
* ObjectQL fallback arm answers none, and this reads none from it.
*/
function writeAnswerWarnings(written: unknown): ValidateDataIssue[] | undefined {
const warnings = (written as { warnings?: unknown } | null | undefined)?.warnings;
return Array.isArray(warnings) && warnings.length > 0 ? (warnings as ValidateDataIssue[]) : undefined;
}

/**
Expand Down Expand Up @@ -5238,12 +5258,19 @@ export async function executeDeclarativeUpdateAction(
};
}

// [#37867] The write's advisory rule hits ride the answer. A warning rule
// lets the save through and tells the person; the data door answers it as
// `warnings`, and a button that performs the same write owes the same
// answer, or the warning holds only for people who edit the form.
const warnings = writeAnswerWarnings(written);

const result: DeclarativeUpdateResult = {
operation: DECLARATIVE_UPDATE_OPERATION,
object: objectName,
id: recordId,
record,
...(undo ? { undo } : {}),
...(warnings ? { warnings } : {}),
};
if (stale) throw withEarnedAnswer(stale, { ...result });
return result;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,17 @@ vi.mock('../../views/FlowRunner', () => ({ FlowRunner: () => null }));
// stub is handed, standing in for the declaration the route resolves by name:
// the request never carries it (objectui#12941).
const routeWrites: Array<Record<string, unknown>> = [];
// What the route answers beside the write: by default the bare success, else
// the declarative-update answer a case sets (objectstack#37867's `warnings`).
let routeAnswerData: Record<string, unknown> | undefined;
vi.mock('../../utils/consoleServerAction', () => ({
createConsoleServerActionHandler: () => vi.fn(async (action: {
params?: Record<string, unknown>;
patch?: Record<string, unknown>;
}) => {
const { _rowRecord: _row, recordId: _id, ...fields } = action.params ?? {};
routeWrites.push({ ...(action.patch ?? {}), ...fields });
return { success: true };
return routeAnswerData ? { success: true, data: routeAnswerData } : { success: true };
}),
}));

Expand Down Expand Up @@ -175,7 +178,9 @@ async function runOnGridRow(action: Record<string, unknown>) {
afterEach(() => {
cleanup();
routeWrites.length = 0;
routeAnswerData = undefined;
vi.mocked(toast.success).mockClear();
vi.mocked(toast.warning).mockClear();
globalUndoManager.clear();
});

Expand Down Expand Up @@ -290,3 +295,55 @@ describe('console runtime — where the field definitions come from (objectui#11
expect(global.context).not.toHaveProperty('objectFields');
});
});

describe('grid row — an update whose write raised warnings warns, on one toast (objectstack#37867)', () => {
const WARNING = 'This deal takes its account over the credit limit.';

it('the runtime raises the warning toast: the success message, the warning under it, and Undo', async () => {
routeAnswerData = {
operation: 'update',
object: OBJECT,
id: 'o1',
record: { ...STORED, account: 'a2' },
warnings: [{ field: 'account', code: 'rule_violation', message: WARNING, rule: 'credit_limit', severity: 'warning' }],
};
const dataSource = makeDataSource();
render(
<I18nProvider config={EN} persistLanguage={false}>
<MemoryRouter>
<ConsoleActionRuntimeProvider dataSource={dataSource} objects={[OBJECT_DEF]} objectName={OBJECT}>
<SchemaRendererProvider dataSource={dataSource as never}>
<ObjectGrid
schema={{
type: 'object-grid',
objectName: OBJECT,
columns: ['name', 'account'],
rowActionDefs: [{
locations: ['list_item'], successMessage: MESSAGE, name: 'set_account', label: 'Set account',
type: 'script', operation: 'update', undoable: true, patch: { account: 'a2' },
}],
} as never}
dataSource={dataSource as never}
/>
</SchemaRendererProvider>
</ConsoleActionRuntimeProvider>
</MemoryRouter>
</I18nProvider>,
);
await waitFor(() => expect(screen.getByText('Deal')).toBeInTheDocument());
await userEvent.click(await screen.findByTestId('row-action-trigger'));
await userEvent.click(await screen.findByTestId('row-action-set_account'));

await waitFor(() => expect(toast.warning).toHaveBeenCalledTimes(1));
const [message, options] = vi.mocked(toast.warning).mock.calls[0] as [string, { description?: string; action?: { onClick: () => void } }];
expect(message).toBe(MESSAGE);
expect(options.description).toBe(WARNING);
expect(options.action).toBeDefined();
// One toast: the warning variant replaces the success one, never joins it.
expect(vi.mocked(toast.success).mock.calls.filter(([m]) => m === MESSAGE)).toHaveLength(0);

// The kept Undo is the runtime's real one.
await act(async () => { options.action!.onClick(); });
await waitFor(() => expect(dataSource.update).toHaveBeenLastCalledWith(OBJECT, 'o1', { account: 'a1' }));
});
});
13 changes: 13 additions & 0 deletions ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,19 @@ export function useConsoleActionRuntime(opts: ConsoleActionRuntimeOptions): Cons

const toastHandler = useCallback<ToastHandler>((message, options) => {
if (options?.type === 'error') { toast.error(message); return; }
// objectstack#37867 — a write that went through with warnings: the
// runner's success toast on its warning variant, the warnings under the
// title, the Undo button kept (the same toast a record save raises).
if (options?.type === 'warning') {
toast.warning(message, {
duration: options.duration,
...(options.description ? { description: options.description } : {}),
...(options.undo
? { action: { label: options.undo.label || 'Undo', onClick: () => { void undoCtl.undo(); } } }
: {}),
});
return;
}
if (options?.undo) {
toast.success(message, {
duration: options.duration,
Expand Down
15 changes: 14 additions & 1 deletion ui/packages/app-shell/src/views/RecordDetailView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1946,8 +1946,21 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri
},
});

const toastHandler = useCallback((message: string, options?: { type?: string; duration?: number; undo?: { label?: string } }) => {
const toastHandler = useCallback((message: string, options?: { type?: string; duration?: number; description?: string; undo?: { label?: string } }) => {
if (options?.type === 'error') { toast.error(message); return; }
// objectstack#37867 — a write that went through with warnings: the
// runner's success toast on its warning variant, the warnings under the
// title, the Undo button kept (the same toast a record save raises).
if (options?.type === 'warning') {
toast.warning(message, {
duration: options.duration,
...(options.description ? { description: options.description } : {}),
...(options.undo
? { action: { label: options.undo.label || 'Undo', onClick: () => { void undoCtl.undo(); } } }
: {}),
});
return;
}
if (options?.undo) {
toast.success(message, {
duration: options.duration,
Expand Down
Loading
Loading