From 1e2741e5e1173fbdba737703560d28dd02a781ef Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 20:32:22 +0000 Subject: [PATCH 1/3] fix(app-shell): an api action declaring opensInNewTab + newTabUrl opens the tab on list surfaces The console's registered `api` handler sent its request to `target` and never read the pair, so the spec's zero-roundtrip new-tab path was dead for `type: 'api'`. `withNewTabUrlFastPath` routes such an action to the server-action handler's existing fast path (same record-id resolution, pre-opened tab, `{recordId}` substitution); every other api action is unchanged. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSH8FbKjEztmGT1sbB --- .../src/hooks/useConsoleActionRuntime.tsx | 18 +++++-- .../src/utils/consoleServerAction.ts | 47 ++++++++++++++++++- 2 files changed, 59 insertions(+), 6 deletions(-) diff --git a/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx b/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx index 006646c8a05..3baa1dd6223 100644 --- a/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx +++ b/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx @@ -52,7 +52,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 { createConsoleServerActionHandler } from '../utils/consoleServerAction.js'; +import { createConsoleServerActionHandler, withNewTabUrlFastPath } from '../utils/consoleServerAction.js'; import { modalTargetRefusalMessage } from '../utils/modalTargetDiagnostics.js'; import { actionContextOrg } from '../utils/actionContextOrg.js'; import { resolveHostAppSegment } from '../utils/appRoute.js'; @@ -803,6 +803,14 @@ export function useConsoleActionRuntime(opts: ConsoleActionRuntimeOptions): Cons [flowDispatch, serverActionHandler], ); + // The registered `api` handler: {@link apiHandler}, except that an action + // declaring `opensInNewTab` + `newTabUrl` takes the server-action handler's + // zero-roundtrip new-tab path, which sends no request (objectstack#26747). + const apiActionHandler = useMemo( + () => withNewTabUrlFastPath(apiHandler, serverActionHandler), + [apiHandler, serverActionHandler], + ); + // Client-side modal transport, shared with RecordDetailView so a // `type: 'modal'` action behaves the SAME on a list page, an SDUI page, a // declared-actions bar and a record page. Before this, only RecordDetailView @@ -883,10 +891,10 @@ export function useConsoleActionRuntime(opts: ConsoleActionRuntimeOptions): Cons onParamCollection: paramCollectionHandler, onResultDialog: resultDialogHandler, onModal: modalHandler, - handlers: { api: apiHandler, flow: flowHandler, script: serverActionHandler, modal: modalActionHandler }, + handlers: { api: apiActionHandler, flow: flowHandler, script: serverActionHandler, modal: modalActionHandler }, }), [ objectName, objectDef, currentUser, activeOrganization, confirmHandler, toastHandler, - navigateHandler, paramCollectionHandler, resultDialogHandler, apiHandler, + navigateHandler, paramCollectionHandler, resultDialogHandler, apiActionHandler, flowHandler, serverActionHandler, modalHandler, modalActionHandler, ]); @@ -982,7 +990,9 @@ export function useConsoleActionRuntime(opts: ConsoleActionRuntimeOptions): Cons navigateHandler, paramCollectionHandler, resultDialogHandler, - apiHandler, + // The composed handler, so every host that registers it (ConsoleShell's + // root provider included) honours the `newTabUrl` fast path. + apiHandler: apiActionHandler, flowHandler, serverActionHandler, modalActionHandler, diff --git a/ui/packages/app-shell/src/utils/consoleServerAction.ts b/ui/packages/app-shell/src/utils/consoleServerAction.ts index 783ac77bdc6..30af0ee14a0 100644 --- a/ui/packages/app-shell/src/utils/consoleServerAction.ts +++ b/ui/packages/app-shell/src/utils/consoleServerAction.ts @@ -49,6 +49,7 @@ import { resolveServerActionRecordId, type ActionContext, type ActionDef, + type ActionResult, type ServerActionFetch, type ServerActionHandler, type ServerActionRecordIdResolver, @@ -165,6 +166,48 @@ function openInTab(preOpenedTab: Window | null, url: string, t: ConsoleServerAct } } +/** + * Whether `action` takes the zero-roundtrip `newTabUrl` fast path: + * `opensInNewTab` plus a non-empty `newTabUrl`. The spec gives that pair one + * meaning whatever the action's `type` — navigate the pre-opened tab, no + * request — so a host's `type: 'api'` handler asks this and hands such an + * action to the handler {@link createConsoleServerActionHandler} builds, + * instead of sending its own request to `target`. + */ +export function takesNewTabUrlFastPath(action: ActionDef): action is ActionDef & { newTabUrl: string } { + return !!action.opensInNewTab && typeof action.newTabUrl === 'string' && action.newTabUrl !== ''; +} + +/** + * A host's registered `type: 'api'` handler, made to honour the `newTabUrl` + * fast path: an action that {@link takesNewTabUrlFastPath} goes to + * `consoleHandler` (the handler {@link createConsoleServerActionHandler} + * built for the same surface, so the record id resolves the way that surface + * resolves it), and every other action to `apiHandler` unchanged. + * + * Without it the console's api handlers sent their request to `target` and + * never read the pair, so a `type: 'api'` action declaring `opensInNewTab` + + * `newTabUrl` opened no tab and POSTed instead, from the record header, its + * more-menu and the list toolbar alike (objectstack#26747). The pair's early + * row-count refusal is the fast path's own, forwarded only for those actions; + * an ordinary api action keeps having none. + */ +export function withNewTabUrlFastPath( + apiHandler: (action: ActionDef, context?: ActionContext) => Promise, + consoleHandler: ServerActionHandler, +): ServerActionHandler { + return Object.assign( + (action: ActionDef, context?: ActionContext) => (takesNewTabUrlFastPath(action) + ? consoleHandler(action, context) + : apiHandler(action, context)), + { + refuseBeforeInput: (action: ActionDef, context?: ActionContext) => (takesNewTabUrlFastPath(action) + ? consoleHandler.refuseBeforeInput?.(action, context) + : undefined), + }, + ); +} + export function createConsoleServerActionHandler(opts: ConsoleServerActionOptions): ServerActionHandler { const dispatch = createServerActionHandler({ fetch: opts.fetch, @@ -185,8 +228,8 @@ export function createConsoleServerActionHandler(opts: ConsoleServerActionOption // until the (possibly slow) endpoint commits its redirect. Record-id // resolution runs BEFORE the pre-open so a blocked resolution // (multi-select, empty selection) never flashes a tab. - const newTabUrl = typeof action.newTabUrl === 'string' ? action.newTabUrl : ''; - if (action.opensInNewTab && newTabUrl) { + if (takesNewTabUrlFastPath(action)) { + const newTabUrl = action.newTabUrl; // Both refusals below are shown in the session's language // (objectui#13397): the resolver's through the pack key it names // (objectui#13384), this wrapper's own through `console.serverAction.*`. From 0c1ffeb2f29bb65b28f91a335a840b50fb24230c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 20:34:30 +0000 Subject: [PATCH 2/3] fix(app-shell): the record header and more-menu open an api action's newTabUrl tab The record page registers its own `api` handler, which also never read `opensInNewTab` + `newTabUrl`. It now goes through the same `withNewTabUrlFastPath` composition against the page's server-action handler. Tests drive the real header and more-menu clicks and the shared runtime's runner; a changeset records the patch. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSH8FbKjEztmGT1sbB --- .changeset/26747-api-action-new-tab-url.md | 17 ++ ...eActionRuntime.apiNewTabUrl-26747.test.tsx | 183 +++++++++++++ ...cordDetailView.apiNewTabUrl-26747.test.tsx | 255 ++++++++++++++++++ .../app-shell/src/views/RecordDetailView.tsx | 14 +- 4 files changed, 467 insertions(+), 2 deletions(-) create mode 100644 .changeset/26747-api-action-new-tab-url.md create mode 100644 ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.apiNewTabUrl-26747.test.tsx create mode 100644 ui/packages/app-shell/src/views/RecordDetailView.apiNewTabUrl-26747.test.tsx diff --git a/.changeset/26747-api-action-new-tab-url.md b/.changeset/26747-api-action-new-tab-url.md new file mode 100644 index 00000000000..24b2c3c7028 --- /dev/null +++ b/.changeset/26747-api-action-new-tab-url.md @@ -0,0 +1,17 @@ +--- +'@object-ui/app-shell': patch +--- + +fix(app-shell): a `type: 'api'` action declaring `opensInNewTab` + `newTabUrl` opens the tab and sends no request + +Clause-②: no +Metadata-protocol: none + +The spec documents `newTabUrl` as the zero-roundtrip target of a new-tab action: on click the console pre-opens a tab and navigates it to `newTabUrl` (with `{recordId}` substituted), and no action request is sent. The console's server-action handler did this, but its `type: 'api'` handlers never read the pair. A `type: 'api'` action declaring both therefore opened no tab and POSTed to its `target` instead, from the record header, its more-menu and the list toolbar. + +What changes: + +- On the record page (header row and the more-menu) and on every surface the shared console runtime serves (the list toolbar and the console's root action provider), a `type: 'api'` action with `opensInNewTab: true` and a `newTabUrl` now takes that path: the record id resolves the way that surface resolves it, the pre-opened tab goes to `newTabUrl`, and nothing is sent to `target`. A list launch with several rows selected is refused before the tab opens, as for a `script` action. +- A `type: 'api'` action without `newTabUrl` sends its request to `target` as before. + +What to do: nothing. An api action that declares the pair now does what it declares. diff --git a/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.apiNewTabUrl-26747.test.tsx b/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.apiNewTabUrl-26747.test.tsx new file mode 100644 index 00000000000..5b6e628ae0e --- /dev/null +++ b/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.apiNewTabUrl-26747.test.tsx @@ -0,0 +1,183 @@ +/** + * 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#26747 — the shared console action runtime (list pages, the + * list toolbar, the console root provider) honours `opensInNewTab` + + * `newTabUrl` on a `type: 'api'` action: the pre-opened tab goes to + * `newTabUrl` with the selected row's id substituted, and no request is sent. + * + * Driven through a real `ActionRunner` carrying the runtime's own context and + * registered handler set, exactly as `ActionProvider` wires them, and through + * the `apiHandler` the hook returns (what `ConsoleShell` registers). + * + * CONTROL: without `newTabUrl` the api action still sends its request to + * `target`. The fast path's row-count refusal is the server-action one: two + * selected rows refuse before any tab opens. + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { renderHook, act } from '@testing-library/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('@object-ui/i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useObjectLabel: () => ({ + fieldLabel: (_o: any, _n: any, l: any) => l, + fieldOptionLabel: (_o: any, _f: any, _v: any, l: any) => l, + actionParamText: (_o: any, _a: any, _p: any, _attr: any, fallback: any) => fallback, + actionParamOptionLabel: (_o: any, _a: any, _p: any, _v: any, fallback: any) => fallback, + actionDescription: (_o: any, _a: any, fallback: any) => fallback, + }), + useObjectTranslation: () => ({ + t: (key: string, options?: any) => String(options?.defaultValue ?? key), + }), +})); + +vi.mock('../useActionModal', () => ({ + useActionModal: () => ({ + modalHandler: vi.fn(async () => ({ success: true })), + modalElement: null, + closeModal: () => {}, + resolveModalTarget: vi.fn(async () => null), + }), +})); + +vi.mock('../../views/ActionConfirmDialog', () => ({ ActionConfirmDialog: () => null })); +vi.mock('../../views/ActionParamDialog', () => ({ ActionParamDialog: () => null })); +vi.mock('../../views/ActionResultDialog', () => ({ ActionResultDialog: () => null })); +vi.mock('../../views/FlowRunner', () => ({ FlowRunner: () => null })); + +vi.mock('sonner', () => { + const fn: any = vi.fn(); + fn.error = vi.fn(); + fn.success = vi.fn(); + return { toast: fn }; +}); + +import { ActionRunner } from '@object-ui/core'; +import { useConsoleActionRuntime } from '../useConsoleActionRuntime'; + +const TARGET = '/api/v1/export/gapdata_item'; +const NEW_TAB_ACTION = { + name: 'export_tab', + label: 'Export', + type: 'api', + target: TARGET, + opensInNewTab: true, + newTabUrl: '/export/{recordId}', + locations: ['list_toolbar'], +}; + +function stubWindowOpen() { + const tab = { + document: { write: vi.fn(), close: vi.fn() }, + location: { href: 'about:blank' }, + close: vi.fn(), + }; + const open = vi.spyOn(window, 'open').mockImplementation(() => tab as unknown as Window); + return { tab, open }; +} + +/** A real runner wired to the runtime the way `ActionProvider` wires it. */ +function runnerFor(selectedRecords: Array>) { + const { result } = renderHook(() => + useConsoleActionRuntime({ dataSource: {}, objects: [], objectName: 'gapdata_item' }), + ); + const props = result.current.actionProviderProps; + const runner = new ActionRunner({ ...props.context, selectedRecords } as any); + for (const [type, handler] of Object.entries(props.handlers ?? {})) { + runner.registerHandler(type, handler as any); + } + return { runner, runtime: result.current }; +} + +beforeEach(() => { + authFetchSpy.mockReset(); + authFetchSpy.mockImplementation(async () => + new Response(JSON.stringify({ success: true, data: {} }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }), + ); + vi.stubGlobal('fetch', vi.fn(async () => new Response('{}', { status: 200 }))); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe('objectstack#26747 — console runtime: an api action with opensInNewTab + newTabUrl opens the tab and sends nothing', () => { + it('list toolbar, one row selected: the pre-opened tab goes to the interpolated newTabUrl, and no request is sent', async () => { + const { runner } = runnerFor([{ id: 'row 7' }]); + const { tab, open } = stubWindowOpen(); + + let result: any; + await act(async () => { + result = await runner.execute({ ...NEW_TAB_ACTION } as any); + }); + + expect(result.success).toBe(true); + expect(open).toHaveBeenCalledTimes(1); + expect(open).toHaveBeenCalledWith('about:blank', '_blank'); + expect(tab.location.href).toBe(`${window.location.origin}/export/row%207`); + expect(authFetchSpy).not.toHaveBeenCalled(); + expect(globalThis.fetch).not.toHaveBeenCalled(); + }); + + it('the apiHandler the hook returns (what ConsoleShell registers) takes the same path', async () => { + const { runtime } = runnerFor([]); + const { tab } = stubWindowOpen(); + + await act(async () => { + await runtime.apiHandler({ ...NEW_TAB_ACTION, params: { recordId: 'rec-1' } } as any); + }); + + expect(tab.location.href).toBe(`${window.location.origin}/export/rec-1`); + expect(authFetchSpy).not.toHaveBeenCalled(); + }); + + it('two rows selected: refused before any tab opens, with nothing sent', async () => { + const { runner } = runnerFor([{ id: 'a' }, { id: 'b' }]); + const { open } = stubWindowOpen(); + + let result: any; + await act(async () => { + result = await runner.execute({ ...NEW_TAB_ACTION } as any); + }); + + expect(result.success).toBe(false); + expect(open).not.toHaveBeenCalled(); + expect(authFetchSpy).not.toHaveBeenCalled(); + }); + + it('CONTROL: without newTabUrl the api action still sends its request to the target', async () => { + const { newTabUrl: _dropped, ...withoutNewTabUrl } = NEW_TAB_ACTION; + const { runner } = runnerFor([{ id: 'row 7' }]); + const { open } = stubWindowOpen(); + + await act(async () => { + await runner.execute({ ...withoutNewTabUrl } as any); + }); + + expect(authFetchSpy).toHaveBeenCalledTimes(1); + const [url, init] = authFetchSpy.mock.calls[0] as unknown as [string, RequestInit]; + expect(url.endsWith(TARGET)).toBe(true); + expect(init.method).toBe('POST'); + expect(open).not.toHaveBeenCalledWith('about:blank', '_blank'); + }); +}); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.apiNewTabUrl-26747.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.apiNewTabUrl-26747.test.tsx new file mode 100644 index 00000000000..9eedd6d4613 --- /dev/null +++ b/ui/packages/app-shell/src/views/RecordDetailView.apiNewTabUrl-26747.test.tsx @@ -0,0 +1,255 @@ +/** + * 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#26747 — a `type: 'api'` action declaring `opensInNewTab` + + * `newTabUrl` takes the spec's zero-roundtrip path on the record page: the + * pre-opened tab goes to `newTabUrl` with `{recordId}` substituted, and no + * request is sent — from the header row and from its `⋯` more-menu alike. + * + * Before the fix the record page's registered `api` handler never read the + * pair: it sent its usual request to `target`, and no tab opened. + * + * CONTROL: the same api action without `newTabUrl` still sends its request + * to `target`. + * + * Harness: the `RecordDetailView.headerMenuIcons-12529` mount (the real + * record page under a real `I18nProvider`, a metadata context and the real + * `FavoritesProvider`), clicked through the real header and menu, so the + * dispatch runs through the page's own `ActionProvider` and handler set. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, waitFor, fireEvent, cleanup, act } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { MemoryRouter, Routes, Route } from 'react-router-dom'; + +const authFetchSpy = vi.fn(); +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: 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('./ActionParamDialog', () => ({ ActionParamDialog: () => null })); +vi.mock('./ActionResultDialog', () => ({ ActionResultDialog: () => null })); +vi.mock('./FlowRunner', () => ({ FlowRunner: () => null })); +vi.mock('./MetadataInspector', () => ({ + MetadataPanel: () => null, + useMetadataInspector: () => ({ showDebug: false, toggle: () => {} }), +})); + +import { I18nProvider } from '@object-ui/i18n'; +import { MetadataCtx } from '@object-ui/react'; +import { RecordDetailView } from './RecordDetailView'; +import { FavoritesProvider } from '../context/FavoritesProvider'; + +const OBJECT_NAME = 'gapdata_item'; +const RECORD_ID = 'rec item 1'; +const RECORD_PATH = `/apps/gap/${OBJECT_NAME}/record/${encodeURIComponent(RECORD_ID)}`; +const TARGET = '/api/v1/export/gapdata_item'; +/** The `{recordId}` substitution the fast path performs (URL-encoded). */ +const EXPECTED_TAB_URL = `${window.location.origin}/export/${encodeURIComponent(RECORD_ID)}`; + +const newTabAction = (name: string, label: string) => ({ + name, + label, + type: 'api', + target: TARGET, + opensInNewTab: true, + newTabUrl: '/export/{recordId}', + locations: ['record_header'], +}); + +const urlAction = (name: string, label: string) => ({ + name, + label, + type: 'url', + target: `https://example.com/${name}`, + locations: ['record_header'], +}); + +async function mountRecordPage(actions: unknown[]) { + const objects = [ + { + name: OBJECT_NAME, + label: 'Gap Item', + managedBy: 'platform', + fields: { + id: { type: 'text', label: 'Id' }, + name: { type: 'text', label: 'Name' }, + }, + actions, + }, + ]; + const metadata = { + objects, + pages: [], + loading: false, + error: null, + refresh: async () => {}, + invalidate: () => {}, + ensureType: async () => [], + getItem: async () => null, + getItemsByType: () => [], + } as any; + const dataSource = { + find: vi.fn(async () => ({ data: [] })), + findOne: vi.fn(async () => ({ id: RECORD_ID, name: 'Item One' })), + create: vi.fn(async () => ({})), + update: vi.fn(async () => ({})), + delete: vi.fn(async () => ({})), + } as any; + render( + + + + + + {}} />} + /> + + + + + , + ); + await waitFor(() => expect(dataSource.findOne).toHaveBeenCalled()); + await waitFor(() => expect(document.querySelector('[role="toolbar"]')).toBeTruthy()); + // Whatever the mount itself fetched is not the dispatch under test. + authFetchSpy.mockClear(); + (globalThis.fetch as any).mockClear(); +} + +/** A stand-in for the tab `window.open('about:blank')` hands back. */ +function stubWindowOpen() { + const tab = { + document: { write: vi.fn(), close: vi.fn() }, + location: { href: 'about:blank' }, + close: vi.fn(), + }; + const open = vi.spyOn(window, 'open').mockImplementation(() => tab as unknown as Window); + return { tab, open }; +} + +/** Every request the click sent, through either fetch. */ +function requestUrls(): string[] { + return [...authFetchSpy.mock.calls, ...(globalThis.fetch as any).mock.calls].map((c) => String(c[0])); +} + +async function openOverflow(): Promise { + const trigger = screen.getByRole('button', { name: 'More actions' }); + fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false, pointerType: 'mouse' }); + await waitFor(() => expect(screen.getByRole('menu')).toBeInTheDocument()); + return screen.getByRole('menu'); +} + +beforeEach(() => { + cleanup(); + localStorage.clear(); + authFetchSpy.mockReset(); + authFetchSpy.mockImplementation(async () => + new Response(JSON.stringify({ success: true, data: {} }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }), + ); + vi.stubGlobal( + 'fetch', + vi.fn(async () => + new Response(JSON.stringify({ data: [] }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }), + ), + ); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe('objectstack#26747 — record page: an api action with opensInNewTab + newTabUrl opens the tab and sends nothing', () => { + it('from the header row: the pre-opened tab goes to the interpolated newTabUrl, and no request reaches the target', async () => { + await mountRecordPage([newTabAction('export_tab', 'Export')]); + const { tab, open } = stubWindowOpen(); + + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Export' })); + }); + + await waitFor(() => expect(tab.location.href).toBe(EXPECTED_TAB_URL)); + expect(open).toHaveBeenCalledTimes(1); + expect(open).toHaveBeenCalledWith('about:blank', '_blank'); + expect(requestUrls().filter((u) => u.includes(TARGET) || u.includes('/export/'))).toEqual([]); + expect(authFetchSpy).not.toHaveBeenCalled(); + }); + + it('from the ⋯ more-menu: the same click opens the same tab, and no request reaches the target', async () => { + // Three actions fill the header's inline slots; the fourth folds into the ⋯. + await mountRecordPage([ + urlAction('convert_lead', 'Convert Lead'), + urlAction('schedule_follow_up', 'Schedule Follow-up'), + urlAction('log_call', 'Log a Call'), + newTabAction('export_tab', 'Export'), + ]); + expect(screen.queryByRole('button', { name: 'Export' })).toBeNull(); + const { tab, open } = stubWindowOpen(); + + const menu = await openOverflow(); + const item = Array.from(menu.querySelectorAll('[role="menuitem"]')) + .find((el) => (el.textContent ?? '').trim() === 'Export'); + expect(item).toBeTruthy(); + await act(async () => { + fireEvent.click(item!); + }); + + await waitFor(() => expect(tab.location.href).toBe(EXPECTED_TAB_URL)); + expect(open).toHaveBeenCalledTimes(1); + expect(open).toHaveBeenCalledWith('about:blank', '_blank'); + expect(requestUrls().filter((u) => u.includes(TARGET) || u.includes('/export/'))).toEqual([]); + expect(authFetchSpy).not.toHaveBeenCalled(); + }); + + it('CONTROL: the same api action without newTabUrl still sends its request to the target', async () => { + const { newTabUrl: _dropped, ...withoutNewTabUrl } = newTabAction('export_tab', 'Export'); + await mountRecordPage([withoutNewTabUrl]); + const { open } = stubWindowOpen(); + + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Export' })); + }); + + await waitFor(() => expect(authFetchSpy).toHaveBeenCalledTimes(1)); + const [url, init] = authFetchSpy.mock.calls[0] as unknown as [string, RequestInit]; + expect(url.endsWith(TARGET)).toBe(true); + expect(init.method).toBe('POST'); + expect(open).not.toHaveBeenCalledWith('about:blank', '_blank'); + }); +}); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 0764b7185c4..44ab1b8d8a4 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -35,7 +35,7 @@ import { RelatedRecordActionsBridge } from './RelatedRecordActionsBridge.js'; import { withPageTabsUrlSync } from '../utils/pageTabsUrlSync.js'; import { RECORD_DETAIL_TAB_PARAM, RECORD_TRAIL_PARAM, decodeRecordTrail, buildRecordTrailHref } from '../urlParams.js'; import { resolveActionParams } from '@object-ui/fields'; -import { createConsoleServerActionHandler } from '../utils/consoleServerAction.js'; +import { createConsoleServerActionHandler, withNewTabUrlFastPath } from '../utils/consoleServerAction.js'; import { modalTargetRefusalMessage } from '../utils/modalTargetDiagnostics.js'; import { actionContextOrg } from '../utils/actionContextOrg.js'; import { resolveHostAppSegment } from '../utils/appRoute.js'; @@ -1582,6 +1582,16 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri [authFetch], ); + // The registered `api` handler: {@link apiHandler}, except that an action + // declaring `opensInNewTab` + `newTabUrl` takes the server-action handler's + // zero-roundtrip new-tab path against THIS page's record, sending no request + // — from the header and its more-menu alike (objectstack#26747). Same + // composition as `useConsoleActionRuntime`. + const apiActionHandler = useMemo( + () => withNewTabUrlFastPath(apiHandler, serverActionHandler), + [apiHandler, serverActionHandler], + ); + /** * `type: 'modal'` dispatch — same rule as the shared console runtime (see * `useConsoleActionRuntime.modalActionHandler`): CLIENT-SIDE ONLY. The @@ -3841,7 +3851,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri onParamCollection={paramCollectionHandler} onResultDialog={resultDialogHandler} onModal={modalHandler} - handlers={{ api: apiHandler, flow: flowHandler, script: serverActionHandler, modal: modalActionHandler }} + handlers={{ api: apiActionHandler, flow: flowHandler, script: serverActionHandler, modal: modalActionHandler }} >
From 1bcc587b53df049e4ddc5dfd584af3eee41ecbc1 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 20:48:00 +0000 Subject: [PATCH 3/3] refactor(app-shell): keep the newTabUrl routing rule out of the factory-stubbed module Nineteen app-shell tests stub `utils/consoleServerAction` with a factory that names only `createConsoleServerActionHandler`, so a rule exported from there was undefined under each of them and the record page and the runtime hook threw on mount. The predicate and the api-handler composition now live in `utils/newTabUrlFastPath`, which those stubs do not touch. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSH8FbKjEztmGT1sbB --- .../src/hooks/useConsoleActionRuntime.tsx | 3 +- .../src/utils/consoleServerAction.ts | 44 +------------ .../app-shell/src/utils/newTabUrlFastPath.ts | 62 +++++++++++++++++++ .../app-shell/src/views/RecordDetailView.tsx | 3 +- 4 files changed, 67 insertions(+), 45 deletions(-) create mode 100644 ui/packages/app-shell/src/utils/newTabUrlFastPath.ts diff --git a/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx b/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx index 3baa1dd6223..4c2a2da34f8 100644 --- a/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx +++ b/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx @@ -52,7 +52,8 @@ 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 { createConsoleServerActionHandler, withNewTabUrlFastPath } from '../utils/consoleServerAction.js'; +import { createConsoleServerActionHandler } from '../utils/consoleServerAction.js'; +import { withNewTabUrlFastPath } from '../utils/newTabUrlFastPath.js'; import { modalTargetRefusalMessage } from '../utils/modalTargetDiagnostics.js'; import { actionContextOrg } from '../utils/actionContextOrg.js'; import { resolveHostAppSegment } from '../utils/appRoute.js'; diff --git a/ui/packages/app-shell/src/utils/consoleServerAction.ts b/ui/packages/app-shell/src/utils/consoleServerAction.ts index 30af0ee14a0..95a9cf072e1 100644 --- a/ui/packages/app-shell/src/utils/consoleServerAction.ts +++ b/ui/packages/app-shell/src/utils/consoleServerAction.ts @@ -49,11 +49,11 @@ import { resolveServerActionRecordId, type ActionContext, type ActionDef, - type ActionResult, type ServerActionFetch, type ServerActionHandler, type ServerActionRecordIdResolver, } from '@object-ui/core'; +import { takesNewTabUrlFastPath } from './newTabUrlFastPath.js'; /** * i18next-style translate function: `t(key, englishDefault)` returns the @@ -166,48 +166,6 @@ function openInTab(preOpenedTab: Window | null, url: string, t: ConsoleServerAct } } -/** - * Whether `action` takes the zero-roundtrip `newTabUrl` fast path: - * `opensInNewTab` plus a non-empty `newTabUrl`. The spec gives that pair one - * meaning whatever the action's `type` — navigate the pre-opened tab, no - * request — so a host's `type: 'api'` handler asks this and hands such an - * action to the handler {@link createConsoleServerActionHandler} builds, - * instead of sending its own request to `target`. - */ -export function takesNewTabUrlFastPath(action: ActionDef): action is ActionDef & { newTabUrl: string } { - return !!action.opensInNewTab && typeof action.newTabUrl === 'string' && action.newTabUrl !== ''; -} - -/** - * A host's registered `type: 'api'` handler, made to honour the `newTabUrl` - * fast path: an action that {@link takesNewTabUrlFastPath} goes to - * `consoleHandler` (the handler {@link createConsoleServerActionHandler} - * built for the same surface, so the record id resolves the way that surface - * resolves it), and every other action to `apiHandler` unchanged. - * - * Without it the console's api handlers sent their request to `target` and - * never read the pair, so a `type: 'api'` action declaring `opensInNewTab` + - * `newTabUrl` opened no tab and POSTed instead, from the record header, its - * more-menu and the list toolbar alike (objectstack#26747). The pair's early - * row-count refusal is the fast path's own, forwarded only for those actions; - * an ordinary api action keeps having none. - */ -export function withNewTabUrlFastPath( - apiHandler: (action: ActionDef, context?: ActionContext) => Promise, - consoleHandler: ServerActionHandler, -): ServerActionHandler { - return Object.assign( - (action: ActionDef, context?: ActionContext) => (takesNewTabUrlFastPath(action) - ? consoleHandler(action, context) - : apiHandler(action, context)), - { - refuseBeforeInput: (action: ActionDef, context?: ActionContext) => (takesNewTabUrlFastPath(action) - ? consoleHandler.refuseBeforeInput?.(action, context) - : undefined), - }, - ); -} - export function createConsoleServerActionHandler(opts: ConsoleServerActionOptions): ServerActionHandler { const dispatch = createServerActionHandler({ fetch: opts.fetch, diff --git a/ui/packages/app-shell/src/utils/newTabUrlFastPath.ts b/ui/packages/app-shell/src/utils/newTabUrlFastPath.ts new file mode 100644 index 00000000000..3ef0dcca408 --- /dev/null +++ b/ui/packages/app-shell/src/utils/newTabUrlFastPath.ts @@ -0,0 +1,62 @@ +/** + * 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 `newTabUrl` fast path's routing rule, shared by the console server-action + * handler (`consoleServerAction`) and the hosts that register a `type: 'api'` + * handler beside it (`useConsoleActionRuntime`, `RecordDetailView`). + * + * It lives apart from `consoleServerAction` on purpose: the hosts' tests stub + * that module with a factory, and a rule kept there would vanish under every + * such stub. Kept here, an api action is routed by the same rule under test as + * in the console. + */ + +import type { ActionContext, ActionDef, ActionResult, ServerActionHandler } from '@object-ui/core'; + +/** + * Whether `action` takes the zero-roundtrip `newTabUrl` fast path: + * `opensInNewTab` plus a non-empty `newTabUrl`. The spec gives that pair one + * meaning whatever the action's `type` — navigate the pre-opened tab, no + * request — so a host's `type: 'api'` handler asks this and hands such an + * action to the handler `createConsoleServerActionHandler` builds, + * instead of sending its own request to `target`. + */ +export function takesNewTabUrlFastPath(action: ActionDef): action is ActionDef & { newTabUrl: string } { + return !!action.opensInNewTab && typeof action.newTabUrl === 'string' && action.newTabUrl !== ''; +} + +/** + * A host's registered `type: 'api'` handler, made to honour the `newTabUrl` + * fast path: an action that {@link takesNewTabUrlFastPath} goes to + * `consoleHandler` (the handler `createConsoleServerActionHandler` + * built for the same surface, so the record id resolves the way that surface + * resolves it), and every other action to `apiHandler` unchanged. + * + * Without it the console's api handlers sent their request to `target` and + * never read the pair, so a `type: 'api'` action declaring `opensInNewTab` + + * `newTabUrl` opened no tab and POSTed instead, from the record header, its + * more-menu and the list toolbar alike (objectstack#26747). The pair's early + * row-count refusal is the fast path's own, forwarded only for those actions; + * an ordinary api action keeps having none. + */ +export function withNewTabUrlFastPath( + apiHandler: (action: ActionDef, context?: ActionContext) => Promise, + consoleHandler: ServerActionHandler, +): ServerActionHandler { + return Object.assign( + (action: ActionDef, context?: ActionContext) => (takesNewTabUrlFastPath(action) + ? consoleHandler(action, context) + : apiHandler(action, context)), + { + refuseBeforeInput: (action: ActionDef, context?: ActionContext) => (takesNewTabUrlFastPath(action) + ? consoleHandler.refuseBeforeInput?.(action, context) + : undefined), + }, + ); +} diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 44ab1b8d8a4..f465d8f0637 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -35,7 +35,8 @@ import { RelatedRecordActionsBridge } from './RelatedRecordActionsBridge.js'; import { withPageTabsUrlSync } from '../utils/pageTabsUrlSync.js'; import { RECORD_DETAIL_TAB_PARAM, RECORD_TRAIL_PARAM, decodeRecordTrail, buildRecordTrailHref } from '../urlParams.js'; import { resolveActionParams } from '@object-ui/fields'; -import { createConsoleServerActionHandler, withNewTabUrlFastPath } from '../utils/consoleServerAction.js'; +import { createConsoleServerActionHandler } from '../utils/consoleServerAction.js'; +import { withNewTabUrlFastPath } from '../utils/newTabUrlFastPath.js'; import { modalTargetRefusalMessage } from '../utils/modalTargetDiagnostics.js'; import { actionContextOrg } from '../utils/actionContextOrg.js'; import { resolveHostAppSegment } from '../utils/appRoute.js';