Skip to content
Draft
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
'@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 what its write told a record save: the message a
hook set (`ctx.notice`) and the fields the engine did not store. Before, a field the engine stripped from the
action's `patch` (a `readonly` field, a true `readonlyWhen`) was answered as a plain success, and the hook's message
was lost. The action's answer (`POST /api/v1/actions/:object/:action`, and MCP `run_action`) now carries the write's
`notice` and `droppedFields`, in the data door's own shapes, each present only when the write produced it. The
console's action runner puts the notice under the toast's title (a notice alone keeps the success toast; with the
success toast turned off it is an info toast of its own), and the console raises the record save's own
"Saved — but some fields did not take effect" toast for the stripped fields, with their labels.
169 changes: 168 additions & 1 deletion packages/runtime/src/action-declarative-update.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
* collapse or the not-found envelope is mocked away.
*/

import { describe, it, expect, vi } from 'vitest';
import { describe, it, expect, vi, afterEach } from 'vitest';
// Paid at collection, not inside a case's clock (check:test-source-alias).
import '@objectstack/metadata';

Expand All @@ -46,7 +46,12 @@ import { assertEngineUpdateDispatch } from '@objectstack/metadata-core';
// loads it lazily (check:test-source-alias).
import '@objectstack/metadata';

import { ObjectQL } from '@objectstack/objectql';
import { SqlDriver } from '@objectstack/driver-sql';
import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol';

import { HttpDispatcher } from './http-dispatcher.js';
import { installDefaultOrganization } from './default-organization.testkit.js';
import {
callData,
invokeBusinessAction,
Expand Down Expand Up @@ -902,3 +907,165 @@ describe('#37867 — a declarative update answers the `warnings` its data-plane
expect('warnings' in res.body.data).toBe(false);
});
});

// ───────────────────────────────────────────────────────────────────────────
// [#38103] The write's `notice` and `droppedFields` ride the action's answer
// ───────────────────────────────────────────────────────────────────────────

/**
* A hook on the write tells the person what it set in motion (`ctx.notice`),
* and the engine reports every field it did not store (`droppedFields`); the
* data door answers both (`protocol.updateData`). A button that performs the
* same write answers the same, at both doors — or the hook's message reaches
* only people who edit the form, and a field the engine stripped from the
* action's `patch` is answered as a plain success.
*
* Unlike the blocks above, nothing here is a double: a REAL `ObjectQL` engine
* on the REAL `SqlDriver` (better-sqlite3, `:memory:`), the REAL `ObjectStackProtocolImplementation`
* as the `protocol` service, and an object whose `closed_reason` is
* `readonly: true` — the strip, the hook's message and the data door's answer
* are the producers' own. Each case compares the action's answer with the
* data door's answer to the SAME write on a fresh engine.
*/
describe('#38103 — a declarative update answers the `notice` and `droppedFields` of its data-plane write', () => {
const FB_OBJECT = 'fb_case';
const FB_RECORD = 'fbc_1';
const NOTICE = 'Closing this case notified the customer.';
const CLOSE_WITH_REASON = {
name: 'close_with_reason',
label: 'Close',
operation: 'update',
// `closed_reason` is `readonly: true`: the engine strips it from the caller's write.
patch: { status: 'closed', closed_reason: 'resolved' },
ai: { exposed: true, description: 'Close this support case and record why it was closed.' },
};
const SET_PRIORITY = {
name: 'set_priority',
label: 'Set priority',
operation: 'update',
patch: { priority: 'high' },
ai: { exposed: true, description: 'Raise the priority of this support case to high.' },
};
const FB_OBJECT_DEF: any = {
name: FB_OBJECT,
fields: {
status: { type: 'text' },
priority: { type: 'text' },
closed_reason: { type: 'text', readonly: true },
},
actions: [CLOSE_WITH_REASON, SET_PRIORITY],
};
const quiet = { info() {}, debug() {}, warn() {}, error() {} };
const booted: ObjectQL[] = [];
afterEach(async () => {
for (const engine of booted.splice(0)) {
try { await engine.destroy(); } catch { /* noop */ }
}
});

async function boot() {
const engine = new ObjectQL({ logger: quiet } as any);
booted.push(engine);
engine.registerDriver(new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }) as any, true);
await engine.init();
engine.registry.registerObject(FB_OBJECT_DEF as never, 'com.objectstack.test.38103');
await engine.syncSchemas();
await installDefaultOrganization(engine);
// The hook says what closing did, from the write it is handed.
engine.registerHook('beforeUpdate', async (ctx: any) => {
if (ctx.input?.data?.status === 'closed') ctx.notice(NOTICE);
}, { object: FB_OBJECT });
await engine.insert(FB_OBJECT, { id: FB_RECORD, status: 'open', priority: 'low' }, { context: { isSystem: true } });
const protocol = new ObjectStackProtocolImplementation(engine as never);
return { engine, protocol };
}

/** The data door's own answer to the write the action makes, on a fresh engine. */
async function dataDoorAnswer(patch: Record<string, unknown>) {
const { protocol } = await boot();
return await protocol.updateData({ object: FB_OBJECT, id: FB_RECORD, data: patch, context: ec(OWNER) } as any) as any;
}

async function restOn(path: string) {
const { engine, protocol } = await boot();
const metadata: any = {
load: vi.fn(async () => null),
loadDiagnosed: vi.fn(async () => ({ data: null, degraded: false, errors: [] })),
listObjects: vi.fn(async () => [FB_OBJECT_DEF]),
getObject: vi.fn(async (n: string) => (n === FB_OBJECT ? FB_OBJECT_DEF : undefined)),
};
const kernel: any = {
context: {
getService: (n: string) =>
n === 'objectql' || n === 'data' ? engine
: n === 'metadata' ? metadata
: n === 'protocol' ? protocol
: null,
},
};
const context: any = { request: {}, environmentId: 'platform', executionContext: ec(OWNER) };
const res: any = await (new HttpDispatcher(kernel) as any).handleActions(path, 'POST', {}, context);
const stored: any = await engine.findOne(FB_OBJECT, { where: { id: FB_RECORD }, context: { isSystem: true } });
return { response: res.response, stored };
}

async function mcpOn(name: string) {
const { engine, protocol } = await boot();
const deps: any = {
resolveService: async (_ctx: unknown, n: string) => (n === 'protocol' ? protocol : undefined),
getObjectQL: async () => engine,
};
const requestContext: any = { request: {}, environmentId: 'platform' };
return await invokeBusinessAction(deps, requestContext, name, { recordId: FB_RECORD } as any, {
driver: undefined,
envId: 'platform',
ec: ec(OWNER),
getMeta: () => ({ listObjects: async () => [FB_OBJECT_DEF] }),
callData: (action, params, dataDriver, scopeId, execCtx) =>
callData(deps, requestContext, action, params, dataDriver, scopeId, execCtx),
}) as any;
}

it('control: the data door answers the hook\'s notice and the stripped field for this write', async () => {
const answer = await dataDoorAnswer(CLOSE_WITH_REASON.patch);
expect(answer.notice).toBe(NOTICE);
expect(answer.droppedFields).toEqual([{ object: FB_OBJECT, fields: ['closed_reason'], reason: 'readonly' }]);
});

it('REST: the 200 answer carries the same `notice` and `droppedFields` as the data door', async () => {
const door = await dataDoorAnswer(CLOSE_WITH_REASON.patch);
const { response, stored } = await restOn(`/${FB_OBJECT}/close_with_reason/${FB_RECORD}`);

expect(response.status).toBe(200);
expect(response.body.success).toBe(true);
expect(response.body.data).toMatchObject({ operation: DECLARATIVE_UPDATE_OPERATION, object: FB_OBJECT, id: FB_RECORD });
expect(response.body.data.notice).toBe(door.notice);
expect(response.body.data.droppedFields).toEqual(door.droppedFields);
// The strip is real: the row took `status` and not `closed_reason`.
expect(stored.status).toBe('closed');
expect(stored.closed_reason ?? null).toBeNull();
});

it('MCP `run_action`: the same write answers the same `notice` and `droppedFields`', async () => {
const door = await dataDoorAnswer(CLOSE_WITH_REASON.patch);
const out = await mcpOn('close_with_reason');

expect(out.ok).toBe(true);
expect(out.result.notice).toBe(door.notice);
expect(out.result.droppedFields).toEqual(door.droppedFields);
});

it('a write no hook spoke on and nothing was stripped from carries neither key', async () => {
// ABSENT, never `''` or `[]` — the data door's own shape; the firing
// positive control is the REST case above, same engine and object.
const door = await dataDoorAnswer(SET_PRIORITY.patch);
expect('notice' in door).toBe(false);
expect('droppedFields' in door).toBe(false);

const { response, stored } = await restOn(`/${FB_OBJECT}/set_priority/${FB_RECORD}`);
expect(response.status).toBe(200);
expect(stored.priority).toBe('high');
expect('notice' in response.body.data).toBe(false);
expect('droppedFields' in response.body.data).toBe(false);
});
});
47 changes: 36 additions & 11 deletions packages/runtime/src/action-execution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { ACTION_PARAM_BUILTIN_KEYS, validateActionParams, resolveI18nLabel, type
import { templateSlotSource } from '@objectstack/spec/automation';
// [#15124] The facade's `find` judges its own parameter against the SAME
// declaration its type names, so the refusal and the type cannot drift apart.
import { EngineQueryOptionsSchema, DATA_ACTION_TO_API_OPERATION } from '@objectstack/spec/data';
import { EngineQueryOptionsSchema, DATA_ACTION_TO_API_OPERATION, type DroppedFieldsEvent } from '@objectstack/spec/data';
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';
Expand Down Expand Up @@ -5030,18 +5030,40 @@ export interface DeclarativeUpdateResult {
* answers the same warnings whichever door the person used.
*/
warnings?: ValidateDataIssue[];
/**
* [#38103] The one message a hook on THIS write set for the person who made
* it (`ctx.notice`), exactly as the data-plane update answered it. Present
* only when a hook set one: the same hook on the same write tells the
* person the same thing whichever door they used.
*/
notice?: string;
/**
* [#38103] The fields the engine did NOT store from this write (a static
* `readonly`, a true `readonlyWhen`, …), exactly as the data-plane update
* answered them — the element is the engine's own `DroppedFieldsEvent`.
* Present only when a field was dropped: without it the answer reads as a
* success that wrote everything the action declared.
*/
droppedFields?: DroppedFieldsEvent[];
}

/**
* [#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.
* [#37867, #38103] What a data-plane write answer tells the person beyond the
* written row: its advisory `warnings`, the `notice` a hook set and the
* `droppedFields` the engine stripped — each only when the answer carries it.
* The protocol's `updateData` sets every one of these members only when there
* is something to say, so an empty or absent member answers the same: nothing.
* Only the protocol arm of `callData` produces them; 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;
function writeAnswerFeedback(written: unknown): Pick<DeclarativeUpdateResult, 'warnings' | 'notice' | 'droppedFields'> {
const answer = (written ?? undefined) as { warnings?: unknown; notice?: unknown; droppedFields?: unknown } | undefined;
const { warnings, notice, droppedFields } = answer && typeof answer === 'object' ? answer : {};
return {
...(Array.isArray(warnings) && warnings.length > 0 ? { warnings: warnings as ValidateDataIssue[] } : {}),
...(typeof notice === 'string' && notice.trim() !== '' ? { notice } : {}),
...(Array.isArray(droppedFields) && droppedFields.length > 0 ? { droppedFields: droppedFields as DroppedFieldsEvent[] } : {}),
};
}

/**
Expand Down Expand Up @@ -5299,15 +5321,18 @@ export async function executeDeclarativeUpdateAction(
// 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);
// [#38103] So do the hook's `notice` and the engine's `droppedFields`: a
// field the engine stripped from the action's patch answered as a bare
// success is a silent field loss.
const feedback = writeAnswerFeedback(written);

const result: DeclarativeUpdateResult = {
operation: DECLARATIVE_UPDATE_OPERATION,
object: objectName,
id: recordId,
record,
...(undo ? { undo } : {}),
...(warnings ? { warnings } : {}),
...feedback,
};
if (stale) throw withEarnedAnswer(stale, { ...result });
return result;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -347,3 +347,83 @@ describe('grid row — an update whose write raised warnings warns, on one toast
await waitFor(() => expect(dataSource.update).toHaveBeenLastCalledWith(OBJECT, 'o1', { account: 'a1' }));
});
});

describe('grid row — an update\'s notice and stripped fields reach the person (objectstack#38103)', () => {
const NOTICE = 'Reassigning this deal notified the new account owner.';
const STRIPPED_TITLE = 'Saved — but some fields did not take effect';

async function runSetAccount() {
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', config: { mode: 'loose' } },
}],
} 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'));
return dataSource;
}

it('the success toast carries the hook\'s notice and Undo; the stripped field gets the record save\'s own toast, labelled', async () => {
routeAnswerData = {
operation: 'update',
object: OBJECT,
id: 'o1',
record: { ...STORED, account: 'a2' },
notice: NOTICE,
droppedFields: [{ object: OBJECT, fields: ['config'], reason: 'readonly' }],
};
const dataSource = await runSetAccount();

const call = await waitFor(() => {
const found = vi.mocked(toast.success).mock.calls.find(([m]) => m === MESSAGE);
expect(found).toBeTruthy();
return found!;
});
const options = call[1] as { description?: string; action?: { onClick: () => void } };
expect(options.description).toBe(NOTICE);
expect(options.action).toBeDefined();

// The stripped field: one warning toast, the record save's title, the field by its label.
await waitFor(() => expect(toast.warning).toHaveBeenCalledTimes(1));
const [title, stripped] = vi.mocked(toast.warning).mock.calls[0] as [string, { description?: string }];
expect(title).toBe(STRIPPED_TITLE);
expect(stripped.description).toContain('Config');
expect(dataSource.getObjectSchema).toHaveBeenCalledWith(OBJECT);

// The kept Undo is the runtime's real one.
await act(async () => { options.action!.onClick(); });
await waitFor(() => expect(dataSource.update).toHaveBeenLastCalledWith(OBJECT, 'o1', expect.objectContaining({ account: 'a1' })));
});

it('control: an answer with neither raises the plain success toast and no stripped-fields toast', async () => {
routeAnswerData = { operation: 'update', object: OBJECT, id: 'o1', record: { ...STORED, account: 'a2' } };
await runSetAccount();

const call = await waitFor(() => {
const found = vi.mocked(toast.success).mock.calls.find(([m]) => m === MESSAGE);
expect(found).toBeTruthy();
return found!;
});
expect((call[1] as { description?: string }).description).toBeUndefined();
expect(toast.warning).not.toHaveBeenCalled();
});
});
Loading
Loading