|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * A declared script action with no handler bound (a "ghost" action): MCP |
| 5 | + * `run_action` answers it as the routing miss REST `/api/v1/actions` answers. |
| 6 | + * |
| 7 | + * Both doors dispatch a script action through `executeRegisteredAction`, and |
| 8 | + * both see the same miss (`dispatched: false`). REST answers it from its |
| 9 | + * routing-miss branch (`domains/actions.ts`): `404`, the closed code the |
| 10 | + * status derives (`RESOURCE_NOT_FOUND`), `Action 'X' on object 'Y' not |
| 11 | + * found`. The MCP bridge (`invokeBusinessAction`) threw a plain uncoded |
| 12 | + * `Error('No handler registered …')`, which `run_action` answers through the |
| 13 | + * `/actions` door's reader (`actionsDoorAnswerOf`, `@objectstack/types`) as |
| 14 | + * that door's bare-`Error` arm, `400 VALIDATION_ERROR`: it told an agent its |
| 15 | + * input was bad when the action has no route. The bridge now throws the |
| 16 | + * coded miss, so the reader gives back the door's own answer. |
| 17 | + * |
| 18 | + * One kernel serves both doors here, so each pin is the agreement between |
| 19 | + * them, not either half alone. The invocation row each door writes for the |
| 20 | + * miss is pinned too: the MCP row used to record the uncoded throw as a `500`. |
| 21 | + */ |
| 22 | + |
| 23 | +import { describe, it, expect, vi, afterEach } from 'vitest'; |
| 24 | +import { actionsDoorAnswerOf } from '@objectstack/types'; |
| 25 | +// Pay the first transform of `@objectstack/metadata`, which the dispatcher's |
| 26 | +// source reaches through a dynamic `import()`, at MODULE LOAD, never inside a |
| 27 | +// clocked `it` (`scripts/check-test-source-alias.mjs`). |
| 28 | +import '@objectstack/metadata'; |
| 29 | + |
| 30 | +import { HttpDispatcher } from './http-dispatcher.js'; |
| 31 | + |
| 32 | +const OBJECT = 'tasks_app_task'; |
| 33 | +const ACTION = { |
| 34 | + name: 'complete_task', label: 'Complete', objectName: OBJECT, type: 'script', |
| 35 | + body: { language: 'js', source: 'return { ok: true };' }, |
| 36 | + ai: { exposed: true, description: 'Mark a task complete.' }, |
| 37 | +}; |
| 38 | +const MISS_SENTENCE = `Action 'complete_task' on object '${OBJECT}' not found`; |
| 39 | + |
| 40 | +function makeKernel(handler?: (ctx: any) => unknown) { |
| 41 | + const object = { name: OBJECT, label: 'Task', fields: {}, actions: [ACTION] }; |
| 42 | + const handlers = new Map<string, (ctx: any) => unknown>(); |
| 43 | + if (handler) handlers.set(`${OBJECT}:complete_task`, handler); |
| 44 | + const ql: any = { |
| 45 | + getSchema: (name: string) => (name === OBJECT ? object : undefined), |
| 46 | + registry: { getObject: (name: string) => (name === OBJECT ? object : undefined), getItem: () => undefined }, |
| 47 | + find: vi.fn(async () => [{ id: 'r1' }]), |
| 48 | + insert: vi.fn(), update: vi.fn(), delete: vi.fn(), |
| 49 | + executeAction: vi.fn(async (obj: string, key: string, ctx: any) => { |
| 50 | + const h = handlers.get(`${obj}:${key}`); |
| 51 | + if (!h) throw new Error(`Action '${key}' on object '${obj}' not found`); |
| 52 | + return h(ctx); |
| 53 | + }), |
| 54 | + listRegisteredActions: () => [...handlers.keys()].map((k) => ({ |
| 55 | + objectName: k.slice(0, k.indexOf(':')), actionName: k.slice(k.indexOf(':') + 1), |
| 56 | + })), |
| 57 | + }; |
| 58 | + const metadata: any = { |
| 59 | + listObjects: vi.fn(async () => [object]), |
| 60 | + getObject: vi.fn(async () => object), |
| 61 | + load: vi.fn(async () => null), |
| 62 | + loadDiagnosed: vi.fn(async () => ({ data: null, degraded: false, errors: [] })), |
| 63 | + }; |
| 64 | + const rows: any[] = []; |
| 65 | + const audit = { recordActionInvocation: vi.fn(async (row: any) => { rows.push(row); }) }; |
| 66 | + const auth: any = { api: { getSession: async () => ({ user: { id: 'u1' } }) } }; |
| 67 | + const automation = { execute: vi.fn(async () => ({ success: true })) }; |
| 68 | + const kernel: any = { |
| 69 | + context: { |
| 70 | + getService: (n: string) => |
| 71 | + n === 'objectql' || n === 'data' ? ql |
| 72 | + : n === 'metadata' ? metadata |
| 73 | + : n === 'audit' ? audit |
| 74 | + : n === 'auth' ? auth |
| 75 | + : n === 'automation' ? automation |
| 76 | + : null, |
| 77 | + }, |
| 78 | + }; |
| 79 | + return { dispatcher: new HttpDispatcher(kernel) as any, rows }; |
| 80 | +} |
| 81 | + |
| 82 | +const ctx = (): any => ({ request: {}, environmentId: 'platform', executionContext: { userId: 'u1', systemPermissions: [] } }); |
| 83 | + |
| 84 | +async function restAnswer(dispatcher: any) { |
| 85 | + const res = await dispatcher.handleActions(`/${OBJECT}/complete_task/r1`, 'POST', {}, ctx()); |
| 86 | + return res.response; |
| 87 | +} |
| 88 | + |
| 89 | +async function mcpThrow(dispatcher: any): Promise<unknown> { |
| 90 | + const bridge = dispatcher.buildMcpBridge(ctx()); |
| 91 | + try { |
| 92 | + await bridge.runAction('complete_task', { objectName: OBJECT, recordId: 'r1' }); |
| 93 | + } catch (err) { |
| 94 | + return err; |
| 95 | + } |
| 96 | + throw new Error('run_action did not throw'); |
| 97 | +} |
| 98 | + |
| 99 | +describe('a declared action with no handler: run_action answers the routing miss /actions answers', () => { |
| 100 | + afterEach(() => { |
| 101 | + vi.restoreAllMocks(); |
| 102 | + }); |
| 103 | + |
| 104 | + it('REST /actions answers 404 RESOURCE_NOT_FOUND, naming the routed object (the measured door answer)', async () => { |
| 105 | + const { dispatcher } = makeKernel(); |
| 106 | + const response = await restAnswer(dispatcher); |
| 107 | + expect(response.status).toBe(404); |
| 108 | + expect(response.body.error).toEqual({ code: 'RESOURCE_NOT_FOUND', message: MISS_SENTENCE, httpStatus: 404 }); |
| 109 | + }); |
| 110 | + |
| 111 | + it('the MCP bridge throws the same miss coded: code, status and sentence equal the REST body', async () => { |
| 112 | + vi.spyOn(console, 'info').mockImplementation(() => {}); |
| 113 | + const { dispatcher } = makeKernel(); |
| 114 | + const rest = (await restAnswer(dispatcher)).body.error; |
| 115 | + const thrown = await mcpThrow(dispatcher) as { code?: unknown; status?: unknown; message?: unknown }; |
| 116 | + expect({ code: thrown.code, status: thrown.status, message: thrown.message }).toEqual({ |
| 117 | + code: 'RESOURCE_NOT_FOUND', status: 404, message: MISS_SENTENCE, |
| 118 | + }); |
| 119 | + expect([thrown.code, thrown.status, thrown.message]).toEqual([rest.code, rest.httpStatus, rest.message]); |
| 120 | + }); |
| 121 | + |
| 122 | + it('run_action reads it through the /actions reader as that door answers it, never 400 VALIDATION_ERROR', async () => { |
| 123 | + vi.spyOn(console, 'info').mockImplementation(() => {}); |
| 124 | + const { dispatcher } = makeKernel(); |
| 125 | + const rest = (await restAnswer(dispatcher)).body.error; |
| 126 | + const answer = actionsDoorAnswerOf(await mcpThrow(dispatcher)); |
| 127 | + expect({ code: answer.code, status: answer.status, message: answer.message }).toEqual({ |
| 128 | + code: 'RESOURCE_NOT_FOUND', status: 404, message: MISS_SENTENCE, |
| 129 | + }); |
| 130 | + expect({ code: answer.code, status: answer.status, message: answer.message }) |
| 131 | + .toEqual({ code: rest.code, status: rest.httpStatus, message: rest.message }); |
| 132 | + expect(answer.declaredCode).toBeUndefined(); |
| 133 | + }); |
| 134 | + |
| 135 | + it('each door writes one failed invocation row for the miss, with the same status and code', async () => { |
| 136 | + vi.spyOn(console, 'info').mockImplementation(() => {}); |
| 137 | + const { dispatcher, rows } = makeKernel(); |
| 138 | + await restAnswer(dispatcher); |
| 139 | + await mcpThrow(dispatcher); |
| 140 | + expect(rows.map((r) => ({ surface: r.context?.surface, outcome: r.outcome, status: r.status, errorCode: r.errorCode }))).toEqual([ |
| 141 | + { surface: 'rest', outcome: 'failed', status: 404, errorCode: 'RESOURCE_NOT_FOUND' }, |
| 142 | + { surface: 'mcp', outcome: 'failed', status: 404, errorCode: 'RESOURCE_NOT_FOUND' }, |
| 143 | + ]); |
| 144 | + }); |
| 145 | + |
| 146 | + it('CONTROL: the same action with a handler bound runs on both doors', async () => { |
| 147 | + vi.spyOn(console, 'info').mockImplementation(() => {}); |
| 148 | + const { dispatcher } = makeKernel(() => ({ done: true })); |
| 149 | + const response = await restAnswer(dispatcher); |
| 150 | + expect(response.status).toBe(200); |
| 151 | + const bridge = dispatcher.buildMcpBridge(ctx()); |
| 152 | + await expect(bridge.runAction('complete_task', { objectName: OBJECT, recordId: 'r1' })) |
| 153 | + .resolves.toMatchObject({ ok: true, result: { done: true } }); |
| 154 | + }); |
| 155 | + |
| 156 | + it('CONTROL: a coded refusal from the handler keeps its code and status on both doors', async () => { |
| 157 | + vi.spyOn(console, 'info').mockImplementation(() => {}); |
| 158 | + vi.spyOn(console, 'error').mockImplementation(() => {}); |
| 159 | + const refuse = () => { |
| 160 | + throw Object.assign(new Error('Record is locked.'), { code: 'RECORD_LOCKED', status: 409 }); |
| 161 | + }; |
| 162 | + const { dispatcher } = makeKernel(refuse); |
| 163 | + const rest = await restAnswer(dispatcher); |
| 164 | + expect(rest.status).toBe(409); |
| 165 | + expect(rest.body.error).toMatchObject({ code: 'RECORD_LOCKED', message: 'Record is locked.', httpStatus: 409 }); |
| 166 | + const answer = actionsDoorAnswerOf(await mcpThrow(dispatcher)); |
| 167 | + expect({ code: answer.code, status: answer.status, message: answer.message }) |
| 168 | + .toEqual({ code: 'RECORD_LOCKED', status: 409, message: 'Record is locked.' }); |
| 169 | + }); |
| 170 | +}); |
0 commit comments