From fe25e492ea9f3068a12d507b277dfdb28dc16c1a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 06:10:29 +0000 Subject: [PATCH 1/3] fix(app-shell): a flow that dropped a read-only field warns the person who clicked, naming the field Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwVkQ2wgvSKnhkFnys --- .changeset/33009-flow-dropped-fields-toast.md | 11 + ...onRuntime.flowDroppedFields-33009.test.tsx | 185 +++++++++++++++++ .../src/hooks/useConsoleActionRuntime.tsx | 6 +- .../__tests__/flowDroppedFields-33009.test.ts | 138 ++++++++++++ .../flowLaunch.translation-12075.test.tsx | 1 + .../app-shell/src/utils/flowDroppedFields.ts | 134 ++++++++++++ ui/packages/app-shell/src/utils/flowLaunch.ts | 24 ++- .../app-shell/src/views/FlowRunner.tsx | 10 +- ...etailView.flowDroppedFields-33009.test.tsx | 196 ++++++++++++++++++ .../app-shell/src/views/RecordDetailView.tsx | 6 +- ui/packages/data-objectstack/src/index.ts | 12 +- 11 files changed, 714 insertions(+), 9 deletions(-) create mode 100644 .changeset/33009-flow-dropped-fields-toast.md create mode 100644 ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.flowDroppedFields-33009.test.tsx create mode 100644 ui/packages/app-shell/src/utils/__tests__/flowDroppedFields-33009.test.ts create mode 100644 ui/packages/app-shell/src/utils/flowDroppedFields.ts create mode 100644 ui/packages/app-shell/src/views/RecordDetailView.flowDroppedFields-33009.test.tsx diff --git a/.changeset/33009-flow-dropped-fields-toast.md b/.changeset/33009-flow-dropped-fields-toast.md new file mode 100644 index 00000000000..6a8b59606e3 --- /dev/null +++ b/.changeset/33009-flow-dropped-fields-toast.md @@ -0,0 +1,11 @@ +--- +'@object-ui/data-objectstack': minor +'@object-ui/app-shell': patch +--- + +fix(app-shell): a flow started from a record action, or resumed from its screen, warns the person who clicked when a write step dropped a read-only field, naming the field by its label + +Clause-②: yes (widening) — `@object-ui/data-objectstack` exports its existing `droppedFields` wire gate and parser (`isWireDroppedFieldsEntry`, `asDroppedFieldsNotice`, and the `WireDroppedFieldsEntry` type they share); no i18n key is added +Metadata-protocol: none + +A flow whose `update_record` step wrote a `readonly` field (「提交审批」 writing `status`) lost the value in silence: the step succeeded, the run answered success and the record stayed where it was. Since objectstack#32861 the run's answer names those fields (`droppedFields`). The console now reads that member on both launch hosts (the list and page action runtime, the record page) and on the screen-flow runner's resume, and shows the same warning a record save shows for the same strip: "Saved — but some fields did not take effect", one line per reason, fields named by their labels from the object's schema. A run that drops nothing, or an answer from a server that predates the member, shows exactly what it showed before. diff --git a/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.flowDroppedFields-33009.test.tsx b/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.flowDroppedFields-33009.test.tsx new file mode 100644 index 00000000000..62e60c82055 --- /dev/null +++ b/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.flowDroppedFields-33009.test.tsx @@ -0,0 +1,185 @@ +/** + * 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. + */ + +/** + * objectstack#33009 — a flow behind a record action whose write step dropped a + * read-only field warns the person who clicked, naming the field by its label. + * + * The #32666 shape: 「提交审批」 starts a flow whose `update_record` step + * writes `status`, which is `readonly: true`. The data engine drops the value, + * the step and the run succeed, and since objectstack#32861 the run's answer + * says so (`droppedFields`). Before this card the console read none of it. + * + * The list / page runtime is one of the two launch hosts (the record page is + * pinned in `RecordDetailView.flowDroppedFields-33009`). Driven end to end: + * the real `ConsoleActionRuntimeProvider` (real `ActionProvider` / + * `ActionRunner`), the real flow handler, launch module, reader and + * `writeWarningToast`, and the real `FlowRunner` it mounts, under the real en + * pack. Only the network (`authFetch`), the router, the toast library and the + * data source's `getObjectSchema` (the label source) are stubbed. + */ + +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { render, screen, fireEvent, waitFor, within } from '@testing-library/react'; +import React from 'react'; + +vi.mock('react-router-dom', () => ({ useNavigate: () => vi.fn() })); + +const authFetchSpy = vi.fn(); +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: { id: 'u1', name: 'User', image: null }, activeOrganization: null }), + createAuthenticatedFetch: () => authFetchSpy, +})); + +vi.mock('sonner', () => { + const fn: any = vi.fn(); + fn.error = vi.fn(); + fn.success = vi.fn(); + fn.info = vi.fn(); + fn.warning = vi.fn(); + return { toast: fn }; +}); + +import { toast } from 'sonner'; +import { ConsoleActionRuntimeProvider } from '../useConsoleActionRuntime'; +import { I18nProvider, useAction } from '@object-ui/react'; + +const OBJECT = 'expense_report'; +const FLOW = 'expense_submit'; +/** The declared action, as the object metadata carries it. */ +const DECLARED = { name: 'submit_for_approval', label: '提交审批', type: 'flow', target: FLOW }; +/** An inline page button naming no declared action: the trigger route. */ +const INLINE = { name: 'inline_submit', label: 'Submit', type: 'flow', target: FLOW }; +/** The object's schema as the adapter serves it: `status` is labelled. */ +const SCHEMA = { name: OBJECT, fields: { status: { type: 'select', label: 'Approval status', readonly: true } } }; + +function answered(data: Record) { + return { ok: true, status: 200, json: async () => ({ success: true, data }) }; +} +/** The #32666 run: completed, its `update_record` step's `status` dropped as read-only. */ +const DROPPED = answered({ + success: true, + status: 'completed', + flowLabel: 'Submit', + droppedFields: [{ object: OBJECT, fields: ['status'], reason: 'readonly' }], +}); +/** A clean run: the same flow, nothing dropped (the member is omitted, as the server omits it). */ +const CLEAN = answered({ success: true, status: 'completed', flowLabel: 'Submit' }); +const PAUSED = answered({ + success: true, + status: 'paused', + runId: 'run-1', + flowLabel: 'Submit', + screen: { nodeId: 'note', title: 'Approval note', fields: [] }, +}); + +const TITLE = 'Saved — but some fields did not take effect'; +const READONLY_LINE = 'Read-only, so it did not take effect: Approval status'; + +const getObjectSchema = vi.fn(async (name: string) => (name === OBJECT ? SCHEMA : undefined)); +const warnings = () => (toast as any).warning.mock.calls as unknown[][]; + +beforeEach(() => { + authFetchSpy.mockReset(); + getObjectSchema.mockClear(); + for (const k of ['error', 'success', 'info', 'warning']) (toast as any)[k].mockClear(); +}); + +/** Mount the runtime, click `action` once through the real runner, and wait for its result. */ +async function click(action: Record) { + const objects = [{ name: OBJECT, label: 'Expense report', fields: SCHEMA.fields, actions: [DECLARED] }]; + let result: any; + function Probe() { + const { execute } = useAction(); + return ( + + ); + } + render( + + + + + , + ); + fireEvent.click(screen.getByText('run-flow')); + await waitFor(() => expect(result).toBeDefined()); + return result; +} + +describe('objectstack#33009 — a flow launch warns about the read-only fields its write steps dropped', () => { + it('the #32666 shape: a record action whose flow dropped readonly `status` warns, naming the label', async () => { + authFetchSpy.mockResolvedValueOnce(DROPPED); + + const result = await click(DECLARED); + + expect(String(authFetchSpy.mock.calls[0][0])).toBe(`/api/v1/actions/${OBJECT}/submit_for_approval`); + // The run still succeeded: the click's own outcome is unchanged. + expect(result).toMatchObject({ success: true }); + await waitFor(() => expect(warnings()).toHaveLength(1)); + expect(warnings()[0]).toEqual([TITLE, { description: READONLY_LINE }]); + expect(getObjectSchema).toHaveBeenCalledWith(OBJECT); + expect((toast as any).error).not.toHaveBeenCalled(); + }); + + it('a clean click warns about nothing', async () => { + authFetchSpy.mockResolvedValueOnce(CLEAN); + + const result = await click(DECLARED); + + expect(result).toMatchObject({ success: true }); + // Let any stray async announcement land before reading the silence. + await new Promise((r) => setTimeout(r, 0)); + expect(warnings()).toEqual([]); + }); + + it('the trigger route (an inline button naming no declared action) warns the same way', async () => { + authFetchSpy.mockResolvedValueOnce(DROPPED); + + await click(INLINE); + + expect(String(authFetchSpy.mock.calls[0][0])).toBe(`/api/v1/automation/${FLOW}/trigger`); + await waitFor(() => expect(warnings()).toHaveLength(1)); + expect(warnings()[0]).toEqual([TITLE, { description: READONLY_LINE }]); + }); + + it('the resume path: a paused run whose write after the pause dropped `status` warns on Submit', async () => { + authFetchSpy.mockResolvedValueOnce(PAUSED); + const result = await click(DECLARED); + expect(result).toEqual({ success: true, silent: true, handedOff: true }); + expect(warnings()).toEqual([]); + + const dialog = await screen.findByRole('dialog'); + authFetchSpy.mockResolvedValueOnce(DROPPED); + fireEvent.click(within(dialog).getByRole('button', { name: 'Submit' })); + await waitFor(() => expect(authFetchSpy).toHaveBeenCalledTimes(2)); + expect(String(authFetchSpy.mock.calls[1][0])).toBe(`/api/v1/automation/${FLOW}/runs/run-1/resume`); + + await waitFor(() => expect(warnings()).toHaveLength(1)); + expect(warnings()[0]).toEqual([TITLE, { description: READONLY_LINE }]); + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()); + }); + + it('control: a resume answer without `droppedFields` closes exactly as before, with no warning', async () => { + authFetchSpy.mockResolvedValueOnce(PAUSED); + await click(DECLARED); + + const dialog = await screen.findByRole('dialog'); + authFetchSpy.mockResolvedValueOnce(CLEAN); + fireEvent.click(within(dialog).getByRole('button', { name: 'Submit' })); + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()); + + expect((toast as any).success.mock.calls.map((c: unknown[]) => c[0])).toEqual(['Flow "Submit" completed']); + expect(warnings()).toEqual([]); + }); +}); diff --git a/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx b/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx index 029cb3d9482..8b4693b010d 100644 --- a/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx +++ b/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx @@ -53,6 +53,7 @@ import { EnvironmentEntitlementDialog, type EntitlementDialogState } from '../en import { entitlementDialogFromError, type EntitlementDialogSpec } from '../environment/entitlements.js'; import { resolvePageVarTokens } from '../utils/resolvePageVarTokens.js'; import { launchConsoleFlow } from '../utils/flowLaunch.js'; +import type { TranslateFn } from '@object-ui/i18n'; import { apiActionRefusalResult } from '../utils/flowResponse.js'; import { findDeclaredApiAction, @@ -787,6 +788,9 @@ export function useConsoleActionRuntime(opts: ConsoleActionRuntimeOptions): Cons triggerParams: params, objects: withKnownObjects(objects, metadata.objects), language, + // The run's `droppedFields` warning (objectstack#33009): labels read + // through this host's data source, the console's adapter. + droppedFields: { t: t as TranslateFn, fieldLabel, dataSource }, }); const judged = launch.judged; // Paused at a `screen` node: FlowRunner renders the form + resumes, and @@ -812,7 +816,7 @@ export function useConsoleActionRuntime(opts: ConsoleActionRuntimeOptions): Cons } catch (error) { return { success: false, error: (error as Error).message }; } - }, [authFetch, objApiName, objects, metadata, refresh, language, t]); + }, [authFetch, objApiName, objects, metadata, refresh, language, t, fieldLabel, dataSource]); // Server-side action handler — POST /api/v1/actions/{object}/{action}, built // from @object-ui/core's `createServerActionHandler` via the shared console diff --git a/ui/packages/app-shell/src/utils/__tests__/flowDroppedFields-33009.test.ts b/ui/packages/app-shell/src/utils/__tests__/flowDroppedFields-33009.test.ts new file mode 100644 index 00000000000..38d484fced0 --- /dev/null +++ b/ui/packages/app-shell/src/utils/__tests__/flowDroppedFields-33009.test.ts @@ -0,0 +1,138 @@ +/** + * 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. + */ + +/** + * objectstack#33009 — the one reader of a flow answer's `droppedFields`, below + * its three hosts (pinned end to end in + * `useConsoleActionRuntime.flowDroppedFields-33009` and + * `RecordDetailView.flowDroppedFields-33009`). + * + * What only this level can say cheaply: the parse is data-objectstack's own + * (its skew arm reaches the toast), a run that wrote two objects is labelled + * per object, an off-spec entry with no `object` is named by api name, and a + * failed launch carrying the member says nothing beyond its failure. + */ + +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { UNRECOGNIZED_DROP_REASON } from '@object-ui/data-objectstack'; + +const toasts = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn(), warning: vi.fn(), info: vi.fn() })); +vi.mock('sonner', () => ({ toast: toasts })); + +import { announceFlowDroppedFields, flowAnswerDroppedFields } from '../flowDroppedFields'; +import { launchConsoleFlow } from '../flowLaunch'; + +const SCHEMAS: Record }> = { + expense_report: { fields: { status: { label: 'Approval status' } } }, + expense_line: { fields: { status: { label: 'Line status' }, amount: { label: 'Amount' } } }, +}; +const dataSource = { getObjectSchema: vi.fn(async (name: string) => SCHEMAS[name]) }; +const t = ((key: string, opts?: { fields?: string; defaultValue?: string }) => + (opts?.defaultValue ?? key).replace('{{fields}}', opts?.fields ?? '')) as never; +const fieldLabel = (_object: string, _field: string, fallback: string) => fallback; +const ctx = { t, fieldLabel, dataSource }; + +function sink() { + return { warning: vi.fn(), info: vi.fn() }; +} +const answer = (droppedFields: unknown) => ({ success: true, data: { success: true, status: 'completed', droppedFields } }); + +beforeEach(() => { + dataSource.getObjectSchema.mockClear(); + for (const fn of Object.values(toasts)) fn.mockClear(); +}); + +describe('flowAnswerDroppedFields — the wire through data-objectstack’s own parser', () => { + it('parses the member, keeps the skew arm for a reason the pin cannot name, and drops an entry naming no field', () => { + expect( + flowAnswerDroppedFields(answer([ + { object: 'expense_report', fields: ['status'], reason: 'readonly' }, + { object: 'expense_report', fields: ['status'], reason: 'from_the_future' }, + { object: 'expense_report', fields: [42] }, + ])), + ).toEqual([ + { object: 'expense_report', fields: ['status'], reason: 'readonly' }, + { object: 'expense_report', fields: ['status'], reason: UNRECOGNIZED_DROP_REASON, unrecognizedReason: 'from_the_future' }, + ]); + }); + + it('control: an answer without the member (or no answer) reads as none', () => { + expect(flowAnswerDroppedFields({ success: true, data: { success: true, status: 'completed' } })).toEqual([]); + expect(flowAnswerDroppedFields(null)).toEqual([]); + }); +}); + +describe('announceFlowDroppedFields', () => { + it('labels each object’s fields on that object: one warning per object', async () => { + const s = sink(); + await announceFlowDroppedFields(answer([ + { object: 'expense_report', fields: ['status'], reason: 'readonly' }, + { object: 'expense_line', fields: ['status', 'amount'], reason: 'readonly' }, + ]), ctx, s); + + expect(s.warning.mock.calls.map((c) => c[1].description)).toEqual([ + 'Read-only, so it did not take effect: Approval status', + 'Read-only, so it did not take effect: Line status, Amount', + ]); + expect(dataSource.getObjectSchema.mock.calls.map((c) => c[0])).toEqual(['expense_report', 'expense_line']); + }); + + it('a reason from the future is named without claiming a cause', async () => { + const s = sink(); + await announceFlowDroppedFields(answer([{ object: 'expense_report', fields: ['status'], reason: 'from_the_future' }]), ctx, s); + expect(s.warning.mock.calls[0][1].description).toBe('Not applied by the server: Approval status'); + }); + + it('an off-spec entry with no `object` is named by api name, never by a guessed object', async () => { + const s = sink(); + await announceFlowDroppedFields(answer([{ fields: ['status'], reason: 'readonly' }]), ctx, s); + expect(s.warning.mock.calls[0][1].description).toBe('Read-only, so it did not take effect: status'); + expect(dataSource.getObjectSchema).not.toHaveBeenCalled(); + }); + + it('a data source without getObjectSchema still warns, by api name', async () => { + const s = sink(); + await announceFlowDroppedFields(answer([{ object: 'expense_report', fields: ['status'], reason: 'readonly' }]), { ...ctx, dataSource: {} }, s); + expect(s.warning.mock.calls[0][1].description).toBe('Read-only, so it did not take effect: status'); + }); + + it('control: no member, no warning', async () => { + const s = sink(); + await announceFlowDroppedFields({ success: true, data: { success: true, status: 'completed' } }, ctx, s); + expect(s.warning).not.toHaveBeenCalled(); + expect(s.info).not.toHaveBeenCalled(); + }); +}); + +describe('launchConsoleFlow — a failed run says only that it failed', () => { + it('a failed answer carrying the member gets its error and no "saved, but" warning', async () => { + const fetch = vi.fn(async () => new Response(JSON.stringify({ + success: true, + data: { + success: false, + status: 'failed', + error: 'boom', + droppedFields: [{ object: 'expense_report', fields: ['status'], reason: 'readonly' }], + }, + }), { status: 200, headers: { 'Content-Type': 'application/json' } })); + const launch = await launchConsoleFlow({ + fetch, + baseUrl: '', + action: { name: 'expense_submit', type: 'flow', target: 'expense_submit' }, + objectName: 'expense_report', + recordId: 'exp-7', + triggerParams: {}, + objects: [], + language: 'en', + droppedFields: ctx, + }); + expect(launch.judged.result.success).toBe(false); + await new Promise((r) => setTimeout(r, 0)); + expect(toasts.warning).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/app-shell/src/utils/__tests__/flowLaunch.translation-12075.test.tsx b/ui/packages/app-shell/src/utils/__tests__/flowLaunch.translation-12075.test.tsx index 02c4c1f60f8..4e8a4c2deb1 100644 --- a/ui/packages/app-shell/src/utils/__tests__/flowLaunch.translation-12075.test.tsx +++ b/ui/packages/app-shell/src/utils/__tests__/flowLaunch.translation-12075.test.tsx @@ -42,6 +42,7 @@ function launch(fetch: ReturnType, language = 'zh-CN') { triggerParams: {}, objects: [], language, + droppedFields: { t: ((key: string) => key) as never, fieldLabel: (_o, _f, fallback) => fallback, dataSource: null }, }); } diff --git a/ui/packages/app-shell/src/utils/flowDroppedFields.ts b/ui/packages/app-shell/src/utils/flowDroppedFields.ts new file mode 100644 index 00000000000..0067b6ddf4a --- /dev/null +++ b/ui/packages/app-shell/src/utils/flowDroppedFields.ts @@ -0,0 +1,134 @@ +/** + * 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. + */ + +/** + * The ONE reader of a flow run's `droppedFields` (objectstack#33009, the + * console half of objectstack#32861). + * + * A flow's `update_record` / `create_record` step that writes a field the data + * engine will not store (the #32666 case: 「提交审批」 writes `status`, which + * is `readonly: true`) used to lose the value in silence: the step succeeded, + * the run answered success, the record stayed 「草稿」 and the person who + * clicked saw nothing. The run's answer now names those fields + * (`AutomationResult.droppedFields`, objectstack#32861): the data engine's own + * `DroppedFieldsEvent`s, one per object and reason, set only when a field was + * dropped. This module turns that member into the same warning toast a record + * save shows for the same strip. + * + * Three hosts read a flow answer and all three come through here: the two + * launch handlers (`useConsoleActionRuntime`, `RecordDetailView`) through + * `launchConsoleFlow`, and `FlowRunner`'s resume of a paused screen run, whose + * terminal answer is where a write after the pause reports its drop. + * + * - **Parse**: `@object-ui/data-objectstack`'s own wire gate and parser + * (`isWireDroppedFieldsEntry`, `asDroppedFieldsNotice`), with its skew arm + * for a `reason` this bundle's spec pin cannot name. ⛔ Never a second copy. + * - **Speak**: `writeWarningToast.emitWriteWarning`, the record save's own + * message — the same title, the same per-reason sentence, the same field + * labels. The flow DID write the record, so its "Saved — but some fields did + * not take effect" title is true here too. + * - **Labels**: from the host's `dataSource`, which in the console IS the + * `ObjectStackAdapter` (`useAdapter()`, cached `getObjectSchema`), so the + * label path is the one `AdapterProvider` hands the save toast. Each host + * already holds it (it is what renders its forms), so no host gains a new + * dependency. A data source without `getObjectSchema` (a test stub) names + * fields by api name, which is still the truthful answer. + * + * One event per object: a flow can write any object, and a label is looked up + * on the object the entry names. Folding a second object's fields under the + * clicked record's object would label `status` with that object's `status`. + * + * A PRESENT member is a drop; an ABSENT one is not proof of none. A `map` + * item's run and a `subflow` child that paused do not roll their drops up yet + * (objectstack#33019), so nothing here ever says "every field was written". + */ + +import { toast } from 'sonner'; +import { + asDroppedFieldsNotice, + isWireDroppedFieldsEntry, + type DroppedFieldsNotice, + type ObjectStackAdapter, +} from '@object-ui/data-objectstack'; +import { + emitWriteWarning, + type FieldLabelFn, + type TranslateFn, + type WriteWarningSink, +} from '../providers/writeWarningToast.js'; + +/** + * What an entry whose wire `object` is missing is attributed to: nothing. + * The spec requires `object`, so only an off-spec answer reaches this; a flow + * can write any object, so the clicked record's object would be a guess. + * Falsy on purpose: `emitWriteWarning` skips the label lookup for an empty + * resource and names the fields by api name. + */ +const UNATTRIBUTED_FLOW_DROP = ''; + +/** What the hosts hand the reader: the translator, the label convention, the data source. */ +export interface FlowDroppedFieldsContext { + t: TranslateFn; + fieldLabel: FieldLabelFn; + /** The host's data source; read for `getObjectSchema` only. */ + dataSource: unknown; +} + +/** + * The parsed `droppedFields` of a flow answer (`{ success, data: AutomationResult }`), + * in wire order; empty when the answer carries none. + */ +export function flowAnswerDroppedFields(json: unknown): DroppedFieldsNotice[] { + const wire = (json as { data?: { droppedFields?: unknown } } | null | undefined)?.data?.droppedFields; + if (!Array.isArray(wire)) return []; + return wire + .filter(isWireDroppedFieldsEntry) + .map((e) => asDroppedFieldsNotice(e, UNATTRIBUTED_FLOW_DROP)); +} + +function schemaSource(dataSource: unknown): Pick | null { + const ds = dataSource as { getObjectSchema?: unknown } | null | undefined; + return ds && typeof ds.getObjectSchema === 'function' + ? (ds as Pick) + : null; +} + +/** + * Warn the person who started the run about every field its write steps + * dropped: one `emitWriteWarning` per object, nothing when the answer names + * none. Never throws — the run already happened, and a failed label lookup + * must not turn it into an error. + */ +export async function announceFlowDroppedFields( + json: unknown, + ctx: FlowDroppedFieldsContext, + sink: WriteWarningSink = toast, +): Promise { + const byObject = new Map(); + for (const notice of flowAnswerDroppedFields(json)) { + const object = notice.object ?? UNATTRIBUTED_FLOW_DROP; + byObject.set(object, [...(byObject.get(object) ?? []), notice]); + } + const adapter = schemaSource(ctx.dataSource); + for (const [object, droppedFields] of byObject) { + try { + await emitWriteWarning( + // `operation` is required by the event type and read only by a record + // save surface's answer-warnings claim, which a flow event (no + // `warnings`, no `notice`) never reaches; the toast does not show it. + { operation: 'update', resource: object, droppedFields }, + ctx.t, + adapter, + ctx.fieldLabel, + sink, + ); + } catch (err) { + console.warn('flowDroppedFields: could not announce dropped fields', err); + } + } +} diff --git a/ui/packages/app-shell/src/utils/flowLaunch.ts b/ui/packages/app-shell/src/utils/flowLaunch.ts index 48b9cb4d5c8..aa9902851c3 100644 --- a/ui/packages/app-shell/src/utils/flowLaunch.ts +++ b/ui/packages/app-shell/src/utils/flowLaunch.ts @@ -89,6 +89,7 @@ import { toast } from 'sonner'; import { createServerActionHandler } from '@object-ui/core'; import type { ActionDef, ActionResult, ServerActionFetch } from '@object-ui/core'; import { interpretFlowResponse, judgeFlowLaunch, type FlowLaunchJudgement } from './flowResponse.js'; +import { announceFlowDroppedFields, type FlowDroppedFieldsContext } from './flowDroppedFields.js'; /** The door a flow click went through. */ export type ConsoleFlowLaunchDoor = 'action' | 'trigger'; @@ -143,6 +144,11 @@ export interface ConsoleFlowLaunchInput { objects: readonly unknown[] | undefined; /** The host's active language, which a refused write's permission line is read in. */ language: string; + /** + * What the run's `droppedFields` warning is spoken with: the host's `t`, + * its field-label convention and its data source (objectstack#33009). + */ + droppedFields: FlowDroppedFieldsContext; } export interface ConsoleFlowLaunch { @@ -160,9 +166,21 @@ export interface ConsoleFlowLaunch { * Hand the launch back to its host, first speaking the success toast the * ActionRunner cannot (see the header). The result is `silent` exactly when * `successToast` is set, so the user reads one toast either way. + * + * Then the answer's `droppedFields` (objectstack#33009): a write step that + * dropped a read-only field ran and the run succeeded, so the user is warned + * beside the success, not instead of it. Not on a failed launch: its toast + * says the run failed, and "saved, but" beside it would contradict it. */ -function settled(launch: ConsoleFlowLaunch): ConsoleFlowLaunch { +function settled( + launch: ConsoleFlowLaunch, + json: unknown, + droppedFields: FlowDroppedFieldsContext, +): ConsoleFlowLaunch { if (launch.judged.successToast) toast.success(launch.judged.successToast); + // Not awaited: the label lookup must not hold the click's outcome (or its + // refresh), and the reader never rejects. + if (launch.judged.result.success !== false) void announceFlowDroppedFields(json, droppedFields); return launch; } @@ -202,7 +220,7 @@ export async function launchConsoleFlow( action.refreshAfter, action.successMessage, ), - }); + }, answered.json, input.droppedFields); } const res = await input.fetch( @@ -222,5 +240,5 @@ export async function launchConsoleFlow( action.refreshAfter, action.successMessage, ), - }); + }, json, input.droppedFields); } diff --git a/ui/packages/app-shell/src/views/FlowRunner.tsx b/ui/packages/app-shell/src/views/FlowRunner.tsx index df6f0d2d42c..73b68129429 100644 --- a/ui/packages/app-shell/src/views/FlowRunner.tsx +++ b/ui/packages/app-shell/src/views/FlowRunner.tsx @@ -322,7 +322,8 @@ import { Button, cn, } from '@object-ui/components'; -import { notifyDataChanged, useObjectTranslation } from '@object-ui/react'; +import { notifyDataChanged, useObjectTranslation, useSafeFieldLabel } from '@object-ui/react'; +import type { TranslateFn } from '@object-ui/i18n'; import { UploadingScopeProvider, useUploadingScope } from '@object-ui/fields'; import type { ActionCopyTemplate } from '@object-ui/core'; import { @@ -347,6 +348,7 @@ import { type ScreenSpec, } from './ScreenView.js'; import { flowSuccessCopy, interpretFlowResponse } from '../utils/flowResponse.js'; +import { announceFlowDroppedFields } from '../utils/flowDroppedFields.js'; import { activeFlowsBundle, type FlowsTranslation } from '../utils/flowsBundle.js'; export type { ScreenSpec, ScreenFieldSpec } from './ScreenView.js'; @@ -521,6 +523,7 @@ export interface FlowRunnerProps { export function FlowRunner({ state, authFetch, baseUrl, onClose, onComplete, dataSource, objects }: FlowRunnerProps) { const { t, i18n, language } = useObjectTranslation(); + const { fieldLabel } = useSafeFieldLabel(); const [screen, setScreen] = useState(null); const [runId, setRunId] = useState(''); const [flowName, setFlowName] = useState(''); @@ -610,6 +613,11 @@ export function FlowRunner({ state, authFetch, baseUrl, onClose, onComplete, dat return; } setResumeError(null); + // A write step after the pause that dropped a read-only field reports it + // on this answer (objectstack#33009): warned beside whatever the answer + // goes on to show, through the launch's own reader. Not awaited — the + // label lookup never holds the next screen or the close. + void announceFlowDroppedFields(json, { t: t as TranslateFn, fieldLabel, dataSource }); // The run reached an `end` node declaring `outcome: 'refused'` — a // successful evaluation that said no (objectstack#14945, ruling of // 2026-09-05). Checked BEFORE the terminal-success tail below, which is diff --git a/ui/packages/app-shell/src/views/RecordDetailView.flowDroppedFields-33009.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.flowDroppedFields-33009.test.tsx new file mode 100644 index 00000000000..46b64726d26 --- /dev/null +++ b/ui/packages/app-shell/src/views/RecordDetailView.flowDroppedFields-33009.test.tsx @@ -0,0 +1,196 @@ +/** + * 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. + */ + +/** + * objectstack#33009 — the #32666 case on the record page: 「提交审批」 starts a + * flow whose `update_record` step writes the read-only `status`; the value is + * dropped and the run succeeds. The person who clicked is warned, with the + * field named by its label. + * + * The record page builds its own action runtime (its own flow handler, its own + * `FlowRunner` mount), so it is pinned apart from the list route + * (`useConsoleActionRuntime.flowDroppedFields-33009`). Harness as in + * `RecordDetailView.flowActionSuccessMessage-12234.test.tsx`: the real + * `RecordDetailView` against a stub data source whose `getObjectSchema` is the + * label source; its `ActionProvider` is captured on the way through and wired + * into a real `ActionRunner`. The flow handler, the launch module, the reader + * and `writeWarningToast` are real, under the real en pack. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, waitFor, act, cleanup } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; + +const authFetchSpy = vi.fn(); +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: { id: 'u1', name: 'Ada', image: null }, activeOrganization: null }), + createAuthenticatedFetch: () => authFetchSpy, +})); + +vi.mock('@object-ui/collaboration', async (importOriginal) => ({ + ...(await importOriginal>()), + useRecordPresence: () => [], + PresenceAvatars: () => null, +})); + +vi.mock('sonner', () => ({ + toast: Object.assign(vi.fn(), { + success: vi.fn(), + error: vi.fn(), + info: vi.fn(), + warning: vi.fn(), + loading: vi.fn(), + dismiss: vi.fn(), + }), +})); + +vi.mock('./MetadataInspector', () => ({ + MetadataPanel: () => null, + useMetadataInspector: () => ({ showDebug: false, toggle: () => {} }), +})); + +const captured: any[] = []; +vi.mock('@object-ui/react', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + ActionProvider: (props: any) => { + captured.push(props); + return React.createElement(actual.ActionProvider as any, props); + }, + SchemaRenderer: () => null, + }; +}); + +import { toast } from 'sonner'; +import { I18nProvider, MetadataCtx } from '@object-ui/react'; +import { ActionRunner } from '@object-ui/core'; +import { RecordDetailView } from './RecordDetailView'; + +const OBJECT_NAME = 'expense_report'; +const RECORD_ID = 'exp-7'; +const FLOW = 'expense_submit'; +const DECLARED = { name: 'submit_for_approval', label: '提交审批', type: 'flow', target: FLOW }; +const FIELDS = { + name: { type: 'text', label: 'Name' }, + status: { type: 'select', label: 'Approval status', readonly: true }, +}; + +function jsonResponse(body: unknown) { + return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } }); +} +const DROPPED = { + success: true, + data: { + success: true, + status: 'completed', + flowLabel: 'Submit', + droppedFields: [{ object: OBJECT_NAME, fields: ['status'], reason: 'readonly' }], + }, +}; +const CLEAN = { success: true, data: { success: true, status: 'completed', flowLabel: 'Submit' } }; + +const warnings = () => (toast as any).warning.mock.calls as unknown[][]; + +beforeEach(() => { + cleanup(); + captured.length = 0; + authFetchSpy.mockReset(); + for (const k of ['success', 'error', 'warning']) (toast as any)[k].mockClear(); + vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ data: [] }))); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +function recordPageProps() { + return [...captured].reverse().find((c) => c.handlers && c.context?.record?.id === RECORD_ID); +} + +/** Mount the record page, click 「提交审批」 through a real runner, the action door answering `answer`. */ +async function clickAnswering(answer: unknown) { + authFetchSpy.mockImplementation(async (url: string) => { + if (String(url).includes(`/api/v1/actions/${OBJECT_NAME}/submit_for_approval`)) return jsonResponse(answer); + return jsonResponse({ data: [] }); + }); + const objects = [{ name: OBJECT_NAME, label: 'Expense report', fields: FIELDS, actions: [DECLARED] }]; + const metadata = { + objects, + pages: [], + loading: false, + error: null, + refresh: async () => {}, + invalidate: () => {}, + ensureType: async () => [], + getItem: async () => null, + getItemsByType: () => [], + } as any; + render( + + + + ({ data: [] })), + findOne: vi.fn(async () => ({ id: RECORD_ID, name: 'EXP-0007', status: 'draft' })), + getObjectSchema: vi.fn(async () => ({ name: OBJECT_NAME, fields: FIELDS })), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + } as any} + objects={objects} + onEdit={() => {}} + objectNameOverride={OBJECT_NAME} + recordIdOverride={RECORD_ID} + embedded + /> + + + , + ); + await waitFor(() => expect(recordPageProps()).toBeTruthy()); + const props = recordPageProps(); + (toast as any).warning.mockClear(); + + const runner = new ActionRunner(props.context); + runner.setToastHandler(props.onToast); + for (const [type, handler] of Object.entries(props.handlers)) runner.registerHandler(type, handler as any); + + let result: any; + await act(async () => { + result = await runner.execute({ ...DECLARED } as any); + }); + const doorCalls = authFetchSpy.mock.calls.filter(([url]) => String(url).includes('/api/v1/actions/')); + expect(doorCalls.map(([url]) => String(url))).toEqual([`/api/v1/actions/${OBJECT_NAME}/submit_for_approval`]); + return result; +} + +describe('objectstack#33009 — the record page warns about a flow’s dropped read-only field', () => { + it('the #32666 shape: 「提交审批」 whose flow dropped readonly `status` warns, naming "Approval status"', async () => { + const result = await clickAnswering(DROPPED); + + expect(result).toMatchObject({ success: true }); + await waitFor(() => expect(warnings()).toHaveLength(1)); + expect(warnings()[0]).toEqual([ + 'Saved — but some fields did not take effect', + { description: 'Read-only, so it did not take effect: Approval status' }, + ]); + expect((toast as any).error).not.toHaveBeenCalled(); + }); + + it('control: a clean click warns about nothing', async () => { + const result = await clickAnswering(CLEAN); + + expect(result).toMatchObject({ success: true }); + await new Promise((r) => setTimeout(r, 0)); + expect(warnings()).toEqual([]); + }); +}); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 7f28eebcc56..35413ccf631 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -64,6 +64,7 @@ import { matchAppBySegment, resolveHostAppSegment } from '../utils/appRoute.js'; import { hostInConsolePath } from '../utils/hostInConsolePath.js'; import { recycleBinRefusalLabelsOf, recycleBinRestoreOf } from '../utils/recycleBinRestore.js'; import { launchConsoleFlow } from '../utils/flowLaunch.js'; +import type { TranslateFn } from '@object-ui/i18n'; import { apiActionRefusalResult } from '../utils/flowResponse.js'; import { findDeclaredApiAction, isSameOriginApiTarget, readApiActionDoorSuccess, sendApiActionThroughDoor } from '../utils/apiActionDoor.js'; import { useNavigationContext, useRecordBreadcrumbTitle } from '../context/NavigationContext.js'; @@ -2050,6 +2051,9 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri triggerParams: flowParams, objects, language, + // The run's `droppedFields` warning (objectstack#33009): labels read + // through this page's data source, the console's adapter. + droppedFields: { t: t as TranslateFn, fieldLabel, dataSource }, }); const judged = launch.judged; // Paused at a `screen` node: FlowRunner renders the form + resumes, and @@ -2075,7 +2079,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri } catch (error) { return { success: false, error: (error as Error).message }; } - }, [authFetch, pureRecordId, objectName, objects, language]); + }, [authFetch, pureRecordId, objectName, objects, language, t, fieldLabel, dataSource]); // Server-side action handler — POST /api/v1/actions/{object}/{action}, // built from @object-ui/core's `createServerActionHandler` via the shared diff --git a/ui/packages/data-objectstack/src/index.ts b/ui/packages/data-objectstack/src/index.ts index 373eca2c733..8618c2b218f 100644 --- a/ui/packages/data-objectstack/src/index.ts +++ b/ui/packages/data-objectstack/src/index.ts @@ -2444,7 +2444,7 @@ export type DroppedFieldsNotice = DroppedFieldsEvent | UnrecognizedDropReasonEve * {@link WriteWarningEvent} — is unchanged: a subscriber's `fields: string[]` * stays `string[]` and is now TRUE rather than asserted. */ -type WireDroppedFieldsEntry = { object?: unknown; fields: unknown[]; reason?: unknown }; +export type WireDroppedFieldsEntry = { object?: unknown; fields: unknown[]; reason?: unknown }; /** Whether the wire's `reason` is an arm the installed spec pin declares. */ function isRecognizedDropReason(reason: unknown): reason is DroppedFieldsEvent['reason'] { @@ -2466,8 +2466,14 @@ function isRecognizedDropReason(reason: unknown): reason is DroppedFieldsEvent[' * them: both are parsed afterwards, so a missing `object` or an unnameable * `reason` still reaches the user as the warning it is (objectui#3484's * silence is the worse failure). + * + * Exported with {@link asDroppedFieldsNotice} (objectstack#33009): a flow + * run's answer carries the same `droppedFields` wire (`AutomationResult`, + * objectstack#32861) but reaches the console outside this adapter, so its + * reader (`app-shell`'s `utils/flowDroppedFields`) parses it with these two — + * one parser for every `droppedFields` the console reads, never a second copy. */ -function isWireDroppedFieldsEntry(e: unknown): e is WireDroppedFieldsEntry { +export function isWireDroppedFieldsEntry(e: unknown): e is WireDroppedFieldsEntry { return ( !!e && typeof e === 'object' && @@ -2506,7 +2512,7 @@ function isWireDroppedFieldsEntry(e: unknown): e is WireDroppedFieldsEntry { * Extra server-sent keys still ride along: the spread preserves them, and only * the three parsed keys are rewritten. */ -function asDroppedFieldsNotice( +export function asDroppedFieldsNotice( entry: WireDroppedFieldsEntry, fallbackObject: string, ): DroppedFieldsNotice { From ab4b072018afc662bf97bdff2927adcbe3bad66c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 06:10:59 +0000 Subject: [PATCH 2/3] refactor(app-shell): the flow droppedFields reader lives in flowLaunch, inside the claimed file surface Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwVkQ2wgvSKnhkFnys --- ...=> flowLaunch.droppedFields-33009.test.ts} | 3 +- .../app-shell/src/utils/flowDroppedFields.ts | 134 ------------------ ui/packages/app-shell/src/utils/flowLaunch.ts | 126 +++++++++++++++- .../app-shell/src/views/FlowRunner.tsx | 2 +- 4 files changed, 127 insertions(+), 138 deletions(-) rename ui/packages/app-shell/src/utils/__tests__/{flowDroppedFields-33009.test.ts => flowLaunch.droppedFields-33009.test.ts} (97%) delete mode 100644 ui/packages/app-shell/src/utils/flowDroppedFields.ts diff --git a/ui/packages/app-shell/src/utils/__tests__/flowDroppedFields-33009.test.ts b/ui/packages/app-shell/src/utils/__tests__/flowLaunch.droppedFields-33009.test.ts similarity index 97% rename from ui/packages/app-shell/src/utils/__tests__/flowDroppedFields-33009.test.ts rename to ui/packages/app-shell/src/utils/__tests__/flowLaunch.droppedFields-33009.test.ts index 38d484fced0..b271912b9d3 100644 --- a/ui/packages/app-shell/src/utils/__tests__/flowDroppedFields-33009.test.ts +++ b/ui/packages/app-shell/src/utils/__tests__/flowLaunch.droppedFields-33009.test.ts @@ -24,8 +24,7 @@ import { UNRECOGNIZED_DROP_REASON } from '@object-ui/data-objectstack'; const toasts = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn(), warning: vi.fn(), info: vi.fn() })); vi.mock('sonner', () => ({ toast: toasts })); -import { announceFlowDroppedFields, flowAnswerDroppedFields } from '../flowDroppedFields'; -import { launchConsoleFlow } from '../flowLaunch'; +import { announceFlowDroppedFields, flowAnswerDroppedFields, launchConsoleFlow } from '../flowLaunch'; const SCHEMAS: Record }> = { expense_report: { fields: { status: { label: 'Approval status' } } }, diff --git a/ui/packages/app-shell/src/utils/flowDroppedFields.ts b/ui/packages/app-shell/src/utils/flowDroppedFields.ts deleted file mode 100644 index 0067b6ddf4a..00000000000 --- a/ui/packages/app-shell/src/utils/flowDroppedFields.ts +++ /dev/null @@ -1,134 +0,0 @@ -/** - * 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. - */ - -/** - * The ONE reader of a flow run's `droppedFields` (objectstack#33009, the - * console half of objectstack#32861). - * - * A flow's `update_record` / `create_record` step that writes a field the data - * engine will not store (the #32666 case: 「提交审批」 writes `status`, which - * is `readonly: true`) used to lose the value in silence: the step succeeded, - * the run answered success, the record stayed 「草稿」 and the person who - * clicked saw nothing. The run's answer now names those fields - * (`AutomationResult.droppedFields`, objectstack#32861): the data engine's own - * `DroppedFieldsEvent`s, one per object and reason, set only when a field was - * dropped. This module turns that member into the same warning toast a record - * save shows for the same strip. - * - * Three hosts read a flow answer and all three come through here: the two - * launch handlers (`useConsoleActionRuntime`, `RecordDetailView`) through - * `launchConsoleFlow`, and `FlowRunner`'s resume of a paused screen run, whose - * terminal answer is where a write after the pause reports its drop. - * - * - **Parse**: `@object-ui/data-objectstack`'s own wire gate and parser - * (`isWireDroppedFieldsEntry`, `asDroppedFieldsNotice`), with its skew arm - * for a `reason` this bundle's spec pin cannot name. ⛔ Never a second copy. - * - **Speak**: `writeWarningToast.emitWriteWarning`, the record save's own - * message — the same title, the same per-reason sentence, the same field - * labels. The flow DID write the record, so its "Saved — but some fields did - * not take effect" title is true here too. - * - **Labels**: from the host's `dataSource`, which in the console IS the - * `ObjectStackAdapter` (`useAdapter()`, cached `getObjectSchema`), so the - * label path is the one `AdapterProvider` hands the save toast. Each host - * already holds it (it is what renders its forms), so no host gains a new - * dependency. A data source without `getObjectSchema` (a test stub) names - * fields by api name, which is still the truthful answer. - * - * One event per object: a flow can write any object, and a label is looked up - * on the object the entry names. Folding a second object's fields under the - * clicked record's object would label `status` with that object's `status`. - * - * A PRESENT member is a drop; an ABSENT one is not proof of none. A `map` - * item's run and a `subflow` child that paused do not roll their drops up yet - * (objectstack#33019), so nothing here ever says "every field was written". - */ - -import { toast } from 'sonner'; -import { - asDroppedFieldsNotice, - isWireDroppedFieldsEntry, - type DroppedFieldsNotice, - type ObjectStackAdapter, -} from '@object-ui/data-objectstack'; -import { - emitWriteWarning, - type FieldLabelFn, - type TranslateFn, - type WriteWarningSink, -} from '../providers/writeWarningToast.js'; - -/** - * What an entry whose wire `object` is missing is attributed to: nothing. - * The spec requires `object`, so only an off-spec answer reaches this; a flow - * can write any object, so the clicked record's object would be a guess. - * Falsy on purpose: `emitWriteWarning` skips the label lookup for an empty - * resource and names the fields by api name. - */ -const UNATTRIBUTED_FLOW_DROP = ''; - -/** What the hosts hand the reader: the translator, the label convention, the data source. */ -export interface FlowDroppedFieldsContext { - t: TranslateFn; - fieldLabel: FieldLabelFn; - /** The host's data source; read for `getObjectSchema` only. */ - dataSource: unknown; -} - -/** - * The parsed `droppedFields` of a flow answer (`{ success, data: AutomationResult }`), - * in wire order; empty when the answer carries none. - */ -export function flowAnswerDroppedFields(json: unknown): DroppedFieldsNotice[] { - const wire = (json as { data?: { droppedFields?: unknown } } | null | undefined)?.data?.droppedFields; - if (!Array.isArray(wire)) return []; - return wire - .filter(isWireDroppedFieldsEntry) - .map((e) => asDroppedFieldsNotice(e, UNATTRIBUTED_FLOW_DROP)); -} - -function schemaSource(dataSource: unknown): Pick | null { - const ds = dataSource as { getObjectSchema?: unknown } | null | undefined; - return ds && typeof ds.getObjectSchema === 'function' - ? (ds as Pick) - : null; -} - -/** - * Warn the person who started the run about every field its write steps - * dropped: one `emitWriteWarning` per object, nothing when the answer names - * none. Never throws — the run already happened, and a failed label lookup - * must not turn it into an error. - */ -export async function announceFlowDroppedFields( - json: unknown, - ctx: FlowDroppedFieldsContext, - sink: WriteWarningSink = toast, -): Promise { - const byObject = new Map(); - for (const notice of flowAnswerDroppedFields(json)) { - const object = notice.object ?? UNATTRIBUTED_FLOW_DROP; - byObject.set(object, [...(byObject.get(object) ?? []), notice]); - } - const adapter = schemaSource(ctx.dataSource); - for (const [object, droppedFields] of byObject) { - try { - await emitWriteWarning( - // `operation` is required by the event type and read only by a record - // save surface's answer-warnings claim, which a flow event (no - // `warnings`, no `notice`) never reaches; the toast does not show it. - { operation: 'update', resource: object, droppedFields }, - ctx.t, - adapter, - ctx.fieldLabel, - sink, - ); - } catch (err) { - console.warn('flowDroppedFields: could not announce dropped fields', err); - } - } -} diff --git a/ui/packages/app-shell/src/utils/flowLaunch.ts b/ui/packages/app-shell/src/utils/flowLaunch.ts index aa9902851c3..a652ff2943a 100644 --- a/ui/packages/app-shell/src/utils/flowLaunch.ts +++ b/ui/packages/app-shell/src/utils/flowLaunch.ts @@ -88,8 +88,132 @@ import { toast } from 'sonner'; import { createServerActionHandler } from '@object-ui/core'; import type { ActionDef, ActionResult, ServerActionFetch } from '@object-ui/core'; +import { + asDroppedFieldsNotice, + isWireDroppedFieldsEntry, + type DroppedFieldsNotice, + type ObjectStackAdapter, +} from '@object-ui/data-objectstack'; +import { + emitWriteWarning, + type FieldLabelFn, + type TranslateFn, + type WriteWarningSink, +} from '../providers/writeWarningToast.js'; import { interpretFlowResponse, judgeFlowLaunch, type FlowLaunchJudgement } from './flowResponse.js'; -import { announceFlowDroppedFields, type FlowDroppedFieldsContext } from './flowDroppedFields.js'; + +/* + * ## The ONE reader of a flow run's `droppedFields` (objectstack#33009, the + * console half of objectstack#32861) + * + * A flow's `update_record` / `create_record` step that writes a field the data + * engine will not store (the #32666 case: 「提交审批」 writes `status`, which + * is `readonly: true`) used to lose the value in silence: the step succeeded, + * the run answered success, the record stayed 「草稿」 and the person who + * clicked saw nothing. The run's answer now names those fields + * (`AutomationResult.droppedFields`, objectstack#32861): the data engine's own + * `DroppedFieldsEvent`s, one per object and reason, set only when a field was + * dropped. {@link announceFlowDroppedFields} turns that member into the + * same warning toast a record save shows for the same strip. + * + * Three hosts read a flow answer and all three come through here: the two + * launch handlers (`useConsoleActionRuntime`, `RecordDetailView`) through + * `launchConsoleFlow`, and `FlowRunner`'s resume of a paused screen run, whose + * terminal answer is where a write after the pause reports its drop. + * + * - **Parse**: `@object-ui/data-objectstack`'s own wire gate and parser + * (`isWireDroppedFieldsEntry`, `asDroppedFieldsNotice`), with its skew arm + * for a `reason` this bundle's spec pin cannot name. ⛔ Never a second copy. + * - **Speak**: `writeWarningToast.emitWriteWarning`, the record save's own + * message — the same title, the same per-reason sentence, the same field + * labels. The flow DID write the record, so its "Saved — but some fields did + * not take effect" title is true here too. + * - **Labels**: from the host's `dataSource`, which in the console IS the + * `ObjectStackAdapter` (`useAdapter()`, cached `getObjectSchema`), so the + * label path is the one `AdapterProvider` hands the save toast. Each host + * already holds it (it is what renders its forms), so no host gains a new + * dependency. A data source without `getObjectSchema` (a test stub) names + * fields by api name, which is still the truthful answer. + * + * One event per object: a flow can write any object, and a label is looked up + * on the object the entry names. Folding a second object's fields under the + * clicked record's object would label `status` with that object's `status`. + * + * A PRESENT member is a drop; an ABSENT one is not proof of none. A `map` + * item's run and a `subflow` child that paused do not roll their drops up yet + * (objectstack#33019), so nothing here ever says "every field was written". + */ + +/** + * What an entry whose wire `object` is missing is attributed to: nothing. + * The spec requires `object`, so only an off-spec answer reaches this; a flow + * can write any object, so the clicked record's object would be a guess. + * Falsy on purpose: `emitWriteWarning` skips the label lookup for an empty + * resource and names the fields by api name. + */ +const UNATTRIBUTED_FLOW_DROP = ''; + +/** What the hosts hand the reader: the translator, the label convention, the data source. */ +export interface FlowDroppedFieldsContext { + t: TranslateFn; + fieldLabel: FieldLabelFn; + /** The host's data source; read for `getObjectSchema` only. */ + dataSource: unknown; +} + +/** + * The parsed `droppedFields` of a flow answer (`{ success, data: AutomationResult }`), + * in wire order; empty when the answer carries none. + */ +export function flowAnswerDroppedFields(json: unknown): DroppedFieldsNotice[] { + const wire = (json as { data?: { droppedFields?: unknown } } | null | undefined)?.data?.droppedFields; + if (!Array.isArray(wire)) return []; + return wire + .filter(isWireDroppedFieldsEntry) + .map((e) => asDroppedFieldsNotice(e, UNATTRIBUTED_FLOW_DROP)); +} + +function schemaSource(dataSource: unknown): Pick | null { + const ds = dataSource as { getObjectSchema?: unknown } | null | undefined; + return ds && typeof ds.getObjectSchema === 'function' + ? (ds as Pick) + : null; +} + +/** + * Warn the person who started the run about every field its write steps + * dropped: one `emitWriteWarning` per object, nothing when the answer names + * none. Never throws — the run already happened, and a failed label lookup + * must not turn it into an error. + */ +export async function announceFlowDroppedFields( + json: unknown, + ctx: FlowDroppedFieldsContext, + sink: WriteWarningSink = toast, +): Promise { + const byObject = new Map(); + for (const notice of flowAnswerDroppedFields(json)) { + const object = notice.object ?? UNATTRIBUTED_FLOW_DROP; + byObject.set(object, [...(byObject.get(object) ?? []), notice]); + } + const adapter = schemaSource(ctx.dataSource); + for (const [object, droppedFields] of byObject) { + try { + await emitWriteWarning( + // `operation` is required by the event type and read only by a record + // save surface's answer-warnings claim, which a flow event (no + // `warnings`, no `notice`) never reaches; the toast does not show it. + { operation: 'update', resource: object, droppedFields }, + ctx.t, + adapter, + ctx.fieldLabel, + sink, + ); + } catch (err) { + console.warn('flowLaunch: could not announce dropped fields', err); + } + } +} /** The door a flow click went through. */ export type ConsoleFlowLaunchDoor = 'action' | 'trigger'; diff --git a/ui/packages/app-shell/src/views/FlowRunner.tsx b/ui/packages/app-shell/src/views/FlowRunner.tsx index 73b68129429..c22bcf22da4 100644 --- a/ui/packages/app-shell/src/views/FlowRunner.tsx +++ b/ui/packages/app-shell/src/views/FlowRunner.tsx @@ -348,7 +348,7 @@ import { type ScreenSpec, } from './ScreenView.js'; import { flowSuccessCopy, interpretFlowResponse } from '../utils/flowResponse.js'; -import { announceFlowDroppedFields } from '../utils/flowDroppedFields.js'; +import { announceFlowDroppedFields } from '../utils/flowLaunch.js'; import { activeFlowsBundle, type FlowsTranslation } from '../utils/flowsBundle.js'; export type { ScreenSpec, ScreenFieldSpec } from './ScreenView.js'; From 0f69f38ae7f1d3f63c1503eea68f008c1158615b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 06:51:25 +0000 Subject: [PATCH 3/3] fix(data-objectstack): the changeset ships patch, and the parser's doc names the reader where it lives Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwVkQ2wgvSKnhkFnys --- .changeset/33009-flow-dropped-fields-toast.md | 2 +- ui/packages/data-objectstack/src/index.ts | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/.changeset/33009-flow-dropped-fields-toast.md b/.changeset/33009-flow-dropped-fields-toast.md index 6a8b59606e3..454efb36cc7 100644 --- a/.changeset/33009-flow-dropped-fields-toast.md +++ b/.changeset/33009-flow-dropped-fields-toast.md @@ -1,5 +1,5 @@ --- -'@object-ui/data-objectstack': minor +'@object-ui/data-objectstack': patch '@object-ui/app-shell': patch --- diff --git a/ui/packages/data-objectstack/src/index.ts b/ui/packages/data-objectstack/src/index.ts index 8618c2b218f..6e4fc627e53 100644 --- a/ui/packages/data-objectstack/src/index.ts +++ b/ui/packages/data-objectstack/src/index.ts @@ -2470,8 +2470,9 @@ function isRecognizedDropReason(reason: unknown): reason is DroppedFieldsEvent[' * Exported with {@link asDroppedFieldsNotice} (objectstack#33009): a flow * run's answer carries the same `droppedFields` wire (`AutomationResult`, * objectstack#32861) but reaches the console outside this adapter, so its - * reader (`app-shell`'s `utils/flowDroppedFields`) parses it with these two — - * one parser for every `droppedFields` the console reads, never a second copy. + * reader (`app-shell`'s `announceFlowDroppedFields` in `utils/flowLaunch`) + * parses it with these two — one parser for every `droppedFields` the + * console reads, never a second copy. */ export function isWireDroppedFieldsEntry(e: unknown): e is WireDroppedFieldsEntry { return (