From bd71f4dc5d68511afde2d10ef85758bbcbd5a737 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 09:09:06 +0000 Subject: [PATCH 1/4] fix(runtime): bind a resume approval to the screen it was given on A handed-off resume_run now names the screen its values were given for (ActionConfirmationHandOff.run.screenNodeId). dispatchActionResume takes it back and step 5 refuses a run no longer paused on that screen with 409 RESOURCE_CONFLICT, leaving the run where it is. An elicited approval is bound the same way. Without the key, the current screen is resumed as before. Claude-Session: https://claude.ai/code/session_01ADHkmSKdmdbBugjg8QSZGa Co-authored-by: Claude --- .../34515-resume-approval-bound-to-screen.md | 18 ++ content/docs/ui/actions.mdx | 16 +- ...confirmation-handoff-33690.dogfood.test.ts | 103 +++++++++++- .../action-confirmation-handoff-33690.test.ts | 157 +++++++++++++++++- packages/runtime/src/action-dispatch.ts | 9 + packages/runtime/src/action-execution.ts | 5 +- packages/runtime/src/domains/mcp.ts | 83 +++++++-- packages/spec/src/contracts/ai-service.ts | 28 +++- 8 files changed, 385 insertions(+), 34 deletions(-) create mode 100644 .changeset/34515-resume-approval-bound-to-screen.md diff --git a/.changeset/34515-resume-approval-bound-to-screen.md b/.changeset/34515-resume-approval-bound-to-screen.md new file mode 100644 index 00000000000..422c89b8061 --- /dev/null +++ b/.changeset/34515-resume-approval-bound-to-screen.md @@ -0,0 +1,18 @@ +--- +'@objectstack/spec': patch +'@objectstack/runtime': patch +--- + +fix(runtime): a resume approval is bound to the screen it was given on, so a wizard that moved on is never handed the earlier screen's values + +Clause-②: yes (widening) +Metadata-protocol: none + +A multi-screen wizard stays paused under the same run id as it moves from screen to screen. So when the MCP `resume_run` tool handed a resume to the person (an action that declares `ai.requiresConfirmation: true`), a second resume of the same pending item was still admitted after the first approval had moved the wizard on: the values given for the first screen were submitted to the next screen, as the approver. The same happened when the agent called `resume_run` twice (two pending items), and when the person advanced the wizard in the app before the item was approved. + +- The hand-off now names the screen its values were given for: `ActionConfirmationHandOff.run.screenNodeId` (the `ScreenSpec.nodeId` the run was parked on). It is optional and absent only when the engine named no node. +- `dispatchActionResume` takes the same optional `screenNodeId`. A host that stores it with the pending item and passes it back on approval binds the approval to that screen: a run no longer paused on it is refused `409 RESOURCE_CONFLICT`, nothing resumes, and the run stays where it is. A `screenNodeId` that is not a non-empty string is refused `400`. +- An elicited approval (a client that can be asked in place) is bound the same way: if the wizard moved on while the person was being asked, the resume is refused `409 RESOURCE_CONFLICT`. +- Nothing already accepted is refused: a call that passes no `screenNodeId` resumes the run's current screen, as before. A host should pass it to get the binding. + +Limit: a wizard that loops back to the same screen node cannot be told apart by node id; no flow doing that has been found in use. diff --git a/content/docs/ui/actions.mdx b/content/docs/ui/actions.mdx index b87e78f74e5..c7f32423d7a 100644 --- a/content/docs/ui/actions.mdx +++ b/content/docs/ui/actions.mdx @@ -768,7 +768,8 @@ whose package is disabled is **404** `OBJECT_PACKAGE_DISABLED`. When the MCP `resume_run` tool hands a resume to the person (an action that declares `ai.requiresConfirmation: true`, on a host with a pending-confirmation -service), the hand-off carries the paused run: `run: { runId, values }`. +service), the hand-off carries the paused run: `run: { runId, values, screenNodeId }`, +where `screenNodeId` names the screen the values were given for. Your approve door resumes that run with `dispatchActionResume`, as the person who approved it, instead of re-implementing the `resume_run` checks: @@ -780,6 +781,7 @@ const answer = await dispatchActionResume(kernel, { environmentId, // optional, placed as for dispatchAction runId: handOff.run.runId, values: handOff.run.values, + screenNodeId: handOff.run.screenNodeId, // binds the approval to that screen confirm: true, // the person's confirmation }); if (answer.status !== 200) throw answer.body.error; @@ -791,11 +793,13 @@ paused and must have been started by them (otherwise **404** that admits the run must pass every `run_action` check, the record is read again as them, and the run must be paused on a screen (otherwise **409**). The run then resumes; it never starts a new run and is never handed off again. -Only a run that is no longer paused is refused: a wizard your approval moved -on to its next screen is still paused under the same run id, so calling again -with the same hand-off resumes that next screen with the same values. Decide -each pending item once in your approve door, and void an item whose run has -moved on. Without `confirm: true`, an action that declares +A wizard stays paused under the same run id as it moves from screen to +screen, so pass `screenNodeId` back: when the run is no longer on that screen +(an earlier approval of the same item moved it on, or the person advanced it +in the app) the call is refused **409** `RESOURCE_CONFLICT`, nothing resumes, +and the run stays where it is. Without `screenNodeId`, the run's current +screen is resumed with the values given. Decide each pending item once in +your approve door. Without `confirm: true`, an action that declares `ai.requiresConfirmation: true` is refused **428** `ACTION_CONFIRMATION_REQUIRED`, and an AI service account is refused whatever it sends. The answer is the REST envelope, with `resume_run`'s `{ ok, action, objectName, recordId, result }` as diff --git a/packages/qa/dogfood/test/action-confirmation-handoff-33690.dogfood.test.ts b/packages/qa/dogfood/test/action-confirmation-handoff-33690.dogfood.test.ts index 301a65439dd..4abe7805f12 100644 --- a/packages/qa/dogfood/test/action-confirmation-handoff-33690.dogfood.test.ts +++ b/packages/qa/dogfood/test/action-confirmation-handoff-33690.dogfood.test.ts @@ -23,11 +23,19 @@ // is written and nobody is asked; // ⭐ CONTROL: the same update through an action that declares no // confirmation runs at once, and nobody is asked. +// ⭐ [#34515] a `resume_run` hand-off on a two-screen wizard names the +// screen its values were given for; the host approves it through +// `dispatchActionResume` with that screen, and a second approval of +// the same item (or one approved after the person advanced the wizard +// in the app) is refused 409 `RESOURCE_CONFLICT` with the run left on +// the next screen. CONTROL: a single-screen run approved with its +// screen completes. import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { type VerifyStack } from '@objectstack/verify'; import { bootStack } from '@objectstack/verify'; import { MCPServerPlugin } from '@objectstack/mcp'; +import { dispatchActionResume } from '@objectstack/runtime'; import { defineStack } from '@objectstack/spec'; import { ObjectSchema, Field } from '@objectstack/spec/data'; import { PermissionSetSchema, type PermissionSet } from '@objectstack/spec/security'; @@ -38,6 +46,11 @@ import { catalogPermissionSet } from './catalog-permission-set.js'; const OBJECT = 'achoff_ticket'; const GATED = 'achoff_close_ticket'; const PLAIN = 'achoff_flag_ticket'; +/** [#34515] A gated flow action whose screen flow is a two-screen wizard, and one whose flow has one screen. */ +const WIZARD_ACTION = 'achoff_close_wizard'; +const WIZARD_FLOW = 'achoff_close_wizard'; +const ONE_SCREEN_ACTION = 'achoff_close_one_screen'; +const ONE_SCREEN_FLOW = 'achoff_close_one_screen'; const PERSON = 'achoff-person@verify.test'; const SYS = { context: { isSystem: true } } as const; const N = 3; @@ -60,9 +73,31 @@ const ticket = ObjectSchema.create({ name: PLAIN, label: 'Flag Ticket', objectName: OBJECT, operation: 'update', patch: { status: 'flagged' }, ai: { exposed: true, description: 'Flag the ticket so a person looks at it during the next review.' }, }, + { + name: WIZARD_ACTION, label: 'Close Ticket (wizard)', objectName: OBJECT, type: 'flow', target: WIZARD_FLOW, + ai: { exposed: true, description: 'Walk the two-step close wizard for this ticket: a reason, then a final sign-off.', requiresConfirmation: true }, + }, + { + name: ONE_SCREEN_ACTION, label: 'Close Ticket (one screen)', objectName: OBJECT, type: 'flow', target: ONE_SCREEN_FLOW, + ai: { exposed: true, description: 'Close this ticket after asking for a comment on one screen.', requiresConfirmation: true }, + }, ], } as never); +/** A screen node collecting an optional `comment`: both wizard screens accept the same bag. */ +const commentScreen = (id: string, title: string) => ({ + id, type: 'screen', label: title, config: { title, fields: [{ name: 'comment', label: 'Comment', type: 'text' }] }, +}); +/** A screen flow walking `screens` in order, start to end. */ +const screenFlow = (name: string, screens: Array>) => { + const path = ['start', ...screens.map((n) => n.id), 'end']; + return { + name, label: name, type: 'screen', status: 'active', runAs: 'user', + nodes: [{ id: 'start', type: 'start', label: 'Start' }, ...screens, { id: 'end', type: 'end', label: 'End' }], + edges: path.slice(1).map((target, i) => ({ id: `e${i}`, source: path[i], target })), + }; +}; + const stackConfig = defineStack({ manifest: { id: 'com.dogfood.action-confirmation-handoff', @@ -72,8 +107,13 @@ const stackConfig = defineStack({ name: 'Action Confirmation Hand-off Fixture', description: 'One object with a confirmation-gated declarative update, run over MCP.', }, + requires: ['automation'], objects: [ticket], -}); + flows: [ + screenFlow(WIZARD_FLOW, [commentScreen('step_1', 'Step 1: reason'), commentScreen('step_2', 'Step 2: final sign-off')]), + screenFlow(ONE_SCREEN_FLOW, [commentScreen('step_1', 'Comment')]), + ], +} as never); const baselineSet: PermissionSet = PermissionSetSchema.parse({ name: 'achoff_baseline', @@ -192,4 +232,65 @@ describe('[#33690] a confirmation-gated action over MCP is handed to the person, expect(await statusOf(id)).toBe('flagged'); expect(handOffs.length).toBe(before); }, 120_000); + + // ── [#34515] a resume approval is bound to the screen it was given on ────── + const automation = () => (stack.kernel as any).getService('automation'); + const screenOf = async (runId: string) => (await automation().getSuspendedScreen(runId))?.nodeId ?? null; + /** The person starts the gated flow action in the app (REST, their confirm): the run pauses on its first screen. */ + const startPaused = async (action: string, id: string): Promise => { + const res = await stack.apiAs(person, 'POST', `/actions/${OBJECT}/${action}/${id}`, { [AI_ACTION_CONFIRMATION_MEMBER]: true }); + const body: any = await res.json(); + expect(res.status, JSON.stringify(body)).toBe(200); + const result = body?.data?.result ?? body?.data; + expect(result?.status, JSON.stringify(body)).toBe('paused'); + return String(result.runId); + }; + /** The agent's `resume_run`, handed to the person: the hand-off it recorded. */ + const handOffOf = async (runId: string, comment: string) => { + const held = await tool('resume_run', { runId, values: { comment } }); + expect(held.payload, held.text).toMatchObject({ status: 'pending_confirmation' }); + return handOffs.at(-1)!.handOff.run as { runId: string; values: Record; screenNodeId?: string }; + }; + /** The host's approve door: the approving person, through `dispatchActionResume`, with the item's screen. */ + const approve = (run: { runId: string; values: Record; screenNodeId?: string }) => + dispatchActionResume(stack.kernel as never, { + executionContext: { userId: personId } as never, runId: run.runId, values: run.values, screenNodeId: run.screenNodeId, confirm: true, + }); + + it('⭐ [#34515] the same item approved twice on a two-screen wizard: the first resumes step 1, the second is refused 409', async () => { + const runId = await startPaused(WIZARD_ACTION, await openTicket('wizard-twice')); + const run = await handOffOf(runId, 'meant for step 1'); + expect(run.screenNodeId).toBe('step_1'); + + const first = await approve(run); + expect(first.status, JSON.stringify(first.body)).toBe(200); + expect(await screenOf(runId)).toBe('step_2'); + + const second = await approve(run); + expect({ status: second.status, code: second.body.error?.code }, JSON.stringify(second.body)).toEqual({ status: 409, code: 'RESOURCE_CONFLICT' }); + expect((await automation().getRun(runId))?.status).toBe('paused'); + expect(await screenOf(runId), 'the refused approval moved the run').toBe('step_2'); + }, 120_000); + + it('⭐ [#34515] an item approved after the person advanced the wizard in the app is refused 409', async () => { + const runId = await startPaused(WIZARD_ACTION, await openTicket('wizard-advanced')); + const run = await handOffOf(runId, 'agent, for step 1'); + const inApp = await stack.apiAs(person, 'POST', `/automation/${WIZARD_FLOW}/runs/${runId}/resume`, { inputs: { comment: 'typed in the app' } }); + expect(inApp.status, await inApp.clone().text()).toBe(200); + expect(await screenOf(runId)).toBe('step_2'); + + const refused = await approve(run); + expect({ status: refused.status, code: refused.body.error?.code }, JSON.stringify(refused.body)).toEqual({ status: 409, code: 'RESOURCE_CONFLICT' }); + expect(await screenOf(runId)).toBe('step_2'); + }, 120_000); + + it('CONTROL [#34515]: a single-screen run approved with its screen completes', async () => { + const runId = await startPaused(ONE_SCREEN_ACTION, await openTicket('one-screen')); + const run = await handOffOf(runId, 'only screen'); + expect(run.screenNodeId).toBe('step_1'); + + const answer = await approve(run); + expect(answer.status, JSON.stringify(answer.body)).toBe(200); + expect((await automation().getRun(runId))?.status).toBe('completed'); + }, 120_000); }); diff --git a/packages/runtime/src/action-confirmation-handoff-33690.test.ts b/packages/runtime/src/action-confirmation-handoff-33690.test.ts index 1b385471099..d881267703b 100644 --- a/packages/runtime/src/action-confirmation-handoff-33690.test.ts +++ b/packages/runtime/src/action-confirmation-handoff-33690.test.ts @@ -67,6 +67,8 @@ const PLAIN = { }; const SCREEN = { nodeId: 'screen_1', title: 'Reason', fields: [{ name: 'reason', label: 'Reason', type: 'text', required: true }] }; +/** [#34515] The second screen of a two-screen wizard: it collects a field of the same name. */ +const SCREEN_2 = { nodeId: 'screen_2', title: 'Final sign-off', fields: [{ name: 'reason', label: 'Reason', type: 'text', required: true }] }; const PERSON = { userId: 'u1', systemPermissions: [] as string[] }; const DELEGATED = { userId: 'u1', principalKind: 'agent', onBehalfOf: { userId: 'u1', principalKind: 'human' }, systemPermissions: [] as string[] }; @@ -78,19 +80,21 @@ function makeConfirmationService() { return { submit: vi.fn(async (_handOff: unknown, _ec: unknown) => ({ pendingId: `pa_${++n}` })) }; } -function makeHarness(opts: { service?: unknown; audit?: unknown } = {}) { +function makeHarness(opts: { service?: unknown; audit?: unknown; screens?: ReadonlyArray } = {}) { + // [#34515] The screens the flow walks, in order: one by default; a wizard has two. + const screens = opts.screens ?? [SCREEN]; const leads = [ { id: 'lead_1', owner: 'u1', name: 'Ada', status: 'open' }, { id: 'lead_2', owner: 'u2', name: 'Grace', status: 'open' }, ]; - const runs = new Map(); + const runs = new Map(); let r = 0; const automation = { getFlow: vi.fn(async (name: string) => ({ name })), execute: vi.fn(async (flowName: string, ctx: any) => { const runId = `run_${++r}`; - runs.set(runId, { flowName, userId: ctx?.userId, recordId: ctx?.record?.id, status: 'paused' }); - return { success: true, status: 'paused', runId, durationMs: 1, screen: SCREEN }; + runs.set(runId, { flowName, userId: ctx?.userId, recordId: ctx?.record?.id, status: 'paused', screen: 0 }); + return { success: true, status: 'paused', runId, durationMs: 1, screen: screens[0] }; }), getRun: vi.fn(async (runId: string) => { const run = runs.get(runId); @@ -99,9 +103,18 @@ function makeHarness(opts: { service?: unknown; audit?: unknown } = {}) { trigger: { type: 'manual', userId: run.userId, object: OBJECT, recordId: run.recordId }, steps: [], } : null; }), - getSuspendedScreen: vi.fn(async (runId: string) => (runs.get(runId)?.status === 'paused' ? SCREEN : null)), + getSuspendedScreen: vi.fn(async (runId: string) => { + const run = runs.get(runId); + return run?.status === 'paused' ? screens[run.screen] : null; + }), + // A resume submits the current screen and moves the run on to the next + // one, still `paused` under the same run id, or completes it after the last. resume: vi.fn(async (runId: string) => { const run = runs.get(runId)!; + run.screen += 1; + if (run.screen < screens.length) { + return { success: true, status: 'paused', runId, durationMs: 1, screen: screens[run.screen] }; + } run.status = 'completed'; return { success: true, status: 'completed', output: {}, durationMs: 1 }; }), @@ -324,7 +337,8 @@ describe('[#33690] resume_run: a resume of a gated action is handed off carrying // The parked run rides the hand-off, so approving it resumes THAT run. expect((service.submit.mock.calls[0] as any[])[0]).toEqual({ actionName: GATED_FLOW.name, objectName: OBJECT, recordId: 'lead_1', params: {}, door: 'mcp', - run: { runId, values: { reason: 'dup' } }, + // [#34515] ...with the screen its values were given for. + run: { runId, values: { reason: 'dup' }, screenNodeId: SCREEN.nodeId }, }); }); @@ -716,3 +730,134 @@ describe('[#34386] dispatchActionResume: approving a handed-off resume_run resum expect(h.automation.getRun).not.toHaveBeenCalled(); }); }); + +/** + * [#34515] An approval is bound to the screen it was given on. A multi-screen + * wizard stays `paused` under the same run id as it moves from screen to + * screen, so without the binding a second resume of the same hand-off (a + * retried approval, a second `resume_run` call's item, or an item approved + * after the person advanced the wizard in the app) submitted the first + * screen's values to the next screen, as the approver. The hand-off now names + * the screen (`run.screenNodeId`), the host passes it back to + * `dispatchActionResume`, and step 5 refuses a run on another screen + * `409 RESOURCE_CONFLICT`, leaving it where it is. + */ +describe('[#34515] a resume approval is bound to the screen it was given on', () => { + const WIZARD = [SCREEN, SCREEN_2]; + async function pausedWizard(h: ReturnType): Promise { + const started: any = await h.automation.execute(GATED_FLOW.target, { userId: 'u1', object: OBJECT, record: { id: 'lead_1' } }); + h.automation.execute.mockClear(); + return started.runId; + } + async function handOffOf(h: ReturnType, service: ReturnType, runId: string, reason: string) { + const pending = await h.bridgeAs(PERSON).resumeRun(runId, { values: { reason } }); + expect(pending).toMatchObject({ status: 'pending_confirmation' }); + return ((service.submit.mock.calls.at(-1) as any[])[0]).run as { runId: string; values: Record; screenNodeId?: string }; + } + const approve = (h: ReturnType, run: { runId: string; values: Record; screenNodeId?: string }) => + h.resumeAsHost(PERSON, { runId: run.runId, values: run.values, screenNodeId: run.screenNodeId, confirm: true }) as Promise; + const screenOf = async (h: ReturnType, runId: string) => ((await h.automation.getSuspendedScreen(runId)) as any)?.nodeId ?? null; + + it('the same hand-off approved twice: the first resumes its screen, the second is refused 409 and the run stays on the next screen', async () => { + const service = makeConfirmationService(); + const h = makeHarness({ service, screens: WIZARD }); + const runId = await pausedWizard(h); + const run = await handOffOf(h, service, runId, 'for step 1'); + expect(run.screenNodeId).toBe(SCREEN.nodeId); + + const first = await approve(h, run); + expect(first.status).toBe(200); + expect(first.body.data.result).toMatchObject({ status: 'paused', screen: { nodeId: SCREEN_2.nodeId } }); + + const second = await approve(h, run); + expect({ status: second.status, code: second.body?.error?.code }).toEqual({ status: 409, code: 'RESOURCE_CONFLICT' }); + expect(second.body.error.message).toContain(`Run '${runId}' has moved on`); + // Resumed once, by the first approval: the second submitted nothing. + expect(h.automation.resume).toHaveBeenCalledTimes(1); + expect(h.runs.get(runId)?.status).toBe('paused'); + expect(await screenOf(h, runId)).toBe(SCREEN_2.nodeId); + }); + + it('two resume_run calls, two items: approving the second after the first is refused 409', async () => { + const service = makeConfirmationService(); + const h = makeHarness({ service, screens: WIZARD }); + const runId = await pausedWizard(h); + const one = await handOffOf(h, service, runId, 'call 1'); + const two = await handOffOf(h, service, runId, 'call 2'); + expect([one.screenNodeId, two.screenNodeId]).toEqual([SCREEN.nodeId, SCREEN.nodeId]); + + expect((await approve(h, one)).status).toBe(200); + const refused = await approve(h, two); + + expect({ status: refused.status, code: refused.body?.error?.code }).toEqual({ status: 409, code: 'RESOURCE_CONFLICT' }); + expect(h.automation.resume).toHaveBeenCalledTimes(1); + expect(await screenOf(h, runId)).toBe(SCREEN_2.nodeId); + }); + + it('an item approved after the person advanced the wizard in the app is refused 409, and the run is not touched', async () => { + const service = makeConfirmationService(); + const h = makeHarness({ service, screens: WIZARD }); + const runId = await pausedWizard(h); + const run = await handOffOf(h, service, runId, 'agent, for step 1'); + await h.automation.resume(runId, { variables: { reason: 'typed in the app' } }); + h.automation.resume.mockClear(); + + const refused = await approve(h, run); + + expect({ status: refused.status, code: refused.body?.error?.code }).toEqual({ status: 409, code: 'RESOURCE_CONFLICT' }); + expect(h.automation.resume).not.toHaveBeenCalled(); + expect(await screenOf(h, runId)).toBe(SCREEN_2.nodeId); + }); + + it('an elicited person who accepts after the wizard moved on meanwhile: refused 409, nothing resumes', async () => { + const h = makeHarness({ service: makeConfirmationService(), screens: WIZARD }); + const runId = await pausedWizard(h); + // While the person is being asked, the wizard is advanced in the app. + const elicitConfirmation = vi.fn(async () => { + await h.automation.resume(runId, { variables: { reason: 'typed in the app' } }); + return 'accept' as const; + }); + h.automation.resume.mockClear(); + + const refused = await refusalOf(h.bridgeAs(PERSON).resumeRun(runId, { values: { reason: 'agent' } }, { elicitConfirmation })); + + expect({ code: refused.code, status: refused.status }).toEqual({ code: 'RESOURCE_CONFLICT', status: 409 }); + expect(h.automation.resume).toHaveBeenCalledTimes(1); // the app's, not the agent's + expect(await screenOf(h, runId)).toBe(SCREEN_2.nodeId); + }); + + it('a screenNodeId that is not a non-empty string is refused 400 before anything is read', async () => { + const h = makeHarness({ service: makeConfirmationService(), screens: WIZARD }); + for (const screenNodeId of ['', 7]) { + const refused: any = await h.resumeAsHost(PERSON, { runId: 'run_1', screenNodeId, confirm: true }); + expect(refused.status, JSON.stringify(screenNodeId)).toBe(400); + } + expect(h.automation.getRun).not.toHaveBeenCalled(); + }); + + it('CONTROL: a single-screen flow approved with its screen resumes and completes', async () => { + const service = makeConfirmationService(); + const h = makeHarness({ service }); + const runId = await pausedWizard(h); + const run = await handOffOf(h, service, runId, 'only screen'); + + const answer = await approve(h, run); + + expect(answer.status).toBe(200); + expect(answer.body.data.result).toMatchObject({ status: 'completed' }); + expect(h.runs.get(runId)?.status).toBe('completed'); + }); + + it('CONTROL (widening): an approval that passes no screen resumes the run\'s current screen, as before', async () => { + const service = makeConfirmationService(); + const h = makeHarness({ service, screens: WIZARD }); + const runId = await pausedWizard(h); + const run = await handOffOf(h, service, runId, 'no binding'); + + const first: any = await h.resumeAsHost(PERSON, { runId, values: run.values, confirm: true }); + const second: any = await h.resumeAsHost(PERSON, { runId, values: run.values, confirm: true }); + + expect([first.status, second.status]).toEqual([200, 200]); + expect(h.runs.get(runId)?.status).toBe('completed'); + }); +}); diff --git a/packages/runtime/src/action-dispatch.ts b/packages/runtime/src/action-dispatch.ts index d5448499c99..574ad8b1c4e 100644 --- a/packages/runtime/src/action-dispatch.ts +++ b/packages/runtime/src/action-dispatch.ts @@ -1048,6 +1048,15 @@ export interface ActionResumeRequest extends AIActionConfirmation { runId: string; /** The screen's field values the handed-off call carried (`ActionConfirmationHandOff.run.values`). */ values?: Record; + /** + * [#34515] The screen the handed-off call was given on + * (`ActionConfirmationHandOff.run.screenNodeId`), which binds the approval + * to it: a run no longer paused on that screen (a wizard that moved on, + * by an earlier approval of the same call or in the app) is refused + * `409 RESOURCE_CONFLICT` and stays where it is. Omitted, the run's + * current screen is resumed, whichever it is. + */ + screenNodeId?: string; } /** diff --git a/packages/runtime/src/action-execution.ts b/packages/runtime/src/action-execution.ts index c4970815025..197a7c95b7e 100644 --- a/packages/runtime/src/action-execution.ts +++ b/packages/runtime/src/action-execution.ts @@ -3026,7 +3026,10 @@ export function actionLooksDestructive(_deps: ActionExecutionDeps, action: any): * * For every other caller, a door that enforces the author's AI opt-in and * still reads the member: today a host's door under the `ai` posture - * (`dispatchAction`, `action-dispatch.ts`). [#33690] The MCP `run_action` + * (`dispatchAction`, `action-dispatch.ts`), and the host's resume door + * (`dispatchActionResume`, `action-dispatch.ts`, #34386), the approval leg of + * a handed-off `resume_run`, which reads the person's `confirm` for the + * candidate action that admits the run as `dispatchAction` reads it. [#33690] The MCP `run_action` * ({@link invokeBusinessAction}) and `resume_run` doors no longer read it: * under the amended contract they hand a declared-gated call to the person * ({@link aiDoorConfirmation}, {@link handOffActionConfirmation}) and the diff --git a/packages/runtime/src/domains/mcp.ts b/packages/runtime/src/domains/mcp.ts index 46c53e6a8eb..ba298769050 100644 --- a/packages/runtime/src/domains/mcp.ts +++ b/packages/runtime/src/domains/mcp.ts @@ -21,7 +21,7 @@ import { type BuiltinMembershipRole, type MembershipReachEntry, } from '@objectstack/spec/identity'; -import type { AIActionConfirmation, IExternalDatasourceService } from '@objectstack/spec/contracts'; +import type { AIActionConfirmation, IExternalDatasourceService, ScreenSpec } from '@objectstack/spec/contracts'; import { FEDERATION_READ_CAPABILITY, FEDERATION_WRITE_CAPABILITY, @@ -1929,7 +1929,11 @@ function notResumableRunMessage(runId: string): string { * the run is not resumed. * 5. **A screen pause only.** `getSuspendedScreen` must return a screen. * The verb submits screen values. A run parked on any other node (a - * timer `wait`, for example) is refused 409 and left alone. + * timer `wait`, for example) is refused 409 and left alone. [#34515] An + * approval is bound to the screen it was given on (an approved hand-off's + * `screenNodeId` at the host door, the screen an elicited person was + * asked about): a run now paused on another screen is refused 409 + * `RESOURCE_CONFLICT` and left alone. * 6. **Resume.** The signal is built one field at a time and the input is * never spread, as the REST door does (#3801). The engine's answer goes * through {@link classifyResumeResult}, the table both doors share. @@ -1979,8 +1983,12 @@ export async function resumeActionRun( * `actionConfirmationRefusal`): nothing is handed off or elicited, * an AI service account is refused whatever it carries, and the * invocation row names no MCP surface. + * + * [#34515] `screenNodeId` is the screen the approved hand-off was given + * on (`ActionConfirmationHandOff.run.screenNodeId`): step 5 refuses a + * run no longer paused on it. */ - hostDoor?: { confirmation: AIActionConfirmation }; + hostDoor?: { confirmation: AIActionConfirmation; screenNodeId?: string }; }, ): Promise { const { driver, envId, ec, getMeta, readObjects, readActions, callData, hostDoor } = wiring; @@ -2092,8 +2100,12 @@ export async function resumeActionRun( // instead, after the same steps: `accept` resumes the run below, as any // admitted resume; any other answer refuses the call and the run stays // parked. Nothing is handed off then. + // [#34515] The screen an approval is bound to: the one the host passed + // back for an approved hand-off, or the one an elicited person was asked + // about (below). Step 5 refuses a run no longer paused on it. + let boundScreenNodeId = hostDoor?.screenNodeId; if (handOff && elicitConfirmation) { - const subject = await refuseUnresumableAdmittedRun(deps, automation, runId, { objectName, recordId, driver, envId, ec, callData }); + const { subject, screen } = await refuseUnresumableAdmittedRun(deps, automation, runId, { objectName, recordId, driver, envId, ec, callData }); const elicited = await actionExec.elicitActionConfirmation( elicitConfirmation, actionExec.actionConfirmationElicitSubject( @@ -2113,15 +2125,21 @@ export async function resumeActionRun( // the subject and the screen again itself (`continueAdmittedRun`). const regated = resumeAdmissionRefusal(deps, admitted, ec, activationEngine); if (regated instanceof Error) throw regated; + // [#34515] The person answered for the screen the run was parked on + // then: a run that moved on meanwhile is refused at step 5. + boundScreenNodeId = screenNodeIdOf(screen); } else if (handOff) { - await refuseUnresumableAdmittedRun(deps, automation, runId, { objectName, recordId, driver, envId, ec, callData }); + // [#34515] The hand-off names the screen the values were given for, + // so the host can bind its approval to it (`dispatchActionResume`). + const { screen } = await refuseUnresumableAdmittedRun(deps, automation, runId, { objectName, recordId, driver, envId, ec, callData }); + const screenNodeId = screenNodeIdOf(screen); const answer = await actionExec.handOffActionConfirmation(deps, context, envId, { actionName: typeof action?.name === 'string' && action.name ? action.name : String(flowName), ...(actionExec.isObjectLessActionKey(objectName) ? {} : { objectName }), ...(recordId !== undefined ? { recordId } : {}), params: {}, door: 'mcp', - run: { runId, values: values ?? {} }, + run: { runId, values: values ?? {}, ...(screenNodeId !== undefined ? { screenNodeId } : {}) }, }, ec); if ('refused' in answer) { throw resumeDoorError(deps, answer.refused.message, answer.refused.status, { @@ -2152,7 +2170,7 @@ export async function resumeActionRun( let answer: any; try { answer = await continueAdmittedRun(deps, automation, runId, values, { - action, objectName, recordId, driver, envId, ec, callData, + action, objectName, recordId, driver, envId, ec, callData, boundScreenNodeId, }); } catch (err) { await recordActionInvocation(deps, context, envId, { @@ -2187,9 +2205,14 @@ export async function resumeActionRun( * the run to be paused on a screen; step 6 resumes it. * * Step 2 refuses only a run that is no longer paused: a wizard moved on to - * its next screen is still paused under the same run id, and a second call - * with the same hand-off resumes that screen with the values given. Deciding - * a pending item once is the host's. + * its next screen is still paused under the same run id. [#34515] So the + * host passes back the screen the hand-off was given on + * (`ActionConfirmationHandOff.run.screenNodeId`, as `screenNodeId`), and + * step 5 refuses a run no longer paused on it, `409 RESOURCE_CONFLICT`, + * leaving it where it is: a second approval of the same hand-off, or one + * that lands after the person advanced the wizard in the app, resumes + * nothing. Without it, the run's current screen is resumed with the values + * given. Deciding a pending item once is the host's. * * Placement is the host action door's ({@link PlaceRequestInEnvironment}). * What stays the host's before it calls, as for `dispatchAction`: resolving @@ -2235,6 +2258,11 @@ export async function resumeActionRunRequest( } const { getMeta, readServedObjects, readServedActions } = actionDeclarationReads(deps, context); const confirmation: AIActionConfirmation = request.confirm !== undefined ? { confirm: request.confirm } : {}; + // [#34515] The screen the approved hand-off was given on, when the host passes it back. + const screenNodeId = request.screenNodeId; + if (screenNodeId !== undefined && (typeof screenNodeId !== 'string' || screenNodeId === '')) { + return deps.error('dispatchActionResume\'s `screenNodeId` names the screen the hand-off was given on: a non-empty string', 400) as ActionDispatchAnswer; + } try { const answer = await resumeActionRun(deps, context, runId, request.values !== undefined ? { values: request.values } : {}, { driver: (context as any).dataDriver, @@ -2244,7 +2272,7 @@ export async function resumeActionRunRequest( readObjects: readServedObjects, readActions: readServedActions, callData: actionExec.callData.bind(null, deps, context), - hostDoor: { confirmation }, + hostDoor: { confirmation, ...(screenNodeId !== undefined ? { screenNodeId } : {}) }, }); return deps.success(answer) as ActionDispatchAnswer; } catch (err) { @@ -2271,6 +2299,8 @@ async function continueAdmittedRun( envId?: string; ec: any; callData: (action: string, params: any, dataDriver?: any, scopeId?: string, ec?: any) => Promise; + /** [#34515] The screen the approval was given on, when it is bound to one. */ + boundScreenNodeId?: string; }, ): Promise { const { action, objectName, recordId } = admitted; @@ -2289,6 +2319,14 @@ async function continueAdmittedRun( * `resume_run` steps 4–5 for an admitted run: the subject record read again * as the caller, and the screen-pause check. Throws the refusal; reads * nothing else. Asked before a resume and before a hand-off (#33690) alike. + * + * [#34515] Step 5 also binds an approval to its screen: given + * `boundScreenNodeId`, a run paused on another screen is refused 409 and left + * where it is. A multi-screen wizard stays `paused` under the same run id as + * it moves from screen to screen, so step 2 alone would let an approval given + * for one screen (a second approval of the same hand-off, or one that lands + * after the person advanced the wizard in the app) submit its values to the + * next screen, as the approver. */ async function refuseUnresumableAdmittedRun( deps: DomainHandlerDeps, @@ -2301,9 +2339,10 @@ async function refuseUnresumableAdmittedRun( envId?: string; ec: any; callData: (action: string, params: any, dataDriver?: any, scopeId?: string, ec?: any) => Promise; + boundScreenNodeId?: string; }, -): Promise { - const { objectName, recordId, driver, envId, ec, callData } = admitted; +): Promise<{ subject: actionExec.ActionSubjectRecordLoad; screen: ScreenSpec }> { + const { objectName, recordId, driver, envId, ec, callData, boundScreenNodeId } = admitted; // ── 4. the subject record, read again in the caller's own scope ────────── const subject = await actionExec.loadActionSubjectRecord(objectName, recordId, () => @@ -2320,8 +2359,24 @@ async function refuseUnresumableAdmittedRun( 409, ); } + // [#34515] An approval bound to a screen resumes that screen and no other. + if (boundScreenNodeId !== undefined && screenNodeIdOf(screen) !== boundScreenNodeId) { + throw resumeDoorError( + deps, + `Run '${runId}' has moved on: this approval was given for screen '${boundScreenNodeId}', and the run is ` + + `now paused on ${screenNodeIdOf(screen) !== undefined ? `screen '${screenNodeIdOf(screen)}'` : 'another screen'}. ` + + 'Nothing was resumed and the run stays where it is; ask again on the screen it is on now.', + 409, + ); + } // [#33712] The subject as read, so an elicitation can name the record by its title. - return subject; + return { subject, screen }; +} + +/** [#34515] A screen's node id (`ScreenSpec.nodeId`), when the engine named one. */ +function screenNodeIdOf(screen: ScreenSpec | null | undefined): string | undefined { + const nodeId = (screen as { nodeId?: unknown } | null | undefined)?.nodeId; + return typeof nodeId === 'string' && nodeId !== '' ? nodeId : undefined; } /** diff --git a/packages/spec/src/contracts/ai-service.ts b/packages/spec/src/contracts/ai-service.ts index 873b9277c5d..6a58a3b636d 100644 --- a/packages/spec/src/contracts/ai-service.ts +++ b/packages/spec/src/contracts/ai-service.ts @@ -533,7 +533,10 @@ export interface ActionConfirmationRequiredDetails { * carries its run ({@link ActionConfirmationHandOff.run}): approving it * resumes THAT parked run with the values the call carried, as the * approver, who must be the run's owner as today; it never starts a new - * run of the flow. + * run of the flow. The approval is bound to the screen the run was + * parked on when the call was handed off (the run's `screenNodeId`): + * when the host passes that screen back and the run has moved on to + * another one, the resume is refused and the run stays where it is. * - Handed off, then rejected in the app: nothing runs. * The approve and reject doors of the pending-confirmation service take a * person's signed-in session to the app and nothing else. They refuse an @@ -721,6 +724,17 @@ export interface ActionConfirmationHandOff { runId: string; /** The screen's field values the call carried. */ values: Record; + /** + * The screen the run was parked on when the call was handed off: its + * `nodeId` (`ScreenSpec.nodeId`, `./automation-service`), the screen + * `values` were given for. Absent when the engine named no node for + * it. A host that stores it and passes it back on approval + * (`ActionResumeRequest.screenNodeId`, `@objectstack/runtime`) binds + * the approval to that screen: a run that has moved on to another + * screen (a wizard the person advanced in the app, or a second + * approval of the same call) is refused, and nothing resumes. + */ + screenNodeId?: string; }; } @@ -777,11 +791,13 @@ export const ACTION_CONFIRMATION_SERVICE = 'ai.actionConfirmation'; * true })` resumes the run a handed-off `resume_run` carries * ({@link ActionConfirmationHandOff.run}) as that person, asking every * `resume_run` gate again: a run no longer paused, or one another person - * started, is refused. That is the only replay it refuses: a wizard the first - * approval moved on to its next screen is still paused under the same run id, - * and a second call with the same hand-off resumes it again with the values - * given. Deciding a pending item once, and voiding an item whose run has - * moved on, are the host's. + * started, is refused. A wizard the first approval moved on to its next + * screen is still paused under the same run id, so the host passes back the + * screen the call was handed off on (`run.screenNodeId`, as `screenNodeId`): + * a run no longer on that screen is refused, `409 RESOURCE_CONFLICT`, and + * stays where it is. Without it, a second call with the same hand-off + * resumes whatever screen the run is on with the values given. Deciding a + * pending item once is the host's. * * A host may build it over its own pending-action store; the * `held` outcome of {@link IAIService.approvePendingAction} is the existing From 1f37c11a097f391462df441dfbdc157ce8fecde9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 09:19:59 +0000 Subject: [PATCH 2/4] test(runtime): the wizard double's resume takes the signal it is given Claude-Session: https://claude.ai/code/session_01ADHkmSKdmdbBugjg8QSZGa Co-authored-by: Claude --- packages/runtime/src/action-confirmation-handoff-33690.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/runtime/src/action-confirmation-handoff-33690.test.ts b/packages/runtime/src/action-confirmation-handoff-33690.test.ts index d881267703b..53377f9266d 100644 --- a/packages/runtime/src/action-confirmation-handoff-33690.test.ts +++ b/packages/runtime/src/action-confirmation-handoff-33690.test.ts @@ -109,7 +109,7 @@ function makeHarness(opts: { service?: unknown; audit?: unknown; screens?: Reado }), // A resume submits the current screen and moves the run on to the next // one, still `paused` under the same run id, or completes it after the last. - resume: vi.fn(async (runId: string) => { + resume: vi.fn(async (runId: string, _signal?: { variables?: Record }) => { const run = runs.get(runId)!; run.screen += 1; if (run.screen < screens.length) { From 542b722475df6b02aadb949d423dbcd9318d6c8e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 10:24:12 +0000 Subject: [PATCH 3/4] docs(changeset): declare the elicited resume's narrowing on the screen binding Claude-Session: https://claude.ai/code/session_01ADHkmSKdmdbBugjg8QSZGa Co-authored-by: Claude --- .../34515-resume-approval-bound-to-screen.md | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/.changeset/34515-resume-approval-bound-to-screen.md b/.changeset/34515-resume-approval-bound-to-screen.md index 422c89b8061..59cbc19c408 100644 --- a/.changeset/34515-resume-approval-bound-to-screen.md +++ b/.changeset/34515-resume-approval-bound-to-screen.md @@ -3,16 +3,22 @@ '@objectstack/runtime': patch --- -fix(runtime): a resume approval is bound to the screen it was given on, so a wizard that moved on is never handed the earlier screen's values +fix(runtime)!: a resume approval is bound to the screen it was given on, so a wizard that moved on is never handed the earlier screen's values -Clause-②: yes (widening) +Clause-②: yes (narrowing) — narrowed: an MCP `resume_run` of a declared-gated flow action on a client that is asked in place (form-mode `elicitation`), where the person accepts after the wizard moved on to another screen in the meantime, is now refused `409 RESOURCE_CONFLICT` and resumes nothing, where it resumed the screen the run had moved on to. Widened beside it: `ActionConfirmationHandOff.run.screenNodeId` and `ActionResumeRequest.screenNodeId` are new optional keys, and a host call that omits `screenNodeId` behaves as before. Metadata-protocol: none +Skills-docs: none — no skill under `skills/**` teaches what a second resume of one run does (`skills/objectstack-ai/SKILL.md` lines 211–217 and `skills/objectstack-platform/SKILL.md` line 344 teach the hand-off, the `confirm` refusal and the elicitation answers only); `content/docs/ui/actions.mdx` gains the rule in this change. -A multi-screen wizard stays paused under the same run id as it moves from screen to screen. So when the MCP `resume_run` tool handed a resume to the person (an action that declares `ai.requiresConfirmation: true`), a second resume of the same pending item was still admitted after the first approval had moved the wizard on: the values given for the first screen were submitted to the next screen, as the approver. The same happened when the agent called `resume_run` twice (two pending items), and when the person advanced the wizard in the app before the item was approved. + + +**BREAKING** for an MCP client that is asked in place: when the person accepts a `resume_run` of a declared-gated action after the wizard has moved on to another screen (advanced in the app while they were being asked), the call is refused `409 RESOURCE_CONFLICT`, nothing resumes, and the run stays on the screen it is on. Before this change the same call resumed that other screen with the values the agent gave for the first one, as the person. The agent asks again on the screen the run is on now. + +A multi-screen wizard stays paused under the same run id as it moves from screen to screen. So when the MCP `resume_run` tool handed a resume to the person, a second resume of the same pending item was still admitted after the first approval had moved the wizard on: the values given for the first screen were submitted to the next screen, as the approver. The same happened when the agent called `resume_run` twice (two pending items), and when the person advanced the wizard in the app before the item was approved. - The hand-off now names the screen its values were given for: `ActionConfirmationHandOff.run.screenNodeId` (the `ScreenSpec.nodeId` the run was parked on). It is optional and absent only when the engine named no node. - `dispatchActionResume` takes the same optional `screenNodeId`. A host that stores it with the pending item and passes it back on approval binds the approval to that screen: a run no longer paused on it is refused `409 RESOURCE_CONFLICT`, nothing resumes, and the run stays where it is. A `screenNodeId` that is not a non-empty string is refused `400`. -- An elicited approval (a client that can be asked in place) is bound the same way: if the wizard moved on while the person was being asked, the resume is refused `409 RESOURCE_CONFLICT`. -- Nothing already accepted is refused: a call that passes no `screenNodeId` resumes the run's current screen, as before. A host should pass it to get the binding. +- A host call that passes no `screenNodeId` resumes the run's current screen, as before. A host should pass it to get the binding. + +Unchanged: a single-screen flow, an elicited approval whose run is still on the screen the person was asked about, and an MCP `resume_run` of an action that declares no confirmation. Limit: a wizard that loops back to the same screen node cannot be told apart by node id; no flow doing that has been found in use. From 85b5f360e19824f42dea785b8036c39c1caf8dbd Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 11:23:48 +0000 Subject: [PATCH 4/4] docs(spec): state the elicited resume binding in rule 4 of the confirmation contract The elicited accept of a resume_run is bound to the screen the run was parked on when the person was asked; a run that moved on meanwhile is refused 409 and stays where it is. The host-door guide also names the 400 for an unusable screenNodeId and the looping-wizard limit. Claude-Session: https://claude.ai/code/session_01ADHkmSKdmdbBugjg8QSZGa Co-authored-by: Claude --- content/docs/ui/actions.mdx | 6 ++++-- packages/spec/src/contracts/ai-service.ts | 4 ++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/content/docs/ui/actions.mdx b/content/docs/ui/actions.mdx index c7f32423d7a..7f7255e72e0 100644 --- a/content/docs/ui/actions.mdx +++ b/content/docs/ui/actions.mdx @@ -798,8 +798,10 @@ screen, so pass `screenNodeId` back: when the run is no longer on that screen (an earlier approval of the same item moved it on, or the person advanced it in the app) the call is refused **409** `RESOURCE_CONFLICT`, nothing resumes, and the run stays where it is. Without `screenNodeId`, the run's current -screen is resumed with the values given. Decide each pending item once in -your approve door. Without `confirm: true`, an action that declares +screen is resumed with the values given. A `screenNodeId` that is `null`, empty +or not a string is refused **400**, so omit the key for an item stored without +one. A wizard that loops back to the same screen is not told apart by its +screen id. Decide each pending item once in your approve door. Without `confirm: true`, an action that declares `ai.requiresConfirmation: true` is refused **428** `ACTION_CONFIRMATION_REQUIRED`, and an AI service account is refused whatever it sends. The answer is the REST envelope, with `resume_run`'s `{ ok, action, objectName, recordId, result }` as diff --git a/packages/spec/src/contracts/ai-service.ts b/packages/spec/src/contracts/ai-service.ts index 6a58a3b636d..d0fcc2ff7b4 100644 --- a/packages/spec/src/contracts/ai-service.ts +++ b/packages/spec/src/contracts/ai-service.ts @@ -517,6 +517,10 @@ export interface ActionConfirmationRequiredDetails { * - Elicited `accept`: the call dispatches as any admitted call does, * exactly once, under the caller's permissions. The confirmation covers * that one call: nothing is stored, and the next call is asked again. + * For a `resume_run` call the accept is bound to the screen the run was + * parked on when the person was asked: when the run has moved on to + * another screen meanwhile, the resume is refused `409 + * RESOURCE_CONFLICT`, nothing resumes, and the run stays where it is. * - Elicited `decline`: the person said no. Refused, reason `declined`; * nothing runs. The caller does not retry unless the person asks again. * - Elicited `cancel`: the person dismissed the question without choosing.