From aee90c0b70dc801355572a5a5d5b65f7d3ae8c5e Mon Sep 17 00:00:00 2001 From: Tegan Churchill Date: Tue, 3 Nov 2026 15:22:25 -0800 Subject: [PATCH 01/19] WIP --- .../catalog/browser/catalog.generated.json | 57 +++++++++++++++++- src/lib/catalog/browser/catalog.generated.ts | 58 ++++++++++++++++++- .../examples/continue-as-new/example.ts | 56 ++++++++++++++++++ .../examples/continue-as-new/workflow.ts | 41 +++++++++++++ .../catalog/worker/examples/corpus.test.ts | 4 ++ src/lib/catalog/worker/examples/index.ts | 50 ++++++++-------- src/lib/catalog/worker/workflows.ts | 1 + .../table-body-cell.svelte | 8 +++ src/lib/i18n/locales/en/workflows.ts | 6 ++ src/lib/pages/workflow-chain.svelte | 55 ++++++++++++++++++ src/lib/utilities/route-for-base-path.test.ts | 2 + src/lib/utilities/route-for.ts | 11 ++++ .../chain/[workflow]/[run]/+page.svelte | 5 ++ 13 files changed, 329 insertions(+), 25 deletions(-) create mode 100644 src/lib/catalog/worker/examples/continue-as-new/example.ts create mode 100644 src/lib/catalog/worker/examples/continue-as-new/workflow.ts create mode 100644 src/lib/pages/workflow-chain.svelte create mode 100644 src/routes/(app)/namespaces/[namespace]/workflows/chain/[workflow]/[run]/+page.svelte diff --git a/src/lib/catalog/browser/catalog.generated.json b/src/lib/catalog/browser/catalog.generated.json index b5c0dde3c2..b8fae5a22e 100644 --- a/src/lib/catalog/browser/catalog.generated.json +++ b/src/lib/catalog/browser/catalog.generated.json @@ -1,5 +1,5 @@ { - "sourceHash": "ab1d28559cd8149433f8505b38591843db129021116c4f63f3a2a9f5e2b9f690", + "sourceHash": "91d6c0b568d98f47fca726e41b49f2b221e088705072c3417318a553de042dfc", "descriptors": [ { "id": "activity-heartbeat", @@ -228,6 +228,61 @@ }, "source": { "id": "oss", "label": "OSS" } }, + { + "id": "continue-as-new", + "title": "Continue-As-New chain", + "description": "Creates a bounded chain of workflow runs with the same Workflow ID and distinct Run IDs, then completes the final run.", + "capabilityTags": ["continue-as-new", "timers", "terminal-outcome"], + "expectedEvidence": [ + "Five runs with the same Workflow ID and distinct Run IDs using the default inputs.", + "The first four runs have Continued-As-New status and link to the next run; the fifth completes.", + "Each run contains a durable timer and carries its progress into the next run through workflow input.", + "The final workflow result reports the total number of runs in the chain." + ], + "input": { + "defaultValue": [5, 2], + "schema": { + "type": "array", + "prefixItems": [ + { + "title": "Total runs in the chain", + "type": "integer", + "minimum": 1, + "maximum": 25 + }, + { + "title": "Delay per run in seconds", + "type": "integer", + "minimum": 1, + "maximum": 30 + } + ], + "items": false, + "maxItems": 2 + } + }, + "startOptions": { + "defaultValue": {}, + "schema": { + "type": "object", + "properties": { + "details": { "type": "string" }, + "searchAttributes": { "type": "object" }, + "summary": { "type": "string" }, + "workflowStartDelay": { "type": "string" }, + "workflowId": { "type": "string", "minLength": 1 } + } + } + }, + "execution": { + "kind": "workflow", + "targetId": "shared-workflows", + "namespace": "default", + "taskQueue": "ui-catalog", + "workflowType": "continueAsNewChain" + }, + "source": { "id": "oss", "label": "OSS" } + }, { "id": "hello", "title": "Hello activity", diff --git a/src/lib/catalog/browser/catalog.generated.ts b/src/lib/catalog/browser/catalog.generated.ts index c737c1e4dd..f7e95c22cf 100644 --- a/src/lib/catalog/browser/catalog.generated.ts +++ b/src/lib/catalog/browser/catalog.generated.ts @@ -2,7 +2,7 @@ import type { BrowserCatalogArtifact } from './types'; export const catalogArtifact: BrowserCatalogArtifact = { sourceHash: - 'ab1d28559cd8149433f8505b38591843db129021116c4f63f3a2a9f5e2b9f690', + '91d6c0b568d98f47fca726e41b49f2b221e088705072c3417318a553de042dfc', descriptors: [ { id: 'activity-heartbeat', @@ -233,6 +233,62 @@ export const catalogArtifact: BrowserCatalogArtifact = { }, source: { id: 'oss', label: 'OSS' }, }, + { + id: 'continue-as-new', + title: 'Continue-As-New chain', + description: + 'Creates a bounded chain of workflow runs with the same Workflow ID and distinct Run IDs, then completes the final run.', + capabilityTags: ['continue-as-new', 'timers', 'terminal-outcome'], + expectedEvidence: [ + 'Five runs with the same Workflow ID and distinct Run IDs using the default inputs.', + 'The first four runs have Continued-As-New status and link to the next run; the fifth completes.', + 'Each run contains a durable timer and carries its progress into the next run through workflow input.', + 'The final workflow result reports the total number of runs in the chain.', + ], + input: { + defaultValue: [5, 2], + schema: { + type: 'array', + prefixItems: [ + { + title: 'Total runs in the chain', + type: 'integer', + minimum: 1, + maximum: 25, + }, + { + title: 'Delay per run in seconds', + type: 'integer', + minimum: 1, + maximum: 30, + }, + ], + items: false, + maxItems: 2, + }, + }, + startOptions: { + defaultValue: {}, + schema: { + type: 'object', + properties: { + details: { type: 'string' }, + searchAttributes: { type: 'object' }, + summary: { type: 'string' }, + workflowStartDelay: { type: 'string' }, + workflowId: { type: 'string', minLength: 1 }, + }, + }, + }, + execution: { + kind: 'workflow', + targetId: 'shared-workflows', + namespace: 'default', + taskQueue: 'ui-catalog', + workflowType: 'continueAsNewChain', + }, + source: { id: 'oss', label: 'OSS' }, + }, { id: 'hello', title: 'Hello activity', diff --git a/src/lib/catalog/worker/examples/continue-as-new/example.ts b/src/lib/catalog/worker/examples/continue-as-new/example.ts new file mode 100644 index 0000000000..7c83c8d2b6 --- /dev/null +++ b/src/lib/catalog/worker/examples/continue-as-new/example.ts @@ -0,0 +1,56 @@ +import { continueAsNewChain } from './workflow.js'; +import type { RuntimeJsonDocument } from '../../../browser/types.js'; +import type { CatalogExampleDefinition } from '../../registry.js'; + +const input: RuntimeJsonDocument = { + defaultValue: [5, 2], + schema: { + type: 'array', + prefixItems: [ + { + title: 'Total runs in the chain', + type: 'integer', + minimum: 1, + maximum: 25, + }, + { + title: 'Delay per run in seconds', + type: 'integer', + minimum: 1, + maximum: 30, + }, + ], + items: false, + maxItems: 2, + }, +}; + +const startOptions: RuntimeJsonDocument = { + defaultValue: {}, + schema: { + type: 'object', + properties: { workflowId: { type: 'string', minLength: 1 } }, + }, +}; + +export const catalogExample: CatalogExampleDefinition = { + id: 'continue-as-new', + title: 'Continue-As-New chain', + description: + 'Creates a bounded chain of workflow runs with the same Workflow ID and distinct Run IDs, then completes the final run.', + capabilityTags: ['continue-as-new', 'timers', 'terminal-outcome'], + expectedEvidence: [ + 'Five runs with the same Workflow ID and distinct Run IDs using the default inputs.', + 'The first four runs have Continued-As-New status and link to the next run; the fifth completes.', + 'Each run contains a durable timer and carries its progress into the next run through workflow input.', + 'The final workflow result reports the total number of runs in the chain.', + ], + input, + startOptions, + execution: { + kind: 'workflow', + workflowType: 'continueAsNewChain', + workflow: continueAsNewChain, + activities: {}, + }, +}; diff --git a/src/lib/catalog/worker/examples/continue-as-new/workflow.ts b/src/lib/catalog/worker/examples/continue-as-new/workflow.ts new file mode 100644 index 0000000000..44ddfd775a --- /dev/null +++ b/src/lib/catalog/worker/examples/continue-as-new/workflow.ts @@ -0,0 +1,41 @@ +import { continueAsNew, log, sleep } from '@temporalio/workflow'; + +export async function continueAsNewChain( + runCount = 5, + delaySeconds = 2, + completedRuns = 0, +): Promise { + if (!Number.isInteger(runCount) || runCount < 1 || runCount > 25) { + throw new Error('Run count must be an integer between 1 and 25.'); + } + if ( + !Number.isInteger(delaySeconds) || + delaySeconds < 1 || + delaySeconds > 30 + ) { + throw new Error('Delay must be an integer between 1 and 30 seconds.'); + } + if ( + !Number.isInteger(completedRuns) || + completedRuns < 0 || + completedRuns >= runCount + ) { + throw new Error( + 'Completed run count must be a non-negative integer below the run count.', + ); + } + + const currentRun = completedRuns + 1; + log.info('Continue-As-New chain run', { currentRun, runCount }); + await sleep(`${delaySeconds} seconds`); + + if (currentRun < runCount) { + return await continueAsNew( + runCount, + delaySeconds, + currentRun, + ); + } + + return `Completed ${runCount} runs in the Continue-As-New chain.`; +} diff --git a/src/lib/catalog/worker/examples/corpus.test.ts b/src/lib/catalog/worker/examples/corpus.test.ts index 0fbbb89f8b..d82a0500ba 100644 --- a/src/lib/catalog/worker/examples/corpus.test.ts +++ b/src/lib/catalog/worker/examples/corpus.test.ts @@ -46,6 +46,7 @@ const migratedWorkflowTypes = [ ] as const; const proofExampleIds = [ + 'continue-as-new', 'priority-fairness', 'standalone-activity', 'nexus-greeting', @@ -179,6 +180,7 @@ describe('shared workflow corpus', () => { expect(Object.keys(target?.workflowExports ?? {}).sort()).toEqual( [ ...migratedWorkflowTypes, + 'continueAsNewChain', 'priorityFairnessWorkflow', 'nexusGreeting', 'satelliteLaunchEventGroups', @@ -604,6 +606,8 @@ describe('shared workflow corpus', () => { 'src/lib/catalog/worker/workflows.ts', 'src/lib/catalog/worker/examples/inventory.ts', 'src/lib/catalog/worker/examples/index.ts', + 'src/lib/catalog/worker/examples/continue-as-new/example.ts', + 'src/lib/catalog/worker/examples/continue-as-new/workflow.ts', 'src/lib/catalog/worker/examples/shared-activities.ts', 'src/lib/catalog/worker/examples/hello/example.ts', 'src/lib/catalog/worker/examples/hello/workflow.ts', diff --git a/src/lib/catalog/worker/examples/index.ts b/src/lib/catalog/worker/examples/index.ts index 8caccb6f85..e85c94d4ec 100644 --- a/src/lib/catalog/worker/examples/index.ts +++ b/src/lib/catalog/worker/examples/index.ts @@ -9,29 +9,30 @@ import { catalogExample as example1 } from './activity-retry/example.js'; import { catalogExample as example2 } from './activity-timeout/example.js'; import { catalogExample as example3 } from './child-fan-out/example.js'; import { catalogExample as example4 } from './child-workflows/example.js'; -import { catalogExample as example5 } from './hello/example.js'; -import { catalogExample as example6 } from './high-event-count/example.js'; -import { catalogExample as example7 } from './large-history/example.js'; -import { catalogExample as example8 } from './local-activity/example.js'; -import { catalogExample as example9 } from './long-activity/example.js'; -import { catalogExample as example10 } from './nexus-greeting/example.js'; -import { catalogExample as example11 } from './parallel-activities/example.js'; -import { catalogExample as example12 } from './pending-activities/example.js'; -import { catalogExample as example13 } from './pending-nexus/example.js'; -import { catalogExample as example14 } from './priority-fairness/example.js'; -import { catalogExample as example15 } from './satellite-launch-event-groups/example.js'; -import { catalogExample as example16 } from './sequential-activities/example.js'; -import { catalogExample as example17 } from './sequential-markdown-activities/example.js'; -import { catalogExample as example18 } from './sequential-multiline-summary-activities/example.js'; -import { catalogExample as example19 } from './sequential-no-summary-activities/example.js'; -import { catalogExample as example20 } from './sequential-plain-text-activities/example.js'; -import { catalogExample as example21 } from './signal-collector/example.js'; -import { catalogExample as example22 } from './signal-handlers/example.js'; -import { catalogExample as example23 } from './slow-nexus-operation/example.js'; -import { catalogExample as example24 } from './standalone-activity/example.js'; -import { catalogExample as example25 } from './timer-driven-repetition/example.js'; -import { catalogExample as example26 } from './workflow-feature-tour/example.js'; -import { catalogExample as example27 } from './workflow-patching/example.js'; +import { catalogExample as example5 } from './continue-as-new/example.js'; +import { catalogExample as example6 } from './hello/example.js'; +import { catalogExample as example7 } from './high-event-count/example.js'; +import { catalogExample as example8 } from './large-history/example.js'; +import { catalogExample as example9 } from './local-activity/example.js'; +import { catalogExample as example10 } from './long-activity/example.js'; +import { catalogExample as example11 } from './nexus-greeting/example.js'; +import { catalogExample as example12 } from './parallel-activities/example.js'; +import { catalogExample as example13 } from './pending-activities/example.js'; +import { catalogExample as example14 } from './pending-nexus/example.js'; +import { catalogExample as example15 } from './priority-fairness/example.js'; +import { catalogExample as example16 } from './satellite-launch-event-groups/example.js'; +import { catalogExample as example17 } from './sequential-activities/example.js'; +import { catalogExample as example18 } from './sequential-markdown-activities/example.js'; +import { catalogExample as example19 } from './sequential-multiline-summary-activities/example.js'; +import { catalogExample as example20 } from './sequential-no-summary-activities/example.js'; +import { catalogExample as example21 } from './sequential-plain-text-activities/example.js'; +import { catalogExample as example22 } from './signal-collector/example.js'; +import { catalogExample as example23 } from './signal-handlers/example.js'; +import { catalogExample as example24 } from './slow-nexus-operation/example.js'; +import { catalogExample as example25 } from './standalone-activity/example.js'; +import { catalogExample as example26 } from './timer-driven-repetition/example.js'; +import { catalogExample as example27 } from './workflow-feature-tour/example.js'; +import { catalogExample as example28 } from './workflow-patching/example.js'; const sharedWorkflowDefinitions = [ example0, @@ -62,6 +63,7 @@ const sharedWorkflowDefinitions = [ example25, example26, example27, + example28, ] satisfies readonly CatalogExampleDefinition[]; export const sharedWorkflowExamples: readonly CatalogExampleRegistration[] = @@ -116,6 +118,8 @@ export const sharedWorkflowSourceFiles = [ 'src/lib/catalog/worker/examples/child-fan-out/workflow.ts', 'src/lib/catalog/worker/examples/child-workflows/example.ts', 'src/lib/catalog/worker/examples/child-workflows/workflow.ts', + 'src/lib/catalog/worker/examples/continue-as-new/example.ts', + 'src/lib/catalog/worker/examples/continue-as-new/workflow.ts', 'src/lib/catalog/worker/examples/hello/example.ts', 'src/lib/catalog/worker/examples/hello/workflow.ts', 'src/lib/catalog/worker/examples/high-event-count/example.ts', diff --git a/src/lib/catalog/worker/workflows.ts b/src/lib/catalog/worker/workflows.ts index 9037d8aefc..f5adb93035 100644 --- a/src/lib/catalog/worker/workflows.ts +++ b/src/lib/catalog/worker/workflows.ts @@ -4,6 +4,7 @@ export { retryWorkflow } from './examples/activity-retry/workflow.js'; export { timeoutWorkflow } from './examples/activity-timeout/workflow.js'; export { childFanOut } from './examples/child-fan-out/workflow.js'; export { childWorkflowTest } from './examples/child-workflows/workflow.js'; +export { continueAsNewChain } from './examples/continue-as-new/workflow.js'; export { hello } from './examples/hello/workflow.js'; export { highEventCountWorkflow } from './examples/high-event-count/workflow.js'; export { largeHistory } from './examples/large-history/workflow.js'; diff --git a/src/lib/components/workflow/workflows-summary-configurable-table/table-body-cell.svelte b/src/lib/components/workflow/workflows-summary-configurable-table/table-body-cell.svelte index 5277b0df7e..883e2e6452 100644 --- a/src/lib/components/workflow/workflows-summary-configurable-table/table-body-cell.svelte +++ b/src/lib/components/workflow/workflows-summary-configurable-table/table-body-cell.svelte @@ -29,6 +29,7 @@ import { routeForWorkerDeployment, routeForWorkflow, + routeForWorkflowChain, } from '$lib/utilities/route-for'; import { TRUNCATE_LENGTH, @@ -64,6 +65,13 @@ ); const hrefFor = (value: QuickFilterValue) => { + if (label === 'Workflow ID' && !archival) { + return routeForWorkflowChain({ + namespace, + workflow: workflow.id, + run: workflow.runId, + }); + } if (['Type', 'Workflow ID', 'Run ID'].includes(label)) { return routeForWorkflow({ namespace, diff --git a/src/lib/i18n/locales/en/workflows.ts b/src/lib/i18n/locales/en/workflows.ts index e1a5ec767d..f8c01992f9 100644 --- a/src/lib/i18n/locales/en/workflows.ts +++ b/src/lib/i18n/locales/en/workflows.ts @@ -1,6 +1,12 @@ export const Namespace = 'workflows' as const; export const Strings = { + 'execution-chain': 'Workflow execution chain', + + 'execution-chain-placeholder': + 'The execution chain visualization is not implemented yet.', + 'execution-chain-back': 'Back to workflows', + 'execution-chain-view-execution': 'View entry execution', 'loading-workflows': 'Loading workflows', 'recent-workflows': 'Recent Workflows', 'recent-workflows-link': 'View Recent Workflows', diff --git a/src/lib/pages/workflow-chain.svelte b/src/lib/pages/workflow-chain.svelte new file mode 100644 index 0000000000..28e070ec82 --- /dev/null +++ b/src/lib/pages/workflow-chain.svelte @@ -0,0 +1,55 @@ + + + + +
+ + {#snippet heading()} + {translate('workflows.execution-chain')} + {/snippet} + {#snippet actions()} + + {translate('workflows.execution-chain-back')} + + + {translate('workflows.execution-chain-view-execution')} + + {/snippet} + {#snippet metadata()} +
+
+
{translate('common.workflow-id')}
+
{workflow}
+
+
+
{translate('common.run-id')}
+
{run}
+
+
+ {/snippet} +
+
+

+ {translate('workflows.execution-chain-placeholder')} +

+
+
diff --git a/src/lib/utilities/route-for-base-path.test.ts b/src/lib/utilities/route-for-base-path.test.ts index 4d8a2fc447..460acd46d0 100644 --- a/src/lib/utilities/route-for-base-path.test.ts +++ b/src/lib/utilities/route-for-base-path.test.ts @@ -60,6 +60,7 @@ import { routeForWorkers, routeForWorkersWithQuery, routeForWorkflow, + routeForWorkflowChain, routeForWorkflowMemo, routeForWorkflowQuery, routeForWorkflows, @@ -91,6 +92,7 @@ describe('routeFor functions should resolve the base path exactly once', () => { }; const cases: [string, () => string | undefined][] = [ + ['routeForWorkflowChain', () => routeForWorkflowChain(workflowParams)], ['routeForNamespaces', () => routeForNamespaces()], ['routeForNexus', () => routeForNexus()], [ diff --git a/src/lib/utilities/route-for.ts b/src/lib/utilities/route-for.ts index 30ad17b446..bb964f2122 100644 --- a/src/lib/utilities/route-for.ts +++ b/src/lib/utilities/route-for.ts @@ -320,6 +320,17 @@ export const routeForArchivalWorkflows = ( return `${routeForNamespace(parameters)}/archival`; }; +export const routeForWorkflowChain = ({ + workflow, + run, + ...parameters +}: WorkflowParameters): ResolvedPathname => { + const id = encodeURIForSvelte(workflow); + const runId = encodeURIForSvelte(run); + + return `${routeForWorkflows(parameters)}/chain/${id}/${runId}`; +}; + export const baseRouteForWorkflow = ({ workflow, run, diff --git a/src/routes/(app)/namespaces/[namespace]/workflows/chain/[workflow]/[run]/+page.svelte b/src/routes/(app)/namespaces/[namespace]/workflows/chain/[workflow]/[run]/+page.svelte new file mode 100644 index 0000000000..fee98209bb --- /dev/null +++ b/src/routes/(app)/namespaces/[namespace]/workflows/chain/[workflow]/[run]/+page.svelte @@ -0,0 +1,5 @@ + + + From cc5b3ef4480c8165329e22bc87627aeeda09f12e Mon Sep 17 00:00:00 2001 From: Tegan Churchill Date: Wed, 4 Nov 2026 14:46:40 -0800 Subject: [PATCH 02/19] Route execution chains by first run ID Use each workflow's firstRunId in chain URLs and redirect legacy run-based paths to the new route. Scope grouped event buffer state per instance to prevent views from sharing workflow data. --- .../table-body-cell.svelte | 4 +- src/lib/i18n/locales/en/workflows.ts | 2 + src/lib/models/workflow-execution.ts | 2 + src/lib/pages/workflow-chain.svelte | 6 +- .../services/grouped-event-buffer.svelte.ts | 56 +- src/lib/services/grouped-event-buffer.ts | 999 +++++++++--------- src/lib/types/workflows.ts | 1 + src/lib/utilities/route-for-base-path.test.ts | 15 +- src/lib/utilities/route-for.ts | 15 +- .../workflows/[workflow]/[run]/chain/+page.ts | 37 + .../chain/[firstRunId]}/+page.svelte | 0 11 files changed, 632 insertions(+), 505 deletions(-) create mode 100644 src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/[run]/chain/+page.ts rename src/routes/(app)/namespaces/[namespace]/workflows/{chain/[workflow]/[run] => [workflow]/chain/[firstRunId]}/+page.svelte (100%) diff --git a/src/lib/components/workflow/workflows-summary-configurable-table/table-body-cell.svelte b/src/lib/components/workflow/workflows-summary-configurable-table/table-body-cell.svelte index 883e2e6452..a16f4af575 100644 --- a/src/lib/components/workflow/workflows-summary-configurable-table/table-body-cell.svelte +++ b/src/lib/components/workflow/workflows-summary-configurable-table/table-body-cell.svelte @@ -29,7 +29,7 @@ import { routeForWorkerDeployment, routeForWorkflow, - routeForWorkflowChain, + routeForWorkflowChainRedirect, } from '$lib/utilities/route-for'; import { TRUNCATE_LENGTH, @@ -66,7 +66,7 @@ const hrefFor = (value: QuickFilterValue) => { if (label === 'Workflow ID' && !archival) { - return routeForWorkflowChain({ + return routeForWorkflowChainRedirect({ namespace, workflow: workflow.id, run: workflow.runId, diff --git a/src/lib/i18n/locales/en/workflows.ts b/src/lib/i18n/locales/en/workflows.ts index f8c01992f9..c0eedb137f 100644 --- a/src/lib/i18n/locales/en/workflows.ts +++ b/src/lib/i18n/locales/en/workflows.ts @@ -7,6 +7,8 @@ export const Strings = { 'The execution chain visualization is not implemented yet.', 'execution-chain-back': 'Back to workflows', 'execution-chain-view-execution': 'View entry execution', + 'execution-chain-first-run-unavailable': + 'The server did not return the first Run ID for this execution chain.', 'loading-workflows': 'Loading workflows', 'recent-workflows': 'Recent Workflows', 'recent-workflows-link': 'View Recent Workflows', diff --git a/src/lib/models/workflow-execution.ts b/src/lib/models/workflow-execution.ts index 8545b92b65..36d00b92b0 100644 --- a/src/lib/models/workflow-execution.ts +++ b/src/lib/models/workflow-execution.ts @@ -88,6 +88,7 @@ export const toWorkflowExecution = ( const name = info?.type?.name ?? ''; const id = info?.execution?.workflowId ?? ''; const runId = info?.execution?.runId ?? ''; + const firstRunId = info?.firstRunId || undefined; const startTime = info?.startTime ?? ''; const endTime = info?.closeTime ?? ''; const executionTime = info?.executionTime ?? ''; @@ -142,6 +143,7 @@ export const toWorkflowExecution = ( name, id, runId, + ...(firstRunId && { firstRunId }), startTime, endTime, executionTime, diff --git a/src/lib/pages/workflow-chain.svelte b/src/lib/pages/workflow-chain.svelte index 28e070ec82..619f4bb7d3 100644 --- a/src/lib/pages/workflow-chain.svelte +++ b/src/lib/pages/workflow-chain.svelte @@ -12,7 +12,7 @@ const namespace = $derived(page.params.namespace); const workflow = $derived(page.params.workflow); - const run = $derived(page.params.run); + const firstRunId = $derived(page.params.firstRunId); @@ -26,7 +26,7 @@ {translate('workflows.execution-chain-back')} - + {translate('workflows.execution-chain-view-execution')} {/snippet} @@ -38,7 +38,7 @@
{translate('common.run-id')}
-
{run}
+
{firstRunId}
{/snippet} diff --git a/src/lib/services/grouped-event-buffer.svelte.ts b/src/lib/services/grouped-event-buffer.svelte.ts index c1c41ddc79..1f83fd898c 100644 --- a/src/lib/services/grouped-event-buffer.svelte.ts +++ b/src/lib/services/grouped-event-buffer.svelte.ts @@ -5,22 +5,14 @@ import type { EventGroupKey } from '$lib/models/event-history/event-group-marker import type { WorkflowEvent } from '$lib/types/events'; import { + defaultGroupedEventBuffer, type EventGroupMatcher, type EventGroupOption, - getEventArray, - getEventGroupMatcher, - getEventGroupOptions, - getGroupArray, - getLazyGroups, - getPendingActivityScheduledEvent, - getWorkflowTaskFailedEvent, + type GroupedEventBuffer, type LazyGroup, materializeGroup, - onChange, } from './grouped-event-buffer'; -const versionStore = writable(0); - /** * Reactive read surface over the grouped-event-buffer. * @@ -34,21 +26,37 @@ const versionStore = writable(0); * requestAnimationFrame — that never fires in a hidden tab, which would leave a * run opened in a background tab with an empty event history until focused. */ -class EventBufferView { +export class EventBufferView { private _version = $state(0); private pending = false; + private disposed = false; + private readonly buffer: GroupedEventBuffer; + private readonly unsubscribe: () => void; + private readonly writableVersionStore = writable(0); + readonly versionStore = readonly(this.writableVersionStore); + + constructor(buffer: GroupedEventBuffer) { + this.buffer = buffer; + this.unsubscribe = buffer.onChange((immediate) => + this.scheduleUpdate(immediate), + ); + } - constructor() { - onChange((immediate) => this.scheduleUpdate(immediate)); + dispose(): void { + if (this.disposed) return; + this.disposed = true; + this.pending = false; + this.unsubscribe(); } private bump(): void { this.pending = false; this._version++; - versionStore.update((current) => current + 1); + this.writableVersionStore.update((current) => current + 1); } private scheduleUpdate(immediate: boolean): void { + if (this.disposed) return; if (immediate) { this.bump(); return; @@ -56,7 +64,7 @@ class EventBufferView { if (this.pending) return; this.pending = true; queueMicrotask(() => { - if (this.pending) this.bump(); + if (!this.disposed && this.pending) this.bump(); }); } @@ -81,7 +89,7 @@ class EventBufferView { */ pendingActivityScheduledEvent(activityId: string): WorkflowEvent | undefined { void this._version; - return getPendingActivityScheduledEvent(activityId); + return this.buffer.getPendingActivityScheduledEvent(activityId); } /** @@ -90,7 +98,7 @@ class EventBufferView { */ readonly lazyGroupsWithoutWorkflowTasks: LazyGroup[] = $derived.by(() => { void this._version; - return getLazyGroups({ excludeWorkflowTasks: true }); + return this.buffer.getLazyGroups({ excludeWorkflowTasks: true }); }); /** @@ -99,13 +107,13 @@ class EventBufferView { */ readonly groupsWithoutWorkflowTasks: EventGroup[] = $derived.by(() => { void this._version; - return getGroupArray({ excludeWorkflowTasks: true }); + return this.buffer.getGroupArray({ excludeWorkflowTasks: true }); }); /** Every event group in the run, in order of first appearance. */ readonly eventGroupOptions: EventGroupOption[] = $derived.by(() => { void this._version; - return getEventGroupOptions(); + return this.buffer.getEventGroupOptions(); }); /** @@ -116,27 +124,27 @@ class EventBufferView { keys: readonly EventGroupKey[], ): EventGroupMatcher | undefined { void this._version; - return getEventGroupMatcher(keys); + return this.buffer.getEventGroupMatcher(keys); } readonly events: WorkflowEvent[] = $derived.by(() => { void this._version; - return getEventArray(); + return this.buffer.getEventArray(); }); /** The active WorkflowTaskFailed/TimedOut event, if the run has one. */ readonly workflowTaskFailedEvent: WorkflowEvent | undefined = $derived.by( () => { void this._version; - return getWorkflowTaskFailedEvent(); + return this.buffer.getWorkflowTaskFailedEvent(); }, ); } -export const eventBuffer = new EventBufferView(); +export const eventBuffer = new EventBufferView(defaultGroupedEventBuffer); /** * Store mirror of `eventBuffer.version`, for the derived stores in * $lib/stores/events that predate runes. Prefer `eventBuffer` in new code. */ -export const bufferVersion = readonly(versionStore); +export const bufferVersion = eventBuffer.versionStore; diff --git a/src/lib/services/grouped-event-buffer.ts b/src/lib/services/grouped-event-buffer.ts index 01cab85007..db39258eb4 100644 --- a/src/lib/services/grouped-event-buffer.ts +++ b/src/lib/services/grouped-event-buffer.ts @@ -129,7 +129,13 @@ class GroupRecord implements LazyGroup { hasTerminalNexus = false; private lastSlot = -1; - constructor(readonly headSlot: number) { + constructor( + readonly headSlot: number, + private readonly applyPendingMetadata: (record: GroupRecord) => boolean, + private readonly materializeRecord: ( + record: GroupRecord, + ) => EventGroup | null, + ) { this.id = String(headSlot + 1); } @@ -147,10 +153,14 @@ class GroupRecord implements LazyGroup { this.headsGroup = isGroupHeadEvent(event as CommonHistoryEvent); } // A head arriving picks pending metadata up; a terminal event drops it. - applyPendingMetadataTo(this); + this.applyPendingMetadata(this); this.version++; } + materialize(): EventGroup | null { + return this.materializeRecord(this); + } + get eventCount(): number { return this.slots.length; } @@ -194,179 +204,6 @@ export type GroupArrayOptions = { excludeWorkflowTasks?: boolean; }; -// --------------------------------------------------------------------------- -// Module state (reset between workflows via reset()) -// --------------------------------------------------------------------------- - -let events: (WorkflowEvent | null)[] = []; -let headGroup = new Int32Array(0); // head slot -> record index + 1 (0 = none) -let records: GroupRecord[] = []; -let maxSlot = -1; - -let failedEvent: HistoryEvent | null = null; - -// Accumulated WFT IDs for marker billable-action dedup. Shared by both cursors -// and the live poll — the direction an event arrives from is a fetch detail, -// and one workflow task's markers bill once however they were loaded. -const processedWorkflowTaskIds = new Set(); -let eventGroupLabels = createEventGroupLabelRegistry(); - -// Event group key -> the events carrying that marker and the lifecycle groups -// they belong to, so the event group filter is a set lookup per row. -let eventGroupIndex = new Map(); -let cachedEventGroupOptions: EventGroupOption[] | null = null; -let cachedEventGroupOptionsRevision = -1; - -// Bumped by every write. Read caches hold the revision they were built at, so -// invalidation is a single counter rather than scattered cache-busting calls. -let revision = 0; - -let cachedGroups: EventGroup[] | null = null; -let cachedGroupsRevision = -1; -let cachedGroupsNoWFT: EventGroup[] | null = null; -let cachedGroupsNoWFTRevision = -1; -let cachedEvents: WorkflowEvent[] | null = null; -let cachedEventsRevision = -1; -let cachedLazyGroups: LazyGroup[] | null = null; -let cachedLazyGroupsRevision = -1; -let cachedLazyGroupsNoWFT: LazyGroup[] | null = null; -let cachedLazyGroupsNoWFTRevision = -1; -let cachedWftFailed: WorkflowEvent | undefined; -let cachedWftFailedRevision = -1; - -const changeListeners = new Set(); - -// Pending metadata from the workflow run, held so a head event arriving later -// can pick its own up. Records currently carrying some are tracked so a walk is -// only needed when there is something to set or clear. -let pendingByActivityId = new Map(); -let pendingByNexusScheduledId = new Map(); -const enrichedRecords = new Set(); - -// Head event of each currently-pending activity's group, keyed by activityId. -// Maintained alongside enrichedRecords so a pending-activity card can diff its -// current options against the ones it was scheduled with without scanning. The -// head is always ActivityTaskScheduled: that is the only branch in -// applyPendingMetadataTo that assigns pendingActivity. -const scheduledEventByActivityId = new Map(); - -/** Returns whether the record's pending metadata changed. */ -function applyPendingMetadataTo(record: GroupRecord): boolean { - const head = record.initialEvent; - if (!head) return false; - - let pendingActivity: PendingActivity | undefined; - let pendingNexusOperation: PendingNexusOperation | undefined; - - // The run can still list an activity the history has already resolved, so a - // terminal event wins. This is the only writer of the record's pending - // fields, so gating here covers the lazy and materialized readings alike. - if (!record.hasTerminalActivity && isActivityTaskScheduledEvent(head)) { - pendingActivity = pendingByActivityId.get( - head.activityTaskScheduledEventAttributes?.activityId ?? '', - ); - } else if (!record.hasTerminalNexus && isNexusOperationScheduledEvent(head)) { - pendingNexusOperation = pendingByNexusScheduledId.get(head.id); - } - - if ( - record.pendingActivity === pendingActivity && - record.pendingNexusOperation === pendingNexusOperation - ) { - return false; - } - - const previousActivityId = record.pendingActivity?.activityId; - record.pendingActivity = pendingActivity; - record.pendingNexusOperation = pendingNexusOperation; - if ( - previousActivityId && - previousActivityId !== pendingActivity?.activityId - ) { - scheduledEventByActivityId.delete(previousActivityId); - } - if (pendingActivity) { - scheduledEventByActivityId.set(pendingActivity.activityId, head); - } - if (pendingActivity || pendingNexusOperation) { - enrichedRecords.add(record); - } else { - enrichedRecords.delete(record); - } - record.version++; - return true; -} - -// --------------------------------------------------------------------------- -// Internal helpers -// --------------------------------------------------------------------------- - -function notifyChanged(immediate = false): void { - for (const listener of changeListeners) listener(immediate); -} - -function grow(slot: number): void { - if (slot < events.length) return; - const size = slot + Math.ceil(slot * 0.25) + 16; - events.length = size; - const grown = new Int32Array(size); - grown.set(headGroup); - headGroup = grown; -} - -function shouldNotAddBillableAction(event: WorkflowEvent): boolean { - if (!failedEvent) return false; - return Number(event.id) < Number(failedEvent.eventId); -} - -function toWorkflowEvent(raw: HistoryEvent): WorkflowEvent { - return toEvent(raw, { - shouldNotAddBillableAction, - processedWorkflowTaskIds, - eventGroupLabels, - }); -} - -// An event whose head is unknown (malformed attributes) heads its own group. -function headSlotFor(event: WorkflowEvent, slot: number): number { - const parsedHeadSlot = parseInt(getGroupId(event as CommonHistoryEvent)) - 1; - return parsedHeadSlot >= 0 ? parsedHeadSlot : slot; -} - -function indexEventGroups( - event: WorkflowEvent, - slot: number, - headSlot: number, -): void { - if (!event.eventGroups) return; - const eventId = slot + 1; - for (const group of event.eventGroups) { - let entry = eventGroupIndex.get(group.key); - if (!entry) { - entry = { - group, - eventCount: 0, - firstEventId: eventId, - headSlots: new Set(), - }; - eventGroupIndex.set(group.key, entry); - } - entry.eventCount++; - if (eventId < entry.firstEventId) entry.firstEventId = eventId; - entry.headSlots.add(headSlot); - } -} - -function recordFor(headSlot: number): GroupRecord { - const existing = headGroup[headSlot]; - if (existing !== 0) return records[existing - 1]; - - const record = new GroupRecord(headSlot); - records.push(record); - headGroup[headSlot] = records.length; - return record; -} - function isTerminalActivityEvent(event: WorkflowEvent): boolean { return ( isActivityTaskCompletedEvent(event) || @@ -385,357 +222,577 @@ function isTerminalNexusEvent(event: WorkflowEvent): boolean { ); } -// Pending metadata is applied as a derived read rather than stored on the -// group, so a terminal event and a stale pending entry can arrive in either -// order without leaving the group reporting isPending alongside a completion. -function applyPendingMetadata(group: EventGroup, record: GroupRecord): void { - // Copies rather than re-deciding — the record is already correct. - group.pendingActivity = record.pendingActivity; - group.pendingNexusOperation = record.pendingNexusOperation; +export function isWorkflowTaskGroup(group: EventGroup | LazyGroup): boolean { + return group.initialEvent.eventType === 'WorkflowTaskScheduled'; } /** - * Build the EventGroup for a record, or null when it has no head event yet or - * its head event doesn't form a group (e.g. WorkflowExecutionStarted). - * Memoized on the record's version — callers may rely on an unchanged record - * returning the identical object. + * The full EventGroup for a lazy group, memoized on its content version: an + * unchanged lazy group returns the identical object, a changed one a new object. + * + * Idempotent — an already-materialized EventGroup passes straight through, so + * views can accept either lazy groups or groups built elsewhere (e.g. + * groupEvents() in graph-widget) without branching at every use site. */ -function materializeEventGroup(record: GroupRecord): EventGroup | null { - if (record.cachedVersion === record.version) return record.cached; - record.cachedVersion = record.version; - record.cached = null; - - const head = events[record.headSlot]; - if (!head) return null; - - const group = - createEventGroup(head as CommonHistoryEvent) ?? - createWorkflowTaskGroup(head as CommonHistoryEvent); - if (!group) return null; - - const followers: WorkflowEvent[] = []; - for (const slot of record.slots) { - if (slot === record.headSlot) continue; - const event = events[slot]; - if (event) followers.push(event); +export function materializeGroup(lazy: LazyGroup): EventGroup { + if (lazy instanceof GroupRecord) { + return lazy.materialize() as EventGroup; } - followers.sort((a, b) => Number(a.id) - Number(b.id)); + return lazy as EventGroup; +} - for (const event of followers) { - group.eventList.push(event); - group.timestamp = event.timestamp; - addEventToGroup(group, event); - } +export function createGroupedEventBuffer() { + // --------------------------------------------------------------------------- + // Buffer state (reset between workflows via reset()) + // --------------------------------------------------------------------------- + + let events: (WorkflowEvent | null)[] = []; + let headGroup = new Int32Array(0); // head slot -> record index + 1 (0 = none) + let records: GroupRecord[] = []; + let maxSlot = -1; + + let failedEvent: HistoryEvent | null = null; + + // Accumulated WFT IDs for marker billable-action dedup. Shared by both cursors + // and the live poll — the direction an event arrives from is a fetch detail, + // and one workflow task's markers bill once however they were loaded. + const processedWorkflowTaskIds = new Set(); + let eventGroupLabels = createEventGroupLabelRegistry(); + + // Event group key -> the events carrying that marker and the lifecycle groups + // they belong to, so the event group filter is a set lookup per row. + let eventGroupIndex = new Map(); + let cachedEventGroupOptions: EventGroupOption[] | null = null; + let cachedEventGroupOptionsRevision = -1; + + // Bumped by every write. Read caches hold the revision they were built at, so + // invalidation is a single counter rather than scattered cache-busting calls. + let revision = 0; + + let cachedGroups: EventGroup[] | null = null; + let cachedGroupsRevision = -1; + let cachedGroupsNoWFT: EventGroup[] | null = null; + let cachedGroupsNoWFTRevision = -1; + let cachedEvents: WorkflowEvent[] | null = null; + let cachedEventsRevision = -1; + let cachedLazyGroups: LazyGroup[] | null = null; + let cachedLazyGroupsRevision = -1; + let cachedLazyGroupsNoWFT: LazyGroup[] | null = null; + let cachedLazyGroupsNoWFTRevision = -1; + let cachedWftFailed: WorkflowEvent | undefined; + let cachedWftFailedRevision = -1; + + const changeListeners = new Set(); + + // Pending metadata from the workflow run, held so a head event arriving later + // can pick its own up. Records currently carrying some are tracked so a walk is + // only needed when there is something to set or clear. + let pendingByActivityId = new Map(); + let pendingByNexusScheduledId = new Map(); + const enrichedRecords = new Set(); + + // Head event of each currently-pending activity's group, keyed by activityId. + // Maintained alongside enrichedRecords so a pending-activity card can diff its + // current options against the ones it was scheduled with without scanning. The + // head is always ActivityTaskScheduled: that is the only branch in + // applyPendingMetadataTo that assigns pendingActivity. + const scheduledEventByActivityId = new Map(); + + /** Returns whether the record's pending metadata changed. */ + function applyPendingMetadataTo(record: GroupRecord): boolean { + const head = record.initialEvent; + if (!head) return false; + + let pendingActivity: PendingActivity | undefined; + let pendingNexusOperation: PendingNexusOperation | undefined; + + // The run can still list an activity the history has already resolved, so a + // terminal event wins. This is the only writer of the record's pending + // fields, so gating here covers the lazy and materialized readings alike. + if (!record.hasTerminalActivity && isActivityTaskScheduledEvent(head)) { + pendingActivity = pendingByActivityId.get( + head.activityTaskScheduledEventAttributes?.activityId ?? '', + ); + } else if ( + !record.hasTerminalNexus && + isNexusOperationScheduledEvent(head) + ) { + pendingNexusOperation = pendingByNexusScheduledId.get(head.id); + } - applyPendingMetadata(group, record); + if ( + record.pendingActivity === pendingActivity && + record.pendingNexusOperation === pendingNexusOperation + ) { + return false; + } - record.cached = group; - return group; -} + const previousActivityId = record.pendingActivity?.activityId; + record.pendingActivity = pendingActivity; + record.pendingNexusOperation = pendingNexusOperation; + if ( + previousActivityId && + previousActivityId !== pendingActivity?.activityId + ) { + scheduledEventByActivityId.delete(previousActivityId); + } + if (pendingActivity) { + scheduledEventByActivityId.set(pendingActivity.activityId, head); + } + if (pendingActivity || pendingNexusOperation) { + enrichedRecords.add(record); + } else { + enrichedRecords.delete(record); + } + record.version++; + return true; + } -// --------------------------------------------------------------------------- -// Public API -// --------------------------------------------------------------------------- + // --------------------------------------------------------------------------- + // Internal helpers + // --------------------------------------------------------------------------- -/** - * (Re)initialise the buffer for a new workflow run. - * Call before starting the bidirectional fetch. - */ -export function reset(historyLength: number): void { - const size = Math.max(historyLength + 16, 16); - - events = new Array(size).fill(null); - headGroup = new Int32Array(size); - records = []; - enrichedRecords.clear(); - scheduledEventByActivityId.clear(); - pendingByActivityId = new Map(); - pendingByNexusScheduledId = new Map(); - maxSlot = -1; - - failedEvent = null; - processedWorkflowTaskIds.clear(); - eventGroupLabels = createEventGroupLabelRegistry(); - eventGroupIndex = new Map(); - cachedEventGroupOptions = null; - - revision++; - cachedGroups = null; - cachedGroupsNoWFT = null; - cachedEvents = null; - cachedLazyGroups = null; - cachedLazyGroupsNoWFT = null; - - notifyChanged(true); -} + function notifyChanged(immediate = false): void { + for (const listener of changeListeners) listener(immediate); + } -/** - * The reset point past which events stop counting toward billableActions. - * Currently unwired — no production caller supplies it. - */ -export function setFailedEvent(raw: HistoryEvent | null): void { - failedEvent = raw; -} + function grow(slot: number): void { + if (slot < events.length) return; + const size = slot + Math.ceil(slot * 0.25) + 16; + events.length = size; + const grown = new Int32Array(size); + grown.set(headGroup); + headGroup = grown; + } -/** - * Add one raw HistoryEvent from either fetch cursor or the live poll. - * Returns false when the event was already present. - */ -export function ingestHistoryEvent(raw: HistoryEvent): boolean { - const slot = parseInt(raw.eventId) - 1; - if (!(slot >= 0)) return false; + function shouldNotAddBillableAction(event: WorkflowEvent): boolean { + if (!failedEvent) return false; + return Number(event.id) < Number(failedEvent.eventId); + } - grow(slot); - if (events[slot]) return false; + function toWorkflowEvent(raw: HistoryEvent): WorkflowEvent { + return toEvent(raw, { + shouldNotAddBillableAction, + processedWorkflowTaskIds, + eventGroupLabels, + }); + } - const event = toWorkflowEvent(raw); - events[slot] = event; - if (slot > maxSlot) maxSlot = slot; + // An event whose head is unknown (malformed attributes) heads its own group. + function headSlotFor(event: WorkflowEvent, slot: number): number { + const parsedHeadSlot = + parseInt(getGroupId(event as CommonHistoryEvent)) - 1; + return parsedHeadSlot >= 0 ? parsedHeadSlot : slot; + } - const headSlot = headSlotFor(event, slot); - grow(headSlot); + function indexEventGroups( + event: WorkflowEvent, + slot: number, + headSlot: number, + ): void { + if (!event.eventGroups) return; + const eventId = slot + 1; + for (const group of event.eventGroups) { + let entry = eventGroupIndex.get(group.key); + if (!entry) { + entry = { + group, + eventCount: 0, + firstEventId: eventId, + headSlots: new Set(), + }; + eventGroupIndex.set(group.key, entry); + } + entry.eventCount++; + if (eventId < entry.firstEventId) entry.firstEventId = eventId; + entry.headSlots.add(headSlot); + } + } - recordFor(headSlot).addMember(slot, event); - indexEventGroups(event, slot, headSlot); - revision++; + function recordFor(headSlot: number): GroupRecord { + const existing = headGroup[headSlot]; + if (existing !== 0) return records[existing - 1]; - notifyChanged(); - return true; -} + const record = new GroupRecord( + headSlot, + applyPendingMetadataTo, + materializeEventGroup, + ); + records.push(record); + headGroup[headSlot] = records.length; + return record; + } -/** - * Annotate activity and nexus groups with pending metadata from the workflow - * run. Safe to call repeatedly — groups whose pending entry is unchanged keep - * their existing reference. - */ -export function setPendingMetadata( - pendingActivities: PendingActivity[], - pendingNexusOperations: PendingNexusOperation[], -): void { - pendingByActivityId = new Map( - pendingActivities.map((pending) => [pending.activityId, pending]), - ); - pendingByNexusScheduledId = new Map( - pendingNexusOperations.map((pending) => [ - String(pending.scheduledEventId), - pending, - ]), - ); + // Pending metadata is applied as a derived read rather than stored on the + // group, so a terminal event and a stale pending entry can arrive in either + // order without leaving the group reporting isPending alongside a completion. + function applyPendingMetadata(group: EventGroup, record: GroupRecord): void { + // Copies rather than re-deciding — the record is already correct. + group.pendingActivity = record.pendingActivity; + group.pendingNexusOperation = record.pendingNexusOperation; + } - const nothingPending = - pendingByActivityId.size === 0 && pendingByNexusScheduledId.size === 0; - if (nothingPending && enrichedRecords.size === 0) return; + /** + * Build the EventGroup for a record, or null when it has no head event yet or + * its head event doesn't form a group (e.g. WorkflowExecutionStarted). + * Memoized on the record's version — callers may rely on an unchanged record + * returning the identical object. + */ + function materializeEventGroup(record: GroupRecord): EventGroup | null { + if (record.cachedVersion === record.version) return record.cached; + record.cachedVersion = record.version; + record.cached = null; + + const head = events[record.headSlot]; + if (!head) return null; + + const group = + createEventGroup(head as CommonHistoryEvent) ?? + createWorkflowTaskGroup(head as CommonHistoryEvent); + if (!group) return null; + + const followers: WorkflowEvent[] = []; + for (const slot of record.slots) { + if (slot === record.headSlot) continue; + const event = events[slot]; + if (event) followers.push(event); + } + followers.sort((a, b) => Number(a.id) - Number(b.id)); - let changed = false; - for (const record of records) { - if (!record.headsGroup) continue; - if (applyPendingMetadataTo(record)) { - revision++; - changed = true; + for (const event of followers) { + group.eventList.push(event); + group.timestamp = event.timestamp; + addEventToGroup(group, event); } + + applyPendingMetadata(group, record); + + record.cached = group; + return group; } - if (changed) notifyChanged(); -} + // --------------------------------------------------------------------------- + // Public API + // --------------------------------------------------------------------------- -/** - * The ActivityTaskScheduled event that started a currently-pending activity, or - * undefined when that event has not been ingested yet. Only pending activities - * are indexed: a resolved one drops out with its pending metadata. - */ -export function getPendingActivityScheduledEvent( - activityId: string, -): WorkflowEvent | undefined { - return scheduledEventByActivityId.get(activityId); -} + /** + * (Re)initialise the buffer for a new workflow run. + * Call before starting the bidirectional fetch. + */ + function reset(historyLength: number): void { + const size = Math.max(historyLength + 16, 16); + + events = new Array(size).fill(null); + headGroup = new Int32Array(size); + records = []; + enrichedRecords.clear(); + scheduledEventByActivityId.clear(); + pendingByActivityId = new Map(); + pendingByNexusScheduledId = new Map(); + maxSlot = -1; + + failedEvent = null; + processedWorkflowTaskIds.clear(); + eventGroupLabels = createEventGroupLabelRegistry(); + eventGroupIndex = new Map(); + cachedEventGroupOptions = null; + + revision++; + cachedGroups = null; + cachedGroupsNoWFT = null; + cachedEvents = null; + cachedLazyGroups = null; + cachedLazyGroupsNoWFT = null; + + notifyChanged(true); + } -/** - * Subscribe to buffer writes. Fires once per ingested event and once per - * pending-metadata change, so subscribers are expected to coalesce. `immediate` - * is true for reset, which subscribers should apply without coalescing so a - * navigation cannot leave the previous run's groups on screen. - * Returns an unsubscribe function. - */ -export function onChange(listener: ChangeListener): () => void { - changeListeners.add(listener); - return () => changeListeners.delete(listener); -} + /** + * The reset point past which events stop counting toward billableActions. + * Currently unwired — no production caller supplies it. + */ + function setFailedEvent(raw: HistoryEvent | null): void { + failedEvent = raw; + } -export function isWorkflowTaskGroup(group: EventGroup | LazyGroup): boolean { - return group.initialEvent.eventType === 'WorkflowTaskScheduled'; -} + /** + * Add one raw HistoryEvent from either fetch cursor or the live poll. + * Returns false when the event was already present. + */ + function ingestHistoryEvent(raw: HistoryEvent): boolean { + const slot = parseInt(raw.eventId) - 1; + if (!(slot >= 0)) return false; -/** - * Sorted LazyGroup[] in ascending event-id order, without building a single - * EventGroup. Cached until the next write; lazy groups are the records themselves, - * so a rebuild allocates only the array. - */ -export function getLazyGroups(opts?: GroupArrayOptions): LazyGroup[] { - const excludeWFT = Boolean(opts?.excludeWorkflowTasks); + grow(slot); + if (events[slot]) return false; - if (excludeWFT) { - if (cachedLazyGroupsNoWFT && cachedLazyGroupsNoWFTRevision === revision) { - return cachedLazyGroupsNoWFT; - } - } else if (cachedLazyGroups && cachedLazyGroupsRevision === revision) { - return cachedLazyGroups; - } + const event = toWorkflowEvent(raw); + events[slot] = event; + if (slot > maxSlot) maxSlot = slot; - // headGroup is indexed by head slot, so scanning it yields groups already in - // ascending event-id order — no sort needed. - const result: LazyGroup[] = new Array(records.length); - let count = 0; - for (let slot = 0; slot <= maxSlot; slot++) { - const recordIdx = headGroup[slot]; - if (recordIdx === 0) continue; - const record = records[recordIdx - 1]; - if (!record.headsGroup) continue; - if (excludeWFT && isWorkflowTaskGroup(record)) continue; - result[count++] = record; - } - result.length = count; - - if (excludeWFT) { - cachedLazyGroupsNoWFT = result; - cachedLazyGroupsNoWFTRevision = revision; - } else { - cachedLazyGroups = result; - cachedLazyGroupsRevision = revision; - } - return result; -} + const headSlot = headSlotFor(event, slot); + grow(headSlot); -/** - * The full EventGroup for a lazy group, memoized on its content version: an - * unchanged lazy group returns the identical object, a changed one a new object. - * - * Idempotent — an already-materialized EventGroup passes straight through, so - * views can accept either lazy groups or groups built elsewhere (e.g. - * groupEvents() in graph-widget) without branching at every use site. - */ -export function materializeGroup(lazy: LazyGroup): EventGroup { - if (lazy instanceof GroupRecord) { - return materializeEventGroup(lazy) as EventGroup; + recordFor(headSlot).addMember(slot, event); + indexEventGroups(event, slot, headSlot); + revision++; + + notifyChanged(); + return true; } - return lazy as EventGroup; -} -/** - * Sorted EventGroup[] in ascending event-id order — materializes every group. - * Prefer getLazyGroups + materializeGroup so only rendered groups are built. - */ -export function getGroupArray(opts?: GroupArrayOptions): EventGroup[] { - const excludeWFT = Boolean(opts?.excludeWorkflowTasks); + /** + * Annotate activity and nexus groups with pending metadata from the workflow + * run. Safe to call repeatedly — groups whose pending entry is unchanged keep + * their existing reference. + */ + function setPendingMetadata( + pendingActivities: PendingActivity[], + pendingNexusOperations: PendingNexusOperation[], + ): void { + pendingByActivityId = new Map( + pendingActivities.map((pending) => [pending.activityId, pending]), + ); + pendingByNexusScheduledId = new Map( + pendingNexusOperations.map((pending) => [ + String(pending.scheduledEventId), + pending, + ]), + ); - if (excludeWFT) { - if (cachedGroupsNoWFT && cachedGroupsNoWFTRevision === revision) { - return cachedGroupsNoWFT; + const nothingPending = + pendingByActivityId.size === 0 && pendingByNexusScheduledId.size === 0; + if (nothingPending && enrichedRecords.size === 0) return; + + let changed = false; + for (const record of records) { + if (!record.headsGroup) continue; + if (applyPendingMetadataTo(record)) { + revision++; + changed = true; + } } - } else if (cachedGroups && cachedGroupsRevision === revision) { - return cachedGroups; - } - const result = getLazyGroups(opts).map(materializeGroup); + if (changed) notifyChanged(); + } - if (excludeWFT) { - cachedGroupsNoWFT = result; - cachedGroupsNoWFTRevision = revision; - } else { - cachedGroups = result; - cachedGroupsRevision = revision; + /** + * The ActivityTaskScheduled event that started a currently-pending activity, or + * undefined when that event has not been ingested yet. Only pending activities + * are indexed: a resolved one drops out with its pending metadata. + */ + function getPendingActivityScheduledEvent( + activityId: string, + ): WorkflowEvent | undefined { + return scheduledEventByActivityId.get(activityId); } - return result; -} -/** Every event group in the run, in order of the first event carrying it. */ -export function getEventGroupOptions(): EventGroupOption[] { - if (cachedEventGroupOptions && cachedEventGroupOptionsRevision === revision) { - return cachedEventGroupOptions; + /** + * Subscribe to buffer writes. Fires once per ingested event and once per + * pending-metadata change, so subscribers are expected to coalesce. `immediate` + * is true for reset, which subscribers should apply without coalescing so a + * navigation cannot leave the previous run's groups on screen. + * Returns an unsubscribe function. + */ + function onChange(listener: ChangeListener): () => void { + changeListeners.add(listener); + return () => changeListeners.delete(listener); } - const result = [...eventGroupIndex.values()] - .map(({ group, eventCount, firstEventId }) => ({ - group, - eventCount, - firstEventId, - })) - .sort((a, b) => a.firstEventId - b.firstEventId); - - cachedEventGroupOptions = result; - cachedEventGroupOptionsRevision = revision; - return result; -} + /** + * Sorted LazyGroup[] in ascending event-id order, without building a single + * EventGroup. Cached until the next write; lazy groups are the records themselves, + * so a rebuild allocates only the array. + */ + function getLazyGroups(opts?: GroupArrayOptions): LazyGroup[] { + const excludeWFT = Boolean(opts?.excludeWorkflowTasks); + + if (excludeWFT) { + if (cachedLazyGroupsNoWFT && cachedLazyGroupsNoWFTRevision === revision) { + return cachedLazyGroupsNoWFT; + } + } else if (cachedLazyGroups && cachedLazyGroupsRevision === revision) { + return cachedLazyGroups; + } -/** - * Matches lifecycle groups, and the events in them, that contain an event - * carrying any of `keys`. Keys not in this run are ignored; returns undefined - * when none remain, so a stale selection never hides the whole history. - */ -export function getEventGroupMatcher( - keys: readonly EventGroupKey[], -): EventGroupMatcher | undefined { - const headSlots = new Set(); - for (const key of keys) { - for (const headSlot of eventGroupIndex.get(key)?.headSlots ?? []) { - headSlots.add(headSlot); + // headGroup is indexed by head slot, so scanning it yields groups already in + // ascending event-id order — no sort needed. + const result: LazyGroup[] = new Array(records.length); + let count = 0; + for (let slot = 0; slot <= maxSlot; slot++) { + const recordIdx = headGroup[slot]; + if (recordIdx === 0) continue; + const record = records[recordIdx - 1]; + if (!record.headsGroup) continue; + if (excludeWFT && isWorkflowTaskGroup(record)) continue; + result[count++] = record; + } + result.length = count; + + if (excludeWFT) { + cachedLazyGroupsNoWFT = result; + cachedLazyGroupsNoWFTRevision = revision; + } else { + cachedLazyGroups = result; + cachedLazyGroupsRevision = revision; } + return result; } - if (!headSlots.size) return; - return { - hasGroup: (groupId) => headSlots.has(parseInt(groupId) - 1), - hasEvent: (event) => - headSlots.has(headSlotFor(event, parseInt(event.id) - 1)), - }; -} + /** + * Sorted EventGroup[] in ascending event-id order — materializes every group. + * Prefer getLazyGroups + materializeGroup so only rendered groups are built. + */ + function getGroupArray(opts?: GroupArrayOptions): EventGroup[] { + const excludeWFT = Boolean(opts?.excludeWorkflowTasks); + + if (excludeWFT) { + if (cachedGroupsNoWFT && cachedGroupsNoWFTRevision === revision) { + return cachedGroupsNoWFT; + } + } else if (cachedGroups && cachedGroupsRevision === revision) { + return cachedGroups; + } -/** Flat WorkflowEvent[] in ascending event-id order. */ -export function getEventArray(): WorkflowEvent[] { - if (cachedEvents && cachedEventsRevision === revision) return cachedEvents; + const result = getLazyGroups(opts).map(materializeGroup); - const result: WorkflowEvent[] = []; - for (let slot = 0; slot <= maxSlot; slot++) { - const event = events[slot]; - if (event) result.push(event); + if (excludeWFT) { + cachedGroupsNoWFT = result; + cachedGroupsNoWFTRevision = revision; + } else { + cachedGroups = result; + cachedGroupsRevision = revision; + } + return result; } - cachedEvents = result; - cachedEventsRevision = revision; - return result; -} + /** Every event group in the run, in order of the first event carrying it. */ + function getEventGroupOptions(): EventGroupOption[] { + if ( + cachedEventGroupOptions && + cachedEventGroupOptionsRevision === revision + ) { + return cachedEventGroupOptions; + } -/** - * The WorkflowTaskFailed/TimedOut event that is currently active (i.e. has no - * subsequent WorkflowTaskCompleted), or undefined if none. - */ -export function getWorkflowTaskFailedEvent(): WorkflowEvent | undefined { - if (cachedWftFailedRevision === revision) return cachedWftFailed; + const result = [...eventGroupIndex.values()] + .map(({ group, eventCount, firstEventId }) => ({ + group, + eventCount, + firstEventId, + })) + .sort((a, b) => a.firstEventId - b.firstEventId); + + cachedEventGroupOptions = result; + cachedEventGroupOptionsRevision = revision; + return result; + } + + /** + * Matches lifecycle groups, and the events in them, that contain an event + * carrying any of `keys`. Keys not in this run are ignored; returns undefined + * when none remain, so a stale selection never hides the whole history. + */ + function getEventGroupMatcher( + keys: readonly EventGroupKey[], + ): EventGroupMatcher | undefined { + const headSlots = new Set(); + for (const key of keys) { + for (const headSlot of eventGroupIndex.get(key)?.headSlots ?? []) { + headSlots.add(headSlot); + } + } + if (!headSlots.size) return; - let lastFailedEvent: WorkflowEvent | undefined; - let maxCompletedId = -1; + return { + hasGroup: (groupId) => headSlots.has(parseInt(groupId) - 1), + hasEvent: (event) => + headSlots.has(headSlotFor(event, parseInt(event.id) - 1)), + }; + } - for (let slot = 0; slot <= maxSlot; slot++) { - const event = events[slot]; - if (!event) continue; + /** Flat WorkflowEvent[] in ascending event-id order. */ + function getEventArray(): WorkflowEvent[] { + if (cachedEvents && cachedEventsRevision === revision) return cachedEvents; - if (event.eventType === 'WorkflowTaskCompleted') { - const id = Number(event.id); - if (id > maxCompletedId) maxCompletedId = id; - continue; + const result: WorkflowEvent[] = []; + for (let slot = 0; slot <= maxSlot; slot++) { + const event = events[slot]; + if (event) result.push(event); } - if ( - (isFailedTaskEvent(event) || isTimedOutTaskEvent(event)) && - !isWorkflowTaskFailedEventDueToReset(event) - ) { - lastFailedEvent = event; + cachedEvents = result; + cachedEventsRevision = revision; + return result; + } + + /** + * The WorkflowTaskFailed/TimedOut event that is currently active (i.e. has no + * subsequent WorkflowTaskCompleted), or undefined if none. + */ + function getWorkflowTaskFailedEvent(): WorkflowEvent | undefined { + if (cachedWftFailedRevision === revision) return cachedWftFailed; + + let lastFailedEvent: WorkflowEvent | undefined; + let maxCompletedId = -1; + + for (let slot = 0; slot <= maxSlot; slot++) { + const event = events[slot]; + if (!event) continue; + + if (event.eventType === 'WorkflowTaskCompleted') { + const id = Number(event.id); + if (id > maxCompletedId) maxCompletedId = id; + continue; + } + + if ( + (isFailedTaskEvent(event) || isTimedOutTaskEvent(event)) && + !isWorkflowTaskFailedEventDueToReset(event) + ) { + lastFailedEvent = event; + } } + + cachedWftFailedRevision = revision; + cachedWftFailed = + lastFailedEvent && Number(lastFailedEvent.id) >= maxCompletedId + ? lastFailedEvent + : undefined; + return cachedWftFailed; } - cachedWftFailedRevision = revision; - cachedWftFailed = - lastFailedEvent && Number(lastFailedEvent.id) >= maxCompletedId - ? lastFailedEvent - : undefined; - return cachedWftFailed; + return { + reset, + setFailedEvent, + ingestHistoryEvent, + setPendingMetadata, + getPendingActivityScheduledEvent, + onChange, + getLazyGroups, + getGroupArray, + getEventGroupOptions, + getEventGroupMatcher, + getEventArray, + getWorkflowTaskFailedEvent, + }; } + +export type GroupedEventBuffer = ReturnType; + +export const defaultGroupedEventBuffer = createGroupedEventBuffer(); + +export const { + reset, + setFailedEvent, + ingestHistoryEvent, + setPendingMetadata, + getPendingActivityScheduledEvent, + onChange, + getLazyGroups, + getGroupArray, + getEventGroupOptions, + getEventGroupMatcher, + getEventArray, + getWorkflowTaskFailedEvent, +} = defaultGroupedEventBuffer; diff --git a/src/lib/types/workflows.ts b/src/lib/types/workflows.ts index 9e8ac90f82..4dd300ecd8 100644 --- a/src/lib/types/workflows.ts +++ b/src/lib/types/workflows.ts @@ -187,6 +187,7 @@ export type WorkflowExecution = { name: string; id: string; runId: string; + firstRunId?: string; startTime: string; endTime: string; executionTime: string; diff --git a/src/lib/utilities/route-for-base-path.test.ts b/src/lib/utilities/route-for-base-path.test.ts index 460acd46d0..2f40107fa6 100644 --- a/src/lib/utilities/route-for-base-path.test.ts +++ b/src/lib/utilities/route-for-base-path.test.ts @@ -61,6 +61,7 @@ import { routeForWorkersWithQuery, routeForWorkflow, routeForWorkflowChain, + routeForWorkflowChainRedirect, routeForWorkflowMemo, routeForWorkflowQuery, routeForWorkflows, @@ -92,7 +93,19 @@ describe('routeFor functions should resolve the base path exactly once', () => { }; const cases: [string, () => string | undefined][] = [ - ['routeForWorkflowChain', () => routeForWorkflowChain(workflowParams)], + [ + 'routeForWorkflowChainRedirect', + () => routeForWorkflowChainRedirect(workflowParams), + ], + [ + 'routeForWorkflowChain', + () => + routeForWorkflowChain({ + namespace: 'default', + workflow: 'wf-id', + firstRunId: 'run-id', + }), + ], ['routeForNamespaces', () => routeForNamespaces()], ['routeForNexus', () => routeForNexus()], [ diff --git a/src/lib/utilities/route-for.ts b/src/lib/utilities/route-for.ts index bb964f2122..18d45d1936 100644 --- a/src/lib/utilities/route-for.ts +++ b/src/lib/utilities/route-for.ts @@ -322,13 +322,16 @@ export const routeForArchivalWorkflows = ( export const routeForWorkflowChain = ({ workflow, - run, + firstRunId, ...parameters -}: WorkflowParameters): ResolvedPathname => { +}: NamespaceParameter & { + workflow: string; + firstRunId: string; +}): ResolvedPathname => { const id = encodeURIForSvelte(workflow); - const runId = encodeURIForSvelte(run); + const runId = encodeURIForSvelte(firstRunId); - return `${routeForWorkflows(parameters)}/chain/${id}/${runId}`; + return `${routeForWorkflows(parameters)}/${id}/chain/${runId}`; }; export const baseRouteForWorkflow = ({ @@ -341,6 +344,10 @@ export const baseRouteForWorkflow = ({ return `${routeForWorkflows(parameters)}/${id}/${run}`; }; +export const routeForWorkflowChainRedirect = ( + parameters: WorkflowParameters, +): ResolvedPathname => `${baseRouteForWorkflow(parameters)}/chain`; + export const routeForSchedules = ( parameters: NamespaceParameter, ): ResolvedPathname => { diff --git a/src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/[run]/chain/+page.ts b/src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/[run]/chain/+page.ts new file mode 100644 index 0000000000..44b5ac5952 --- /dev/null +++ b/src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/[run]/chain/+page.ts @@ -0,0 +1,37 @@ +import { error, redirect } from '@sveltejs/kit'; + +import type { PageLoad } from './$types'; + +import { translate } from '$lib/i18n/translate'; +import { fetchWorkflow } from '$lib/services/workflow-service'; +import { routeForWorkflowChain } from '$lib/utilities/route-for'; + +export const load: PageLoad = async ({ params, fetch, parent }) => { + await parent(); + + const { namespace, workflow: workflowId, run: runId } = params; + const { workflow, error: workflowError } = await fetchWorkflow( + { namespace, workflowId, runId }, + fetch, + ); + + if (workflowError) { + error( + workflowError.statusCode, + workflowError.message || workflowError.statusText, + ); + } + + if (!workflow?.firstRunId) { + error(502, translate('workflows.execution-chain-first-run-unavailable')); + } + + redirect( + 302, + routeForWorkflowChain({ + namespace, + workflow: workflowId, + firstRunId: workflow.firstRunId, + }), + ); +}; diff --git a/src/routes/(app)/namespaces/[namespace]/workflows/chain/[workflow]/[run]/+page.svelte b/src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/chain/[firstRunId]/+page.svelte similarity index 100% rename from src/routes/(app)/namespaces/[namespace]/workflows/chain/[workflow]/[run]/+page.svelte rename to src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/chain/[firstRunId]/+page.svelte From 0bb7eda4f9a22f1938c9ce95e1246d578fe31905 Mon Sep 17 00:00:00 2001 From: Tegan Churchill Date: Wed, 4 Nov 2026 16:26:33 -0800 Subject: [PATCH 03/19] Refactor activity controls across workflow views --- .../activity/activity-command-controls.svelte | 128 +++++++++++ .../activity/activity-commands.svelte | 206 +++++++----------- .../activity/activity-options-form.svelte | 2 +- .../activity-options-update-drawer.svelte | 11 +- src/lib/components/event/event-card.svelte | 15 +- .../event/event-details-full.svelte | 26 ++- .../event/event-details-link.svelte | 18 +- .../components/event/event-summary-row.svelte | 11 +- .../event/event-summary-table.svelte | 9 + src/lib/components/event/event-summary.svelte | 21 +- .../event/pending-activity-summary-row.svelte | 6 +- .../event/pending-nexus-summary-row.svelte | 11 +- .../timeline-graph/graph-widget.svelte | 29 ++- .../timeline-graph/group-details-row.svelte | 19 +- .../timeline-graph/timeline-graph-row.svelte | 5 +- .../timeline-graph/timeline-graph.svelte | 63 ++++-- .../pending-activity-card.svelte | 32 +-- .../layouts/workflow-history-layout.svelte | 21 +- .../layouts/workflow-timeline-layout.svelte | 45 +++- src/lib/pages/workflow-history-event.svelte | 17 +- .../pages/workflow-pending-activities.svelte | 29 ++- .../services/grouped-event-buffer.svelte.ts | 5 + src/lib/types/workflows.ts | 6 + 23 files changed, 518 insertions(+), 217 deletions(-) create mode 100644 src/lib/components/activity/activity-command-controls.svelte diff --git a/src/lib/components/activity/activity-command-controls.svelte b/src/lib/components/activity/activity-command-controls.svelte new file mode 100644 index 0000000000..f3e186eb16 --- /dev/null +++ b/src/lib/components/activity/activity-command-controls.svelte @@ -0,0 +1,128 @@ + + +
+ + + + + + + + + +
+ + + + + + + + +{#key optionsUpdateDrawerOpen} + +{/key} diff --git a/src/lib/components/activity/activity-commands.svelte b/src/lib/components/activity/activity-commands.svelte index 69843f3444..015980edeb 100644 --- a/src/lib/components/activity/activity-commands.svelte +++ b/src/lib/components/activity/activity-commands.svelte @@ -1,174 +1,126 @@ - -
- - - - - - - - - -
- - - - - + const onUpdateOptions = async (options: ActivityOptions) => { + const refresh = onRefresh; + await updateActivityOptions({ + namespace: executionIdentity.namespace, + execution: { + workflowId: executionIdentity.workflowId, + runId: executionIdentity.runId, + }, + id: activity.activityId, + activityOptions: options, + identity, + }); + await refresh(Action.Update); + }; + - -{#key optionsUpdateDrawerOpen} - -{/key} +{/if} diff --git a/src/lib/components/activity/activity-options-form.svelte b/src/lib/components/activity/activity-options-form.svelte index 7adc2a35fa..d6f342ecba 100644 --- a/src/lib/components/activity/activity-options-form.svelte +++ b/src/lib/components/activity/activity-options-form.svelte @@ -102,7 +102,7 @@ // NOT reset reactively if the activity prop changes while the user is // mid-edit — untrack() captures the initial values intentionally. Re-seeding // on each open comes from the {#key} around the drawer in - // activity-commands.svelte, which remounts this form. + // activity-command-controls.svelte, which remounts this form. const initialData: z.infer = untrack(() => ({ taskQueue: initialOptions?.taskQueue?.name ?? '', scheduleToCloseTimeout: String( diff --git a/src/lib/components/activity/activity-options-update-drawer.svelte b/src/lib/components/activity/activity-options-update-drawer.svelte index 1a857e5e50..dfd87ba6f0 100644 --- a/src/lib/components/activity/activity-options-update-drawer.svelte +++ b/src/lib/components/activity/activity-options-update-drawer.svelte @@ -15,9 +15,16 @@ namespace: string; execution: WorkflowExecution; activity: PendingActivity; + onRefresh?: (action: Action) => void; }; - let { open = $bindable(), namespace, execution, activity }: Props = $props(); + let { + open = $bindable(), + namespace, + execution, + activity, + onRefresh = triggerRefresh, + }: Props = $props(); const identity = getIdentity(); @@ -29,7 +36,7 @@ activityOptions, identity, }); - triggerRefresh(Action.Update); + onRefresh(Action.Update); }; diff --git a/src/lib/components/event/event-card.svelte b/src/lib/components/event/event-card.svelte index 1bd36ea74f..658ae46bca 100644 --- a/src/lib/components/event/event-card.svelte +++ b/src/lib/components/event/event-card.svelte @@ -24,6 +24,7 @@ import type { EventLink as ELink } from '$lib/types'; import { type Payload as RawPayload } from '$lib/types'; import type { WorkflowEvent } from '$lib/types/events'; + import type { WorkflowExecutionIdentity } from '$lib/types/workflows'; import { isRawPayload } from '$lib/utilities/decode-payload'; import { type EventLinkDisplay, @@ -54,13 +55,21 @@ event, lazy = false, initiatingEvent = undefined, + executionIdentity, }: { event: WorkflowEvent; + executionIdentity?: WorkflowExecutionIdentity; lazy?: boolean; /** The operation's NexusOperationScheduled event, when this is part of a group. */ initiatingEvent?: WorkflowEvent; } = $props(); - const { namespace, workflow, run } = $derived(page.params); + const namespace = $derived( + executionIdentity?.namespace ?? page.params.namespace, + ); + const workflow = $derived( + executionIdentity?.workflowId ?? page.params.workflow, + ); + const run = $derived(executionIdentity?.runId ?? page.params.run); const systemNexus = $derived( resolveSystemNexusEvent(event, { @@ -128,8 +137,7 @@ typeof value !== 'object' && displayLinkType(key, attributes) === 'none' && !hiddenDetailFields.includes(key) && - (key !== 'namespace' || - (key === 'namespace' && page.params.namespace !== value)), + (key !== 'namespace' || (key === 'namespace' && namespace !== value)), ), ); @@ -393,6 +401,7 @@ container-class="min-w-0" > + import type { Snippet } from 'svelte'; + import type { EventGroup } from '$lib/models/event-groups/event-groups'; import { resolveSystemNexusEvent } from '$lib/system-nexus-endpoints'; - import type { WorkflowEvent } from '$lib/types/events'; + import type { PendingActivity, WorkflowEvent } from '$lib/types/events'; + import type { WorkflowExecutionIdentity } from '$lib/types/workflows'; + import { isActivityTaskScheduledEvent } from '$lib/utilities/is-event-type'; import PendingActivityCard from '../workflow/pending-activity/pending-activity-card.svelte'; import PendingNexusOperationCard from '../workflow/pending-nexus-operation/pending-nexus-operation-card.svelte'; @@ -13,12 +17,16 @@ event = undefined, lazy = false, groupRow = false, + executionIdentity, + activityActions, }: { group?: EventGroup; event?: WorkflowEvent; lazy?: boolean; /** The row that opened this represents the whole group, not one event. */ groupRow?: boolean; + executionIdentity?: WorkflowExecutionIdentity; + activityActions?: Snippet<[PendingActivity]>; } = $props(); const pendingEvent = $derived( @@ -46,12 +54,19 @@ {#if showEventGroup}
{#if group?.pendingActivity} - + {:else if group?.pendingNexusOperation} {/if} {#each group?.eventList ?? [] as groupEvent (groupEvent.id)} {:else if event} - + {/if} diff --git a/src/lib/components/event/event-details-link.svelte b/src/lib/components/event/event-details-link.svelte index 02089c4c42..9f14c63765 100644 --- a/src/lib/components/event/event-details-link.svelte +++ b/src/lib/components/event/event-details-link.svelte @@ -2,6 +2,7 @@ import { page } from '$app/state'; import Link from '$lib/holocene/link.svelte'; + import type { WorkflowExecutionIdentity } from '$lib/types/workflows'; import type { CombinedAttributes } from '$lib/utilities/format-event-attributes'; import { type EventLinkType } from '$lib/utilities/get-single-attribute-for-event'; import { @@ -15,12 +16,23 @@ attributes: CombinedAttributes; type: EventLinkType; class?: string; + executionIdentity?: WorkflowExecutionIdentity; } - let { value, attributes, type, class: className = '' }: Props = $props(); + let { + value, + attributes, + type, + executionIdentity, + class: className = '', + }: Props = $props(); - const namespace = $derived(page.params.namespace); - const workflow = $derived(page.params.workflow); + const namespace = $derived( + executionIdentity?.namespace ?? page.params.namespace, + ); + const workflow = $derived( + executionIdentity?.workflowId ?? page.params.workflow, + ); function getHref( ns: string, diff --git a/src/lib/components/event/event-summary-row.svelte b/src/lib/components/event/event-summary-row.svelte index b8ed853d67..05889dcf7c 100644 --- a/src/lib/components/event/event-summary-row.svelte +++ b/src/lib/components/event/event-summary-row.svelte @@ -1,5 +1,5 @@

{activity.activityType}

- {#if showActivityCommands} - - {/if} + {@render actions?.(activity)}
diff --git a/src/lib/layouts/workflow-history-layout.svelte b/src/lib/layouts/workflow-history-layout.svelte index 054262a8fa..27098bd134 100644 --- a/src/lib/layouts/workflow-history-layout.svelte +++ b/src/lib/layouts/workflow-history-layout.svelte @@ -4,6 +4,7 @@ import { beforeNavigate, goto } from '$app/navigation'; import { page } from '$app/state'; + import ActivityCommands from '$lib/components/activity/activity-commands.svelte'; import EventSummaryTable from '$lib/components/event/event-summary-table.svelte'; import EventGroupFilter from '$lib/components/lines-and-dots/event-group-filter/event-group-filter.svelte'; import EventTypeFilter from '$lib/components/lines-and-dots/event-type-filter.svelte'; @@ -38,7 +39,7 @@ import { eventFilterSort, eventViewType } from '$lib/stores/event-view'; import { pauseLiveUpdates } from '$lib/stores/events'; import { eventCategoryFilter, eventTypeFilter } from '$lib/stores/filters'; - import { workflowRun } from '$lib/stores/workflow-run'; + import { triggerRefresh, workflowRun } from '$lib/stores/workflow-run'; import type { EventTypeCategory, WorkflowEvent, @@ -311,7 +312,23 @@
{:else}
- + + {#snippet activityActions(activity)} + {#if workflow} + + {/if} + {/snippet} +
{/if}
diff --git a/src/lib/layouts/workflow-timeline-layout.svelte b/src/lib/layouts/workflow-timeline-layout.svelte index 9de6d7d4f5..5eac1e641e 100644 --- a/src/lib/layouts/workflow-timeline-layout.svelte +++ b/src/lib/layouts/workflow-timeline-layout.svelte @@ -4,6 +4,7 @@ import { beforeNavigate, goto } from '$app/navigation'; import { page } from '$app/state'; + import ActivityCommands from '$lib/components/activity/activity-commands.svelte'; import EventGroupFilter from '$lib/components/lines-and-dots/event-group-filter/event-group-filter.svelte'; import EventHistoryLegend from '$lib/components/lines-and-dots/event-history-legend.svelte'; import EventTypeFilter from '$lib/components/lines-and-dots/event-type-filter.svelte'; @@ -30,8 +31,8 @@ import { clearActives } from '$lib/stores/active-events'; import { collapseIdleTime, eventFilterSort } from '$lib/stores/event-view'; import { pauseLiveUpdates } from '$lib/stores/events'; - import { eventTypeFilter } from '$lib/stores/filters'; - import { workflowRun } from '$lib/stores/workflow-run'; + import { eventStatusFilter, eventTypeFilter } from '$lib/stores/filters'; + import { triggerRefresh, workflowRun } from '$lib/stores/workflow-run'; import type { WorkflowTaskFailedEvent, WorkflowTaskTimedOutEvent, @@ -231,16 +232,36 @@ no scroll-offset bridge). --> {#if workflow} - + {#key JSON.stringify([namespace, workflow.id, workflow.runId])} + + {#snippet activityActions(activity)} + + {/snippet} + + {/key} {/if} diff --git a/src/lib/pages/workflow-history-event.svelte b/src/lib/pages/workflow-history-event.svelte index f10c8ee7df..b0dc2e8616 100644 --- a/src/lib/pages/workflow-history-event.svelte +++ b/src/lib/pages/workflow-history-event.svelte @@ -1,6 +1,7 @@ +{#snippet activityActions(activity: PendingActivity)} + {#if workflow} + + {/if} +{/snippet} +
-{:else if workflowError} - +{:else if displayError} + {:else if !$workflowRun.workflow} {:else} diff --git a/src/lib/services/fetch-bidirectional.ts b/src/lib/services/fetch-bidirectional.ts index 7bcd1b471e..898082b5e0 100644 --- a/src/lib/services/fetch-bidirectional.ts +++ b/src/lib/services/fetch-bidirectional.ts @@ -78,13 +78,9 @@ export const fetchBidirectional = async ({ const t0 = performance.now(); + const rootCtrl = new AbortController(); const ascCtrl = new AbortController(); const descCtrl = new AbortController(); - const onAbort = () => { - ascCtrl.abort(); - descCtrl.abort(); - }; - signal?.addEventListener('abort', onAbort); let ascMaxId = 0; let descMinId = Infinity; @@ -105,8 +101,36 @@ export const fetchBidirectional = async ({ // onPause is called. resume() resolves it, unblocking both loops. let pauseLatch: Promise | null = null; - const checkPause = async () => { - if (pauseLatch) await pauseLatch; + let resumePause: (() => void) | undefined; + + const releasePause = () => { + pauseLatch = null; + resumePause?.(); + resumePause = undefined; + }; + + const onAbort = () => { + rootCtrl.abort(); + ascCtrl.abort(); + descCtrl.abort(); + releasePause(); + }; + signal?.addEventListener('abort', onAbort); + + const checkPause = async (cursorSignal: AbortSignal) => { + if (!pauseLatch || cursorSignal.aborted) return; + let onCursorAbort = () => {}; + try { + await Promise.race([ + pauseLatch, + new Promise((resolve) => { + onCursorAbort = resolve; + cursorSignal.addEventListener('abort', onCursorAbort, { once: true }); + }), + ]); + } finally { + cursorSignal.removeEventListener('abort', onCursorAbort); + } }; const maybePause = () => { @@ -118,13 +142,9 @@ export const fetchBidirectional = async ({ ) { pauseFired = true; pauseLatch = new Promise((resolve) => { - onPause({ - resume: () => { - pauseLatch = null; - resolve(); - }, - }); + resumePause = resolve; }); + onPause({ resume: releasePause }); } }; @@ -147,7 +167,7 @@ export const fetchBidirectional = async ({ const route = routeForApi('events.ascending', { namespace, workflowId }); let token: Token; while (!ascCtrl.signal.aborted) { - await checkPause(); + await checkPause(ascCtrl.signal); if (ascCtrl.signal.aborted) break; const g = gap(); if (g <= 0) { @@ -176,11 +196,14 @@ export const fetchBidirectional = async ({ options: { signal: ascCtrl.signal }, }, ); - } catch { - break; + } catch (error) { + if (ascCtrl.signal.aborted) break; + onAbort(); + throw error; } + if (rootCtrl.signal.aborted) break; - const events = (response?.history?.events ?? []) as HistoryEvent[]; + const events = response?.history?.events ?? []; if (!events.length) break; ascPages++; @@ -196,14 +219,16 @@ export const fetchBidirectional = async ({ } } if (fresh.length) onRawPage(fresh, true); + if (rootCtrl.signal.aborted) break; reportProgress(); + if (rootCtrl.signal.aborted) break; maybePause(); if (!response?.nextPageToken || gap() <= 0) { descCtrl.abort(); break; } - token = response.nextPageToken as unknown as string; + token = String(response.nextPageToken); } }; @@ -211,7 +236,7 @@ export const fetchBidirectional = async ({ const route = routeForApi('events.descending', { namespace, workflowId }); let token: Token; while (!descCtrl.signal.aborted) { - await checkPause(); + await checkPause(descCtrl.signal); if (descCtrl.signal.aborted) break; const g = gap(); if (g <= 0) { @@ -240,11 +265,14 @@ export const fetchBidirectional = async ({ options: { signal: descCtrl.signal }, }, ); - } catch { - break; + } catch (error) { + if (descCtrl.signal.aborted) break; + onAbort(); + throw error; } + if (rootCtrl.signal.aborted) break; - const events = (response?.history?.events ?? []) as HistoryEvent[]; + const events = response?.history?.events ?? []; if (!events.length) break; descPages++; @@ -264,20 +292,27 @@ export const fetchBidirectional = async ({ } } if (fresh.length) onRawPage(fresh, false); + if (rootCtrl.signal.aborted) break; if (descPages === 1) onFirstDescPage?.(fresh); + if (rootCtrl.signal.aborted) break; reportProgress(); + if (rootCtrl.signal.aborted) break; maybePause(); if (!response?.nextPageToken || gap() <= 0) { ascCtrl.abort(); break; } - token = response.nextPageToken as unknown as string; + token = String(response.nextPageToken); } }; - await Promise.allSettled([runAscending(), runDescending()]); - signal?.removeEventListener('abort', onAbort); + try { + await Promise.all([runAscending(), runDescending()]); + } finally { + onAbort(); + signal?.removeEventListener('abort', onAbort); + } const durationMs = performance.now() - t0; const total = seen.size; diff --git a/src/lib/services/live-poll.ts b/src/lib/services/live-poll.ts index 790095ef22..fae7044df6 100644 --- a/src/lib/services/live-poll.ts +++ b/src/lib/services/live-poll.ts @@ -18,6 +18,7 @@ export type LivePollOptions = { onEvent: (ev: HistoryEvent) => boolean; /** Optional hook, called once per poll iteration that added new events. */ onNewEvents?: () => void; + onToken?: (token: string) => void; /** ms to wait when a long-poll times out with no new events. Default 2000. */ backoffMs?: number; /** ms to wait after a network error before retrying. Default 5000. */ @@ -50,9 +51,23 @@ export async function runLivePoll({ signal, onEvent, onNewEvents, + onToken, backoffMs = 2000, errorBackoffMs = 5000, }: LivePollOptions): Promise { + const wait = (delay: number): Promise => { + if (signal.aborted) return Promise.resolve(); + return new Promise((resolve) => { + const finish = () => { + clearTimeout(timer); + signal.removeEventListener('abort', finish); + resolve(); + }; + const timer = setTimeout(finish, delay); + signal.addEventListener('abort', finish, { once: true }); + }); + }; + let token: string = startToken; while (!signal.aborted) { try { @@ -66,7 +81,7 @@ export async function runLivePoll({ }, options: { signal }, }); - const events = (response?.history?.events ?? []) as HistoryEvent[]; + const events = response?.history?.events ?? []; let added = 0; for (const ev of events) { if (onEvent(ev)) added++; @@ -75,16 +90,18 @@ export async function runLivePoll({ if (isWorkflowCloseEvent(events.at(-1))) break; if (response?.nextPageToken) { - token = response.nextPageToken as unknown as string; + token = String(response.nextPageToken); + onToken?.(token); } else { token = ''; + onToken?.(token); if (added === 0) { - await new Promise((r) => setTimeout(r, backoffMs)); + await wait(backoffMs); } } } catch { if (!signal.aborted) { - await new Promise((r) => setTimeout(r, errorBackoffMs)); + await wait(errorBackoffMs); } } } diff --git a/src/lib/services/workflow-history-controller.svelte.ts b/src/lib/services/workflow-history-controller.svelte.ts new file mode 100644 index 0000000000..1794e2097b --- /dev/null +++ b/src/lib/services/workflow-history-controller.svelte.ts @@ -0,0 +1,291 @@ +import type { HistoryEvent } from '$lib/types/events'; +import type { NetworkError } from '$lib/types/global'; +import type { + WorkflowExecution, + WorkflowExecutionIdentity, +} from '$lib/types/workflows'; +import { getErrorMessage } from '$lib/utilities/error-message'; +import { isWorkflowCloseEvent } from '$lib/utilities/is-event-type'; +import { isNetworkError } from '$lib/utilities/is-network-error'; +import { routeForApi } from '$lib/utilities/route-for-api'; + +import { fetchBidirectional, type PauseHandle } from './fetch-bidirectional'; +import { + createGroupedEventBuffer, + type GroupedEventBuffer, +} from './grouped-event-buffer'; +import { runLivePoll } from './live-poll'; + +import { EventBufferView } from './grouped-event-buffer.svelte'; + +type HistoryLoadSession = { + controller: AbortController; + livePollController: AbortController | null; + livePollTask: Promise | null; + lastPollToken: string; + workflowIsRunning: boolean; + historyClosed: boolean; +}; + +type WorkflowHistoryControllerOptions = { + workflowExecutionIdentity: WorkflowExecutionIdentity; + buffer?: GroupedEventBuffer; + maximumPageSize?: number; + pauseAfterPages?: number; + liveUpdatesPaused?: boolean; +}; + +export class WorkflowHistoryController { + readonly workflowExecutionIdentity: Readonly; + readonly history: EventBufferView; + + fetchComplete = $state(false); + latestEventId = $state(0); + totalExpectedEvents = $state(0); + descMinId = $state(0); + error = $state.raw(null); + + private started = $state(false); + private disposed = false; + private historyRequested = false; + private liveUpdatesPaused: boolean; + private pauseHandle: PauseHandle | null = null; + private session: HistoryLoadSession | null = null; + private readonly buffer: GroupedEventBuffer; + private readonly maximumPageSize: number; + private readonly pauseAfterPages: number | undefined; + + constructor({ + workflowExecutionIdentity, + buffer = createGroupedEventBuffer(), + maximumPageSize = 1000, + pauseAfterPages, + liveUpdatesPaused = false, + }: WorkflowHistoryControllerOptions) { + const { namespace, workflowId, runId } = workflowExecutionIdentity; + if (!namespace || !workflowId || !runId) { + throw new Error( + 'Workflow history requires a namespace, Workflow ID, and Run ID.', + ); + } + this.workflowExecutionIdentity = Object.freeze({ + ...workflowExecutionIdentity, + }); + this.buffer = buffer; + this.history = new EventBufferView(buffer); + this.maximumPageSize = maximumPageSize; + this.pauseAfterPages = pauseAfterPages; + this.liveUpdatesPaused = liveUpdatesPaused; + } + + get loading(): boolean { + return this.started && !this.fetchComplete && !this.error; + } + + get resumeRequested(): boolean { + return this.historyRequested; + } + + async load(workflow: WorkflowExecution): Promise { + if (this.disposed) + throw new Error('Cannot load a disposed workflow history.'); + this.verifyWorkflow(workflow); + this.stopSession(); + + this.fetchComplete = false; + this.latestEventId = 0; + this.totalExpectedEvents = 0; + this.descMinId = 0; + this.error = null; + this.started = true; + this.buffer.reset(parseInt(workflow.historyEvents ?? '0') || 0); + this.buffer.setPendingMetadata( + workflow.pendingActivities ?? [], + workflow.pendingNexusOperations ?? [], + ); + + const session: HistoryLoadSession = { + controller: new AbortController(), + livePollController: null, + livePollTask: null, + lastPollToken: '', + workflowIsRunning: workflow.isRunning, + historyClosed: false, + }; + this.session = session; + this.startLivePoll(session); + + try { + await fetchBidirectional({ + ...this.workflowExecutionIdentity, + signal: session.controller.signal, + maximumPageSize: this.maximumPageSize, + pauseAfterPages: this.pauseAfterPages, + onProgress: (progress) => { + if (!this.isCurrent(session)) return; + this.totalExpectedEvents = progress.totalEstimated; + this.descMinId = progress.descMinId; + }, + onPause: (handle) => { + if (!this.isCurrent(session) || this.historyRequested) { + handle.resume(); + return; + } + this.pauseHandle = handle; + }, + onRawPage: (events) => { + if (!this.isCurrent(session)) return; + for (const event of events) this.ingestEvent(event, session); + }, + }); + if (this.isCurrent(session)) { + this.pauseHandle = null; + this.fetchComplete = true; + } + } catch (error) { + if (!this.isCurrent(session)) return; + this.error = + error instanceof Error || isNetworkError(error) + ? error + : new Error(getErrorMessage(error)); + this.stopSession(); + } + } + + updateWorkflow(workflow: WorkflowExecution): void { + if (this.disposed) return; + this.verifyWorkflow(workflow); + this.buffer.setPendingMetadata( + workflow.pendingActivities ?? [], + workflow.pendingNexusOperations ?? [], + ); + const session = this.session; + if (!session) return; + session.workflowIsRunning = workflow.isRunning; + if (!workflow.isRunning) { + session.livePollController?.abort(); + return; + } + this.startLivePoll(session); + } + + setLiveUpdatesPaused(paused: boolean): void { + if (this.disposed) return; + this.liveUpdatesPaused = paused; + const session = this.session; + if (!session) return; + if (paused) { + session.livePollController?.abort(); + return; + } + this.startLivePoll(session); + } + + resume(): void { + if (this.disposed) return; + this.historyRequested = true; + const handle = this.pauseHandle; + this.pauseHandle = null; + handle?.resume(); + } + + dispose(): void { + if (this.disposed) return; + this.disposed = true; + this.started = false; + this.stopSession(); + this.history.dispose(); + } + + private verifyWorkflow(workflow: WorkflowExecution): void { + if ( + workflow.id !== this.workflowExecutionIdentity.workflowId || + workflow.runId !== this.workflowExecutionIdentity.runId + ) { + throw new Error('Workflow does not match this history controller.'); + } + } + + private isCurrent(session: HistoryLoadSession): boolean { + return ( + !this.disposed && + this.session === session && + !session.controller.signal.aborted + ); + } + + private canPoll(session: HistoryLoadSession): boolean { + return ( + this.isCurrent(session) && + !this.liveUpdatesPaused && + session.workflowIsRunning && + !session.historyClosed + ); + } + + private ingestEvent( + event: HistoryEvent, + session: HistoryLoadSession, + ): boolean { + if (!this.isCurrent(session)) return false; + const isNew = this.buffer.ingestHistoryEvent(event); + this.latestEventId = Math.max( + this.latestEventId, + parseInt(event.eventId) || 0, + ); + if (isWorkflowCloseEvent(event)) { + session.historyClosed = true; + session.livePollController?.abort(); + } + return isNew; + } + + private startLivePoll(session: HistoryLoadSession): void { + if (!this.canPoll(session) || session.livePollTask) return; + const controller = new AbortController(); + session.livePollController = controller; + session.livePollTask = runLivePoll({ + route: routeForApi('events.ascending', this.workflowExecutionIdentity), + runId: this.workflowExecutionIdentity.runId, + startToken: session.lastPollToken, + signal: controller.signal, + onEvent: (event) => { + if (controller.signal.aborted) return false; + return this.ingestEvent(event, session); + }, + onToken: (token) => { + if (this.isCurrent(session) && !controller.signal.aborted) { + session.lastPollToken = token; + } + }, + }) + .then((token) => { + if (!this.isCurrent(session) || controller.signal.aborted) return; + session.lastPollToken = token; + session.historyClosed = true; + }) + .catch((error) => { + if (!this.isCurrent(session) || controller.signal.aborted) return; + this.error = + error instanceof Error || isNetworkError(error) + ? error + : new Error(getErrorMessage(error)); + this.stopSession(); + }) + .finally(() => { + session.livePollTask = null; + session.livePollController = null; + if (controller.signal.aborted) this.startLivePoll(session); + }); + } + + private stopSession(): void { + const session = this.session; + this.session = null; + session?.controller.abort(); + session?.livePollController?.abort(); + const handle = this.pauseHandle; + this.pauseHandle = null; + handle?.resume(); + } +} From 8e5ef2cb19f0e938ccd109c465645dad3e204541 Mon Sep 17 00:00:00 2001 From: Tegan Churchill Date: Thu, 5 Nov 2026 11:02:37 -0800 Subject: [PATCH 06/19] Propagate history through workflow views --- .../components/event/event-summary-row.svelte | 2 +- .../event/event-summary-table.svelte | 48 +++++++++++------ src/lib/components/event/event-summary.svelte | 26 +++++++-- .../history-graph/history-graph.svelte | 11 ++-- .../lines-and-dots/workflow-details.svelte | 10 ++-- .../task-queue-workers-table.svelte | 11 +++- .../worker-heartbeats-sdk-warning.svelte | 12 +++-- .../workers-table/workers-table.svelte | 9 +++- src/lib/components/workflow-actions.svelte | 20 ++++--- .../reset-confirmation-modal.svelte | 12 +++-- .../workflow/input-and-results.svelte | 6 ++- .../workflow-family-node-tree.svelte | 11 ++-- .../relationships/workflow-family-tree.svelte | 5 +- .../workflow/workflow-callbacks.svelte | 9 ++-- .../workflow/workflow-common-errors.svelte | 16 ++++-- .../workflow-relationships-old.svelte | 10 +++- .../workflow/workflow-relationships.svelte | 15 ++++-- src/lib/contexts/history-context.ts | 3 ++ src/lib/layouts/workflow-header.svelte | 24 ++++++--- .../layouts/workflow-history-layout.svelte | 39 ++++++++------ src/lib/layouts/workflow-run-layout.svelte | 33 +++++------- .../layouts/workflow-timeline-layout.svelte | 23 ++++---- src/lib/pages/workflow-history-event.svelte | 54 ++++++------------- src/lib/pages/workflow-history-json.svelte | 8 ++- src/lib/pages/workflow-nexus-links.svelte | 21 ++++---- .../pages/workflow-pending-activities.svelte | 10 +++- src/lib/services/events-service.ts | 12 ++--- .../services/grouped-event-buffer.svelte.ts | 25 +++++---- src/lib/services/grouped-event-buffer.ts | 12 +++++ src/lib/stores/events.ts | 41 -------------- .../[run]/history/compact/+page.svelte | 4 +- .../[run]/history/feed/+page.svelte | 7 ++- .../[workflow]/[run]/history/+page.svelte | 8 ++- 33 files changed, 316 insertions(+), 241 deletions(-) diff --git a/src/lib/components/event/event-summary-row.svelte b/src/lib/components/event/event-summary-row.svelte index 64a44de704..b2b192590f 100644 --- a/src/lib/components/event/event-summary-row.svelte +++ b/src/lib/components/event/event-summary-row.svelte @@ -58,7 +58,7 @@ workflowExecutionIdentity: WorkflowExecutionIdentity; event: IterableEvent; group: EventGroup | undefined; - initialItem: WorkflowEvent; + initialItem: WorkflowEvent | undefined; index: number; compact?: boolean; expanded?: boolean; diff --git a/src/lib/components/event/event-summary-table.svelte b/src/lib/components/event/event-summary-table.svelte index 6c6fd44070..810b8d9712 100644 --- a/src/lib/components/event/event-summary-table.svelte +++ b/src/lib/components/event/event-summary-table.svelte @@ -9,20 +9,22 @@ import TableHeaderRow from '$lib/holocene/table/table-header-row.svelte'; import { translate } from '$lib/i18n/translate'; import { buildGroupIndex, isEventGroup } from '$lib/models/event-groups'; - import type { EventGroups } from '$lib/models/event-groups/event-groups'; + import type { + EventGroup, + EventGroups, + } from '$lib/models/event-groups/event-groups'; import { isEvent } from '$lib/models/event-history'; import { isLazyGroup, type LazyGroup, } from '$lib/services/grouped-event-buffer'; - import { eventBuffer } from '$lib/services/grouped-event-buffer.svelte'; import { isCloud } from '$lib/stores/advanced-visibility'; - import { fullEventHistory } from '$lib/stores/events'; import { eventStatusFilter } from '$lib/stores/filters'; import { currentPageKey, perPageKey } from '$lib/stores/pagination'; import type { IterableEventWithPending, PendingActivity, + WorkflowEvent, WorkflowEventWithPending, } from '$lib/types/events'; import type { WorkflowExecutionIdentity } from '$lib/types/workflows'; @@ -45,22 +47,34 @@ /** Discriminated on `compact` so `items` narrows without a cast. */ type Props = { workflowExecutionIdentity: WorkflowExecutionIdentity; + initialEvent: WorkflowEvent | undefined; updating?: boolean; loading?: boolean; minimized?: boolean; activityActions?: Snippet<[PendingActivity]>; } & ( - | { compact: true; items: LazyGroup[]; groups?: never } + | { + compact: true; + items: LazyGroup[]; + materializeGroup: (group: LazyGroup) => EventGroup; + groups?: never; + workflowTaskGroups?: never; + } | { compact?: false; items: IterableEventWithPending[]; + materializeGroup?: never; groups?: EventGroups; + workflowTaskGroups?: EventGroups; } ); // `const` with no default on `compact` — `let` or a default breaks narrowing. const { workflowExecutionIdentity, + initialEvent, + materializeGroup, + workflowTaskGroups = [], items, compact, groups = [], @@ -74,7 +88,6 @@ let hoveredEventId = $state(undefined); const showGraph = $derived(!minimized && !compact); - const initialItem = $derived($fullEventHistory?.[0]); const groupIndex = $derived(buildGroupIndex(groups)); const url = $derived(page.url); const perPageParam = $derived(url.searchParams.get(perPageKey) ?? '100'); @@ -93,10 +106,15 @@ // The gutter graph sits outside Paginated, so it re-derives the page. const graphHistory = $derived( showGraph - ? (filteredItems as WorkflowEventWithPending[]).slice( - (parseInt(currentPageParam) - 1) * parseInt(perPageParam), - parseInt(currentPageParam) * parseInt(perPageParam), - ) + ? filteredItems + .filter( + (item): item is WorkflowEventWithPending => + !isLazyGroup(item) && !isEventGroup(item), + ) + .slice( + (parseInt(currentPageParam) - 1) * parseInt(perPageParam), + parseInt(currentPageParam) * parseInt(perPageParam), + ) : [], ); @@ -110,7 +128,7 @@ const materializeRowReactive = ( item: IterableEventWithPending | LazyGroup, - ) => (isLazyGroup(item) ? eventBuffer.materializeGroup(item) : item); + ) => (isLazyGroup(item) ? (compact ? materializeGroup(item) : item) : item); const iterableKey = (event: IterableEventWithPending | LazyGroup) => { if (isPendingNexusOperation(event)) { @@ -137,7 +155,7 @@
{#if showGraph} - + {/if}
{:else if isPendingActivity(row)} - {:else} + {:else if !isLazyGroup(row)} {/if} {:else} - + {/each} {/snippet} diff --git a/src/lib/components/event/event-summary.svelte b/src/lib/components/event/event-summary.svelte index 784f624fb2..d4ccfe84ed 100644 --- a/src/lib/components/event/event-summary.svelte +++ b/src/lib/components/event/event-summary.svelte @@ -7,33 +7,47 @@ import TabButtons from '$lib/holocene/tab-buttons/tab-buttons.svelte'; import { IconCode, IconCompact, IconFeed } from '$lib/io/icon'; import type { EventGroups } from '$lib/models/event-groups/event-groups'; + import { isEvent } from '$lib/models/event-history'; import WorkflowHistoryJson from '$lib/pages/workflow-history-json.svelte'; + import { materializeGroup } from '$lib/services/grouped-event-buffer'; import { eventFilterSort, eventViewType } from '$lib/stores/event-view'; - import { fullEventHistory } from '$lib/stores/events'; - import { eventCategoryFilter } from '$lib/stores/filters'; + import { eventCategoryFilter, eventTypeFilter } from '$lib/stores/filters'; import { triggerRefresh, workflowRun } from '$lib/stores/workflow-run'; import type { EventTypeCategory, IterableEventWithPending, + WorkflowEvent, } from '$lib/types/events'; import type { WorkflowExecutionIdentity } from '$lib/types/workflows'; import { orderGroupsByPending } from '$lib/utilities/order-groups-by-pending'; let { history, + initialEvent, + workflowTaskGroups = [], groups, workflowExecutionIdentity, minimized = true, + loading = false, + updating = false, }: { history: IterableEventWithPending[]; + initialEvent: WorkflowEvent | undefined; + workflowTaskGroups?: EventGroups; groups: EventGroups; workflowExecutionIdentity: WorkflowExecutionIdentity; minimized?: boolean; + loading?: boolean; + updating?: boolean; } = $props(); const workflow = $derived($workflowRun.workflow); const reverseSort = $derived($eventFilterSort === 'descending'); - const updating = $derived(!$fullEventHistory.length); + const filteredEvents = $derived( + history + .filter(isEvent) + .filter((event) => $eventTypeFilter.includes(event.category)), + ); const compact = $derived($eventViewType === 'compact'); $effect(() => { @@ -54,6 +68,7 @@ ? { compact: true as const, items: orderGroupsByPending(groups, reverseSort), + materializeGroup, } : { compact: false as const, @@ -61,6 +76,7 @@ ? [...pendingNexusOperations, ...pendingActivities, ...history] : [...history, ...pendingActivities, ...pendingNexusOperations], groups, + workflowTaskGroups, }, ); @@ -106,12 +122,14 @@
{#if $eventViewType === 'json'}
- +
{:else}
- import { groupWorkflowTaskEvents } from '$lib/models/event-groups'; import type { EventGroups } from '$lib/models/event-groups/event-groups'; import { eventFilterSort } from '$lib/stores/event-view'; - import { filteredEventHistory } from '$lib/stores/events'; import type { WorkflowEventWithPending } from '$lib/types/events'; import { getGroupForEventOrPendingEvent } from '$lib/utilities/pending-activities'; @@ -14,13 +12,10 @@ interface Props { groups: EventGroups; history: WorkflowEventWithPending[]; + workflowTaskGroups: EventGroups; } - let { groups, history }: Props = $props(); - - const workflowTaskGroups = $derived( - groupWorkflowTaskEvents($filteredEventHistory, $eventFilterSort), - ); + let { groups, history, workflowTaskGroups }: Props = $props(); const allGroups = $derived([...workflowTaskGroups, ...groups]); const nodeBuffer = 4 * RADIUS; @@ -69,7 +64,7 @@ height={canvasHeight} width={canvasWidth} > - {#each history as event, index} + {#each history as event, index (index)} {@const group = getGroupForEventOrPendingEvent(allGroups, event)} {#if group} (undefined); @@ -83,12 +83,12 @@ : '', ); let totalActions = $derived( - eventBuffer.events + history.events .reduce((acc, event) => (event?.billableActions ?? 0) + acc, 0) .toString(), ); - const { sdk, version: sdkVersion } = $derived($sdkInfo); + const { sdk, version: sdkVersion } = $derived(history.sdkInfo); const fetchLatestRun = async () => { const result = await fetchWorkflow({ diff --git a/src/lib/components/workers/workers-table/task-queue-workers-table.svelte b/src/lib/components/workers/workers-table/task-queue-workers-table.svelte index 381c04cf5c..53c45f90bb 100644 --- a/src/lib/components/workers/workers-table/task-queue-workers-table.svelte +++ b/src/lib/components/workers/workers-table/task-queue-workers-table.svelte @@ -1,5 +1,11 @@ @@ -62,7 +68,7 @@
{translate('workers.no-worker-heartbeats')}
{#if currentSdk} {@const { href, sdk, version } = currentSdk} - {#if !minimumVersionRequired(version, $sdkInfo.version)} + {#if !minimumVersionRequired(version, sdkInfo.version)}

{translate('workers.worker-heartbeats-sdk-link-preface')} diff --git a/src/lib/components/workers/workers-table/workers-table.svelte b/src/lib/components/workers/workers-table/workers-table.svelte index f9803640e6..e819c1841f 100644 --- a/src/lib/components/workers/workers-table/workers-table.svelte +++ b/src/lib/components/workers/workers-table/workers-table.svelte @@ -9,7 +9,10 @@ import { translate } from '$lib/i18n/translate'; import { workflowRun } from '$lib/stores/workflow-run'; import type { WorkerHeartbeat, WorkerListInfo } from '$lib/types'; - import { formatSDKName } from '$lib/utilities/get-sdk-version'; + import { + formatSDKName, + type getSDKandVersion, + } from '$lib/utilities/get-sdk-version'; import { getWorkerHostName } from '$lib/utilities/get-worker-host-name'; import { isRunningWithNoWorkers } from '$lib/utilities/is-running-with-no-workers'; import { toWorkerStatusReadable } from '$lib/utilities/screaming-enums'; @@ -21,6 +24,7 @@ interface Props { filterable?: boolean; + sdkInfo?: ReturnType; namespace: string; onFetch: () => Promise>; onError?: (err: unknown) => void; @@ -30,6 +34,7 @@ let { filterable = false, + sdkInfo, namespace, onFetch, onError, @@ -125,7 +130,7 @@ {:else if runningWithNoWorkers} {:else} - + {/if}

{/snippet} diff --git a/src/lib/components/workflow-actions.svelte b/src/lib/components/workflow-actions.svelte index c0f0ce15d7..52372c51e2 100644 --- a/src/lib/components/workflow-actions.svelte +++ b/src/lib/components/workflow-actions.svelte @@ -17,9 +17,8 @@ import Menu from '$lib/holocene/menu/menu.svelte'; import { translate } from '$lib/i18n/translate'; import { isCloud } from '$lib/stores/advanced-visibility'; - import { resetEvents } from '$lib/stores/events'; import { temporalVersion } from '$lib/stores/versions'; - import type { WorkflowEvent } from '$lib/types/events'; + import type { WorkflowEvents } from '$lib/types/events'; import type { WorkflowExecution } from '$lib/types/workflows'; import { isWorkflowDelayed } from '$lib/utilities/delayed-workflows'; import { routeForWorkflowStart } from '$lib/utilities/route-for'; @@ -33,13 +32,21 @@ import { workflowUpdateEnabled } from '$lib/utilities/workflow-update-enabled'; interface Props { workflow: WorkflowExecution; + resetEvents: WorkflowEvents; namespace: string; cancelInProgress: boolean; first?: string; next?: string; } - let { workflow, namespace, cancelInProgress, first, next }: Props = $props(); + let { + workflow, + resetEvents, + namespace, + cancelInProgress, + first, + next, + }: Props = $props(); const isRunning = $derived(workflow?.isRunning); const isPaused = $derived(workflow?.isPaused); @@ -81,7 +88,7 @@ let resetEnabled = $derived( resetAuthorized && canResetWithPendingChildWorkflows && - $resetEvents.length > 0, + resetEvents.length > 0, ); let startWorkflowDisabled = $derived( @@ -103,7 +110,7 @@ }: { resetAuthorized: boolean; canResetWithPendingChildWorkflows: boolean; - resetEvents: WorkflowEvent[]; + resetEvents: WorkflowEvents; }) => { if (!resetAuthorized) { return translate('workflows.reset-disabled-unauthorized'); @@ -123,7 +130,7 @@ getResetDescription({ resetAuthorized, canResetWithPendingChildWorkflows, - resetEvents: $resetEvents, + resetEvents, }), ); @@ -323,6 +330,7 @@ {#if resetEnabled} - {#each $resetEvents as event (event.eventId)} + {#each resetEvents as event (event.eventId)} {/each} diff --git a/src/lib/components/workflow/input-and-results.svelte b/src/lib/components/workflow/input-and-results.svelte index b011168f34..438eabc73b 100644 --- a/src/lib/components/workflow/input-and-results.svelte +++ b/src/lib/components/workflow/input-and-results.svelte @@ -4,8 +4,8 @@ createDecodedPayload, type DecodedPayloadState, } from '$lib/runes/decoded-payload.svelte'; - import { fullEventHistory } from '$lib/stores/events'; import { workflowRun } from '$lib/stores/workflow-run'; + import type { WorkflowEvents } from '$lib/types/events'; import { isParsedPayload } from '$lib/utilities/decode-payload'; import { getWorkflowStartedCompletedAndTaskFailedEvents, @@ -16,8 +16,10 @@ import InputAndResultsPayload from './input-and-results-payload.svelte'; import PayloadPreview from './payload-preview.svelte'; + let { events }: { events: WorkflowEvents } = $props(); + const workflowEvents = $derived( - getWorkflowStartedCompletedAndTaskFailedEvents($fullEventHistory), + getWorkflowStartedCompletedAndTaskFailedEvents(events), ); const isPending = $derived( $workflowRun.workflow?.isRunning || diff --git a/src/lib/components/workflow/relationships/workflow-family-node-tree.svelte b/src/lib/components/workflow/relationships/workflow-family-node-tree.svelte index 6c9a295cbe..1d45cfa2b2 100644 --- a/src/lib/components/workflow/relationships/workflow-family-node-tree.svelte +++ b/src/lib/components/workflow/relationships/workflow-family-node-tree.svelte @@ -6,8 +6,8 @@ import { translate } from '$lib/i18n/translate'; import { IconTemporalSchedules } from '$lib/io/icon'; import type { RootNode } from '$lib/services/workflow-service'; - import { fullEventHistory } from '$lib/stores/events'; import { workflowRun } from '$lib/stores/workflow-run'; + import type { WorkflowEvents } from '$lib/types/events'; import type { WorkflowExecution } from '$lib/types/workflows'; import { getWorkflowRelationships } from '$lib/utilities/get-workflow-relationships'; import { @@ -21,6 +21,7 @@ interface Props { root: RootNode; + events: WorkflowEvents; width: number; height: number; zoomLevel: number; @@ -35,6 +36,7 @@ let { root, + events, width, height, zoomLevel, @@ -52,11 +54,7 @@ const namespace = $derived(page.params.namespace); const fullWorkflow = $derived($workflowRun.workflow); const workflowRelationships = $derived( - getWorkflowRelationships( - fullWorkflow, - $fullEventHistory, - page.data.namespace, - ), + getWorkflowRelationships(fullWorkflow, events, page.data.namespace), ); const first = $derived(workflowRelationships.first); const next = $derived(workflowRelationships.next); @@ -170,6 +168,7 @@ {#if child.children.length && isExpanded(child)} (undefined); @@ -86,6 +88,7 @@ {#snippet graph({ width, height, zoomLevel })} import AccordionLight from '$lib/holocene/accordion/accordion-light.svelte'; - import { fullEventHistory } from '$lib/stores/events'; + import type { WorkflowEvent } from '$lib/types/events'; import type { Callback } from '$lib/types/nexus'; import WorkflowCallback from './workflow-callback.svelte'; - let { callbacks }: { callbacks: Callback[] } = $props(); - - const initialEvent = $derived($fullEventHistory[0]); + let { + callbacks, + initialEvent, + }: { callbacks: Callback[]; initialEvent?: WorkflowEvent } = $props(); const link = $derived(initialEvent?.links?.[0]); const firstCallback = $derived(callbacks[0]); diff --git a/src/lib/components/workflow/workflow-common-errors.svelte b/src/lib/components/workflow/workflow-common-errors.svelte index 1f892235eb..7ec818db41 100644 --- a/src/lib/components/workflow/workflow-common-errors.svelte +++ b/src/lib/components/workflow/workflow-common-errors.svelte @@ -9,18 +9,24 @@ - +
{#if workflowTaskFailedError} {/if} {#if workflow?.callbacks?.length} - + {/if}
@@ -281,7 +289,7 @@ {/if} - +
- {:else} + {:else if historyView}
{ - $fullEventHistory = eventBuffer.events; - }); - const clearWorkflowData = () => { - $timelineEvents = null; $workflowRun = initialWorkflowRun; - $fullEventHistory = []; + workflowError = null; _refetchSeq++; abortAll(); @@ -351,9 +344,9 @@
{:else if displayError} -{:else if !$workflowRun.workflow} +{:else if !$workflowRun.workflow || !historyController} {:else} - + {@render children()} {/if} diff --git a/src/lib/layouts/workflow-timeline-layout.svelte b/src/lib/layouts/workflow-timeline-layout.svelte index f89f466eac..a87d5e102e 100644 --- a/src/lib/layouts/workflow-timeline-layout.svelte +++ b/src/lib/layouts/workflow-timeline-layout.svelte @@ -27,7 +27,6 @@ IconCollapse, IconDownload, } from '$lib/io/icon'; - import { eventBuffer } from '$lib/services/grouped-event-buffer.svelte'; import { clearActives } from '$lib/stores/active-events'; import { collapseIdleTime, eventFilterSort } from '$lib/stores/event-view'; import { pauseLiveUpdates } from '$lib/stores/events'; @@ -44,6 +43,7 @@ import { getTimelineGroups } from '$lib/utilities/sort-timeline-groups'; const historyCtx = getContext(HISTORY_CTX); + const historyView = $derived(historyCtx.history); const namespace = $derived(page.params.namespace); const workflow = $derived($workflowRun.workflow); @@ -64,10 +64,12 @@ const reverseSort = $derived($eventFilterSort === 'descending'); - const bufferLazyGroups = $derived(eventBuffer.lazyGroupsWithoutWorkflowTasks); + const bufferLazyGroups = $derived( + historyView?.lazyGroupsWithoutWorkflowTasks ?? [], + ); const eventGroupMatcher = $derived( - eventBuffer.eventGroupMatcher(urlParams.eventGroups), + historyView?.eventGroupMatcher(urlParams.eventGroups), ); const filteredBufferLazyGroups = $derived.by(() => { @@ -90,7 +92,7 @@ const workflowTaskFailedError = $derived.by(() => { if (!historyCtx.fetchComplete) return undefined; - return eventBuffer.workflowTaskFailedEvent as + return historyView?.workflowTaskFailedEvent as | WorkflowTaskFailedEvent | WorkflowTaskTimedOutEvent | undefined; @@ -143,7 +145,7 @@ }; - +
{#if workflowTaskFailedError} {/if} {#if workflow?.callbacks?.length} - + {/if}
@@ -195,7 +200,7 @@ : translate('workflows.hide-idle-time')} - + - {#if workflow} + {#if workflow && historyView} {#key JSON.stringify([namespace, workflow.id, workflow.runId])} - import { onMount } from 'svelte'; + import { getContext, onMount } from 'svelte'; import ActivityCommands from '$lib/components/activity/activity-commands.svelte'; import EventSummaryRow from '$lib/components/event/event-summary-row.svelte'; + import { + HISTORY_CTX, + type HistoryContext, + } from '$lib/contexts/history-context'; import Button from '$lib/holocene/button.svelte'; import { IconArrowDown, IconArrowUp } from '$lib/io/icon'; import { buildGroupIndex, groupEvents } from '$lib/models/event-groups'; import { isEvent } from '$lib/models/event-history'; - import { fetchAllEvents } from '$lib/services/events-service'; import { eventFilterSort } from '$lib/stores/event-view'; - import { fullEventHistory } from '$lib/stores/events'; import { triggerRefresh, workflowRun } from '$lib/stores/workflow-run'; import type { PendingActivity } from '$lib/types/events'; import type { WorkflowExecutionIdentity } from '$lib/types/workflows'; @@ -22,30 +24,13 @@ } const { eventId, namespace, workflowId, runId }: Props = $props(); + const historyCtx = getContext(HISTORY_CTX); + const events = $derived(historyCtx.history?.events ?? []); let ids = $derived([eventId]); - const resetFullHistory = () => { - $fullEventHistory = []; - }; - - const fetchEvents = async ( - namespace: string, - workflowId: string, - runId: string, - ) => { - if (!$fullEventHistory.length) { - resetFullHistory(); - $fullEventHistory = await fetchAllEvents({ - namespace, - workflowId, - runId, - }); - } - }; - onMount(() => { - fetchEvents(namespace, workflowId, runId); + historyCtx.resume(); }); const { workflow } = $derived($workflowRun); @@ -58,12 +43,7 @@ const pendingNexusOperations = $derived(workflow?.pendingNexusOperations); const ascendingGroups = $derived( - groupEvents( - $fullEventHistory, - 'ascending', - pendingActivities, - pendingNexusOperations, - ), + groupEvents(events, 'ascending', pendingActivities, pendingNexusOperations), ); const groups = $derived( $eventFilterSort === 'ascending' @@ -73,7 +53,7 @@ const groupIndex = $derived(buildGroupIndex(groups)); const initialEvent = $derived( - $fullEventHistory.find( + events.find( (e) => e.id === eventId || e.id === @@ -84,14 +64,10 @@ ); const visibleItems = $derived( - $fullEventHistory.filter( - (e) => ids.includes(e.id) || e.id === initialEvent?.id, - ), - ); - const loading = $derived(!visibleItems.length); - const lastEventId = $derived( - $fullEventHistory[$fullEventHistory.length - 1]?.id, + events.filter((e) => ids.includes(e.id) || e.id === initialEvent?.id), ); + const loading = $derived(!historyCtx.fetchComplete && !visibleItems.length); + const lastEventId = $derived(events.at(-1)?.id); const loadPrevious = () => { const firstId = parseInt(ids[0]); @@ -113,7 +89,7 @@ const start = lastId + 1; for (let i = 0; i < 10; i++) { - if (start + i <= $fullEventHistory.length) { + if (start + i <= Number(lastEventId ?? 0)) { nextTen.push((start + i).toString()); } } @@ -153,7 +129,7 @@ {index} expanded={event.id === initialEvent?.id} group={isEvent(event) ? groupIndex.get(event.id) : undefined} - initialItem={$fullEventHistory[0]} + initialItem={historyCtx.history?.initialEvent} {activityActions} /> {/each} diff --git a/src/lib/pages/workflow-history-json.svelte b/src/lib/pages/workflow-history-json.svelte index 8774e1573a..7839707647 100644 --- a/src/lib/pages/workflow-history-json.svelte +++ b/src/lib/pages/workflow-history-json.svelte @@ -2,19 +2,17 @@ import WorkflowJsonNavigator from '$lib/components/workflow/workflow-json-navigator.svelte'; import ToggleSwitch from '$lib/holocene/toggle-switch.svelte'; import { translate } from '$lib/i18n/translate'; - import { decodeEventHistory, filteredEventHistory } from '$lib/stores/events'; + import { decodeEventHistory } from '$lib/stores/events'; import type { WorkflowEvent } from '$lib/types/events'; interface Props { - events?: WorkflowEvent[]; + events: WorkflowEvent[]; } let { events }: Props = $props(); - - const resolvedEvents = $derived(events ?? $filteredEventHistory); - + {#snippet decode()} + import { getContext } from 'svelte'; + import { page } from '$app/state'; + import { + HISTORY_CTX, + type HistoryContext, + } from '$lib/contexts/history-context'; import EmptyState from '$lib/holocene/empty-state.svelte'; import Link from '$lib/holocene/link.svelte'; import PaginatedTable from '$lib/holocene/table/paginated-table/paginated.svelte'; @@ -17,7 +23,6 @@ getInboundLinkForEvent, getVisibleInboundNexusLinkEvents, } from '$lib/runes/inbound-nexus-links.svelte'; - import { fullEventHistory } from '$lib/stores/events'; import { workflowRun } from '$lib/stores/workflow-run'; import { isSystemNexusScheduledEvent } from '$lib/system-nexus-endpoints'; import { @@ -35,18 +40,16 @@ import { routeForEventHistoryEvent } from '$lib/utilities/route-for'; import { updateQueryParameters } from '$lib/utilities/update-query-parameters'; + const historyCtx = getContext(HISTORY_CTX); + const events = $derived(historyCtx.history?.events ?? []); + const { namespace, workflow: workflowId, run } = $derived(page.params); const { workflow } = $derived($workflowRun); const pendingActivities = $derived(workflow?.pendingActivities); const pendingNexusOperations = $derived(workflow?.pendingNexusOperations); const groups = $derived( - groupEvents( - $fullEventHistory, - 'ascending', - pendingActivities, - pendingNexusOperations, - ), + groupEvents(events, 'ascending', pendingActivities, pendingNexusOperations), ); const nexusGroups = $derived( groups.filter( @@ -56,9 +59,7 @@ !group.eventList.some((event) => isSystemNexusScheduledEvent(event)), ), ); - const inboundLinks = getVisibleInboundNexusLinkEvents( - () => $fullEventHistory, - ); + const inboundLinks = getVisibleInboundNexusLinkEvents(() => events); const inboundLinkEvents = $derived(inboundLinks.events); const counts = $derived({ diff --git a/src/lib/pages/workflow-pending-activities.svelte b/src/lib/pages/workflow-pending-activities.svelte index b737d97879..f72dc88652 100644 --- a/src/lib/pages/workflow-pending-activities.svelte +++ b/src/lib/pages/workflow-pending-activities.svelte @@ -1,13 +1,19 @@ - + diff --git a/src/routes/(app)/namespaces/[namespace]/archival/[workflow]/[run]/history/+page.svelte b/src/routes/(app)/namespaces/[namespace]/archival/[workflow]/[run]/history/+page.svelte index 9ce938a6d7..87d5c7b63a 100644 --- a/src/routes/(app)/namespaces/[namespace]/archival/[workflow]/[run]/history/+page.svelte +++ b/src/routes/(app)/namespaces/[namespace]/archival/[workflow]/[run]/history/+page.svelte @@ -11,6 +11,7 @@ import { IconChevronLeft } from '$lib/io/icon'; import { groupEvents } from '$lib/models/event-groups'; import type { WorkflowExecutionIdentity } from '$lib/types/workflows'; + import { isWorkflowExecutionStartedEvent } from '$lib/utilities/is-event-type'; import { routeForArchivalWorkflows } from '$lib/utilities/route-for'; let { data }: { data: PageData } = $props(); @@ -49,7 +50,12 @@ {:then history} {@const groups = groupEvents(history, 'ascending', [], [])} - + {:catch error}

From 92fbb96f19d23ae208214cc7d05e089ba2a51e20 Mon Sep 17 00:00:00 2001 From: Tegan Churchill Date: Thu, 5 Nov 2026 11:21:05 -0800 Subject: [PATCH 07/19] Remove workflow execution chain support --- .../catalog/browser/catalog.generated.json | 57 +----------------- src/lib/catalog/browser/catalog.generated.ts | 58 +------------------ .../examples/continue-as-new/example.ts | 56 ------------------ .../examples/continue-as-new/workflow.ts | 41 ------------- .../catalog/worker/examples/corpus.test.ts | 4 -- src/lib/catalog/worker/examples/index.ts | 50 ++++++++-------- src/lib/catalog/worker/workflows.ts | 1 - .../table-body-cell.svelte | 8 --- src/lib/i18n/locales/en/workflows.ts | 8 --- src/lib/models/workflow-execution.ts | 2 - src/lib/pages/workflow-chain.svelte | 55 ------------------ .../workflow-history-controller.svelte.ts | 12 ++-- src/lib/types/workflows.ts | 1 - src/lib/utilities/route-for-base-path.test.ts | 15 ----- src/lib/utilities/route-for.ts | 18 ------ .../workflows/[workflow]/[run]/chain/+page.ts | 37 ------------ .../chain/[firstRunId]/+page.svelte | 5 -- 17 files changed, 29 insertions(+), 399 deletions(-) delete mode 100644 src/lib/catalog/worker/examples/continue-as-new/example.ts delete mode 100644 src/lib/catalog/worker/examples/continue-as-new/workflow.ts delete mode 100644 src/lib/pages/workflow-chain.svelte delete mode 100644 src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/[run]/chain/+page.ts delete mode 100644 src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/chain/[firstRunId]/+page.svelte diff --git a/src/lib/catalog/browser/catalog.generated.json b/src/lib/catalog/browser/catalog.generated.json index b8fae5a22e..b5c0dde3c2 100644 --- a/src/lib/catalog/browser/catalog.generated.json +++ b/src/lib/catalog/browser/catalog.generated.json @@ -1,5 +1,5 @@ { - "sourceHash": "91d6c0b568d98f47fca726e41b49f2b221e088705072c3417318a553de042dfc", + "sourceHash": "ab1d28559cd8149433f8505b38591843db129021116c4f63f3a2a9f5e2b9f690", "descriptors": [ { "id": "activity-heartbeat", @@ -228,61 +228,6 @@ }, "source": { "id": "oss", "label": "OSS" } }, - { - "id": "continue-as-new", - "title": "Continue-As-New chain", - "description": "Creates a bounded chain of workflow runs with the same Workflow ID and distinct Run IDs, then completes the final run.", - "capabilityTags": ["continue-as-new", "timers", "terminal-outcome"], - "expectedEvidence": [ - "Five runs with the same Workflow ID and distinct Run IDs using the default inputs.", - "The first four runs have Continued-As-New status and link to the next run; the fifth completes.", - "Each run contains a durable timer and carries its progress into the next run through workflow input.", - "The final workflow result reports the total number of runs in the chain." - ], - "input": { - "defaultValue": [5, 2], - "schema": { - "type": "array", - "prefixItems": [ - { - "title": "Total runs in the chain", - "type": "integer", - "minimum": 1, - "maximum": 25 - }, - { - "title": "Delay per run in seconds", - "type": "integer", - "minimum": 1, - "maximum": 30 - } - ], - "items": false, - "maxItems": 2 - } - }, - "startOptions": { - "defaultValue": {}, - "schema": { - "type": "object", - "properties": { - "details": { "type": "string" }, - "searchAttributes": { "type": "object" }, - "summary": { "type": "string" }, - "workflowStartDelay": { "type": "string" }, - "workflowId": { "type": "string", "minLength": 1 } - } - } - }, - "execution": { - "kind": "workflow", - "targetId": "shared-workflows", - "namespace": "default", - "taskQueue": "ui-catalog", - "workflowType": "continueAsNewChain" - }, - "source": { "id": "oss", "label": "OSS" } - }, { "id": "hello", "title": "Hello activity", diff --git a/src/lib/catalog/browser/catalog.generated.ts b/src/lib/catalog/browser/catalog.generated.ts index f7e95c22cf..c737c1e4dd 100644 --- a/src/lib/catalog/browser/catalog.generated.ts +++ b/src/lib/catalog/browser/catalog.generated.ts @@ -2,7 +2,7 @@ import type { BrowserCatalogArtifact } from './types'; export const catalogArtifact: BrowserCatalogArtifact = { sourceHash: - '91d6c0b568d98f47fca726e41b49f2b221e088705072c3417318a553de042dfc', + 'ab1d28559cd8149433f8505b38591843db129021116c4f63f3a2a9f5e2b9f690', descriptors: [ { id: 'activity-heartbeat', @@ -233,62 +233,6 @@ export const catalogArtifact: BrowserCatalogArtifact = { }, source: { id: 'oss', label: 'OSS' }, }, - { - id: 'continue-as-new', - title: 'Continue-As-New chain', - description: - 'Creates a bounded chain of workflow runs with the same Workflow ID and distinct Run IDs, then completes the final run.', - capabilityTags: ['continue-as-new', 'timers', 'terminal-outcome'], - expectedEvidence: [ - 'Five runs with the same Workflow ID and distinct Run IDs using the default inputs.', - 'The first four runs have Continued-As-New status and link to the next run; the fifth completes.', - 'Each run contains a durable timer and carries its progress into the next run through workflow input.', - 'The final workflow result reports the total number of runs in the chain.', - ], - input: { - defaultValue: [5, 2], - schema: { - type: 'array', - prefixItems: [ - { - title: 'Total runs in the chain', - type: 'integer', - minimum: 1, - maximum: 25, - }, - { - title: 'Delay per run in seconds', - type: 'integer', - minimum: 1, - maximum: 30, - }, - ], - items: false, - maxItems: 2, - }, - }, - startOptions: { - defaultValue: {}, - schema: { - type: 'object', - properties: { - details: { type: 'string' }, - searchAttributes: { type: 'object' }, - summary: { type: 'string' }, - workflowStartDelay: { type: 'string' }, - workflowId: { type: 'string', minLength: 1 }, - }, - }, - }, - execution: { - kind: 'workflow', - targetId: 'shared-workflows', - namespace: 'default', - taskQueue: 'ui-catalog', - workflowType: 'continueAsNewChain', - }, - source: { id: 'oss', label: 'OSS' }, - }, { id: 'hello', title: 'Hello activity', diff --git a/src/lib/catalog/worker/examples/continue-as-new/example.ts b/src/lib/catalog/worker/examples/continue-as-new/example.ts deleted file mode 100644 index 7c83c8d2b6..0000000000 --- a/src/lib/catalog/worker/examples/continue-as-new/example.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { continueAsNewChain } from './workflow.js'; -import type { RuntimeJsonDocument } from '../../../browser/types.js'; -import type { CatalogExampleDefinition } from '../../registry.js'; - -const input: RuntimeJsonDocument = { - defaultValue: [5, 2], - schema: { - type: 'array', - prefixItems: [ - { - title: 'Total runs in the chain', - type: 'integer', - minimum: 1, - maximum: 25, - }, - { - title: 'Delay per run in seconds', - type: 'integer', - minimum: 1, - maximum: 30, - }, - ], - items: false, - maxItems: 2, - }, -}; - -const startOptions: RuntimeJsonDocument = { - defaultValue: {}, - schema: { - type: 'object', - properties: { workflowId: { type: 'string', minLength: 1 } }, - }, -}; - -export const catalogExample: CatalogExampleDefinition = { - id: 'continue-as-new', - title: 'Continue-As-New chain', - description: - 'Creates a bounded chain of workflow runs with the same Workflow ID and distinct Run IDs, then completes the final run.', - capabilityTags: ['continue-as-new', 'timers', 'terminal-outcome'], - expectedEvidence: [ - 'Five runs with the same Workflow ID and distinct Run IDs using the default inputs.', - 'The first four runs have Continued-As-New status and link to the next run; the fifth completes.', - 'Each run contains a durable timer and carries its progress into the next run through workflow input.', - 'The final workflow result reports the total number of runs in the chain.', - ], - input, - startOptions, - execution: { - kind: 'workflow', - workflowType: 'continueAsNewChain', - workflow: continueAsNewChain, - activities: {}, - }, -}; diff --git a/src/lib/catalog/worker/examples/continue-as-new/workflow.ts b/src/lib/catalog/worker/examples/continue-as-new/workflow.ts deleted file mode 100644 index 44ddfd775a..0000000000 --- a/src/lib/catalog/worker/examples/continue-as-new/workflow.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { continueAsNew, log, sleep } from '@temporalio/workflow'; - -export async function continueAsNewChain( - runCount = 5, - delaySeconds = 2, - completedRuns = 0, -): Promise { - if (!Number.isInteger(runCount) || runCount < 1 || runCount > 25) { - throw new Error('Run count must be an integer between 1 and 25.'); - } - if ( - !Number.isInteger(delaySeconds) || - delaySeconds < 1 || - delaySeconds > 30 - ) { - throw new Error('Delay must be an integer between 1 and 30 seconds.'); - } - if ( - !Number.isInteger(completedRuns) || - completedRuns < 0 || - completedRuns >= runCount - ) { - throw new Error( - 'Completed run count must be a non-negative integer below the run count.', - ); - } - - const currentRun = completedRuns + 1; - log.info('Continue-As-New chain run', { currentRun, runCount }); - await sleep(`${delaySeconds} seconds`); - - if (currentRun < runCount) { - return await continueAsNew( - runCount, - delaySeconds, - currentRun, - ); - } - - return `Completed ${runCount} runs in the Continue-As-New chain.`; -} diff --git a/src/lib/catalog/worker/examples/corpus.test.ts b/src/lib/catalog/worker/examples/corpus.test.ts index d82a0500ba..0fbbb89f8b 100644 --- a/src/lib/catalog/worker/examples/corpus.test.ts +++ b/src/lib/catalog/worker/examples/corpus.test.ts @@ -46,7 +46,6 @@ const migratedWorkflowTypes = [ ] as const; const proofExampleIds = [ - 'continue-as-new', 'priority-fairness', 'standalone-activity', 'nexus-greeting', @@ -180,7 +179,6 @@ describe('shared workflow corpus', () => { expect(Object.keys(target?.workflowExports ?? {}).sort()).toEqual( [ ...migratedWorkflowTypes, - 'continueAsNewChain', 'priorityFairnessWorkflow', 'nexusGreeting', 'satelliteLaunchEventGroups', @@ -606,8 +604,6 @@ describe('shared workflow corpus', () => { 'src/lib/catalog/worker/workflows.ts', 'src/lib/catalog/worker/examples/inventory.ts', 'src/lib/catalog/worker/examples/index.ts', - 'src/lib/catalog/worker/examples/continue-as-new/example.ts', - 'src/lib/catalog/worker/examples/continue-as-new/workflow.ts', 'src/lib/catalog/worker/examples/shared-activities.ts', 'src/lib/catalog/worker/examples/hello/example.ts', 'src/lib/catalog/worker/examples/hello/workflow.ts', diff --git a/src/lib/catalog/worker/examples/index.ts b/src/lib/catalog/worker/examples/index.ts index e85c94d4ec..8caccb6f85 100644 --- a/src/lib/catalog/worker/examples/index.ts +++ b/src/lib/catalog/worker/examples/index.ts @@ -9,30 +9,29 @@ import { catalogExample as example1 } from './activity-retry/example.js'; import { catalogExample as example2 } from './activity-timeout/example.js'; import { catalogExample as example3 } from './child-fan-out/example.js'; import { catalogExample as example4 } from './child-workflows/example.js'; -import { catalogExample as example5 } from './continue-as-new/example.js'; -import { catalogExample as example6 } from './hello/example.js'; -import { catalogExample as example7 } from './high-event-count/example.js'; -import { catalogExample as example8 } from './large-history/example.js'; -import { catalogExample as example9 } from './local-activity/example.js'; -import { catalogExample as example10 } from './long-activity/example.js'; -import { catalogExample as example11 } from './nexus-greeting/example.js'; -import { catalogExample as example12 } from './parallel-activities/example.js'; -import { catalogExample as example13 } from './pending-activities/example.js'; -import { catalogExample as example14 } from './pending-nexus/example.js'; -import { catalogExample as example15 } from './priority-fairness/example.js'; -import { catalogExample as example16 } from './satellite-launch-event-groups/example.js'; -import { catalogExample as example17 } from './sequential-activities/example.js'; -import { catalogExample as example18 } from './sequential-markdown-activities/example.js'; -import { catalogExample as example19 } from './sequential-multiline-summary-activities/example.js'; -import { catalogExample as example20 } from './sequential-no-summary-activities/example.js'; -import { catalogExample as example21 } from './sequential-plain-text-activities/example.js'; -import { catalogExample as example22 } from './signal-collector/example.js'; -import { catalogExample as example23 } from './signal-handlers/example.js'; -import { catalogExample as example24 } from './slow-nexus-operation/example.js'; -import { catalogExample as example25 } from './standalone-activity/example.js'; -import { catalogExample as example26 } from './timer-driven-repetition/example.js'; -import { catalogExample as example27 } from './workflow-feature-tour/example.js'; -import { catalogExample as example28 } from './workflow-patching/example.js'; +import { catalogExample as example5 } from './hello/example.js'; +import { catalogExample as example6 } from './high-event-count/example.js'; +import { catalogExample as example7 } from './large-history/example.js'; +import { catalogExample as example8 } from './local-activity/example.js'; +import { catalogExample as example9 } from './long-activity/example.js'; +import { catalogExample as example10 } from './nexus-greeting/example.js'; +import { catalogExample as example11 } from './parallel-activities/example.js'; +import { catalogExample as example12 } from './pending-activities/example.js'; +import { catalogExample as example13 } from './pending-nexus/example.js'; +import { catalogExample as example14 } from './priority-fairness/example.js'; +import { catalogExample as example15 } from './satellite-launch-event-groups/example.js'; +import { catalogExample as example16 } from './sequential-activities/example.js'; +import { catalogExample as example17 } from './sequential-markdown-activities/example.js'; +import { catalogExample as example18 } from './sequential-multiline-summary-activities/example.js'; +import { catalogExample as example19 } from './sequential-no-summary-activities/example.js'; +import { catalogExample as example20 } from './sequential-plain-text-activities/example.js'; +import { catalogExample as example21 } from './signal-collector/example.js'; +import { catalogExample as example22 } from './signal-handlers/example.js'; +import { catalogExample as example23 } from './slow-nexus-operation/example.js'; +import { catalogExample as example24 } from './standalone-activity/example.js'; +import { catalogExample as example25 } from './timer-driven-repetition/example.js'; +import { catalogExample as example26 } from './workflow-feature-tour/example.js'; +import { catalogExample as example27 } from './workflow-patching/example.js'; const sharedWorkflowDefinitions = [ example0, @@ -63,7 +62,6 @@ const sharedWorkflowDefinitions = [ example25, example26, example27, - example28, ] satisfies readonly CatalogExampleDefinition[]; export const sharedWorkflowExamples: readonly CatalogExampleRegistration[] = @@ -118,8 +116,6 @@ export const sharedWorkflowSourceFiles = [ 'src/lib/catalog/worker/examples/child-fan-out/workflow.ts', 'src/lib/catalog/worker/examples/child-workflows/example.ts', 'src/lib/catalog/worker/examples/child-workflows/workflow.ts', - 'src/lib/catalog/worker/examples/continue-as-new/example.ts', - 'src/lib/catalog/worker/examples/continue-as-new/workflow.ts', 'src/lib/catalog/worker/examples/hello/example.ts', 'src/lib/catalog/worker/examples/hello/workflow.ts', 'src/lib/catalog/worker/examples/high-event-count/example.ts', diff --git a/src/lib/catalog/worker/workflows.ts b/src/lib/catalog/worker/workflows.ts index f5adb93035..9037d8aefc 100644 --- a/src/lib/catalog/worker/workflows.ts +++ b/src/lib/catalog/worker/workflows.ts @@ -4,7 +4,6 @@ export { retryWorkflow } from './examples/activity-retry/workflow.js'; export { timeoutWorkflow } from './examples/activity-timeout/workflow.js'; export { childFanOut } from './examples/child-fan-out/workflow.js'; export { childWorkflowTest } from './examples/child-workflows/workflow.js'; -export { continueAsNewChain } from './examples/continue-as-new/workflow.js'; export { hello } from './examples/hello/workflow.js'; export { highEventCountWorkflow } from './examples/high-event-count/workflow.js'; export { largeHistory } from './examples/large-history/workflow.js'; diff --git a/src/lib/components/workflow/workflows-summary-configurable-table/table-body-cell.svelte b/src/lib/components/workflow/workflows-summary-configurable-table/table-body-cell.svelte index a16f4af575..5277b0df7e 100644 --- a/src/lib/components/workflow/workflows-summary-configurable-table/table-body-cell.svelte +++ b/src/lib/components/workflow/workflows-summary-configurable-table/table-body-cell.svelte @@ -29,7 +29,6 @@ import { routeForWorkerDeployment, routeForWorkflow, - routeForWorkflowChainRedirect, } from '$lib/utilities/route-for'; import { TRUNCATE_LENGTH, @@ -65,13 +64,6 @@ ); const hrefFor = (value: QuickFilterValue) => { - if (label === 'Workflow ID' && !archival) { - return routeForWorkflowChainRedirect({ - namespace, - workflow: workflow.id, - run: workflow.runId, - }); - } if (['Type', 'Workflow ID', 'Run ID'].includes(label)) { return routeForWorkflow({ namespace, diff --git a/src/lib/i18n/locales/en/workflows.ts b/src/lib/i18n/locales/en/workflows.ts index c0eedb137f..e1a5ec767d 100644 --- a/src/lib/i18n/locales/en/workflows.ts +++ b/src/lib/i18n/locales/en/workflows.ts @@ -1,14 +1,6 @@ export const Namespace = 'workflows' as const; export const Strings = { - 'execution-chain': 'Workflow execution chain', - - 'execution-chain-placeholder': - 'The execution chain visualization is not implemented yet.', - 'execution-chain-back': 'Back to workflows', - 'execution-chain-view-execution': 'View entry execution', - 'execution-chain-first-run-unavailable': - 'The server did not return the first Run ID for this execution chain.', 'loading-workflows': 'Loading workflows', 'recent-workflows': 'Recent Workflows', 'recent-workflows-link': 'View Recent Workflows', diff --git a/src/lib/models/workflow-execution.ts b/src/lib/models/workflow-execution.ts index 36d00b92b0..8545b92b65 100644 --- a/src/lib/models/workflow-execution.ts +++ b/src/lib/models/workflow-execution.ts @@ -88,7 +88,6 @@ export const toWorkflowExecution = ( const name = info?.type?.name ?? ''; const id = info?.execution?.workflowId ?? ''; const runId = info?.execution?.runId ?? ''; - const firstRunId = info?.firstRunId || undefined; const startTime = info?.startTime ?? ''; const endTime = info?.closeTime ?? ''; const executionTime = info?.executionTime ?? ''; @@ -143,7 +142,6 @@ export const toWorkflowExecution = ( name, id, runId, - ...(firstRunId && { firstRunId }), startTime, endTime, executionTime, diff --git a/src/lib/pages/workflow-chain.svelte b/src/lib/pages/workflow-chain.svelte deleted file mode 100644 index 619f4bb7d3..0000000000 --- a/src/lib/pages/workflow-chain.svelte +++ /dev/null @@ -1,55 +0,0 @@ - - - - -
- - {#snippet heading()} - {translate('workflows.execution-chain')} - {/snippet} - {#snippet actions()} - - {translate('workflows.execution-chain-back')} - - - {translate('workflows.execution-chain-view-execution')} - - {/snippet} - {#snippet metadata()} -
-
-
{translate('common.workflow-id')}
-
{workflow}
-
-
-
{translate('common.run-id')}
-
{firstRunId}
-
-
- {/snippet} -
-
-

- {translate('workflows.execution-chain-placeholder')} -

-
-
diff --git a/src/lib/services/workflow-history-controller.svelte.ts b/src/lib/services/workflow-history-controller.svelte.ts index 1794e2097b..bd5d840771 100644 --- a/src/lib/services/workflow-history-controller.svelte.ts +++ b/src/lib/services/workflow-history-controller.svelte.ts @@ -23,7 +23,7 @@ type HistoryLoadSession = { livePollController: AbortController | null; livePollTask: Promise | null; lastPollToken: string; - workflowIsRunning: boolean; + workflowWasRunning: boolean; historyClosed: boolean; }; @@ -109,7 +109,7 @@ export class WorkflowHistoryController { livePollController: null, livePollTask: null, lastPollToken: '', - workflowIsRunning: workflow.isRunning, + workflowWasRunning: workflow.isRunning, historyClosed: false, }; this.session = session; @@ -161,11 +161,7 @@ export class WorkflowHistoryController { ); const session = this.session; if (!session) return; - session.workflowIsRunning = workflow.isRunning; - if (!workflow.isRunning) { - session.livePollController?.abort(); - return; - } + session.workflowWasRunning ||= workflow.isRunning; this.startLivePoll(session); } @@ -218,7 +214,7 @@ export class WorkflowHistoryController { return ( this.isCurrent(session) && !this.liveUpdatesPaused && - session.workflowIsRunning && + session.workflowWasRunning && !session.historyClosed ); } diff --git a/src/lib/types/workflows.ts b/src/lib/types/workflows.ts index 66df5d0c64..3653656d51 100644 --- a/src/lib/types/workflows.ts +++ b/src/lib/types/workflows.ts @@ -193,7 +193,6 @@ export type WorkflowExecution = { name: string; id: string; runId: string; - firstRunId?: string; startTime: string; endTime: string; executionTime: string; diff --git a/src/lib/utilities/route-for-base-path.test.ts b/src/lib/utilities/route-for-base-path.test.ts index 2f40107fa6..4d8a2fc447 100644 --- a/src/lib/utilities/route-for-base-path.test.ts +++ b/src/lib/utilities/route-for-base-path.test.ts @@ -60,8 +60,6 @@ import { routeForWorkers, routeForWorkersWithQuery, routeForWorkflow, - routeForWorkflowChain, - routeForWorkflowChainRedirect, routeForWorkflowMemo, routeForWorkflowQuery, routeForWorkflows, @@ -93,19 +91,6 @@ describe('routeFor functions should resolve the base path exactly once', () => { }; const cases: [string, () => string | undefined][] = [ - [ - 'routeForWorkflowChainRedirect', - () => routeForWorkflowChainRedirect(workflowParams), - ], - [ - 'routeForWorkflowChain', - () => - routeForWorkflowChain({ - namespace: 'default', - workflow: 'wf-id', - firstRunId: 'run-id', - }), - ], ['routeForNamespaces', () => routeForNamespaces()], ['routeForNexus', () => routeForNexus()], [ diff --git a/src/lib/utilities/route-for.ts b/src/lib/utilities/route-for.ts index 18d45d1936..30ad17b446 100644 --- a/src/lib/utilities/route-for.ts +++ b/src/lib/utilities/route-for.ts @@ -320,20 +320,6 @@ export const routeForArchivalWorkflows = ( return `${routeForNamespace(parameters)}/archival`; }; -export const routeForWorkflowChain = ({ - workflow, - firstRunId, - ...parameters -}: NamespaceParameter & { - workflow: string; - firstRunId: string; -}): ResolvedPathname => { - const id = encodeURIForSvelte(workflow); - const runId = encodeURIForSvelte(firstRunId); - - return `${routeForWorkflows(parameters)}/${id}/chain/${runId}`; -}; - export const baseRouteForWorkflow = ({ workflow, run, @@ -344,10 +330,6 @@ export const baseRouteForWorkflow = ({ return `${routeForWorkflows(parameters)}/${id}/${run}`; }; -export const routeForWorkflowChainRedirect = ( - parameters: WorkflowParameters, -): ResolvedPathname => `${baseRouteForWorkflow(parameters)}/chain`; - export const routeForSchedules = ( parameters: NamespaceParameter, ): ResolvedPathname => { diff --git a/src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/[run]/chain/+page.ts b/src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/[run]/chain/+page.ts deleted file mode 100644 index 44b5ac5952..0000000000 --- a/src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/[run]/chain/+page.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { error, redirect } from '@sveltejs/kit'; - -import type { PageLoad } from './$types'; - -import { translate } from '$lib/i18n/translate'; -import { fetchWorkflow } from '$lib/services/workflow-service'; -import { routeForWorkflowChain } from '$lib/utilities/route-for'; - -export const load: PageLoad = async ({ params, fetch, parent }) => { - await parent(); - - const { namespace, workflow: workflowId, run: runId } = params; - const { workflow, error: workflowError } = await fetchWorkflow( - { namespace, workflowId, runId }, - fetch, - ); - - if (workflowError) { - error( - workflowError.statusCode, - workflowError.message || workflowError.statusText, - ); - } - - if (!workflow?.firstRunId) { - error(502, translate('workflows.execution-chain-first-run-unavailable')); - } - - redirect( - 302, - routeForWorkflowChain({ - namespace, - workflow: workflowId, - firstRunId: workflow.firstRunId, - }), - ); -}; diff --git a/src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/chain/[firstRunId]/+page.svelte b/src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/chain/[firstRunId]/+page.svelte deleted file mode 100644 index fee98209bb..0000000000 --- a/src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/chain/[firstRunId]/+page.svelte +++ /dev/null @@ -1,5 +0,0 @@ - - - From de5b410d5a73c4e5943a4407ba7c30bd5cade39e Mon Sep 17 00:00:00 2001 From: Tegan Churchill Date: Thu, 5 Nov 2026 11:35:22 -0800 Subject: [PATCH 08/19] Add workflow run detail integration tests --- .../workflow-run-detail-refresh.spec.ts | 201 +++++++++++ .../workflow-run-detail-smoke.spec.ts | 338 ++++++++++++++++++ 2 files changed, 539 insertions(+) create mode 100644 tests/integration/workflow-run-detail-refresh.spec.ts create mode 100644 tests/integration/workflow-run-detail-smoke.spec.ts diff --git a/tests/integration/workflow-run-detail-refresh.spec.ts b/tests/integration/workflow-run-detail-refresh.spec.ts new file mode 100644 index 0000000000..9277a1f19f --- /dev/null +++ b/tests/integration/workflow-run-detail-refresh.spec.ts @@ -0,0 +1,201 @@ +import { expect, type Page, test } from '@playwright/test'; + +import { + makeActivityCompleted, + makeActivityScheduled, + makeActivityStarted, + makeWorkflowCompleted, + makeWorkflowStarted, +} from '$src/lib/services/test-helpers/synthetic-events'; +import type { HistoryEvent } from '$src/lib/types/events'; +import { mockWorkflowApis } from '~/test-utilities/mock-apis'; +import { + EVENT_HISTORY_API, + EVENT_HISTORY_API_REVERSE, +} from '~/test-utilities/mocks/event-history'; +import { mockWorkflow, WORKFLOW_API } from '~/test-utilities/mocks/workflow'; + +const { workflowId, runId } = mockWorkflow.workflowExecutionInfo.execution; +const historyUrl = `/namespaces/default/workflows/${workflowId}/${runId}/history`; +const initialEvents: HistoryEvent[] = [ + makeWorkflowStarted(1), + makeActivityScheduled(2, 'RefreshActivity'), + makeActivityStarted(3, 2), +]; +const activityCompletion = makeActivityCompleted(4, 2, 3); +const workflowCompletion = makeWorkflowCompleted(5); + +const historyPage = (events: HistoryEvent[]) => ({ + history: { events }, + rawHistory: [], + nextPageToken: null, + archived: false, +}); + +function gate() { + let release = () => {}; + const promise = new Promise((resolve) => { + release = resolve; + }); + return { promise, release }; +} + +async function mockRunDetail(page: Page, liveEvents: HistoryEvent[]) { + const runningWorkflow = { + ...mockWorkflow, + workflowExecutionInfo: { + ...mockWorkflow.workflowExecutionInfo, + status: 'Running', + closeTime: '', + historyLength: String(initialEvents.length), + }, + pendingActivities: [], + pendingChildren: [], + }; + const requests = { describe: 0, initial: 0, reverse: 0, live: 0 }; + const state = { completed: false }; + const liveRequested = gate(); + const liveResponse = gate(); + + await mockWorkflowApis(page, runningWorkflow); + await page.route(WORKFLOW_API, (route) => { + requests.describe += 1; + return route.fulfill({ + json: state.completed + ? { + ...runningWorkflow, + workflowExecutionInfo: { + ...runningWorkflow.workflowExecutionInfo, + status: 'Completed', + closeTime: '2024-01-01T00:00:01Z', + historyLength: '5', + }, + } + : runningWorkflow, + }); + }); + await page.route(EVENT_HISTORY_API, async (route) => { + if ( + new URL(route.request().url()).searchParams.get('waitNewEvent') === 'true' + ) { + requests.live += 1; + if (requests.live === 1) { + liveRequested.release(); + await liveResponse.promise; + return route.fulfill({ json: historyPage(liveEvents) }); + } + return route.fulfill({ json: historyPage([]) }); + } + requests.initial += 1; + return route.fulfill({ json: historyPage(initialEvents) }); + }); + await page.route(EVENT_HISTORY_API_REVERSE, (route) => { + requests.reverse += 1; + return route.fulfill({ json: historyPage([...initialEvents].reverse()) }); + }); + + return { requests, state, liveRequested, liveResponse }; +} + +async function openHistory(page: Page, refreshOff: boolean) { + await page.clock.install(); + await page.clock.pauseAt((await page.evaluate(() => Date.now())) + 1000); + await page.goto(`${historyUrl}?refresh_off=${refreshOff}&sort=ascending`); + await expect(page.getByTestId('event-summary-table')).toBeVisible(); + await page.getByTestId('feed').click(); + await expect(page.getByTestId('event-summary-row')).toHaveCount(3); + await expect(page.locator('[data-eventid="2"]')).toContainText( + 'RefreshActivity', + ); + await expect(page.getByTestId('execution-status')).toHaveText('Running'); +} + +test.describe('Workflow run detail refresh', () => { + test('loads initial history with refresh off without live history or ambient Describe polls', async ({ + page, + }) => { + const { requests, liveResponse } = await mockRunDetail(page, []); + try { + await openHistory(page, true); + await expect(page.getByTestId('pause')).toHaveText('Auto Refresh Off'); + expect(requests.initial).toBeGreaterThan(0); + expect(requests.reverse).toBeGreaterThan(0); + expect(requests.describe).toBe(1); + expect(requests.live).toBe(0); + + const before = { ...requests }; + await page.clock.runFor(30_000); + + expect(requests).toEqual(before); + await expect(page.getByTestId('event-summary-row')).toHaveCount(3); + } finally { + liveResponse.release(); + } + }); + + test('receives a live completion after enabling refresh and stops requests when disabled again', async ({ + page, + }) => { + const { requests, liveRequested, liveResponse } = await mockRunDetail( + page, + [activityCompletion], + ); + try { + await openHistory(page, true); + await page.getByTestId('pause').click(); + await expect(page.getByTestId('pause')).toHaveText('Auto Refresh On'); + await expect(page).not.toHaveURL(/refresh_off=true/); + await liveRequested.promise; + await expect(page.locator('[data-eventid="4"]')).toHaveCount(0); + + liveResponse.release(); + await expect(page.locator('[data-eventid="4"]')).toBeVisible(); + await expect(page.getByTestId('event-summary-row')).toHaveCount(4); + await page.clock.runFor(10_000); + await expect.poll(() => requests.describe).toBeGreaterThan(1); + + await page.getByTestId('pause').click(); + await expect(page.getByTestId('pause')).toHaveText('Auto Refresh Off'); + await expect(page).toHaveURL(/refresh_off=true/); + const before = { ...requests }; + await page.clock.runFor(30_000); + + expect(requests).toEqual(before); + await expect(page.locator('[data-eventid="4"]')).toBeVisible(); + } finally { + liveResponse.release(); + } + }); + + test('keeps the final history tail when Describe completes before the held terminal history response', async ({ + page, + }) => { + const { requests, state, liveRequested, liveResponse } = + await mockRunDetail(page, [activityCompletion, workflowCompletion]); + try { + await openHistory(page, false); + await liveRequested.promise; + await expect(page.locator('[data-eventid="5"]')).toHaveCount(0); + state.completed = true; + + await page.clock.runFor(10_000); + await expect(page.getByTestId('execution-status')).toHaveText( + 'Completed', + ); + await expect(page.locator('[data-eventid="4"]')).toHaveCount(0); + await expect(page.locator('[data-eventid="5"]')).toHaveCount(0); + + liveResponse.release(); + await expect(page.locator('[data-eventid="4"]')).toBeVisible(); + await expect(page.locator('[data-eventid="5"]')).toBeVisible(); + await expect(page.getByTestId('event-summary-row')).toHaveCount(5); + + const before = { ...requests }; + await page.clock.runFor(30_000); + expect(requests).toEqual(before); + await expect(page.locator('[data-eventid="5"]')).toBeVisible(); + } finally { + liveResponse.release(); + } + }); +}); diff --git a/tests/integration/workflow-run-detail-smoke.spec.ts b/tests/integration/workflow-run-detail-smoke.spec.ts new file mode 100644 index 0000000000..db90f12d94 --- /dev/null +++ b/tests/integration/workflow-run-detail-smoke.spec.ts @@ -0,0 +1,338 @@ +import { test as base, expect } from '@playwright/test'; + +import { + makeActivityCompleted, + makeActivityScheduled, + makeActivityStarted, + makeWorkflowCompleted, + makeWorkflowStarted, +} from '$src/lib/services/test-helpers/synthetic-events'; +import type { HistoryEvent } from '$src/lib/types/events'; +import type { WorkflowExecutionAPIResponse } from '$src/lib/types/workflows'; +import { + mockEventHistoryApi, + mockWorkflowApis, + WORKFLOW_API, +} from '~/test-utilities/mock-apis'; +import { + EVENT_HISTORY_API, + EVENT_HISTORY_API_REVERSE, +} from '~/test-utilities/mocks/event-history'; +import { mockWorkflow } from '~/test-utilities/mocks/workflow'; + +const { workflowId, runId } = mockWorkflow.workflowExecutionInfo.execution; +const secondRunId = '61797bf4-0d48-43d6-94aa-1921f7893200'; +const runUrl = `/namespaces/default/workflows/${workflowId}/${runId}`; +const secondRunUrl = `/namespaces/default/workflows/${workflowId}/${secondRunId}`; + +const atSecond = (event: HistoryEvent, second: number): HistoryEvent => ({ + ...event, + eventTime: `2024-01-01T00:00:${String(second).padStart(2, '0')}.000000000Z`, +}); + +const historyFor = (activityName: string): HistoryEvent[] => [ + makeWorkflowStarted(1), + atSecond(makeActivityScheduled(2, activityName), 10), + atSecond(makeActivityStarted(3, 2), 15), + atSecond(makeActivityCompleted(4, 2, 3), 30), + atSecond(makeWorkflowCompleted(5), 40), +]; + +const events = historyFor('SmokeFirstRunActivity'); +const workflowFor = (id: string): WorkflowExecutionAPIResponse => ({ + ...mockWorkflow, + workflowExecutionInfo: { + ...mockWorkflow.workflowExecutionInfo, + execution: { workflowId, runId: id }, + status: 'Completed', + startTime: events[0].eventTime, + executionTime: events[0].eventTime, + closeTime: events[4].eventTime, + historyLength: String(events.length), + }, + pendingActivities: [], + pendingChildren: [], +}); + +const test = base.extend<{ pageErrors: Error[] }>({ + pageErrors: [ + async ({ page }, use) => { + const errors: Error[] = []; + page.on('pageerror', (error) => errors.push(error)); + await use(errors); + expect(errors.map((error) => error.message)).toEqual([]); + }, + { auto: true }, + ], +}); + +test.describe('Workflow run detail smoke', () => { + test.beforeEach(async ({ page }) => { + await page.addInitScript(() => { + localStorage.setItem('autoRefreshWorkflow', JSON.stringify('off')); + localStorage.setItem('eventView', JSON.stringify('feed')); + localStorage.setItem('eventFilterSort', JSON.stringify('descending')); + }); + await mockWorkflowApis(page, workflowFor(runId)); + await mockEventHistoryApi(page, { + history: { events }, + nextPageToken: null, + }); + }); + + test('navigates timeline, feed, compact, JSON, and event detail back to history', async ({ + page, + }) => { + await page.goto(`${runUrl}/timeline`); + await page + .getByRole('img', { name: `Workflow ${workflowId}: Completed` }) + .scrollIntoViewIfNeeded(); + await expect( + page.getByRole('img', { name: `Workflow ${workflowId}: Completed` }), + ).toBeVisible(); + await expect( + page.getByRole('button', { + name: 'Event SmokeFirstRunActivity: Completed', + }), + ).toBeVisible(); + + await page.getByTestId('history-tab').click(); + await expect(page.getByTestId('event-summary-row')).toHaveCount(5); + await page.getByTestId('compact').click(); + await expect(page.getByTestId('event-summary-row')).toHaveCount(1); + await expect( + page.getByTestId('event-summary-row').getByTestId('link'), + ).toHaveText(['2', '3', '4']); + await expect(page.getByTestId('event-summary-table')).toContainText( + 'SmokeFirstRunActivity', + ); + await page.getByTestId('json').click(); + await expect(page.getByTestId('event-history-json')).toContainText( + 'WorkflowExecutionStarted', + ); + await page.getByRole('button', { name: 'Next', exact: true }).click(); + await expect(page.getByTestId('event-history-json')).toContainText( + 'SmokeFirstRunActivity', + ); + await expect(page.getByTestId('event-summary-table')).toBeHidden(); + await page.getByTestId('feed').click(); + await expect(page.getByTestId('event-summary-row')).toHaveCount(5); + + await page + .getByTestId('event-summary-row') + .filter({ has: page.getByRole('link', { name: '2', exact: true }) }) + .getByRole('link', { name: '2', exact: true }) + .click(); + await expect(page).toHaveURL(`${runUrl}/history/events/2`); + await expect(page.getByTestId('event-summary-log')).toContainText( + 'SmokeFirstRunActivity', + ); + await expect(page.getByTestId('event-summary-row-expanded')).toBeVisible(); + await page.goBack(); + await expect(page).toHaveURL(`${runUrl}/history`); + await expect(page.getByTestId('event-summary-row')).toHaveCount(5); + }); + + test('preserves category and sort filters across timeline and history views', async ({ + page, + }) => { + await page.goto(`${runUrl}/history?sort=ascending`); + await expect(page.getByTestId('event-summary-row')).toHaveCount(5); + await page.locator('button[aria-controls="status-menu"]').click(); + await page.locator('#event-type-menu').getByTestId('Activity').click(); + await page.keyboard.press('Escape'); + await expect(page.getByTestId('event-summary-row')).toHaveCount(2); + await expect(page.getByTestId('event-summary-table')).not.toContainText( + 'SmokeFirstRunActivity', + ); + const filteredQuery = new URL(page.url()).search; + expect(new URL(page.url()).searchParams.get('sort')).toBe('ascending'); + expect(new URL(page.url()).searchParams.has('category')).toBe(true); + + await page.getByTestId('timeline-tab').click(); + await expect(page).toHaveURL(`${runUrl}/timeline${filteredQuery}`); + await page + .getByRole('img', { name: `Workflow ${workflowId}: Completed` }) + .scrollIntoViewIfNeeded(); + await expect( + page.getByRole('img', { name: `Workflow ${workflowId}: Completed` }), + ).toBeVisible(); + await expect( + page.getByRole('button', { name: /Event SmokeFirstRunActivity:/ }), + ).toBeHidden(); + await page.getByTestId('history-tab').click(); + await expect(page).toHaveURL(`${runUrl}/history${filteredQuery}`); + await expect(page.getByTestId('event-summary-row')).toHaveCount(2); + await expect(page.getByTestId('event-summary-row').first()).toContainText( + 'Workflow Execution Started', + ); + await page.getByTestId('compact').click(); + await expect(page.getByTestId('event-summary-row')).toHaveCount(0); + await expect(page.getByTestId('event-summary-table')).toContainText( + 'No Events Match', + ); + await page.getByTestId('json').click(); + await expect(page.getByTestId('event-history-json')).toContainText( + 'WorkflowExecutionStarted', + ); + await expect(page.getByRole('slider')).toHaveAttribute('max', '2'); + await page.getByTestId('feed').click(); + await expect(page.getByTestId('event-summary-row')).toHaveCount(2); + }); + + test('waits for the workflow start before showing an elapsed-time baseline', async ({ + page, + }) => { + let releaseAscending = () => {}; + const ascendingHeld = new Promise((resolve) => { + releaseAscending = resolve; + }); + await page.route(EVENT_HISTORY_API, async (route) => { + await ascendingHeld; + await route.fulfill({ + json: { history: { events }, nextPageToken: null }, + }); + }); + let reversePages = 0; + await page.route(EVENT_HISTORY_API_REVERSE, async (route) => { + reversePages += 1; + if (reversePages === 1) { + await route.fulfill({ + json: { + history: { events: events.slice(1).reverse() }, + nextPageToken: 'workflow-start', + }, + }); + return; + } + await ascendingHeld; + await route.fulfill({ + json: { history: { events: [events[0]] }, nextPageToken: null }, + }); + }); + + try { + await page.goto(`${runUrl}/history`); + const scheduled = page + .getByTestId('event-summary-row') + .filter({ has: page.getByRole('link', { name: '2', exact: true }) }); + await expect(scheduled).toBeVisible(); + await expect(page.getByTestId('event-summary-row')).toHaveCount(4); + await scheduled + .getByRole('cell') + .filter({ visible: true }) + .nth(1) + .hover(); + await expect( + scheduled.getByRole('tooltip', { name: /^\+/ }), + ).toBeHidden(); + + releaseAscending(); + await expect(page.getByTestId('event-summary-row')).toHaveCount(5); + await scheduled + .getByRole('cell') + .filter({ visible: true }) + .nth(1) + .hover(); + await expect( + scheduled.getByRole('tooltip', { name: '+10s', exact: true }), + ).toBeVisible(); + } finally { + releaseAscending(); + } + }); + + test('switches runs through an execution link and browser Back without leaking history', async ({ + page, + }) => { + const firstStarted = makeWorkflowStarted(1); + const linkedEvents = [ + { + ...firstStarted, + workflowExecutionStartedEventAttributes: { + ...firstStarted.workflowExecutionStartedEventAttributes, + continuedExecutionRunId: secondRunId, + }, + }, + ...events.slice(1), + ]; + const secondEvents = historyFor('SmokeSecondRunActivity'); + await page.route(WORKFLOW_API, (route) => { + const requestedRun = new URL(route.request().url()).searchParams.get( + 'execution.runId', + ); + return route.fulfill({ + json: workflowFor(requestedRun === secondRunId ? secondRunId : runId), + }); + }); + for (const api of [EVENT_HISTORY_API, EVENT_HISTORY_API_REVERSE]) { + await page.route(api, (route) => { + const url = new URL(route.request().url()); + const runEvents = + url.searchParams.get('execution.runId') === secondRunId + ? secondEvents + : linkedEvents; + return route.fulfill({ + json: { + history: { + events: url.pathname.endsWith('history-reverse') + ? [...runEvents].reverse() + : runEvents, + }, + nextPageToken: null, + }, + }); + }); + } + + await page.goto(`${runUrl}/history/events/1`); + await expect(page.getByTestId('event-summary-log')).toBeVisible(); + const documentRequests: string[] = []; + page.on('request', (request) => { + if ( + request.isNavigationRequest() && + request.frame() === page.mainFrame() + ) { + documentRequests.push(request.url()); + } + }); + const documentTimeOrigin = await page.evaluate( + () => performance.timeOrigin, + ); + await page.getByRole('link', { name: secondRunId, exact: true }).click(); + await expect(page).toHaveURL(`${secondRunUrl}/timeline`); + await page.getByTestId('history-tab').click(); + await expect(page.getByTestId('event-summary-row')).toHaveCount(5); + await expect(page.getByTestId('event-summary-table')).toContainText( + 'SmokeSecondRunActivity', + ); + await expect(page.getByTestId('event-summary-table')).not.toContainText( + 'SmokeFirstRunActivity', + ); + await page.getByTestId('compact').click(); + await expect(page.getByTestId('event-summary-row')).toHaveCount(1); + await expect( + page.getByTestId('event-summary-row').getByTestId('link'), + ).toHaveText(['2', '3', '4']); + await expect(page.getByTestId('event-summary-table')).toContainText( + 'SmokeSecondRunActivity', + ); + await page.goBack(); + await expect(page).toHaveURL(`${secondRunUrl}/timeline`); + await page.goBack(); + await expect(page).toHaveURL(`${runUrl}/history/events/1`); + await page.getByTestId('history-tab').click(); + await page.getByTestId('feed').click(); + await expect(page.getByTestId('event-summary-row')).toHaveCount(5); + await expect(page.getByTestId('event-summary-table')).toContainText( + 'SmokeFirstRunActivity', + ); + await expect(page.getByTestId('event-summary-table')).not.toContainText( + 'SmokeSecondRunActivity', + ); + expect(await page.evaluate(() => performance.timeOrigin)).toBe( + documentTimeOrigin, + ); + expect(documentRequests).toEqual([]); + }); +}); From 2be10f3357f0b8f3b1f7ea55d90b276b2712544d Mon Sep 17 00:00:00 2001 From: Tegan Churchill Date: Thu, 5 Nov 2026 14:03:20 -0800 Subject: [PATCH 09/19] Isolate workflow history by run --- .../timeline-graph/timeline-graph.svelte | 8 +- .../task-queue-workers-table.svelte | 12 +- .../workflow/workflow-common-errors.svelte | 11 +- .../workflow/workflow-relationships.svelte | 11 +- src/lib/contexts/history-context.ts | 17 - src/lib/i18n/locales/en/workflows.ts | 4 + .../layouts/workflow-history-layout.svelte | 48 +- .../layouts/workflow-history-provider.svelte | 18 + src/lib/layouts/workflow-history-scope.svelte | 19 + src/lib/layouts/workflow-run-layout.svelte | 81 +- .../layouts/workflow-timeline-layout.svelte | 56 +- src/lib/pages/workflow-history-event.svelte | 19 +- src/lib/pages/workflow-nexus-links.svelte | 11 +- .../pages/workflow-pending-activities.svelte | 11 +- src/lib/services/fetch-bidirectional.test.ts | 456 +++++++- src/lib/services/fetch-bidirectional.ts | 130 ++- src/lib/services/grouped-event-buffer.test.ts | 1023 ++++++++--------- src/lib/services/grouped-event-buffer.ts | 17 - ...workflow-history-controller.svelte.test.ts | 406 +++++++ .../workflow-history-controller.svelte.ts | 49 +- .../[workflow]/[run]/workers/+page.svelte | 3 + ...workflow-run-detail-history-errors.spec.ts | 202 ++++ .../workflow-run-detail-resume.spec.ts | 184 +++ .../workflow-run-detail-selection.spec.ts | 198 ++++ 24 files changed, 2232 insertions(+), 762 deletions(-) delete mode 100644 src/lib/contexts/history-context.ts create mode 100644 src/lib/layouts/workflow-history-provider.svelte create mode 100644 src/lib/layouts/workflow-history-scope.svelte create mode 100644 src/lib/services/workflow-history-controller.svelte.test.ts create mode 100644 tests/integration/workflow-run-detail-history-errors.spec.ts create mode 100644 tests/integration/workflow-run-detail-resume.spec.ts create mode 100644 tests/integration/workflow-run-detail-selection.spec.ts diff --git a/src/lib/components/lines-and-dots/timeline-graph/timeline-graph.svelte b/src/lib/components/lines-and-dots/timeline-graph/timeline-graph.svelte index 7ccba9629b..7036f2db17 100644 --- a/src/lib/components/lines-and-dots/timeline-graph/timeline-graph.svelte +++ b/src/lib/components/lines-and-dots/timeline-graph/timeline-graph.svelte @@ -62,6 +62,7 @@ totalExpectedEvents?: number; descMinId?: number; panelHeight?: number; + activeGroupId?: string; onTimelineInit?: (timeline: Timeline) => void; } @@ -80,6 +81,7 @@ totalExpectedEvents = 0, descMinId = 0, panelHeight = $bindable(0), + activeGroupId = $bindable(), onTimelineInit, }: Props = $props(); @@ -89,8 +91,6 @@ runId: workflow.runId, }); - let activeGroupId = $state(); - const selectGroup = (group: { id: string }) => { panelHeight = 0; activeGroupId = activeGroupId === group.id ? undefined : group.id; @@ -319,8 +319,8 @@ : undefined, ); - $effect(() => { - if (activeIdx < 0) panelHeight = 0; + $effect.pre(() => { + if (activeIdx < 0) closeGroup(); }); // Open detail panel pushes rows below the active one down by panelHeight. diff --git a/src/lib/components/workers/workers-table/task-queue-workers-table.svelte b/src/lib/components/workers/workers-table/task-queue-workers-table.svelte index 53c45f90bb..fe929eb308 100644 --- a/src/lib/components/workers/workers-table/task-queue-workers-table.svelte +++ b/src/lib/components/workers/workers-table/task-queue-workers-table.svelte @@ -1,11 +1,5 @@ - +
{#if workflowTaskFailedError} {/if}
@@ -289,7 +285,9 @@ {/if} - +

- {:else if historyView} + {:else}
+ import type { Snippet } from 'svelte'; + + import type { WorkflowHistoryController } from '$lib/services/workflow-history-controller.svelte.js'; + + import WorkflowHistoryScope from './workflow-history-scope.svelte'; + + interface Props { + controller: WorkflowHistoryController; + children: Snippet; + } + + const { controller, children }: Props = $props(); + + +{#key controller} + +{/key} diff --git a/src/lib/layouts/workflow-history-scope.svelte b/src/lib/layouts/workflow-history-scope.svelte new file mode 100644 index 0000000000..f6d1f4e64f --- /dev/null +++ b/src/lib/layouts/workflow-history-scope.svelte @@ -0,0 +1,19 @@ + + +{@render children()} diff --git a/src/lib/layouts/workflow-run-layout.svelte b/src/lib/layouts/workflow-run-layout.svelte index c0451da841..54e4bc325a 100644 --- a/src/lib/layouts/workflow-run-layout.svelte +++ b/src/lib/layouts/workflow-run-layout.svelte @@ -1,23 +1,23 @@ - +
{#if workflowTaskFailedError} {/if}
@@ -188,8 +183,8 @@ - + - {#if workflow && historyView} + {#if workflow} {#key JSON.stringify([namespace, workflow.id, workflow.runId])} diff --git a/src/lib/pages/workflow-history-event.svelte b/src/lib/pages/workflow-history-event.svelte index f13d08c209..29a4793842 100644 --- a/src/lib/pages/workflow-history-event.svelte +++ b/src/lib/pages/workflow-history-event.svelte @@ -1,16 +1,13 @@ - -
-
- - All - Compact - JSON - -
-
-{#if $eventViewType === 'json'} -
- -
-{:else} -
- - {#snippet activityActions(activity)} - {#if workflow} - - {/if} - {/snippet} - -
-{/if} diff --git a/src/lib/components/lines-and-dots/event-group-filter/event-group-filter-menu.svelte b/src/lib/components/lines-and-dots/event-group-filter/event-group-filter-menu.svelte index 7bc5eff450..be7f46256e 100644 --- a/src/lib/components/lines-and-dots/event-group-filter/event-group-filter-menu.svelte +++ b/src/lib/components/lines-and-dots/event-group-filter/event-group-filter-menu.svelte @@ -20,7 +20,6 @@ formatEventGroupName, } from '$lib/models/event-history/event-group-markers'; import type { EventGroupOption } from '$lib/services/grouped-event-buffer'; - import { clearActiveGroups } from '$lib/stores/active-events'; import { parseEventFilterParams, updateEventFilterParams, @@ -101,7 +100,6 @@ }); const setSelection = (keys: EventGroupKey[]) => { - clearActiveGroups(); updateEventFilterParams( page.url, { eventGroups: keys.length ? keys : null }, diff --git a/src/lib/components/lines-and-dots/event-type-filter.svelte b/src/lib/components/lines-and-dots/event-type-filter.svelte index 492f23c7b9..1f5e15d84a 100644 --- a/src/lib/components/lines-and-dots/event-type-filter.svelte +++ b/src/lib/components/lines-and-dots/event-type-filter.svelte @@ -16,7 +16,6 @@ allEventTypeOptions, compactEventTypeOptions, } from '$lib/models/event-history/get-event-categorization'; - import { clearActiveGroups } from '$lib/stores/active-events'; import { eventViewType } from '$lib/stores/event-view'; import { eventStatusFilter, eventTypeFilter } from '$lib/stores/filters'; import { temporalVersion } from '$lib/stores/versions'; @@ -59,7 +58,6 @@ }); const onOptionClick = ({ value }: (typeof options)[number]) => { - clearActiveGroups(); const newCategories = $eventTypeFilter.some((type) => type === value) ? $eventTypeFilter.filter((type) => type !== value) : [...$eventTypeFilter, value]; diff --git a/src/lib/layouts/workflow-history-layout.svelte b/src/lib/layouts/workflow-history-layout.svelte index 98ecf32b3d..5141ac8c28 100644 --- a/src/lib/layouts/workflow-history-layout.svelte +++ b/src/lib/layouts/workflow-history-layout.svelte @@ -1,7 +1,7 @@ - - diff --git a/src/lib/layouts/workflow-history-layout.svelte b/src/lib/layouts/workflow-history-layout.svelte index 5141ac8c28..3b154488dd 100644 --- a/src/lib/layouts/workflow-history-layout.svelte +++ b/src/lib/layouts/workflow-history-layout.svelte @@ -42,7 +42,6 @@ WorkflowTaskFailedEvent, WorkflowTaskTimedOutEvent, } from '$lib/types/events'; - import type { WorkflowExecutionIdentity } from '$lib/types/workflows'; import { parseEventFilterParams, updateEventFilterParams, @@ -51,13 +50,7 @@ const historyController = getWorkflowHistoryController(); - const { namespace } = $derived(page.params); const { workflow } = $derived($workflowRun); - const workflowExecutionIdentity: WorkflowExecutionIdentity = $derived({ - namespace, - workflowId: workflow?.id ?? page.params.workflow, - runId: workflow?.runId ?? page.params.run, - }); $effect(() => { const urlParams = parseEventFilterParams(page.url); @@ -316,7 +309,7 @@
@@ -324,7 +317,7 @@ {#if workflow} diff --git a/src/lib/layouts/workflow-run-layout.svelte b/src/lib/layouts/workflow-run-layout.svelte index b83afd0f18..6102e01695 100644 --- a/src/lib/layouts/workflow-run-layout.svelte +++ b/src/lib/layouts/workflow-run-layout.svelte @@ -30,10 +30,7 @@ workflowRun, } from '$lib/stores/workflow-run'; import type { NetworkError } from '$lib/types/global'; - import type { - WorkflowExecution, - WorkflowExecutionIdentity, - } from '$lib/types/workflows'; + import type { WorkflowExecution } from '$lib/types/workflows'; import { copyToClipboard } from '$lib/utilities/copy-to-clipboard'; import { decodePayloadAndParseDataToJSON } from '$lib/utilities/decode-payload'; import { stringifyWithBigInt } from '$lib/utilities/parse-with-big-int'; @@ -60,7 +57,6 @@ let workflowError: NetworkError | null = $state(null); let workflowRunController: AbortController | null = null; let historyController = $state(null); - let workflowExecutionIdentity: WorkflowExecutionIdentity | null = null; let _refetchSeq = 0; @@ -151,19 +147,16 @@ const workers = await getPollers({ queue: taskQueue!, namespace: ns }); if (!isCurrent()) return; - const identity = { - namespace: ns, - workflowId: workflow.id, - runId: workflow.runId, - }; const history = new WorkflowHistoryController({ - workflowExecutionIdentity: identity, - - maximumPageSize: 1000, + workflowExecutionIdentity: { + namespace: ns, + workflowId: workflow.id, + runId: workflow.runId, + }, pauseAfterPages: 2, liveUpdatesPaused: $pauseLiveUpdates, }); - workflowExecutionIdentity = identity; + historyController = history; void history.load(workflow); @@ -204,7 +197,7 @@ isRunning: $workflowRun?.workflow?.isRunning, }); const controller = workflowRunController; - const identity = workflowExecutionIdentity; + const identity = historyController?.workflowExecutionIdentity; if (!shouldFetch || !controller || !identity || !historyController) return; // The 10s poll and an action's refetch overlap, so a poll that started @@ -234,7 +227,6 @@ workflowRunController = null; historyController?.dispose(); historyController = null; - workflowExecutionIdentity = null; }; // Pending metadata comes from the workflow run, not the history. The buffer @@ -245,8 +237,8 @@ if ( workflow && controller && - workflow.id === workflowExecutionIdentity?.workflowId && - workflow.runId === workflowExecutionIdentity?.runId + workflow.id === controller.workflowExecutionIdentity.workflowId && + workflow.runId === controller.workflowExecutionIdentity.runId ) { untrack(() => controller.updateWorkflow(workflow)); } @@ -302,7 +294,6 @@ return () => { clearInterval(refreshInterval); - clearWorkflowData(); }; }); diff --git a/src/lib/pages/workflow-history-event.svelte b/src/lib/pages/workflow-history-event.svelte index e3b810ec73..d84e2367df 100644 --- a/src/lib/pages/workflow-history-event.svelte +++ b/src/lib/pages/workflow-history-event.svelte @@ -8,7 +8,6 @@ import { getWorkflowHistoryController } from '$lib/services/workflow-history-controller.svelte.js'; import { triggerRefresh, workflowRun } from '$lib/stores/workflow-run'; import type { PendingActivity } from '$lib/types/events'; - import type { WorkflowExecutionIdentity } from '$lib/types/workflows'; interface Props { eventId: string; @@ -17,7 +16,7 @@ runId: string; } - const { eventId, namespace, workflowId, runId }: Props = $props(); + const { eventId }: Props = $props(); const historyController = getWorkflowHistoryController(); let ids = $derived([eventId]); @@ -25,11 +24,6 @@ onMount(() => historyController.resume()); const { workflow } = $derived($workflowRun); - const workflowExecutionIdentity: WorkflowExecutionIdentity = $derived({ - namespace, - workflowId: workflow?.id ?? workflowId, - runId: workflow?.runId ?? runId, - }); const initialEvent = $derived( historyController.history.event(eventId) ?? historyController.history.event( @@ -81,7 +75,7 @@ {#if workflow} {#each visibleItems as event, index} - import { page } from '$app/state'; - import ActivityCommands from '$lib/components/activity/activity-commands.svelte'; import PendingActivityCard from '$lib/components/workflow/pending-activity/pending-activity-card.svelte'; import EmptyState from '$lib/holocene/empty-state.svelte'; @@ -36,11 +34,7 @@ {#if workflow} ; beforeEach(async () => { const mod = await import('$lib/utilities/request-from-api'); - requestFromAPI = mod.requestFromAPI as ReturnType; + requestFromAPI = vi.mocked(mod.requestFromAPI); }); afterEach(() => { @@ -68,72 +69,26 @@ const emptyPage = { history: { events: [] }, nextPageToken: '' }; // --------------------------------------------------------------------------- describe('fetchBidirectional onRawPage', () => { - it('delivers all ascending events via onRawPage with isAscending=true', async () => { - const received: { id: string; asc: boolean }[] = []; - requestFromAPI.mockImplementation((url: string) => { - if (url === 'asc') return Promise.resolve(ascPage([1, 2, 3])); - return Promise.resolve(emptyPage); - }); - - await fetchBidirectional({ - namespace: 'ns', - workflowId: 'wf', - runId: 'run', - onRawPage: (evts, isAsc) => { - for (const e of evts) received.push({ id: e.eventId, asc: isAsc }); - }, - }); - - expect(received.every((r) => r.asc)).toBe(true); - expect(received.map((r) => r.id)).toEqual(['1', '2', '3']); - }); - - it('delivers descending events via onRawPage with isAscending=false', async () => { - const received: { id: string; asc: boolean }[] = []; - requestFromAPI.mockImplementation((url: string) => { - if (url === 'desc') return Promise.resolve(descPage([3, 2, 1])); - return Promise.resolve(emptyPage); - }); - - await fetchBidirectional({ - namespace: 'ns', - workflowId: 'wf', - runId: 'run', - onRawPage: (evts, isAsc) => { - for (const e of evts) received.push({ id: e.eventId, asc: isAsc }); - }, - }); - - const descEvents = received.filter((r) => !r.asc); - expect(descEvents.length).toBeGreaterThan(0); - expect(descEvents.every((r) => !r.asc)).toBe(true); - }); - - it('deduplicates events that both cursors return', async () => { - // Ascending: events 1-3. Descending: events 3-1 (overlap at 3). - const received: string[] = []; - let ascCall = 0; - requestFromAPI.mockImplementation((url: string) => { - if (url === 'asc') { - ascCall++; - if (ascCall === 1) return Promise.resolve(ascPage([1, 2, 3])); - return Promise.resolve(emptyPage); - } - return Promise.resolve(descPage([3, 2, 1])); - }); + it('retains each event once when cursor pages overlap', async () => { + const buffer = createGroupedEventBuffer(); + requestFromAPI.mockImplementation((url: string) => + Promise.resolve(url === 'asc' ? ascPage([1, 2, 3]) : descPage([3, 2, 1])), + ); await fetchBidirectional({ namespace: 'ns', workflowId: 'wf', runId: 'run', - onRawPage: (evts) => { - for (const e of evts) received.push(e.eventId); + onRawPage: (events) => { + for (const event of events) buffer.ingestHistoryEvent(event); }, }); - // Event 3 should only appear once (deduped by the `seen` set). - const countOf3 = received.filter((id) => id === '3').length; - expect(countOf3).toBe(1); + expect(buffer.getEventArray().map((event) => event.id)).toEqual([ + '1', + '2', + '3', + ]); }); }); @@ -164,48 +119,48 @@ describe('fetchBidirectional multi-page ascending', () => { }); expect(ascCall).toBe(2); - expect(allReceived).toContain('1'); - expect(allReceived).toContain('4'); + expect(allReceived).toEqual(['1', '2', '3', '4']); }); }); -// --------------------------------------------------------------------------- -// BidirectionalStats shape -// --------------------------------------------------------------------------- - -describe('fetchBidirectional stats', () => { - it('returns winner=ascending when ascending completes in fewer pages', async () => { - requestFromAPI.mockImplementation((url: string) => { - if (url === 'asc') return Promise.resolve(ascPage([1, 2, 3])); - return Promise.resolve(emptyPage); - }); +describe('fetchBidirectional progress', () => { + it('reports zero descending bounds until a descending page arrives', async () => { + const onProgress = vi.fn(); + requestFromAPI.mockImplementation((url: string) => + Promise.resolve(url === 'asc' ? ascPage([1, 2, 3]) : emptyPage), + ); - const stats = await fetchBidirectional({ + await fetchBidirectional({ namespace: 'ns', workflowId: 'wf', runId: 'run', onRawPage: () => {}, + onProgress, + }); + expect(onProgress).toHaveBeenCalledExactlyOnceWith({ + totalEstimated: 0, + descMinId: 0, }); - - expect(stats.totalEvents).toBe(3); - expect(typeof stats.durationMs).toBe('number'); - expect(['ascending', 'descending', 'tie']).toContain(stats.winner); }); - it('counts overlap when both cursors return the same events', async () => { - requestFromAPI.mockImplementation((url: string) => { - if (url === 'asc') return Promise.resolve(ascPage([1, 2, 3])); - return Promise.resolve(descPage([3, 2, 1])); - }); + it('reports descending bounds even when the raw page overlaps', async () => { + const onProgress = vi.fn(); + requestFromAPI.mockImplementation((url: string) => + Promise.resolve(url === 'asc' ? ascPage([1, 2, 3]) : descPage([3, 2, 1])), + ); - const stats = await fetchBidirectional({ + await fetchBidirectional({ namespace: 'ns', workflowId: 'wf', runId: 'run', onRawPage: () => {}, + onProgress, }); - expect(stats.overlap).toBeGreaterThan(0); + expect(onProgress).toHaveBeenLastCalledWith({ + totalEstimated: 3, + descMinId: 1, + }); }); }); @@ -305,7 +260,7 @@ describe('fetchBidirectional failure recovery', () => { }); const onPause = vi.fn(); - const stats = await fetchBidirectional({ + await fetchBidirectional({ namespace: 'ns', workflowId: 'wf', runId: 'run', @@ -317,7 +272,6 @@ describe('fetchBidirectional failure recovery', () => { expect(healthyCalls).toBe(3); expect(received.toSorted()).toEqual(['1', '2', '3', '4', '5', '6']); - expect(stats.totalEvents).toBe(6); expect(onPause).not.toHaveBeenCalled(); expect( requestFromAPI.mock.calls.filter(([url]) => url === failedDirection), @@ -363,6 +317,8 @@ describe('fetchBidirectional failure recovery', () => { }); it('succeeds when recovery closes the gap without reaching a terminal token', async () => { + const received: string[] = []; + const onProgress = vi.fn(); requestFromAPI.mockImplementation( (url: string, init: { token?: string }) => { if (url === 'desc') { @@ -382,9 +338,19 @@ describe('fetchBidirectional failure recovery', () => { namespace: 'ns', workflowId: 'wf', runId: 'run', - onRawPage: vi.fn(), + onRawPage: (events) => + received.push(...events.map((event) => event.eventId)), + onProgress, }), - ).resolves.toMatchObject({ totalEvents: 10, ascPages: 4, descPages: 1 }); + ).resolves.toBeUndefined(); + expect(received.toSorted((a, b) => Number(a) - Number(b))).toEqual( + Array.from({ length: 10 }, (_, index) => String(index + 1)), + ); + expect(requestFromAPI).toHaveBeenCalledTimes(6); + expect(onProgress).toHaveBeenLastCalledWith({ + totalEstimated: 10, + descMinId: 9, + }); }); it('preserves NetworkError failures', async () => { @@ -454,6 +420,7 @@ describe('fetchBidirectional failure recovery', () => { const failingPage = deferred>(); const paused = deferred(); const onPause = vi.fn(() => paused.resolve()); + const onRawPage = vi.fn(); let descendingCalls = 0; requestFromAPI.mockImplementation((url: string) => { if (url === 'asc') return failingPage.promise; @@ -467,43 +434,72 @@ describe('fetchBidirectional failure recovery', () => { namespace: 'ns', workflowId: 'wf', runId: 'run', - onRawPage: vi.fn(), + onRawPage, pauseAfterPages: 1, onPause, }); await paused.promise; failingPage.reject(new Error('ascending failed while descending paused')); - await expect(done).resolves.toMatchObject({ totalEvents: 4 }); + await expect(done).resolves.toBeUndefined(); + expect( + onRawPage.mock.calls.flatMap(([events]) => + events.map((event: ReturnType) => event.eventId), + ), + ).toEqual(['4', '3', '2', '1']); expect(descendingCalls).toBe(2); expect(onPause).toHaveBeenCalledTimes(1); }); - it('does not swallow unexpected page callback errors', async () => { - const error = new Error('ingestion failed'); - const latePage = deferred>(); - requestFromAPI.mockImplementation((url: string) => - url === 'asc' ? Promise.resolve(ascPage([1, 2], 'a2')) : latePage.promise, - ); - const onRawPage = vi.fn(() => { - throw error; - }); - const onProgress = vi.fn(); + it.each(['onRawPage', 'onProgress', 'onPause'])( + 'propagates %s errors, aborting both requests and suppressing late callbacks', + async (callback) => { + const error = new Error('callback failed'); + const latePage = deferred>(); + const signals: AbortSignal[] = []; + requestFromAPI.mockImplementation( + (url: string, init: { options: { signal: AbortSignal } }) => { + signals.push(init.options.signal); + return url === 'asc' + ? Promise.resolve(ascPage([1, 2], 'a2')) + : latePage.promise; + }, + ); + const callbacks = { + onRawPage: vi.fn(), + onProgress: vi.fn(), + onPause: vi.fn(), + }; + for (const [name, handler] of Object.entries(callbacks)) { + if (name === callback) + handler.mockImplementation(() => { + throw error; + }); + } - await expect( - fetchBidirectional({ - namespace: 'ns', - workflowId: 'wf', - runId: 'run', - onRawPage, - onProgress, - }), - ).rejects.toBe(error); - latePage.resolve(descPage([10, 9])); - await latePage.promise; - expect(onRawPage).toHaveBeenCalledTimes(1); - expect(onProgress).not.toHaveBeenCalled(); - }); + await expect( + fetchBidirectional({ + namespace: 'ns', + workflowId: 'wf', + runId: 'run', + pauseAfterPages: 1, + ...callbacks, + }), + ).rejects.toBe(error); + expect(signals).toHaveLength(2); + expect(signals.every((signal) => signal.aborted)).toBe(true); + latePage.resolve(descPage([10, 9])); + await latePage.promise; + expect(callbacks.onRawPage).toHaveBeenCalledTimes(1); + expect(callbacks.onProgress).toHaveBeenCalledTimes( + callback === 'onRawPage' ? 0 : 1, + ); + expect(callbacks.onPause).toHaveBeenCalledTimes( + callback === 'onPause' ? 1 : 0, + ); + expect(requestFromAPI).toHaveBeenCalledTimes(2); + }, + ); }); describe('fetchBidirectional empty pages', () => { @@ -529,7 +525,7 @@ describe('fetchBidirectional empty pages', () => { onRawPage: (events) => received.push(...events.map((event) => event.eventId)), }), - ).resolves.toMatchObject({ totalEvents: 1 }); + ).resolves.toBeUndefined(); expect(received).toEqual(['1']); expect(requestFromAPI).toHaveBeenCalledWith( direction, @@ -562,6 +558,7 @@ describe('fetchBidirectional empty pages', () => { }); it('accepts an empty terminal page as completed pagination', async () => { + const onRawPage = vi.fn(); requestFromAPI.mockImplementation((url: string) => url === 'asc' ? Promise.resolve(emptyPage) @@ -572,9 +569,11 @@ describe('fetchBidirectional empty pages', () => { namespace: 'ns', workflowId: 'wf', runId: 'run', - onRawPage: vi.fn(), + onRawPage, }), - ).resolves.toMatchObject({ totalEvents: 0 }); + ).resolves.toBeUndefined(); + expect(onRawPage).not.toHaveBeenCalled(); + expect(requestFromAPI).toHaveBeenCalledTimes(2); }); it('does not treat a missing response as completed pagination', async () => { @@ -590,6 +589,52 @@ describe('fetchBidirectional empty pages', () => { }); }); +describe('fetchBidirectional pause', () => { + it('pauses both cursors at the threshold, resumes once, and lets the winner cancel its sibling', async () => { + const paused = deferred(); + let resume = () => {}; + const onPause = vi.fn((handle: PauseHandle) => { + resume = handle.resume; + paused.resolve(); + }); + const signals: AbortSignal[] = []; + const received: string[] = []; + requestFromAPI.mockImplementation( + ( + url: string, + init: { token?: string; options: { signal: AbortSignal } }, + ) => { + signals.push(init.options.signal); + if (init.token) { + expect(url).toBe('asc'); + expect(signals[1].aborted).toBe(true); + return Promise.resolve(ascPage([3, 4], 'a3')); + } + return Promise.resolve( + url === 'asc' ? ascPage([1, 2], 'a2') : descPage([6, 5], 'd2'), + ); + }, + ); + const done = fetchBidirectional({ + namespace: 'ns', + workflowId: 'wf', + runId: 'run', + pauseAfterPages: 1, + onPause, + onRawPage: (events) => + received.push(...events.map((event) => event.eventId)), + }); + await paused.promise; + expect(requestFromAPI).toHaveBeenCalledTimes(2); + resume(); + await expect(done).resolves.toBeUndefined(); + resume(); + expect(onPause).toHaveBeenCalledTimes(1); + expect(requestFromAPI).toHaveBeenCalledTimes(3); + expect(received.toSorted()).toEqual(['1', '2', '3', '4', '5', '6']); + }); +}); + describe('fetchBidirectional abort', () => { it('exits cleanly when signal is pre-aborted', async () => { const ctrl = new AbortController(); @@ -646,7 +691,6 @@ describe('fetchBidirectional abort', () => { }, ); const onRawPage = vi.fn(); - const onFirstDescPage = vi.fn(); const onProgress = vi.fn(); const onPause = vi.fn(); const done = fetchBidirectional({ @@ -655,7 +699,6 @@ describe('fetchBidirectional abort', () => { runId: 'run', signal: controller.signal, onRawPage, - onFirstDescPage, onProgress, onPause, pauseAfterPages: 1, @@ -668,7 +711,6 @@ describe('fetchBidirectional abort', () => { expect(signals.every((signal) => signal.aborted)).toBe(true); expect(onRawPage).not.toHaveBeenCalled(); - expect(onFirstDescPage).not.toHaveBeenCalled(); expect(onProgress).not.toHaveBeenCalled(); expect(onPause).not.toHaveBeenCalled(); }); diff --git a/src/lib/services/fetch-bidirectional.ts b/src/lib/services/fetch-bidirectional.ts index ecff19844a..b0465e5807 100644 --- a/src/lib/services/fetch-bidirectional.ts +++ b/src/lib/services/fetch-bidirectional.ts @@ -13,24 +13,8 @@ import { import { routeForApi } from '$lib/utilities/route-for-api'; type BidirectionalProgress = { - ascEvents: number; - descEvents: number; - ascPages: number; - descPages: number; - elapsedMs: number; - ascMaxId: number; - descMinId: number; totalEstimated: number; -}; - -type BidirectionalStats = { - durationMs: number; - totalEvents: number; - overlap: number; - ascPages: number; - descPages: number; - eventsPerSecond: number; - winner: 'ascending' | 'descending' | 'tie'; + descMinId: number; }; export type PauseHandle = { @@ -44,13 +28,7 @@ export type FetchBidirectionalParams = { runId: string; signal?: AbortSignal; onProgress?: (p: BidirectionalProgress) => void; - /** Fires after every page with that page's raw events and direction flag. - * Feed directly into processEvent() to resolve buffer Promises live. */ - onRawPage: (events: HistoryEvent[], isAscending: boolean) => void; - /** Fires once with the raw events from the first descending page — the most - * recent events in the history. Use to call setFailedEvent() before the - * ascending cursor processes events that affect billableActions. */ - onFirstDescPage?: (events: HistoryEvent[]) => void; + onRawPage: (events: HistoryEvent[]) => void; maximumPageSize?: number; /** After this many total pages (asc + desc combined), pause both cursors and * call onPause with a handle whose resume() continues the fetch. */ @@ -66,30 +44,17 @@ export const fetchBidirectional = async ({ signal, onProgress, onRawPage, - onFirstDescPage, maximumPageSize, pauseAfterPages, onPause, -}: FetchBidirectionalParams): Promise => { - if (signal?.aborted) { - return { - durationMs: 0, - totalEvents: 0, - overlap: 0, - ascPages: 0, - descPages: 0, - eventsPerSecond: 0, - winner: 'tie', - }; - } +}: FetchBidirectionalParams): Promise => { + if (signal?.aborted) return; const handlePageError: ErrorCallback = (error) => { handleUnauthorizedOrForbiddenError(error); throw error; }; - const t0 = performance.now(); - const rootCtrl = new AbortController(); const ascCtrl = new AbortController(); const descCtrl = new AbortController(); @@ -97,17 +62,14 @@ export const fetchBidirectional = async ({ let ascMaxId = 0; let descMinId = Infinity; let descMaxId = 0; - let ascPages = 0; - let descPages = 0; + let pages = 0; let observedPageSize = 0; let winnerChosen = false; - let totalEvents = 0; + let pauseFired = false; let failure: Error | NetworkError | null = null; let reachedEnd = false; - const seen = new Set(); - const gap = () => Math.max(0, descMinId - ascMaxId - 1); // Pause latch: both cursor loops await this before each iteration. @@ -152,7 +114,7 @@ export const fetchBidirectional = async ({ !pauseFired && pauseAfterPages !== undefined && onPause && - ascPages + descPages >= pauseAfterPages + pages >= pauseAfterPages ) { pauseFired = true; pauseLatch = new Promise((resolve) => { @@ -164,12 +126,6 @@ export const fetchBidirectional = async ({ const reportProgress = () => { onProgress?.({ - ascEvents: ascMaxId, - descEvents: totalEvents - descMinId + 1, - ascPages, - descPages, - elapsedMs: performance.now() - t0, - ascMaxId, descMinId: descMinId === Infinity ? 0 : descMinId, totalEstimated: descMaxId, }); @@ -210,23 +166,33 @@ export const fetchBidirectional = async ({ } }; - const runAscending = async () => { - const route = routeForApi('events.ascending', { namespace, workflowId }); + const runCursor = async ({ + direction, + controller, + sibling, + updateBounds, + }: { + direction: 'ascending' | 'descending'; + controller: AbortController; + sibling: AbortController; + updateBounds: (id: number) => void; + }) => { + const route = routeForApi(`events.${direction}`, { namespace, workflowId }); let token: Token; - while (!ascCtrl.signal.aborted) { - await checkPause(ascCtrl.signal); - if (ascCtrl.signal.aborted) break; + while (!controller.signal.aborted) { + await checkPause(controller.signal); + if (controller.signal.aborted) break; const g = gap(); if (g <= 0) { - descCtrl.abort(); + sibling.abort(); break; } if (observedPageSize > 0 && g <= observedPageSize && !winnerChosen) { winnerChosen = true; - descCtrl.abort(); + sibling.abort(); } - const response = await fetchPage(route, ascCtrl, token); + const response = await fetchPage(route, controller, token); if (!response || rootCtrl.signal.aborted) break; const events = response.history?.events ?? []; @@ -239,19 +205,10 @@ export const fetchBidirectional = async ({ break; } - ascPages++; + pages++; observedPageSize = Math.max(observedPageSize, events.length); - - const fresh: HistoryEvent[] = []; - for (const e of events) { - const id = parseInt(e.eventId); - if (id > ascMaxId) ascMaxId = id; - if (!seen.has(id)) { - seen.add(id); - fresh.push(e); - } - } - if (fresh.length) onRawPage(fresh, true); + for (const event of events) updateBounds(parseInt(event.eventId)); + onRawPage(events); if (rootCtrl.signal.aborted) break; reportProgress(); if (rootCtrl.signal.aborted) break; @@ -259,69 +216,7 @@ export const fetchBidirectional = async ({ if (!response.nextPageToken) reachedEnd = true; if (!response.nextPageToken || gap() <= 0) { - descCtrl.abort(); - break; - } - token = String(response.nextPageToken); - } - }; - - const runDescending = async () => { - const route = routeForApi('events.descending', { namespace, workflowId }); - let token: Token; - while (!descCtrl.signal.aborted) { - await checkPause(descCtrl.signal); - if (descCtrl.signal.aborted) break; - const g = gap(); - if (g <= 0) { - ascCtrl.abort(); - break; - } - if (observedPageSize > 0 && g <= observedPageSize && !winnerChosen) { - winnerChosen = true; - ascCtrl.abort(); - } - - const response = await fetchPage(route, descCtrl, token); - if (!response || rootCtrl.signal.aborted) break; - - const events = response.history?.events ?? []; - if (!events.length) { - if (response.nextPageToken) { - token = String(response.nextPageToken); - continue; - } - reachedEnd = true; - break; - } - - descPages++; - observedPageSize = Math.max(observedPageSize, events.length); - - const fresh: HistoryEvent[] = []; - for (const e of events) { - const id = parseInt(e.eventId); - if (id < descMinId) descMinId = id; - if (id > descMaxId) { - descMaxId = id; - totalEvents = id; - } - if (!seen.has(id)) { - seen.add(id); - fresh.push(e); - } - } - if (fresh.length) onRawPage(fresh, false); - if (rootCtrl.signal.aborted) break; - if (descPages === 1) onFirstDescPage?.(fresh); - if (rootCtrl.signal.aborted) break; - reportProgress(); - if (rootCtrl.signal.aborted) break; - maybePause(); - - if (!response.nextPageToken) reachedEnd = true; - if (!response.nextPageToken || gap() <= 0) { - ascCtrl.abort(); + sibling.abort(); break; } token = String(response.nextPageToken); @@ -329,7 +224,25 @@ export const fetchBidirectional = async ({ }; try { - await Promise.all([runAscending(), runDescending()]); + await Promise.all([ + runCursor({ + direction: 'ascending', + controller: ascCtrl, + sibling: descCtrl, + updateBounds: (id) => { + ascMaxId = Math.max(ascMaxId, id); + }, + }), + runCursor({ + direction: 'descending', + controller: descCtrl, + sibling: ascCtrl, + updateBounds: (id) => { + descMinId = Math.min(descMinId, id); + descMaxId = Math.max(descMaxId, id); + }, + }), + ]); if (!signal?.aborted && failure && !reachedEnd && gap() > 0) { throw failure; } @@ -337,27 +250,4 @@ export const fetchBidirectional = async ({ onAbort(); signal?.removeEventListener('abort', onAbort); } - - const durationMs = performance.now() - t0; - const total = seen.size; - const fetched = - ascPages * (observedPageSize || 1) + descPages * (observedPageSize || 1); - const overlap = Math.max(0, fetched - total); - - const winner: BidirectionalStats['winner'] = - ascPages === descPages - ? 'tie' - : ascPages > descPages - ? 'ascending' - : 'descending'; - - return { - durationMs, - totalEvents: total, - overlap, - ascPages, - descPages, - eventsPerSecond: Math.round(total / (durationMs / 1000)), - winner, - }; }; diff --git a/src/lib/services/grouped-event-buffer.svelte.ts b/src/lib/services/grouped-event-buffer.svelte.ts index 7699bf715d..33b843553f 100644 --- a/src/lib/services/grouped-event-buffer.svelte.ts +++ b/src/lib/services/grouped-event-buffer.svelte.ts @@ -1,5 +1,3 @@ -import { readonly, writable } from 'svelte/store'; - import type { EventGroup } from '$lib/models/event-groups/event-groups'; import type { EventGroupKey } from '$lib/models/event-history/event-group-markers'; import type { WorkflowEvent } from '$lib/types/events'; @@ -37,8 +35,6 @@ export class EventBufferView { private disposed = false; private readonly buffer: GroupedEventBuffer; private readonly unsubscribe: () => void; - private readonly writableVersionStore = writable(0); - readonly versionStore = readonly(this.writableVersionStore); constructor(buffer: GroupedEventBuffer) { this.buffer = buffer; @@ -57,7 +53,6 @@ export class EventBufferView { private bump(): void { this.pending = false; this._version++; - this.writableVersionStore.update((current) => current + 1); } private scheduleUpdate(immediate: boolean): void { @@ -73,11 +68,6 @@ export class EventBufferView { }); } - /** Bumped once per batch of buffer writes. */ - get version(): number { - return this._version; - } - /** * Materialize a group, re-running whenever the buffer changes. A GroupRecord's * identity is stable for the life of the run, so a caller deriving off the diff --git a/src/lib/services/workflow-history-controller.svelte.test.ts b/src/lib/services/workflow-history-controller.svelte.test.ts index d2cb7027af..6c4f8d292f 100644 --- a/src/lib/services/workflow-history-controller.svelte.test.ts +++ b/src/lib/services/workflow-history-controller.svelte.test.ts @@ -27,16 +27,6 @@ function deferred() { return { promise, resolve, reject }; } -const stats: Awaited> = { - durationMs: 1, - totalEvents: 2, - overlap: 0, - ascPages: 1, - descPages: 1, - eventsPerSecond: 2, - winner: 'tie', -}; - function workflow(runId = 'run-1', isRunning = false): WorkflowExecution { return { name: 'TestWorkflow', @@ -106,12 +96,6 @@ function createController(runId = 'run-1') { function progress(index: number, totalEstimated = 10, descMinId = 8) { request(index).options.onProgress?.({ - ascEvents: 1, - descEvents: 3, - ascPages: 1, - descPages: 1, - elapsedMs: 1, - ascMaxId: 1, descMinId, totalEstimated, }); @@ -138,7 +122,7 @@ beforeEach(() => { afterEach(async () => { for (const controller of controllers.splice(0)) controller.dispose(); - for (const { result } of requests) result.resolve(stats); + for (const { result } of requests) result.resolve(); for (const { result } of polls) result.resolve(''); await Promise.all([ ...requests.map(({ result }) => result.promise.catch(() => {})), @@ -153,10 +137,10 @@ describe('WorkflowHistoryController', () => { const firstLoad = first.controller.load(workflow('run-1', true)); const secondLoad = second.controller.load(workflow('run-2', true)); - request(0).options.onRawPage([makeWorkflowStarted(1)], true); + request(0).options.onRawPage([makeWorkflowStarted(1)]); progress(0); request(0).result.reject(new Error('history failed')); - request(1).result.resolve(stats); + request(1).result.resolve(); await Promise.all([firstLoad, secondLoad]); expect(first.buffer.getEventArray().map((event) => event.id)).toEqual([ @@ -185,7 +169,7 @@ describe('WorkflowHistoryController', () => { const reset = vi.spyOn(buffer, 'reset'); const metadata = vi.spyOn(buffer, 'setPendingMetadata'); const load = controller.load(workflow()); - request(0).options.onRawPage([makeWorkflowStarted(1)], true); + request(0).options.onRawPage([makeWorkflowStarted(1)]); progress(0); const failure = new Error('history unavailable'); request(0).result.reject(failure); @@ -211,9 +195,9 @@ describe('WorkflowHistoryController', () => { progress(1, 9, 9); expect(controller.totalExpectedEvents).toBe(10); expect(controller.descMinId).toBe(8); - request(1).options.onRawPage([makeWorkflowStarted(1)], true); - request(1).options.onRawPage([makeWorkflowCompleted(10)], false); - request(1).result.resolve(stats); + request(1).options.onRawPage([makeWorkflowStarted(1)]); + request(1).options.onRawPage([makeWorkflowCompleted(10)]); + request(1).result.resolve(); await retry; await Promise.resolve(); @@ -243,7 +227,7 @@ describe('WorkflowHistoryController', () => { expect(request(0).options.signal?.aborted).toBe(true); expect(poll(0).options.signal.aborted).toBe(true); expect(resume).toHaveBeenCalledOnce(); - request(0).result.resolve(stats); + request(0).result.resolve(); await load; expect(controller.error).toBe(failure); expect(controller.fetchComplete).toBe(false); @@ -253,9 +237,9 @@ describe('WorkflowHistoryController', () => { it('keeps load reset behavior after buffered history', async () => { const { controller, buffer } = createController(); const load = controller.load(workflow()); - request(0).options.onRawPage([makeWorkflowStarted(1)], true); + request(0).options.onRawPage([makeWorkflowStarted(1)]); progress(0); - request(0).result.resolve(stats); + request(0).result.resolve(); await load; const nextLoad = controller.load(workflow()); @@ -264,7 +248,7 @@ describe('WorkflowHistoryController', () => { expect(controller.totalExpectedEvents).toBe(0); expect(controller.descMinId).toBe(0); expect(controller.fetchComplete).toBe(false); - request(1).result.resolve(stats); + request(1).result.resolve(); await nextLoad; }); @@ -280,7 +264,7 @@ describe('WorkflowHistoryController', () => { expect(requests).toHaveLength(1); expect(request(0).options.signal?.aborted).toBe(false); expect(poll(0).options.signal.aborted).toBe(false); - request(0).result.resolve(stats); + request(0).result.resolve(); await load; }); @@ -294,14 +278,14 @@ describe('WorkflowHistoryController', () => { expect(request(0).options.signal?.aborted).toBe(true); expect(poll(0).options.signal.aborted).toBe(true); - request(0).options.onRawPage([makeWorkflowCompleted(10)], false); + request(0).options.onRawPage([makeWorkflowCompleted(10)]); progress(0); const staleResume = vi.fn(); request(0).options.onPause?.({ resume: staleResume }); expect(staleResume).toHaveBeenCalledOnce(); expect(poll(0).options.onEvent(makeWorkflowCompleted(10))).toBe(false); poll(0).options.onToken?.('stale-token'); - request(0).result.resolve(stats); + request(0).result.resolve(); poll(0).result.resolve('stale-token'); await load; await Promise.resolve(); @@ -312,7 +296,7 @@ describe('WorkflowHistoryController', () => { expect(controller.error).toBeNull(); expect(polls).toHaveLength(2); expect(poll(1).options.startToken).toBe(''); - request(1).result.resolve(stats); + request(1).result.resolve(); await retry; }); @@ -326,7 +310,7 @@ describe('WorkflowHistoryController', () => { await Promise.resolve(); expect(controller.error).toBeNull(); expect(request(1).options.signal?.aborted).toBe(false); - request(1).result.resolve(stats); + request(1).result.resolve(); await retry; }); @@ -342,8 +326,6 @@ describe('WorkflowHistoryController', () => { controller.resume(); expect(resume).toHaveBeenCalledOnce(); expect(otherResume).not.toHaveBeenCalled(); - expect(controller.resumeRequested).toBe(true); - expect(other.resumeRequested).toBe(false); request(0).result.reject(new Error('retry required')); await load; @@ -353,8 +335,8 @@ describe('WorkflowHistoryController', () => { expect(retryResume).toHaveBeenCalledOnce(); other.resume(); expect(otherResume).toHaveBeenCalledOnce(); - request(1).result.resolve(stats); - request(2).result.resolve(stats); + request(1).result.resolve(); + request(2).result.resolve(); await Promise.all([otherLoad, retry]); }); @@ -374,15 +356,15 @@ describe('WorkflowHistoryController', () => { await vi.waitFor(() => expect(polls).toHaveLength(3)); expect(poll(2).options.startToken).toBe('first-token'); expect(poll(2).options.runId).toBe('run-1'); - request(0).result.resolve(stats); - request(1).result.resolve(stats); + request(0).result.resolve(); + request(1).result.resolve(); await Promise.all([firstLoad, secondLoad]); }); it('does not repoll observed closed history after a failed session and retry', async () => { const { controller } = createController(); const load = controller.load(workflow('run-1', true)); - request(0).options.onRawPage([makeWorkflowCompleted(10)], false); + request(0).options.onRawPage([makeWorkflowCompleted(10)]); expect(poll(0).options.signal.aborted).toBe(true); request(0).result.reject(new Error('missing middle history')); await load; @@ -393,7 +375,7 @@ describe('WorkflowHistoryController', () => { poll(0).result.resolve(''); await Promise.resolve(); expect(polls).toHaveLength(1); - request(1).result.resolve(stats); + request(1).result.resolve(); await retry; expect(controller.fetchComplete).toBe(true); }); @@ -410,10 +392,10 @@ describe('WorkflowHistoryController', () => { expect(resume).toHaveBeenCalledOnce(); expect(request(0).options.signal?.aborted).toBe(true); expect(poll(0).options.signal.aborted).toBe(true); - request(0).options.onRawPage([makeWorkflowStarted(1)], true); + request(0).options.onRawPage([makeWorkflowStarted(1)]); progress(0); expect(poll(0).options.onEvent(makeWorkflowStarted(1))).toBe(false); - request(0).result.resolve(stats); + request(0).result.resolve(); await load; controller.resume(); controller.updateWorkflow(workflow('run-1', true)); @@ -421,7 +403,10 @@ describe('WorkflowHistoryController', () => { expect(buffer.getEventArray()).toEqual([]); expect(controller.loading).toBe(false); expect(controller.fetchComplete).toBe(false); - expect(controller.resumeRequested).toBe(false); + expect(resume).toHaveBeenCalledOnce(); + const lateResume = vi.fn(); + request(0).options.onPause?.({ resume: lateResume }); + expect(lateResume).toHaveBeenCalledOnce(); expect(polls).toHaveLength(1); await expect(controller.load(workflow())).rejects.toThrow('disposed'); await expect(controller.retry(workflow())).rejects.toThrow('disposed'); diff --git a/src/lib/services/workflow-history-controller.svelte.ts b/src/lib/services/workflow-history-controller.svelte.ts index edeb4da484..e6ce9ebb25 100644 --- a/src/lib/services/workflow-history-controller.svelte.ts +++ b/src/lib/services/workflow-history-controller.svelte.ts @@ -87,10 +87,6 @@ export class WorkflowHistoryController { return this.started && !this.fetchComplete && !this.error; } - get resumeRequested(): boolean { - return this.historyRequested; - } - load(workflow: WorkflowExecution): Promise { return this.loadHistory(workflow, { preserveHistory: false }); } @@ -280,9 +276,8 @@ export class WorkflowHistoryController { } }, }) - .then((token) => { + .then(() => { if (!this.isCurrent(session) || controller.signal.aborted) return; - session.lastPollToken = token; this.historyClosed = true; }) .catch((error) => { From 9a604821e0a8c941964c31a3908535be4120389d Mon Sep 17 00:00:00 2001 From: Tegan Churchill Date: Thu, 5 Nov 2026 15:25:07 -0800 Subject: [PATCH 13/19] Move live poll cursor handling to callback --- src/lib/layouts/workflow-run-layout.svelte | 5 +- src/lib/pages/workflow-history-event.svelte | 11 ++-- src/lib/services/live-poll.test.ts | 62 +++++++++---------- src/lib/services/live-poll.ts | 8 +-- ...workflow-history-controller.svelte.test.ts | 12 ++-- .../history/events/[eventId]/+page.svelte | 7 +-- 6 files changed, 46 insertions(+), 59 deletions(-) diff --git a/src/lib/layouts/workflow-run-layout.svelte b/src/lib/layouts/workflow-run-layout.svelte index 6102e01695..f6c5bce698 100644 --- a/src/lib/layouts/workflow-run-layout.svelte +++ b/src/lib/layouts/workflow-run-layout.svelte @@ -197,8 +197,9 @@ isRunning: $workflowRun?.workflow?.isRunning, }); const controller = workflowRunController; - const identity = historyController?.workflowExecutionIdentity; - if (!shouldFetch || !controller || !identity || !historyController) return; + const history = historyController; + if (!shouldFetch || !controller || !history) return; + const identity = history.workflowExecutionIdentity; // The 10s poll and an action's refetch overlap, so a poll that started // before a mutation can resolve after it and write back a pre-mutation diff --git a/src/lib/pages/workflow-history-event.svelte b/src/lib/pages/workflow-history-event.svelte index d84e2367df..e09505fff6 100644 --- a/src/lib/pages/workflow-history-event.svelte +++ b/src/lib/pages/workflow-history-event.svelte @@ -11,9 +11,6 @@ interface Props { eventId: string; - namespace: string; - workflowId: string; - runId: string; } const { eventId }: Props = $props(); @@ -40,7 +37,7 @@ .sort((a, b) => Number(a.id) - Number(b.id)), ); const loading = $derived(historyController.loading && !visibleItems.length); - const lastEventId = $derived(String(historyController.latestEventId)); + const lastEventId = $derived(historyController.latestEventId); const loadPrevious = () => { const firstId = parseInt(ids[0]); @@ -62,7 +59,7 @@ const start = lastId + 1; for (let i = 0; i < 10; i++) { - if (start + i <= Number(lastEventId ?? 0)) { + if (start + i <= lastEventId) { nextTen.push((start + i).toString()); } } @@ -95,7 +92,7 @@ - {#each visibleItems as event, index} + {#each visibleItems as event, index (event.id)} Show Next 10 diff --git a/src/lib/services/live-poll.test.ts b/src/lib/services/live-poll.test.ts index ce43bea21f..ddeffe46d2 100644 --- a/src/lib/services/live-poll.test.ts +++ b/src/lib/services/live-poll.test.ts @@ -586,102 +586,104 @@ describe('runLivePoll — abort', () => { }); }); -// --------------------------------------------------------------------------- -// Pause / resume — returned cursor -// -// runLivePoll resolves with the last cursor token it held when aborted. -// The caller saves this and passes it as startToken when resuming, so the -// server picks up exactly where polling left off instead of re-fetching from -// the start. -// --------------------------------------------------------------------------- - describe('runLivePoll — pause/resume cursor', () => { - it('returns empty string when aborted before any request', async () => { + it('does not publish a cursor when aborted before any request', async () => { const ctrl = new AbortController(); + const onToken = vi.fn(); ctrl.abort(); - const token = await runLivePoll({ + await runLivePoll({ route: '/api/events', runId: 'run-1', startToken: '', signal: ctrl.signal, onEvent: vi.fn(), onNewEvents: vi.fn(), + onToken, ...FAST, }); - expect(token).toBe(''); + expect(onToken).not.toHaveBeenCalled(); + expect(requestFromAPI).not.toHaveBeenCalled(); }); - it('returns the startToken when aborted mid-request with no new token received', async () => { + it('publishes an empty cursor when a response has no nextPageToken', async () => { const ctrl = new AbortController(); + const onToken = vi.fn(); requestFromAPI.mockImplementationOnce(() => { ctrl.abort(); return Promise.resolve(pollResponse([])); }); - const token = await runLivePoll({ + await runLivePoll({ route: '/api/events', runId: 'run-1', startToken: 'resume-tok', signal: ctrl.signal, onEvent: vi.fn(), onNewEvents: vi.fn(), + onToken, ...FAST, }); - // No nextPageToken in the response so token reset to ''. - expect(token).toBe(''); + expect(requestFromAPI.mock.calls[0]?.[1]?.token).toBe('resume-tok'); + expect(onToken).toHaveBeenCalledExactlyOnceWith(''); }); - it('returns the latest nextPageToken when aborted while mid-page', async () => { + it('publishes successive cursors and resets at the frontier', async () => { const ctrl = new AbortController(); - // First response has a nextPageToken → token advances. + const onToken = vi.fn(); requestFromAPI.mockImplementationOnce(() => Promise.resolve(pollResponse([], 'page-2-tok')), ); - // Second request (following the token) is where abort fires. + requestFromAPI.mockImplementationOnce(() => { ctrl.abort(); return Promise.resolve(pollResponse([])); }); - const token = await runLivePoll({ + await runLivePoll({ route: '/api/events', runId: 'run-1', startToken: '', signal: ctrl.signal, onEvent: vi.fn(), onNewEvents: vi.fn(), + onToken, ...FAST, }); - // After following 'page-2-tok', the second response has no nextPageToken - // so token resets to ''. - expect(token).toBe(''); + expect(onToken).toHaveBeenCalledTimes(2); + expect(onToken).toHaveBeenNthCalledWith(1, 'page-2-tok'); + expect(onToken).toHaveBeenNthCalledWith(2, ''); + expect(requestFromAPI.mock.calls[1]?.[1]?.token).toBe('page-2-tok'); }); - it('can be resumed from the returned cursor without re-fetching old events', async () => { - // Simulate pausing mid-stream: first poll run is aborted after two pages. + it('can be resumed from the onToken cursor without re-fetching old events', async () => { const ctrl1 = new AbortController(); + let resumeToken = ''; requestFromAPI .mockImplementationOnce(() => Promise.resolve(pollResponse([1], 'tok-a'))) .mockImplementationOnce(() => { ctrl1.abort(); - return Promise.resolve(pollResponse([2])); + return Promise.resolve(pollResponse([2], 'tok-b')); }); - const resumeToken = await runLivePoll({ + await runLivePoll({ route: '/api/events', runId: 'run-1', startToken: '', signal: ctrl1.signal, + onToken: (token) => { + resumeToken = token; + }, onEvent: vi.fn().mockReturnValue(true), onNewEvents: vi.fn(), ...FAST, }); - // Resume: second poll run starts from the saved cursor. + expect(resumeToken).toBe('tok-b'); + const ctrl2 = new AbortController(); requestFromAPI.mockImplementationOnce(() => { ctrl2.abort(); @@ -699,10 +701,8 @@ describe('runLivePoll — pause/resume cursor', () => { ...FAST, }); - // The resumed poll sent the saved cursor as its first token. const secondCallToken = requestFromAPI.mock.calls[2]?.[1]?.token; - expect(secondCallToken).toBe(resumeToken || undefined); - // It delivered only the new event (event 3). + expect(secondCallToken).toBe('tok-b'); expect(onEvent2).toHaveBeenCalledTimes(1); expect(onEvent2.mock.calls[0][0].eventId).toBe('3'); }); diff --git a/src/lib/services/live-poll.ts b/src/lib/services/live-poll.ts index 6d9861a1f3..db2a5d0511 100644 --- a/src/lib/services/live-poll.ts +++ b/src/lib/services/live-poll.ts @@ -40,11 +40,6 @@ export type LivePollOptions = { * The loop exits cleanly when `signal` is aborted or once it receives the * workflow's close event. */ -/** - * Returns the last cursor token when the loop exits (due to abort or close). - * Rejects if response processing or a callback throws. - * The caller can save this token and pass it as `startToken` when resuming. - */ export async function runLivePoll({ route, runId, @@ -55,7 +50,7 @@ export async function runLivePoll({ onToken, backoffMs = 2000, errorBackoffMs = 5000, -}: LivePollOptions): Promise { +}: LivePollOptions): Promise { const wait = (delay: number): Promise => { if (signal.aborted) return Promise.resolve(); return new Promise((resolve) => { @@ -110,5 +105,4 @@ export async function runLivePoll({ } } } - return token; } diff --git a/src/lib/services/workflow-history-controller.svelte.test.ts b/src/lib/services/workflow-history-controller.svelte.test.ts index 6c4f8d292f..7ce5eb6243 100644 --- a/src/lib/services/workflow-history-controller.svelte.test.ts +++ b/src/lib/services/workflow-history-controller.svelte.test.ts @@ -62,7 +62,7 @@ const requests: { }[] = []; const polls: { options: LivePollOptions; - result: ReturnType>; + result: ReturnType>; }[] = []; const controllers: WorkflowHistoryController[] = []; @@ -114,7 +114,7 @@ beforeEach(() => { vi.mocked(runLivePoll) .mockReset() .mockImplementation((options) => { - const result = deferred(); + const result = deferred(); polls.push({ options, result }); return result.promise; }); @@ -123,7 +123,7 @@ beforeEach(() => { afterEach(async () => { for (const controller of controllers.splice(0)) controller.dispose(); for (const { result } of requests) result.resolve(); - for (const { result } of polls) result.resolve(''); + for (const { result } of polls) result.resolve(); await Promise.all([ ...requests.map(({ result }) => result.promise.catch(() => {})), ...polls.map(({ result }) => result.promise.catch(() => {})), @@ -286,7 +286,7 @@ describe('WorkflowHistoryController', () => { expect(poll(0).options.onEvent(makeWorkflowCompleted(10))).toBe(false); poll(0).options.onToken?.('stale-token'); request(0).result.resolve(); - poll(0).result.resolve('stale-token'); + poll(0).result.resolve(); await load; await Promise.resolve(); @@ -350,7 +350,7 @@ describe('WorkflowHistoryController', () => { first.setLiveUpdatesPaused(true); expect(poll(0).options.signal.aborted).toBe(true); expect(poll(1).options.signal.aborted).toBe(false); - poll(0).result.resolve('ignored'); + poll(0).result.resolve(); await vi.waitFor(() => expect(polls).toHaveLength(2)); first.setLiveUpdatesPaused(false); await vi.waitFor(() => expect(polls).toHaveLength(3)); @@ -372,7 +372,7 @@ describe('WorkflowHistoryController', () => { const retry = controller.retry(workflow('run-1', true)); controller.updateWorkflow(workflow('run-1', true)); controller.setLiveUpdatesPaused(false); - poll(0).result.resolve(''); + poll(0).result.resolve(); await Promise.resolve(); expect(polls).toHaveLength(1); request(1).result.resolve(); diff --git a/src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/[run]/history/events/[eventId]/+page.svelte b/src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/[run]/history/events/[eventId]/+page.svelte index d8116e18c6..40034c5f98 100644 --- a/src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/[run]/history/events/[eventId]/+page.svelte +++ b/src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/[run]/history/events/[eventId]/+page.svelte @@ -16,9 +16,4 @@ )} | ${params.workflow} | Event ${params.eventId}`} url={page.url.href} /> - + From efeb7b7ba4924fbf0a32db5343de280cf69048ee Mon Sep 17 00:00:00 2001 From: Tegan Churchill Date: Thu, 5 Nov 2026 15:58:45 -0800 Subject: [PATCH 14/19] Fix history pagination and isolate loading failures --- .../activity/activity-commands.svelte | 25 ++- .../event/event-summary-table.svelte | 37 ----- .../layouts/workflow-history-layout.svelte | 2 +- .../layouts/workflow-timeline-layout.svelte | 8 +- src/lib/pages/workflow-history-event.svelte | 15 +- ...workflow-history-controller.svelte.test.ts | 146 +++++++++++++++++- .../workflow-history-controller.svelte.ts | 38 +++-- .../workflow-event-detail-live.spec.ts | 85 +++++----- ...workflow-run-detail-history-errors.spec.ts | 47 ++++++ 9 files changed, 282 insertions(+), 121 deletions(-) diff --git a/src/lib/components/activity/activity-commands.svelte b/src/lib/components/activity/activity-commands.svelte index 9901b808bb..4134e2a88d 100644 --- a/src/lib/components/activity/activity-commands.svelte +++ b/src/lib/components/activity/activity-commands.svelte @@ -49,14 +49,16 @@ (workflow.isRunning || workflow.isPaused), ); + const execution = $derived({ + workflowId: workflowExecutionIdentity.workflowId, + runId: workflowExecutionIdentity.runId, + }); + const onPause = async (reason: string) => { const refresh = onRefresh; await pauseActivity({ namespace: workflowExecutionIdentity.namespace, - execution: { - workflowId: workflowExecutionIdentity.workflowId, - runId: workflowExecutionIdentity.runId, - }, + execution, id: activity.activityId, reason, identity, @@ -68,10 +70,7 @@ const refresh = onRefresh; await unpauseActivity({ namespace: workflowExecutionIdentity.namespace, - execution: { - workflowId: workflowExecutionIdentity.workflowId, - runId: workflowExecutionIdentity.runId, - }, + execution, id: activity.activityId, identity, }); @@ -83,10 +82,7 @@ const activityId = activity.activityId; await resetActivity({ namespace: workflowExecutionIdentity.namespace, - execution: { - workflowId: workflowExecutionIdentity.workflowId, - runId: workflowExecutionIdentity.runId, - }, + execution, id: activityId, resetHeartbeat, identity, @@ -102,10 +98,7 @@ const refresh = onRefresh; await updateActivityOptions({ namespace: workflowExecutionIdentity.namespace, - execution: { - workflowId: workflowExecutionIdentity.workflowId, - runId: workflowExecutionIdentity.runId, - }, + execution, id: activity.activityId, activityOptions: options, identity, diff --git a/src/lib/components/event/event-summary-table.svelte b/src/lib/components/event/event-summary-table.svelte index 810b8d9712..5d9ea903ce 100644 --- a/src/lib/components/event/event-summary-table.svelte +++ b/src/lib/components/event/event-summary-table.svelte @@ -1,8 +1,6 @@ - -{#snippet dot( - point: [number, number], - eventClassification: EventClassification | 'pending' | undefined, -)} - {@const colors = dotColors(eventClassification)} - -{/snippet} - -{#snippet line(opts: { - startPoint: [number, number]; - endPoint: [number, number]; - category?: EventTypeCategory | 'pending' | 'retry'; - pending?: boolean; -})} - {@const { - startPoint, - endPoint, - category: lineCategory, - pending = false, - } = opts} - -{/snippet} - - - {#if connectLine} - {@render line({ - startPoint: [canvasWidth, centerY], - endPoint: [canvasWidth - horizontalOffset - RADIUS, centerY], - })} - {/if} - {#if !reverseSort} - {@render dot([canvasWidth - horizontalOffset, centerY], classification)} - {/if} - {#if zoomNextDistance} - {@render line({ - startPoint: [ - canvasWidth - horizontalOffset - RADIUS / 2 + strokeWidth, - centerY + RADIUS + strokeWidth / 2, - ], - endPoint: [ - canvasWidth - horizontalOffset - RADIUS / 2 + strokeWidth, - centerY + zoomNextDistance + RADIUS, - ], - category: group?.pendingActivity - ? Number(group.pendingActivity.attempt) > 1 - ? 'retry' - : 'pending' - : category, - pending: nextIsPending, - })} - {/if} - {#if reverseSort} - {@render dot([canvasWidth - horizontalOffset, centerY], classification)} - {/if} - - - diff --git a/src/lib/components/lines-and-dots/history-graph/history-graph.svelte b/src/lib/components/lines-and-dots/history-graph/history-graph.svelte deleted file mode 100644 index 4584583373..0000000000 --- a/src/lib/components/lines-and-dots/history-graph/history-graph.svelte +++ /dev/null @@ -1,82 +0,0 @@ - - - diff --git a/src/lib/components/lines-and-dots/history-graph/positioning.ts b/src/lib/components/lines-and-dots/history-graph/positioning.ts deleted file mode 100644 index cbbdaedd6c..0000000000 --- a/src/lib/components/lines-and-dots/history-graph/positioning.ts +++ /dev/null @@ -1,125 +0,0 @@ -import type { - EventGroup, - EventGroups, -} from '$lib/models/event-groups/event-groups'; -import { isEvent } from '$lib/models/event-history'; -import type { EventSortOrder } from '$lib/stores/event-view'; -import type { - WorkflowEvent, - WorkflowEventWithPending, -} from '$lib/types/events'; -import { getGroupForEventOrPendingEvent } from '$lib/utilities/pending-activities'; - -export const isMiddleEvent = ( - event: WorkflowEvent, - groups: EventGroups | Map, -): boolean => { - const group = - groups instanceof Map - ? groups.get(event.id) - : groups.find((candidate) => - candidate.eventList.some((listEvent) => listEvent.id === event.id), - ); - if (!group) return false; - return ( - group.eventList.findIndex((listEvent) => listEvent.id === event.id) === 1 && - group.eventList.length === 3 - ); -}; - -const pairIsConsecutive = (firstId: string, secondId: string): boolean => { - return parseInt(firstId) === parseInt(secondId) - 1; -}; - -const isConsecutiveGroup = (group: EventGroup): boolean => { - const { eventList } = group; - if (eventList.length === 1) return true; - if (eventList.length === 2) - return pairIsConsecutive(eventList[0].id, eventList[1].id); - if (eventList.length === 3) { - return ( - pairIsConsecutive(eventList[0].id, eventList[1].id) && - pairIsConsecutive(eventList[1].id, eventList[2].id) - ); - } - return false; -}; - -const getOpenGroups = ( - event: WorkflowEventWithPending, - groups: EventGroups, -): number => { - const group = getGroupForEventOrPendingEvent(groups, event); - if (!group) return 0; - if (group.level !== undefined) return group.level; - - const pendingGroups = groups - .filter((other) => other.isPending && other.id !== group.id) - .filter( - (other) => - parseInt(other.initialEvent.id) < parseInt(group.initialEvent.id), - ); - - const nonPendingGroups = groups - .filter( - (other) => - other.eventList.length > 1 && !other.isPending && other.id !== group.id, - ) - .filter( - (other) => - parseInt(other.initialEvent.id) < parseInt(group.initialEvent.id), - ) - .filter( - (other) => parseInt(other.lastEvent.id) > parseInt(group.initialEvent.id), - ); - - const openGroups = [...pendingGroups, ...nonPendingGroups]; - - if (!openGroups.length && isConsecutiveGroup(group)) { - group.level = 0; - } - group.level = openGroups.length + 1; - return group.level; -}; - -export const getNextDistanceAndOffset = ( - history: WorkflowEventWithPending[], - event: WorkflowEventWithPending, - groups: EventGroups, - height: number, - sort: EventSortOrder, -): { nextDistance: number; offset: number } => { - const group = getGroupForEventOrPendingEvent(groups, event); - let nextDistance = 0; - let offset = 0; - - if (!group) { - return { nextDistance, offset }; - } - - if (group.eventList.length === 1 && !group.isPending) { - return { nextDistance, offset }; - } - - const currentIndex = isEvent(event) ? group.eventList.indexOf(event) : -1; - const nextEvent = isEvent(event) - ? group.eventList[currentIndex + 1] - : undefined; - if (!isEvent(event) || event.category !== 'workflow') { - offset = getOpenGroups(event, groups); - } - - if (!nextEvent && !group.isPending) { - return { nextDistance, offset }; - } - - let diff = 0; - if (nextEvent && isEvent(event)) { - diff = parseInt(nextEvent.id) - parseInt(event.id); - } else if (group.isPending && isEvent(event)) { - diff = history.length - parseInt(event.id) + 2; - } - const distance = diff * height; - nextDistance = sort === 'ascending' ? distance : -distance; - return { nextDistance, offset }; -}; From 0ed6a4c8bc27b7950af538083101ebd6371ee7e8 Mon Sep 17 00:00:00 2001 From: Tegan Churchill Date: Thu, 5 Nov 2026 16:42:11 -0800 Subject: [PATCH 16/19] consolidate some testing --- src/lib/services/fetch-bidirectional.test.ts | 92 ++++++++----------- .../grouped-event-buffer.svelte.test.ts | 14 +-- src/lib/services/grouped-event-buffer.test.ts | 2 +- ...workflow-history-controller.svelte.test.ts | 30 ++---- ...workflow-run-detail-history-errors.spec.ts | 13 +-- .../workflow-run-detail-refresh.spec.ts | 25 ++--- .../workflow-run-detail-smoke.spec.ts | 15 +-- 7 files changed, 63 insertions(+), 128 deletions(-) diff --git a/src/lib/services/fetch-bidirectional.test.ts b/src/lib/services/fetch-bidirectional.test.ts index e2ece39a8c..62384e9f60 100644 --- a/src/lib/services/fetch-bidirectional.test.ts +++ b/src/lib/services/fetch-bidirectional.test.ts @@ -183,50 +183,47 @@ function deferred() { } describe('fetchBidirectional request error policy', () => { - it.each([401, 403, 503])( - 'delegates status %i to auth handling and rethrows without global reporting', - async (statusCode) => { - const callbacks: ErrorCallback[] = []; - requestFromAPI.mockImplementation( - ( - _url: string, - init: { handleError: ErrorCallback; notifyOnError?: boolean }, - ) => { - expect(init.notifyOnError).not.toBe(false); - callbacks.push(init.handleError); - return Promise.resolve(emptyPage); - }, - ); - await fetchBidirectional({ - namespace: 'ns', - workflowId: 'wf', - runId: 'run', - onRawPage: vi.fn(), - }); - expect(callbacks).toHaveLength(2); - const error = { - status: statusCode, - statusCode, - statusText: 'Request failed', - response: new Response(), + it('delegates request errors to auth handling and rethrows without global reporting', async () => { + const callbacks: ErrorCallback[] = []; + requestFromAPI.mockImplementation( + ( + _url: string, + init: { handleError: ErrorCallback; notifyOnError?: boolean }, + ) => { + expect(init.notifyOnError).not.toBe(false); + callbacks.push(init.handleError); + return Promise.resolve(emptyPage); + }, + ); + await fetchBidirectional({ + namespace: 'ns', + workflowId: 'wf', + runId: 'run', + onRawPage: vi.fn(), + }); + expect(callbacks).toHaveLength(2); + const error = { + status: 403, + statusCode: 403, + statusText: 'Request failed', + response: new Response(), + message: 'History request failed', + body: { + code: 403, message: 'History request failed', - body: { - code: statusCode, - message: 'History request failed', - details: [], - }, - }; + details: [], + }, + }; - for (const callback of callbacks) { - await expect( - Promise.resolve().then(() => callback(error)), - ).rejects.toBe(error); - } - expect(handleUnauthorizedOrForbiddenError).toHaveBeenCalledTimes(2); - expect(handleUnauthorizedOrForbiddenError).toHaveBeenCalledWith(error); - expect(handleError).not.toHaveBeenCalled(); - }, - ); + for (const callback of callbacks) { + await expect(Promise.resolve().then(() => callback(error))).rejects.toBe( + error, + ); + } + + expect(handleUnauthorizedOrForbiddenError).toHaveBeenCalledWith(error); + expect(handleError).not.toHaveBeenCalled(); + }); }); describe('fetchBidirectional failure recovery', () => { @@ -276,14 +273,6 @@ describe('fetchBidirectional failure recovery', () => { expect( requestFromAPI.mock.calls.filter(([url]) => url === failedDirection), ).toHaveLength(1); - expect(requestFromAPI).toHaveBeenCalledWith( - 'asc', - expect.objectContaining({ handleError: expect.any(Function) }), - ); - expect(requestFromAPI).toHaveBeenCalledWith( - 'desc', - expect.objectContaining({ handleError: expect.any(Function) }), - ); }, ); @@ -313,7 +302,6 @@ describe('fetchBidirectional failure recovery', () => { ).rejects.toBe(error); expect(received).toEqual(['1', '2', '10', '9']); - expect(requestFromAPI).toHaveBeenCalledTimes(4); }); it('succeeds when recovery closes the gap without reaching a terminal token', async () => { @@ -346,7 +334,6 @@ describe('fetchBidirectional failure recovery', () => { expect(received.toSorted((a, b) => Number(a) - Number(b))).toEqual( Array.from({ length: 10 }, (_, index) => String(index + 1)), ); - expect(requestFromAPI).toHaveBeenCalledTimes(6); expect(onProgress).toHaveBeenLastCalledWith({ totalEstimated: 10, descMinId: 9, @@ -413,7 +400,6 @@ describe('fetchBidirectional failure recovery', () => { onRawPage: vi.fn(), }), ).rejects.toBe(error); - expect(requestFromAPI).toHaveBeenCalledTimes(3); }); it('releases an existing pause on failure so the healthy cursor can finish', async () => { diff --git a/src/lib/services/grouped-event-buffer.svelte.test.ts b/src/lib/services/grouped-event-buffer.svelte.test.ts index 7eec1eb0b3..8966dc1443 100644 --- a/src/lib/services/grouped-event-buffer.svelte.test.ts +++ b/src/lib/services/grouped-event-buffer.svelte.test.ts @@ -29,8 +29,6 @@ describe('EventBufferView direct lookups', () => { const events = vi.spyOn(buffer, 'getEventArray'); const groups = vi.spyOn(buffer, 'getGroupArray'); const lazyGroups = vi.spyOn(buffer, 'getLazyGroups'); - const eventLookup = vi.spyOn(buffer, 'getEvent'); - const groupLookup = vi.spyOn(buffer, 'getEventGroup'); const snapshots: { event: WorkflowEvent | undefined; group: EventGroup | undefined; @@ -80,16 +78,12 @@ describe('EventBufferView direct lookups', () => { buffer.reset(20); flushSync(); expect(snapshots.at(-1)).toEqual({ event: undefined, group: undefined }); - expect(eventLookup).toHaveBeenCalledWith('2'); - expect(groupLookup).toHaveBeenCalledWith('2', { - excludeWorkflowTasks: true, - }); expect(events).not.toHaveBeenCalled(); expect(groups).not.toHaveBeenCalled(); expect(lazyGroups).not.toHaveBeenCalled(); }); - it('forwards filtering and invalid IDs and isolates views', async () => { + it('forwards filtering and isolates views', async () => { const buffer = createGroupedEventBuffer(); const otherBuffer = createGroupedEventBuffer(); buffer.reset(3); @@ -110,16 +104,10 @@ describe('EventBufferView direct lookups', () => { expect( history.eventGroup('2', { excludeWorkflowTasks: true }), ).toBeUndefined(); - expect(history.eventGroup('2', { excludeWorkflowTasks: false })).toBe( - history.eventGroup('1'), - ); expect(other.event('2')?.eventType).toBe('TimerFired'); expect(other.eventGroup('2')?.category).toBe('timer'); - expect(history.event('2-request-id')).toBeUndefined(); - expect(history.eventGroup('2-request-id')).toBeUndefined(); buffer.reset(0); expect(history.event('2')).toBeUndefined(); - expect(history.eventGroup('2')).toBeUndefined(); expect(other.event('2')?.eventType).toBe('TimerFired'); }); }); diff --git a/src/lib/services/grouped-event-buffer.test.ts b/src/lib/services/grouped-event-buffer.test.ts index 1173e2d897..a51f541e8e 100644 --- a/src/lib/services/grouped-event-buffer.test.ts +++ b/src/lib/services/grouped-event-buffer.test.ts @@ -219,7 +219,7 @@ describe('direct event lookups', () => { buffer.getEventGroup(event.id, { excludeWorkflowTasks }), ).toEqual(expected.get(event.id)); } - for (const group of expected.values()) { + for (const group of new Set(expected.values())) { for (const event of group.eventList) { expect(buffer.getEventGroup(event.id, { excludeWorkflowTasks })).toBe( buffer.getEventGroup(group.initialEvent.id, { diff --git a/src/lib/services/workflow-history-controller.svelte.test.ts b/src/lib/services/workflow-history-controller.svelte.test.ts index cd0409c888..d30ac0c296 100644 --- a/src/lib/services/workflow-history-controller.svelte.test.ts +++ b/src/lib/services/workflow-history-controller.svelte.test.ts @@ -166,8 +166,6 @@ describe('WorkflowHistoryController', () => { it('retains partial history on error and recovers without resetting during retry', async () => { const { controller, buffer } = createController(); - const reset = vi.spyOn(buffer, 'reset'); - const metadata = vi.spyOn(buffer, 'setPendingMetadata'); const load = controller.load(workflow()); request(0).options.onRawPage([makeWorkflowStarted(1)]); progress(0); @@ -181,8 +179,6 @@ describe('WorkflowHistoryController', () => { expect(buffer.getEventArray().map((event) => event.id)).toEqual(['1']); const retry = controller.retry(workflow()); - expect(reset).toHaveBeenCalledTimes(1); - expect(metadata).toHaveBeenCalledTimes(2); expect(controller.error).toBeNull(); expect(controller.fetchComplete).toBe(false); expect(controller.loading).toBe(true); @@ -350,30 +346,24 @@ describe('WorkflowHistoryController', () => { }, ); - it('clears the saved poll token on a fresh load that resets history', async () => { + it('resets buffered history, progress, completion, and the saved poll token on a fresh load', async () => { const { controller, buffer } = createController(); const load = controller.load(workflow('run-1', true)); - poll(0).options.onEvent(makeWorkflowStarted(1)); - poll(0).options.onToken?.('old-token'); - const nextLoad = controller.load(workflow('run-1', true)); - expect(poll(0).options.signal.aborted).toBe(true); - expect(poll(1).options.startToken).toBe(''); - expect(buffer.getEventArray()).toEqual([]); - request(0).result.resolve(); - request(1).result.resolve(); - await Promise.all([load, nextLoad]); - }); - - it('keeps load reset behavior after buffered history', async () => { - const { controller, buffer } = createController(); - const load = controller.load(workflow()); request(0).options.onRawPage([makeWorkflowStarted(1)]); progress(0); + poll(0).options.onEvent(makeWorkflowStarted(2)); + poll(0).options.onToken?.('old-token'); request(0).result.resolve(); await load; + expect(buffer.getEventArray().map((event) => event.id)).toEqual(['1', '2']); + expect(controller.latestEventId).toBe(2); + expect(controller.totalExpectedEvents).toBe(10); + expect(controller.descMinId).toBe(8); + expect(controller.fetchComplete).toBe(true); const nextLoad = controller.load(workflow('run-1', true)); - expect(poll(0).options.startToken).toBe(''); + expect(poll(0).options.signal.aborted).toBe(true); + expect(poll(1).options.startToken).toBe(''); expect(buffer.getEventArray()).toEqual([]); expect(controller.latestEventId).toBe(0); expect(controller.totalExpectedEvents).toBe(0); diff --git a/tests/integration/workflow-run-detail-history-errors.spec.ts b/tests/integration/workflow-run-detail-history-errors.spec.ts index 33e11343d5..b5f22611c4 100644 --- a/tests/integration/workflow-run-detail-history-errors.spec.ts +++ b/tests/integration/workflow-run-detail-history-errors.spec.ts @@ -76,18 +76,14 @@ test.describe('Workflow run detail history loading errors', () => { test('loads every event through the healthy paginated direction when the other direction returns HTTP 503', async ({ page, }) => { - const ascendingTokens: (string | null)[] = []; let descendingFailures = 0; await page.route(EVENT_HISTORY_API_REVERSE, (route) => { descendingFailures += 1; return failHistoryPage(route); }); - await page.route(EVENT_HISTORY_API, (route) => { - ascendingTokens.push( - new URL(route.request().url()).searchParams.get('next_page_token'), - ); - return fulfillHistoryPage(route, false); - }); + await page.route(EVENT_HISTORY_API, (route) => + fulfillHistoryPage(route, false), + ); await page.goto(historyUrl); @@ -104,8 +100,7 @@ test.describe('Workflow run detail history loading errors', () => { await expect( page.getByTestId('event-summary-table').getByRole('table'), ).not.toHaveAttribute('aria-busy', 'true'); - expect(descendingFailures).toBe(1); - expect(ascendingTokens).toEqual([null, '2', '4', '6', '8']); + expect(descendingFailures).toBeGreaterThan(0); }); test('shows the status text fallback when both history directions return HTTP 503 with an empty message', async ({ diff --git a/tests/integration/workflow-run-detail-refresh.spec.ts b/tests/integration/workflow-run-detail-refresh.spec.ts index 9277a1f19f..d83dfabe51 100644 --- a/tests/integration/workflow-run-detail-refresh.spec.ts +++ b/tests/integration/workflow-run-detail-refresh.spec.ts @@ -111,10 +111,13 @@ async function openHistory(page: Page, refreshOff: boolean) { } test.describe('Workflow run detail refresh', () => { - test('loads initial history with refresh off without live history or ambient Describe polls', async ({ + test('loads history with refresh off, receives a live completion when enabled, and stops requests when disabled again', async ({ page, }) => { - const { requests, liveResponse } = await mockRunDetail(page, []); + const { requests, liveRequested, liveResponse } = await mockRunDetail( + page, + [activityCompletion], + ); try { await openHistory(page, true); await expect(page.getByTestId('pause')).toHaveText('Auto Refresh Off'); @@ -123,25 +126,11 @@ test.describe('Workflow run detail refresh', () => { expect(requests.describe).toBe(1); expect(requests.live).toBe(0); - const before = { ...requests }; + const initiallyOff = { ...requests }; await page.clock.runFor(30_000); - - expect(requests).toEqual(before); + expect(requests).toEqual(initiallyOff); await expect(page.getByTestId('event-summary-row')).toHaveCount(3); - } finally { - liveResponse.release(); - } - }); - test('receives a live completion after enabling refresh and stops requests when disabled again', async ({ - page, - }) => { - const { requests, liveRequested, liveResponse } = await mockRunDetail( - page, - [activityCompletion], - ); - try { - await openHistory(page, true); await page.getByTestId('pause').click(); await expect(page.getByTestId('pause')).toHaveText('Auto Refresh On'); await expect(page).not.toHaveURL(/refresh_off=true/); diff --git a/tests/integration/workflow-run-detail-smoke.spec.ts b/tests/integration/workflow-run-detail-smoke.spec.ts index db90f12d94..ea1b8d110b 100644 --- a/tests/integration/workflow-run-detail-smoke.spec.ts +++ b/tests/integration/workflow-run-detail-smoke.spec.ts @@ -99,10 +99,6 @@ test.describe('Workflow run detail smoke', () => { await page.getByTestId('history-tab').click(); await expect(page.getByTestId('event-summary-row')).toHaveCount(5); await page.getByTestId('compact').click(); - await expect(page.getByTestId('event-summary-row')).toHaveCount(1); - await expect( - page.getByTestId('event-summary-row').getByTestId('link'), - ).toHaveText(['2', '3', '4']); await expect(page.getByTestId('event-summary-table')).toContainText( 'SmokeFirstRunActivity', ); @@ -167,7 +163,6 @@ test.describe('Workflow run detail smoke', () => { 'Workflow Execution Started', ); await page.getByTestId('compact').click(); - await expect(page.getByTestId('event-summary-row')).toHaveCount(0); await expect(page.getByTestId('event-summary-table')).toContainText( 'No Events Match', ); @@ -309,20 +304,12 @@ test.describe('Workflow run detail smoke', () => { await expect(page.getByTestId('event-summary-table')).not.toContainText( 'SmokeFirstRunActivity', ); - await page.getByTestId('compact').click(); - await expect(page.getByTestId('event-summary-row')).toHaveCount(1); - await expect( - page.getByTestId('event-summary-row').getByTestId('link'), - ).toHaveText(['2', '3', '4']); - await expect(page.getByTestId('event-summary-table')).toContainText( - 'SmokeSecondRunActivity', - ); + await page.goBack(); await expect(page).toHaveURL(`${secondRunUrl}/timeline`); await page.goBack(); await expect(page).toHaveURL(`${runUrl}/history/events/1`); await page.getByTestId('history-tab').click(); - await page.getByTestId('feed').click(); await expect(page.getByTestId('event-summary-row')).toHaveCount(5); await expect(page.getByTestId('event-summary-table')).toContainText( 'SmokeFirstRunActivity', From 7150453d41c7ac877d746bfd43b1e96a18cb1335 Mon Sep 17 00:00:00 2001 From: Tegan Churchill Date: Mon, 16 Nov 2026 13:26:48 -0800 Subject: [PATCH 17/19] Address review feedback on history loading - Surface non-retryable live-poll errors to the history controller - Keep the pause when one bidirectional cursor fails; stop and reject instead of draining - Gate the workflow-task-failed banner on fetchComplete - Clear the run error on a successful refresh and pause live polling while it shows - Update integration test event filter selectors --- .../layouts/workflow-history-layout.svelte | 2 +- src/lib/layouts/workflow-run-layout.svelte | 3 +- .../layouts/workflow-timeline-layout.svelte | 2 +- src/lib/services/fetch-bidirectional.test.ts | 44 ++++++++--- src/lib/services/fetch-bidirectional.ts | 17 ++++- src/lib/services/live-poll.test.ts | 76 +++++++++++++++++++ src/lib/services/live-poll.ts | 32 ++++++-- .../workflow-run-detail-selection.spec.ts | 4 +- 8 files changed, 155 insertions(+), 25 deletions(-) diff --git a/src/lib/layouts/workflow-history-layout.svelte b/src/lib/layouts/workflow-history-layout.svelte index b368a7df83..a897f79e84 100644 --- a/src/lib/layouts/workflow-history-layout.svelte +++ b/src/lib/layouts/workflow-history-layout.svelte @@ -114,7 +114,7 @@ ); const workflowTaskFailedError = $derived.by(() => { - if (historyController.loading) return undefined; + if (!historyController.fetchComplete) return undefined; return historyController.history.workflowTaskFailedEvent as | WorkflowTaskFailedEvent | WorkflowTaskTimedOutEvent diff --git a/src/lib/layouts/workflow-run-layout.svelte b/src/lib/layouts/workflow-run-layout.svelte index f6c5bce698..a8ec2840ef 100644 --- a/src/lib/layouts/workflow-run-layout.svelte +++ b/src/lib/layouts/workflow-run-layout.svelte @@ -220,6 +220,7 @@ workflowError = error; return; } + workflowError = null; $workflowRun.workflow = workflow ?? null; }; @@ -282,7 +283,7 @@ $effect(() => { const controller = historyController; - const paused = $pauseLiveUpdates; + const paused = $pauseLiveUpdates || !!workflowError; untrack(() => controller?.setLiveUpdatesPaused(paused)); }); diff --git a/src/lib/layouts/workflow-timeline-layout.svelte b/src/lib/layouts/workflow-timeline-layout.svelte index 258e896555..de8d3a0799 100644 --- a/src/lib/layouts/workflow-timeline-layout.svelte +++ b/src/lib/layouts/workflow-timeline-layout.svelte @@ -192,7 +192,7 @@ }; const workflowTaskFailedError = $derived.by(() => { - if (historyController.loading) return undefined; + if (!historyController.fetchComplete) return undefined; return historyController.history.workflowTaskFailedEvent as | WorkflowTaskFailedEvent | WorkflowTaskTimedOutEvent diff --git a/src/lib/services/fetch-bidirectional.test.ts b/src/lib/services/fetch-bidirectional.test.ts index 62384e9f60..9f5eab9781 100644 --- a/src/lib/services/fetch-bidirectional.test.ts +++ b/src/lib/services/fetch-bidirectional.test.ts @@ -255,27 +255,52 @@ describe('fetchBidirectional failure recovery', () => { ), ); }); - const onPause = vi.fn(); await fetchBidirectional({ namespace: 'ns', workflowId: 'wf', runId: 'run', - pauseAfterPages: 2, - onPause, onRawPage: (events) => received.push(...events.map((event) => event.eventId)), }); expect(healthyCalls).toBe(3); expect(received.toSorted()).toEqual(['1', '2', '3', '4', '5', '6']); - expect(onPause).not.toHaveBeenCalled(); expect( requestFromAPI.mock.calls.filter(([url]) => url === failedDirection), ).toHaveLength(1); }, ); + it('stops the healthy cursor at the pause threshold after a failure', async () => { + const error = new Error('ascending failed'); + let descendingCalls = 0; + requestFromAPI.mockImplementation((url: string) => { + if (url === 'asc') return Promise.reject(error); + descendingCalls++; + return Promise.resolve( + descPage( + descendingCalls === 1 ? [6, 5] : [4, 3], + `d${descendingCalls + 1}`, + ), + ); + }); + const onPause = vi.fn(); + + await expect( + fetchBidirectional({ + namespace: 'ns', + workflowId: 'wf', + runId: 'run', + pauseAfterPages: 2, + onPause, + onRawPage: vi.fn(), + }), + ).rejects.toBe(error); + expect(descendingCalls).toBe(2); + expect(onPause).not.toHaveBeenCalled(); + }); + it('rejects after both directions fail with a gap, retaining delivered pages', async () => { const error = new Error('ascending failed'); const received: string[] = []; @@ -402,7 +427,7 @@ describe('fetchBidirectional failure recovery', () => { ).rejects.toBe(error); }); - it('releases an existing pause on failure so the healthy cursor can finish', async () => { + it('stops a paused cursor and rejects when the other cursor fails', async () => { const failingPage = deferred>(); const paused = deferred(); const onPause = vi.fn(() => paused.resolve()); @@ -425,15 +450,16 @@ describe('fetchBidirectional failure recovery', () => { onPause, }); await paused.promise; - failingPage.reject(new Error('ascending failed while descending paused')); + const error = new Error('ascending failed while descending paused'); + failingPage.reject(error); - await expect(done).resolves.toBeUndefined(); + await expect(done).rejects.toBe(error); expect( onRawPage.mock.calls.flatMap(([events]) => events.map((event: ReturnType) => event.eventId), ), - ).toEqual(['4', '3', '2', '1']); - expect(descendingCalls).toBe(2); + ).toEqual(['4', '3']); + expect(descendingCalls).toBe(1); expect(onPause).toHaveBeenCalledTimes(1); }); diff --git a/src/lib/services/fetch-bidirectional.ts b/src/lib/services/fetch-bidirectional.ts index b0465e5807..4bcc439f07 100644 --- a/src/lib/services/fetch-bidirectional.ts +++ b/src/lib/services/fetch-bidirectional.ts @@ -85,10 +85,14 @@ export const fetchBidirectional = async ({ resumePause = undefined; }; - const onAbort = () => { - rootCtrl.abort(); + const stopCursors = () => { ascCtrl.abort(); descCtrl.abort(); + }; + + const onAbort = () => { + rootCtrl.abort(); + stopCursors(); releasePause(); }; signal?.addEventListener('abort', onAbort); @@ -117,6 +121,10 @@ export const fetchBidirectional = async ({ pages >= pauseAfterPages ) { pauseFired = true; + if (failure) { + stopCursors(); + return; + } pauseLatch = new Promise((resolve) => { resumePause = resolve; }); @@ -161,8 +169,9 @@ export const fetchBidirectional = async ({ error instanceof Error || isNetworkError(error) ? error : new Error(getErrorMessage(error)); - pauseFired = true; - releasePause(); + if (pauseLatch) { + stopCursors(); + } } }; diff --git a/src/lib/services/live-poll.test.ts b/src/lib/services/live-poll.test.ts index ddeffe46d2..235d89ca90 100644 --- a/src/lib/services/live-poll.test.ts +++ b/src/lib/services/live-poll.test.ts @@ -8,12 +8,18 @@ import { vi, } from 'vitest'; +import { handleUnauthorizedOrForbiddenError } from '$lib/utilities/handle-error'; + import { runLivePoll } from './live-poll'; // --------------------------------------------------------------------------- // Mocks // --------------------------------------------------------------------------- +vi.mock('$lib/utilities/handle-error', () => ({ + handleUnauthorizedOrForbiddenError: vi.fn(), +})); + vi.mock('$lib/utilities/request-from-api', () => ({ requestFromAPI: vi.fn(), })); @@ -541,6 +547,76 @@ describe('runLivePoll — back-off', () => { }); }); +describe('runLivePoll — request errors', () => { + const networkError = (statusCode: number) => ({ + statusCode, + statusText: 'Request failed', + response: new Response(null, { status: statusCode }), + }); + + it('delegates request errors to auth handling and rethrows them', async () => { + const ctrl = new AbortController(); + requestFromAPI.mockImplementationOnce(() => { + ctrl.abort(); + return Promise.resolve(pollResponse([])); + }); + + await runLivePoll({ + route: '/api/events', + runId: 'run-1', + startToken: '', + signal: ctrl.signal, + onEvent: vi.fn(), + ...FAST, + }); + + const { handleError } = requestFromAPI.mock.calls[0][1] as { + handleError: (error: unknown) => void; + }; + const error = networkError(403); + expect(() => handleError(error)).toThrow(); + expect(handleUnauthorizedOrForbiddenError).toHaveBeenCalledWith(error); + }); + + it('rejects on a non-retryable error response', async () => { + const error = networkError(404); + requestFromAPI.mockRejectedValueOnce(error); + + await expect( + runLivePoll({ + route: '/api/events', + runId: 'run-1', + startToken: '', + signal: new AbortController().signal, + onEvent: vi.fn(), + ...FAST, + }), + ).rejects.toBe(error); + expect(requestFromAPI).toHaveBeenCalledTimes(1); + }); + + it.each([408, 429, 503])('retries a %s error response', async (status) => { + const ctrl = new AbortController(); + requestFromAPI + .mockRejectedValueOnce(networkError(status)) + .mockImplementationOnce(() => { + ctrl.abort(); + return Promise.resolve(pollResponse([])); + }); + + await runLivePoll({ + route: '/api/events', + runId: 'run-1', + startToken: '', + signal: ctrl.signal, + onEvent: vi.fn(), + ...FAST, + }); + + expect(requestFromAPI).toHaveBeenCalledTimes(2); + }); +}); + // --------------------------------------------------------------------------- // Abort / cleanup // --------------------------------------------------------------------------- diff --git a/src/lib/services/live-poll.ts b/src/lib/services/live-poll.ts index db2a5d0511..5768d1f7f3 100644 --- a/src/lib/services/live-poll.ts +++ b/src/lib/services/live-poll.ts @@ -2,8 +2,13 @@ import type { GetWorkflowExecutionHistoryResponse, HistoryEvent, } from '$lib/types/events'; +import { handleUnauthorizedOrForbiddenError } from '$lib/utilities/handle-error'; import { isWorkflowCloseEvent } from '$lib/utilities/is-event-type'; -import { requestFromAPI } from '$lib/utilities/request-from-api'; +import { isNetworkError } from '$lib/utilities/is-network-error'; +import { + type ErrorCallback, + requestFromAPI, +} from '$lib/utilities/request-from-api'; export type LivePollOptions = { route: string; @@ -21,10 +26,21 @@ export type LivePollOptions = { onToken?: (token: string) => void; /** ms to wait when a long-poll times out with no new events. Default 2000. */ backoffMs?: number; - /** ms to wait after a network error before retrying. Default 5000. */ + /** ms to wait after a retryable error before retrying. Default 5000. */ errorBackoffMs?: number; }; +const handlePollError: ErrorCallback = (error) => { + handleUnauthorizedOrForbiddenError(error); + throw error; +}; + +const isRetryableError = (error: unknown): boolean => { + if (!isNetworkError(error)) return true; + const { statusCode } = error; + return statusCode === 408 || statusCode === 429 || statusCode >= 500; +}; + /** * Token-based long-poll loop for streaming new workflow history events. * @@ -35,7 +51,8 @@ export type LivePollOptions = { * continue immediately. * - nextPageToken absent, no new events (timeout) → reset token; back off * 2 s before retrying so we don't spin on an idle workflow. - * - Network error → back off 5 s and retry. + * - Network failure, 408, 429 or 5xx → back off 5 s and retry. + * - Any other error response → reject so the caller can surface it. * * The loop exits cleanly when `signal` is aborted or once it receives the * workflow's close event. @@ -78,12 +95,13 @@ export async function runLivePoll({ waitNewEvent: 'true', }, options: { signal }, + handleError: handlePollError, }, ); - } catch { - if (!signal.aborted) { - await wait(errorBackoffMs); - } + } catch (error) { + if (signal.aborted) break; + if (!isRetryableError(error)) throw error; + await wait(errorBackoffMs); continue; } const events = response?.history?.events ?? []; diff --git a/tests/integration/workflow-run-detail-selection.spec.ts b/tests/integration/workflow-run-detail-selection.spec.ts index 838f3c4298..cd9014a7db 100644 --- a/tests/integration/workflow-run-detail-selection.spec.ts +++ b/tests/integration/workflow-run-detail-selection.spec.ts @@ -72,8 +72,8 @@ async function openActivity(page: Page) { } async function toggleFilter(page: Page, name: string) { - await page.locator('button[aria-controls="status-menu"]').click(); - await page.locator('#event-type-menu').getByTestId(name).click(); + await page.locator('button[aria-controls="event-type-filter"]').click(); + await page.locator('#event-type-filter').getByTestId(name).click(); await page.keyboard.press('Escape'); } From b0c6f1d03dd49c57f7a8033415d3536244d724a7 Mon Sep 17 00:00:00 2001 From: Tegan Churchill Date: Mon, 16 Nov 2026 13:38:59 -0800 Subject: [PATCH 18/19] Show SDK info in standalone activity workers --- src/lib/pages/standalone-activity-workers.svelte | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/lib/pages/standalone-activity-workers.svelte b/src/lib/pages/standalone-activity-workers.svelte index a1bd3ea80e..b5ffd8bb3e 100644 --- a/src/lib/pages/standalone-activity-workers.svelte +++ b/src/lib/pages/standalone-activity-workers.svelte @@ -4,6 +4,7 @@ import WorkersTable from '$lib/components/workers/workers-table/task-queue-workers-table.svelte'; import { activityWorkerCount } from '$lib/stores/activities'; import { parseSearchAttributes } from '$lib/utilities/decode-payload'; + import { formatSDKName } from '$lib/utilities/get-sdk-version'; import { activityExecution } from '$lib/utilities/standalone-activity-poller.svelte'; interface Props { @@ -15,6 +16,10 @@ const searchAttributes = $derived($activityExecution?.info?.searchAttributes); const taskQueue = $derived($activityExecution?.info?.taskQueue ?? ''); + const sdkInfo = $derived({ + sdk: formatSDKName($activityExecution?.info?.sdkName), + version: $activityExecution?.info?.sdkVersion ?? '', + }); const workerHeartbeatsEnabled = $derived( !!page.data.namespace.namespaceInfo?.capabilities?.workerHeartbeats, ); @@ -28,6 +33,7 @@ {namespace} {taskQueue} searchAttributes={decodedSearchAttributes} + {sdkInfo} useFallback={!workerHeartbeatsEnabled || useFallback} onCount={(count) => ($activityWorkerCount = count)} /> From 37ff107edceb588f1dd613f87baec0e342942b98 Mon Sep 17 00:00:00 2001 From: Tegan Churchill Date: Tue, 17 Nov 2026 10:19:40 -0800 Subject: [PATCH 19/19] Fix history integration tests after review feedback - Let the healthy cursor keep loading after a failure when the pause is released immediately - Expect the workflow-task failure banner to stay hidden while history is partial - Scroll the virtualized timeline into view before finding rows on mobile - Use the event-type-filter selectors in the smoke spec - Fix type errors in the history errors spec --- src/lib/services/fetch-bidirectional.test.ts | 36 ++++++++++++++++++- src/lib/services/fetch-bidirectional.ts | 9 ++--- ...workflow-run-detail-history-errors.spec.ts | 30 +++++++++------- .../workflow-run-detail-resume.spec.ts | 3 ++ .../workflow-run-detail-smoke.spec.ts | 4 +-- 5 files changed, 62 insertions(+), 20 deletions(-) diff --git a/src/lib/services/fetch-bidirectional.test.ts b/src/lib/services/fetch-bidirectional.test.ts index 9f5eab9781..520c5d3d90 100644 --- a/src/lib/services/fetch-bidirectional.test.ts +++ b/src/lib/services/fetch-bidirectional.test.ts @@ -298,7 +298,41 @@ describe('fetchBidirectional failure recovery', () => { }), ).rejects.toBe(error); expect(descendingCalls).toBe(2); - expect(onPause).not.toHaveBeenCalled(); + expect(onPause).toHaveBeenCalledTimes(1); + }); + + it('lets the healthy cursor finish after a failure when the pause is released immediately', async () => { + let descendingCalls = 0; + const pages = [ + [6, 5], + [4, 3], + [2, 1], + ]; + requestFromAPI.mockImplementation((url: string) => { + if (url === 'asc') return Promise.reject(new Error('ascending failed')); + const ids = pages[descendingCalls]; + descendingCalls++; + return Promise.resolve( + descPage( + ids, + descendingCalls < pages.length ? `d${descendingCalls + 1}` : '', + ), + ); + }); + const received: string[] = []; + + await fetchBidirectional({ + namespace: 'ns', + workflowId: 'wf', + runId: 'run', + pauseAfterPages: 2, + onPause: (handle) => handle.resume(), + onRawPage: (events) => + received.push(...events.map((event) => event.eventId)), + }); + + expect(descendingCalls).toBe(3); + expect(received).toEqual(['6', '5', '4', '3', '2', '1']); }); it('rejects after both directions fail with a gap, retaining delivered pages', async () => { diff --git a/src/lib/services/fetch-bidirectional.ts b/src/lib/services/fetch-bidirectional.ts index 4bcc439f07..b9959b2aae 100644 --- a/src/lib/services/fetch-bidirectional.ts +++ b/src/lib/services/fetch-bidirectional.ts @@ -85,6 +85,8 @@ export const fetchBidirectional = async ({ resumePause = undefined; }; + const isPaused = () => pauseLatch !== null; + const stopCursors = () => { ascCtrl.abort(); descCtrl.abort(); @@ -121,14 +123,13 @@ export const fetchBidirectional = async ({ pages >= pauseAfterPages ) { pauseFired = true; - if (failure) { - stopCursors(); - return; - } pauseLatch = new Promise((resolve) => { resumePause = resolve; }); onPause({ resume: releasePause }); + if (failure && isPaused()) { + stopCursors(); + } } }; diff --git a/tests/integration/workflow-run-detail-history-errors.spec.ts b/tests/integration/workflow-run-detail-history-errors.spec.ts index b5f22611c4..004fdc6102 100644 --- a/tests/integration/workflow-run-detail-history-errors.spec.ts +++ b/tests/integration/workflow-run-detail-history-errors.spec.ts @@ -10,7 +10,10 @@ import { makeWorkflowTaskStarted, } from '$src/lib/services/test-helpers/synthetic-events'; import type { HistoryEvent } from '$src/lib/types/events'; -import type { WorkflowExecutionAPIResponse } from '$src/lib/types/workflows'; +import type { + WorkflowExecutionAPIResponse, + WorkflowExecutionInfo, +} from '$src/lib/types/workflows'; import { mockWorkflowApis } from '~/test-utilities/mock-apis'; import { EVENT_HISTORY_API, @@ -28,16 +31,17 @@ const events: HistoryEvent[] = [ makeWorkflowCompleted(9), ]; const pageSize = 2; +const completedExecutionInfo: WorkflowExecutionInfo = { + ...mockWorkflow.workflowExecutionInfo, + status: 'Completed', + startTime: events[0].eventTime, + executionTime: events[0].eventTime, + closeTime: events[8].eventTime, + historyLength: String(events.length), +}; const completedWorkflow: WorkflowExecutionAPIResponse = { ...mockWorkflow, - workflowExecutionInfo: { - ...mockWorkflow.workflowExecutionInfo, - status: 'Completed', - startTime: events[0].eventTime, - executionTime: events[0].eventTime, - closeTime: events[8].eventTime, - historyLength: String(events.length), - }, + workflowExecutionInfo: completedExecutionInfo, pendingActivities: [], pendingChildren: [], }; @@ -106,7 +110,7 @@ test.describe('Workflow run detail history loading errors', () => { test('shows the status text fallback when both history directions return HTTP 503 with an empty message', async ({ page, }) => { - const failedDirections = new Set(); + const failedDirections = new Set(); for (const api of [EVENT_HISTORY_API, EVENT_HISTORY_API_REVERSE]) { await page.route(api, (route) => { failedDirections.add(api); @@ -132,13 +136,13 @@ test.describe('Workflow run detail history loading errors', () => { }); for (const view of ['history', 'timeline']) { - test(`shows a loaded workflow-task failure on ${view} after a partial history error`, async ({ + test(`hides a loaded workflow-task failure on ${view} after a partial history error`, async ({ page, }) => { await mockWorkflowApis(page, { ...completedWorkflow, workflowExecutionInfo: { - ...completedWorkflow.workflowExecutionInfo, + ...completedExecutionInfo, status: 'Running', closeTime: '', }, @@ -171,7 +175,7 @@ test.describe('Workflow run detail history loading errors', () => { await expect(page.getByTestId('history-load-error')).toBeVisible(); await expect( page.getByText('Non Deterministic Error', { exact: true }), - ).toBeVisible(); + ).toBeHidden(); }); } diff --git a/tests/integration/workflow-run-detail-resume.spec.ts b/tests/integration/workflow-run-detail-resume.spec.ts index 61d28e343a..4d91533cb8 100644 --- a/tests/integration/workflow-run-detail-resume.spec.ts +++ b/tests/integration/workflow-run-detail-resume.spec.ts @@ -146,6 +146,9 @@ test.describe('Workflow run detail resume ownership', () => { { view: 'timeline', verify: async (page: Page) => { + await page + .getByRole('img', { name: `Workflow ${workflowId}: Completed` }) + .scrollIntoViewIfNeeded(); const activity = page.getByRole('button', { name: 'Event ResumeSecondRunActivity3: Completed', }); diff --git a/tests/integration/workflow-run-detail-smoke.spec.ts b/tests/integration/workflow-run-detail-smoke.spec.ts index ea1b8d110b..1087c5a828 100644 --- a/tests/integration/workflow-run-detail-smoke.spec.ts +++ b/tests/integration/workflow-run-detail-smoke.spec.ts @@ -134,8 +134,8 @@ test.describe('Workflow run detail smoke', () => { }) => { await page.goto(`${runUrl}/history?sort=ascending`); await expect(page.getByTestId('event-summary-row')).toHaveCount(5); - await page.locator('button[aria-controls="status-menu"]').click(); - await page.locator('#event-type-menu').getByTestId('Activity').click(); + await page.locator('button[aria-controls="event-type-filter"]').click(); + await page.locator('#event-type-filter').getByTestId('Activity').click(); await page.keyboard.press('Escape'); await expect(page.getByTestId('event-summary-row')).toHaveCount(2); await expect(page.getByTestId('event-summary-table')).not.toContainText(