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
14 changes: 14 additions & 0 deletions .changeset/25809-flow-write-refusal-locale.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@objectstack/service-automation': patch
---

fix(service-automation): a refusal a flow's write node meets is worded in the language of the person who started the run, as their own record save is

Clause-②: no
Metadata-protocol: none

A validation rule tripped through a record door (`POST` / `PATCH /api/v1/data/...`, batch, import) answers in the caller's locale: the engine looks the authored `message` up at `objects.OBJECT._validations.RULE.message` in the app's bundle. The same rule tripped by a flow's `create_record` or `update_record` answered in the authored English, and a `DELETE_RESTRICTED` refusal met by `delete_record` named its objects by their English labels — so a `FLOW_FAILED` from `POST /api/v1/actions/...` carried an English `innerRefusal.message` on a request whose screens rendered in Chinese.

The run already knew the language (`AutomationContext.locale`, seeded by the `/actions` and trigger doors); `resolveRunDataContext` dropped it from the context its data nodes hand the engine. It now carries `locale` on both `runAs` arms, and the engine's one translation hook does the rest. Nothing new translates anything: a run no person started has no locale and keeps the authored text.

What to do: nothing. Ship your translations under `objects.OBJECT._validations.RULE.message` as you already do for the record doors; a flow write now reads the same entry.
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* A refusal a flow's write node meets is worded in the run's locale, as the
* same refusal on a record door is.
*
* The record doors hand `ExecutionContext.locale` to the engine, and the
* engine resolves the refusal's text through its ONE translation hook
* (`ObjectQL#validationMessageContext`, bridged to the i18n service): an
* authored rule's `objects.<o>._validations.<rule>.message`, the built-in
* catalog, a `DELETE_RESTRICTED` sentence's labels. A flow run started by a
* person carries that person's locale on `AutomationContext.locale` (the
* `/actions` and trigger doors seed it), but the data nodes' context
* (`resolveRunDataContext`) dropped it — so the engine translated nothing and
* the run's `innerRefusal.message` (the `FLOW_FAILED` details member the doors
* emit) came back in the authored English while the same request's screens
* rendered in Chinese.
*
* The fix adds no translation of its own: the locale rides into the data
* context and the engine's existing hook does the rest. So these tests drive a
* REAL engine (ObjectQL + better-sqlite3) with a bundle on its i18n service,
* and assert what the run hands its caller — for every flow node that writes:
* `create_record`, `update_record`, `delete_record`, under both `runAs` arms.
* A run with no locale keeps the authored text: nothing is translated for a
* caller who asked for no language.
*/

import { describe, it, expect, afterEach } from 'vitest';
import { ObjectKernel } from '@objectstack/core';
import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql';
import { SqlDriver } from '@objectstack/driver-sql';
import { AutomationServicePlugin } from './plugin.js';
import type { AutomationEngine } from './engine.js';
import { installDefaultOrganization } from './default-organization.testkit.js';

function makeSqliteDriver() {
return new SqlDriver({
client: 'better-sqlite3',
connection: { filename: ':memory:' },
useNullAsDefault: true,
});
}

const RULE_EN = 'Amount must not be negative.';
const RULE_ZH = '金额不能为负数。';

const crmAccount = {
name: 'crm_account',
label: 'Account',
fields: {
name: { name: 'name', label: 'Name', type: 'text' },
},
};

/** An authored rule whose message the app's zh-CN bundle translates. */
const crmDeal = {
name: 'crm_deal',
label: 'Deal',
fields: {
name: { name: 'name', label: 'Name', type: 'text' },
amount: { name: 'amount', label: 'Amount', type: 'number' },
account: { name: 'account', label: 'Account', type: 'lookup', reference: 'crm_account', deleteBehavior: 'restrict' },
},
validations: [{
type: 'script',
name: 'amount_not_negative',
message: RULE_EN,
condition: 'record.amount < 0',
fields: ['amount'],
}],
};

/** The app's zh-CN bundle, as an `II18nService` (a miss echoes the key back). */
const ZH_BUNDLE: Record<string, string> = {
'objects.crm_deal._validations.amount_not_negative.message': RULE_ZH,
'objects.crm_account.label': '客户',
'objects.crm_deal.label': '商机',
'objects.crm_deal.fields.account.label': '所属客户',
};
const zhI18n = {
t: (key: string, locale: string) => (locale?.startsWith('zh') ? ZH_BUNDLE[key] ?? key : key),
};

const USER = { userId: 'usr_seller', tenantId: 'org_1', positions: [] as string[], permissions: [] as string[] };
const SYS = { isSystem: true } as const;

type RunAs = 'user' | 'system';

/** start → one write node → end. */
const oneNodeFlow = (name: string, runAs: RunAs, node: Record<string, unknown>) => ({
name,
label: name,
type: 'autolaunched',
runAs,
nodes: [
{ id: 'start', type: 'start', label: 'Start' },
{ id: 'write', label: 'Write', ...node },
{ id: 'end', type: 'end', label: 'End' },
],
edges: [
{ id: 'e1', source: 'start', target: 'write' },
{ id: 'e2', source: 'write', target: 'end' },
],
});

describe('a flow write node\'s refusal speaks the run\'s locale, as the record doors do', () => {
let kernel: ObjectKernel;
let ql: ObjectQL;
let automation: AutomationEngine;

afterEach(async () => {
try { await kernel?.shutdown(); } catch { /* noop */ }
});

async function boot() {
kernel = new ObjectKernel({ logger: { level: 'fatal' } });
await kernel.use(new ObjectQLPlugin());
await kernel.use(new AutomationServicePlugin({ suspendedRunStore: 'memory' }));
await kernel.bootstrap();

ql = kernel.getService<ObjectQL>('objectql');
automation = kernel.getService<AutomationEngine>('automation');

const driver = makeSqliteDriver();
await driver.connect();
ql.registerDriver(driver, true);
ql.registry.registerObject(crmAccount as any, 'locale-test', 'locale-test');
ql.registry.registerObject(crmDeal as any, 'locale-test', 'locale-test');
await ql.syncSchemas();
await installDefaultOrganization(ql);
ql.setI18nService(zhI18n as any);
}

/** Run `node` in a fresh flow; return the refused run's result. */
async function refusedRun(runAs: RunAs, node: Record<string, unknown>, locale?: string) {
const name = `write_${runAs}_${String(node.type)}_${locale ?? 'none'}`.replace(/-/g, '_').toLowerCase();
automation.registerFlow(name, oneNodeFlow(name, runAs, node) as any);
const res = await automation.execute(name, { ...USER, ...(locale ? { locale } : {}) });
expect(res.success, `the write must be refused: ${JSON.stringify(res)}`).toBe(false);
return res;
}

const createBad = { type: 'create_record', config: { objectName: 'crm_deal', fields: { name: 'D1', amount: -5 } } };

for (const runAs of ['user', 'system'] as const) {
describe(`runAs: '${runAs}'`, () => {
it('create_record: the authored rule message arrives in zh-CN, as a POST to the record door answers', async () => {
await boot();
// The control: the record door's own answer for the same write.
const door = await ql.insert('crm_deal', { name: 'D0', amount: -1 }, { context: { ...USER, locale: 'zh-CN' } })
.then(() => undefined, (e: any) => String(e?.message));
expect(door).toBe(RULE_ZH);

const res = await refusedRun(runAs, createBad, 'zh-CN');
expect(res.innerRefusal).toEqual({ code: 'VALIDATION_FAILED', message: RULE_ZH });
expect(res.error).toBe(`Node 'write' failed: create_record(crm_deal) failed: ${RULE_ZH}`);
});

it('update_record: the same rule tripped by an update arrives in zh-CN', async () => {
await boot();
const deal = await ql.insert('crm_deal', { name: 'D2', amount: 10 }, { context: { ...USER } });
const res = await refusedRun(runAs, {
type: 'update_record',
config: { objectName: 'crm_deal', filter: { id: String(deal.id) }, fields: { amount: -1 } },
}, 'zh-CN');
expect(res.innerRefusal).toEqual({ code: 'VALIDATION_FAILED', message: RULE_ZH });
const after = await ql.findOne('crm_deal', { where: { id: deal.id }, context: SYS });
expect(after!.amount, 'the refused update never landed').toBe(10);
});

it('delete_record: a DELETE_RESTRICTED refusal names the objects by their zh-CN labels', async () => {
await boot();
const account = await ql.insert('crm_account', { name: 'Acme' }, { context: { ...USER } });
await ql.insert('crm_deal', { name: 'D3', amount: 1, account: account.id }, { context: { ...USER } });
const res = await refusedRun(runAs, {
type: 'delete_record',
config: { objectName: 'crm_account', filter: { id: String(account.id) } },
}, 'zh-CN');
expect(res.innerRefusal?.code).toBe('DELETE_RESTRICTED');
expect(res.innerRefusal?.message).toContain('客户');
expect(res.innerRefusal?.message).toContain('商机');
expect(res.innerRefusal?.message).not.toContain('crm_account');
});

it('no locale on the run: the authored text, untranslated', async () => {
await boot();
const res = await refusedRun(runAs, createBad);
expect(res.innerRefusal).toEqual({ code: 'VALIDATION_FAILED', message: RULE_EN });
});
});
}
});
27 changes: 25 additions & 2 deletions packages/services/service-automation/src/runtime-identity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,21 @@ export class UnscopedRunDataAccessError extends Error {
* run. A run that resolves no principal is handed no context at all; it is
* refused ({@link UnscopedRunDataAccessError}).
*/
export interface RunDataContext extends RunIdentityContext {}
export interface RunDataContext extends RunIdentityContext {
/**
* The run's {@link AutomationContext.locale} — the language of the person
* who started it — carried as `ExecutionContext.locale`, the field a record
* door's write carries. The engine words a refused write in it through its
* one translation hook (an authored rule's
* `objects.<o>._validations.<rule>.message`, the built-in catalog, a
* `DELETE_RESTRICTED` sentence's labels), so a flow's write node meets the
* refusal the same request's record save would, and hands it to the run's
* caller as `innerRefusal.message`. Nothing here translates: absent on a run
* no person started, which keeps the authored text. Presentation, not
* identity: no security middleware keys on it, on either `runAs` arm.
*/
locale?: string;
}

/**
* A flow run's {@link AutomationContext} as run setup leaves it: the context
Expand Down Expand Up @@ -262,6 +276,10 @@ export function runOrgUserIds(context: AutomationContext | undefined): string[]
* deciding user, so approvals cascades resolve here instead of being refused
* (#3783). Only its machine-driven sweeps stay user-less.
*
* Both principal arms also carry the run's `locale` when it has one
* ({@link RunDataContext.locale}), so a refused write is worded for the
* person who started the run, as their own record save would be.
*
* The engine sets {@link AutomationContext.runAs} on the run context at setup;
* this function is the single place that maps it to an ObjectQL context, shared
* by every data-touching node so the policy can't drift between node types —
Expand All @@ -271,6 +289,9 @@ export function runOrgUserIds(context: AutomationContext | undefined): string[]
*/
export function resolveRunDataContext(context: AutomationContext | undefined): RunDataContext | undefined {
const flowRunId = context?.flowRunId;
// The starter's language rides into every write, on both arms — see
// RunDataContext.locale.
const locale = typeof context?.locale === 'string' && context.locale.length > 0 ? context.locale : undefined;
if (context?.runAs === 'system') {
// Name the flow as the acting service principal (`svc:flow:<name>`,
// ADR-0014 D2) — the audit writer falls back to `session.actor` when
Expand Down Expand Up @@ -320,6 +341,7 @@ export function resolveRunDataContext(context: AutomationContext | undefined): R
// refused for want of one.
...(context.userId ? {} : { positions: [], permissions: [] }),
...(flowRunId ? { flowRunId } : {}),
...(locale ? { locale } : {}),
};
}
if (!context?.userId) {
Expand All @@ -340,7 +362,7 @@ export function resolveRunDataContext(context: AutomationContext | undefined): R
throw new UnscopedRunDataAccessError(context);
}
// `context` is now narrowed to a defined AutomationContext with a userId.
const out: RunIdentityContext = {
const out: RunDataContext = {
isSystem: false,
userId: context.userId,
positions: Array.isArray(context.positions) ? context.positions : [],
Expand All @@ -351,6 +373,7 @@ export function resolveRunDataContext(context: AutomationContext | undefined): R
if (context.email) out.email = context.email;
if (context.tenantId) out.tenantId = context.tenantId;
if (flowRunId) out.flowRunId = flowRunId;
if (locale) out.locale = locale;
return out;
}

Expand Down
Loading