diff --git a/services/platform/app/features/automations/components/automation-editor.test.tsx b/services/platform/app/features/automations/components/automation-editor.test.tsx index be713f5e79..9cd33cce10 100644 --- a/services/platform/app/features/automations/components/automation-editor.test.tsx +++ b/services/platform/app/features/automations/components/automation-editor.test.tsx @@ -1,6 +1,7 @@ import { ActiveEditorProvider } from '@tale/ui/editor'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { useState, type AnchorHTMLAttributes } from 'react'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { checkAccessibility } from '@/tests/utils/a11y'; import { act, render, screen, waitFor, within } from '@/tests/utils/render'; @@ -26,6 +27,7 @@ const { startRun, deploy, toastSpy, + refetch, } = vi.hoisted(() => ({ state: { document: { @@ -44,6 +46,8 @@ const { deployedUnpinnedAgentNodes: undefined as string[] | undefined, /** A `?version=` the read refuses with `AUTOMATION_VERSION_UNKNOWN`. */ missingVersion: undefined as number | undefined, + detailError: undefined as Error | undefined, + realDetailRead: false, }, /** The org's projects and the automation's bindings — the run-scope picker * appears only when two or more projects are bound. */ @@ -66,6 +70,7 @@ const { startRun: { mutate: vi.fn(), isPending: false }, deploy: { mutate: vi.fn(), isPending: false, variables: undefined }, toastSpy: vi.fn(), + refetch: vi.fn(), })); // `EditorActions` owns every piece of save feedback and reaches for the @@ -92,63 +97,91 @@ vi.mock('@/app/features/projects/hooks/queries', () => ({ useProjectHarnesses: () => ({ data: { harnesses: [], models: [] } }), })); -vi.mock('../hooks/queries', () => ({ - useAutomation: (_organizationId: string, _name: string, version?: number) => - version !== undefined && version === state.missingVersion - ? { - data: undefined, - isPending: false, - isError: true, - error: { - data: { - code: 'AUTOMATION_VERSION_UNKNOWN', - message: `version ${version} does not exist`, - latestVersion: state.version, - }, - }, - } - : { - data: { - document: - version === state.deployedVersion && - state.deployedDocument !== undefined - ? state.deployedDocument - : state.document, - version: version ?? state.version, - deployedVersion: state.deployedVersion, - ...(state.presentation !== undefined - ? { presentation: state.presentation } - : {}), - settings: state.settings, - taskContract: state.taskContract, - ...(state.deployedUnpinnedAgentNodes !== undefined - ? { deployedUnpinnedAgentNodes: state.deployedUnpinnedAgentNodes } - : {}), - }, - isPending: false, - isError: false, - error: null, +vi.mock('../hooks/queries', async (importOriginal) => { + const actual = await importOriginal(); + return { + useAutomation: ( + _organizationId: string, + _name: string, + version?: number, + ) => + state.realDetailRead + ? actual.useAutomation(_organizationId, _name, version) + : version === undefined && state.detailError !== undefined + ? { + data: undefined, + isPending: false, + isError: true, + error: state.detailError, + isFetching: false, + errorUpdateCount: 1, + refetch, + } + : version !== undefined && version === state.missingVersion + ? { + data: undefined, + isPending: false, + isError: true, + isFetching: false, + errorUpdateCount: 1, + error: { + data: { + code: 'AUTOMATION_VERSION_UNKNOWN', + message: `version ${version} does not exist`, + latestVersion: state.version, + }, + }, + refetch, + } + : { + data: { + document: + version === state.deployedVersion && + state.deployedDocument !== undefined + ? state.deployedDocument + : state.document, + version: version ?? state.version, + deployedVersion: state.deployedVersion, + ...(state.presentation !== undefined + ? { presentation: state.presentation } + : {}), + settings: state.settings, + taskContract: state.taskContract, + ...(state.deployedUnpinnedAgentNodes !== undefined + ? { + deployedUnpinnedAgentNodes: + state.deployedUnpinnedAgentNodes, + } + : {}), + }, + isPending: false, + isError: false, + isFetching: false, + errorUpdateCount: 0, + error: null, + refetch, + }, + useAutomationVersions: () => ({ + data: [ + { + version: 3, + message: 'tightened the prompt', + createdBy: 'user:a', + createdAt: 1_700_000_100_000, }, - useAutomationVersions: () => ({ - data: [ - { - version: 3, - message: 'tightened the prompt', - createdBy: 'user:a', - createdAt: 1_700_000_100_000, - }, - { - version: 2, - message: 'first cut', - createdBy: 'user:a', - createdAt: 1_700_000_000_000, - }, - ], - }), - useAutomationRuns: () => ({ data: runsData }), - useAutomationProjects: () => ({ data: projectsData.bound }), - useNodeTypeCatalog: () => ({ data: undefined, isError: false }), -})); + { + version: 2, + message: 'first cut', + createdBy: 'user:a', + createdAt: 1_700_000_000_000, + }, + ], + }), + useAutomationRuns: () => ({ data: runsData }), + useAutomationProjects: () => ({ data: projectsData.bound }), + useNodeTypeCatalog: () => ({ data: undefined, isError: false }), + }; +}); vi.mock('../hooks/mutations', () => ({ useSaveAutomation: () => saveMutation, @@ -325,6 +358,199 @@ beforeEach(() => { state.deployedVersion = 2; state.deployedUnpinnedAgentNodes = undefined; state.missingVersion = undefined; + state.detailError = undefined; + state.realDetailRead = false; + refetch.mockClear(); +}); + +const detailQueryKey = [ + 'backend', + 'org-1', + 'automation', + 'detail', + 'billing/dunning', + 'latest', +]; + +function realReadPage() { + state.realDetailRead = true; + const client = new QueryClient({ + defaultOptions: { queries: { retryDelay: 0, gcTime: Infinity } }, + }); + const view = render( + + + {page()} + , + ); + return { ...view, client }; +} + +function automationResponse() { + return Response.json({ + document: state.document, + version: state.version, + deployedVersion: state.deployedVersion, + }); +} + +function failedReadResponse() { + return Response.json({ message: 'Service unavailable' }, { status: 503 }); +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('AutomationEditor real detail read recovery', () => { + it.each(['retry', 'outside'] as const)( + 'keeps keyboard retry stable and respects %s focus on recovery', + async (recoveryFocus) => { + let recovering = false; + let finishRead: ((response: Response) => void) | undefined; + vi.stubGlobal( + 'fetch', + vi.fn((url: string) => { + if ( + new URL(url, window.location.origin).searchParams.has('version') + ) { + return Promise.resolve(automationResponse()); + } + if (!recovering) return Promise.resolve(failedReadResponse()); + return new Promise((resolve) => { + finishRead = resolve; + }); + }), + ); + const { user } = realReadPage(); + const retryButton = await screen.findByRole( + 'button', + { name: 'Try again' }, + { timeout: 15000 }, + ); + await user.click(screen.getByRole('button', { name: 'Outside editor' })); + await user.tab(); + expect(retryButton).toHaveFocus(); + recovering = true; + await user.keyboard('{Enter}'); + await waitFor(() => expect(finishRead).toBeDefined()); + expect(retryButton).toHaveFocus(); + expect(screen.getByRole('alert')).toHaveTextContent( + 'Service unavailable', + ); + expect(screen.queryByText('Loading the automation…')).toBeNull(); + expect(retryButton).toHaveAttribute('aria-busy', 'true'); + await act(async () => { + finishRead?.( + Response.json({ message: 'Still unavailable' }, { status: 400 }), + ); + }); + await waitFor(() => expect(retryButton).not.toHaveAttribute('aria-busy')); + expect(screen.getByRole('button', { name: 'Try again' })).toBe( + retryButton, + ); + expect(retryButton).toHaveFocus(); + expect(screen.getByRole('alert')).toHaveTextContent('Still unavailable'); + finishRead = undefined; + await user.keyboard('{Enter}'); + await waitFor(() => expect(finishRead).toBeDefined()); + if (recoveryFocus === 'outside') { + await user.click( + screen.getByRole('button', { name: 'Outside editor' }), + ); + } + await act(async () => { + finishRead?.(automationResponse()); + }); + await screen.findByTestId('canvas'); + await waitFor(() => expect(screen.queryByRole('alert')).toBeNull()); + await waitFor(() => { + const target = + recoveryFocus === 'retry' + ? screen.getByRole('region', { name: 'Editor' }) + : screen.getByRole('button', { name: 'Outside editor' }); + expect(target).toHaveFocus(); + }); + }, + 30000, + ); + + it('keeps the canvas, inspector and dirty draft after a failed background read', async () => { + let failRefresh = false; + vi.stubGlobal( + 'fetch', + vi.fn((url: string) => { + const deployed = new URL(url, window.location.origin).searchParams.has( + 'version', + ); + return Promise.resolve( + failRefresh && !deployed + ? failedReadResponse() + : automationResponse(), + ); + }), + ); + const { user, client } = realReadPage(); + await screen.findByTestId('canvas'); + await editTheNode(user); + const canvas = screen.getByTestId('canvas'); + const draftField = whenField(); + expect(draftField).toHaveValue('x'); + failRefresh = true; + await act(async () => { + await client.invalidateQueries({ queryKey: detailQueryKey }); + }); + await waitFor( + () => expect(client.getQueryState(detailQueryKey)?.status).toBe('error'), + { timeout: 15000 }, + ); + expect(screen.getByTestId('canvas')).toBe(canvas); + expect(whenField()).toBe(draftField); + expect(draftField).toHaveValue('x'); + expect(saveButton()).toBeEnabled(); + expect(screen.queryByRole('alert')).toBeNull(); + }, 30000); + + it('does not steal outside focus when the initial failure settles', async () => { + let finishRead: ((response: Response) => void) | undefined; + vi.stubGlobal( + 'fetch', + vi.fn( + () => + new Promise((resolve) => { + finishRead = resolve; + }), + ), + ); + const { user } = realReadPage(); + await user.click(screen.getByRole('button', { name: 'Outside editor' })); + await act(async () => { + finishRead?.( + Response.json({ message: 'Service unavailable' }, { status: 400 }), + ); + }); + await screen.findByRole('alert', {}, { timeout: 15000 }); + expect( + screen.getByRole('button', { name: 'Outside editor' }), + ).toHaveFocus(); + }, 30000); +}); + +describe('AutomationEditor detail read failure', () => { + it('names the error and retries instead of staying loading', async () => { + state.detailError = new Error('Request failed with status 503'); + const { user } = renderPage(); + + expect(screen.getByRole('alert')).toHaveTextContent( + "Couldn't load the automation: Request failed with status 503", + ); + const retryButton = screen.getByRole('button', { name: 'Try again' }); + expect(retryButton).not.toHaveFocus(); + expect(screen.queryByText('Loading the automation…')).toBeNull(); + + await user.click(retryButton); + expect(refetch).toHaveBeenCalledOnce(); + }); }); /** diff --git a/services/platform/app/features/automations/components/automation-editor.tsx b/services/platform/app/features/automations/components/automation-editor.tsx index 451ef1d7b1..c094b015c3 100644 --- a/services/platform/app/features/automations/components/automation-editor.tsx +++ b/services/platform/app/features/automations/components/automation-editor.tsx @@ -3,6 +3,7 @@ import { Alert } from '@tale/ui/alert'; import { Badge } from '@tale/ui/badge'; import { Button } from '@tale/ui/button'; +import { CatalogLoadError } from '@tale/ui/catalog/catalog-view'; import { cn } from '@tale/ui/cn'; import { ContentArea } from '@tale/ui/content-area'; import { ConfirmDialog } from '@tale/ui/dialog/confirm-dialog'; @@ -41,6 +42,7 @@ import { useCallback, useId, useMemo, useRef, useState } from 'react'; import { useProjects } from '@/app/features/projects/hooks/queries'; import { useAbility } from '@/app/hooks/use-ability'; +import { readStateOf } from '@/app/lib/backend/read-state'; import type { NodeDef, Automation } from '@/lib/engine/core/types'; import { useT } from '@/lib/i18n/client'; @@ -263,6 +265,12 @@ function AutomationEditorScope({ automationSlug, version, ); + const automationRead = readStateOf(automationQuery); + const editorRegionRef = useRef(null); + const readErrorRef = useRef(''); + if (automationQuery.isError) { + readErrorRef.current = automationErrorMessage(automationQuery.error); + } const deployedQuery = useAutomation( organizationId, automationSlug, @@ -495,6 +503,19 @@ function AutomationEditorScope({ ); } + if (automationRead.unavailable) { + return ( + + void automationQuery.refetch()} + onFocusLost={() => editorRegionRef.current?.focus()} + /> + + ); + } if (!automation) { return ( @@ -794,7 +815,13 @@ function AutomationEditorScope({ table's rows, the canvas's background runs behind the pill, and its own zoom cluster and action toolbar (`FlowCanvas`) keep themselves clear of it instead of the workbench flooring on it site-wide. */} -
+
{/* A refused RUN, kept inline: it is the engine's own account of why nothing started, which the author has to read next to the automation it concerns. Save feedback goes through the editor cluster instead. diff --git a/services/platform/messages/de.yml b/services/platform/messages/de.yml index f4c920b2da..a06010694b 100644 --- a/services/platform/messages/de.yml +++ b/services/platform/messages/de.yml @@ -650,6 +650,8 @@ automations: Organisation. detail: loading: Automatisierung wird geladen … + loadFailed: + title: Automatisierung konnte nicht geladen werden # Eine gelöschte Automatisierung behält ihre Laufhistorie, bis die # Aufbewahrung sie entfernt; die Läufe-Seiten öffnen unter diesem Banner. deleted: diff --git a/services/platform/messages/en.yml b/services/platform/messages/en.yml index 012b2afba2..eca1650555 100644 --- a/services/platform/messages/en.yml +++ b/services/platform/messages/en.yml @@ -620,6 +620,8 @@ automations: organization. detail: loading: Loading the automation… + loadFailed: + title: Couldn't load the automation # A deleted automation keeps its run history until retention removes # it; the Runs pages still open under this banner. deleted: diff --git a/services/platform/messages/fr.yml b/services/platform/messages/fr.yml index 3d6e65c4cd..95b27da429 100644 --- a/services/platform/messages/fr.yml +++ b/services/platform/messages/fr.yml @@ -657,6 +657,8 @@ automations: organisation. detail: loading: Chargement de l’automatisation… + loadFailed: + title: Impossible de charger l’automatisation # Une automatisation supprimée garde son historique d’exécutions jusqu’à # ce que la rétention l’efface ; les pages Exécutions s’ouvrent sous ce # bandeau.