Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { describe, expect, it } from 'vitest';
import type { ExecutionApproval, ExecutionNode } from '@/api/executions';
import type { Execution, ExecutionApproval, ExecutionNode } from '@/api/executions';
import {
buildExecutionNodeStateMap,
buildTraceDetailSections,
getCancelButtonState,
getReadableJsonItemTitle,
getReadableJsonSummary,
getReadableJsonTable,
Expand All @@ -12,6 +13,7 @@ import {
getSelectedNodeApproval,
getSelectedNodeApprovals,
parseExecutionPayload,
shouldShowExecutionCancel,
} from './workflow-execution-viewer-model';

function trace(partial: Partial<ExecutionNode> & Pick<ExecutionNode, 'id' | 'nodeId' | 'status'>): ExecutionNode {
Expand Down Expand Up @@ -233,6 +235,67 @@ describe('workflow execution viewer model', () => {
});
});

describe('cancel button state (armed double-click)', () => {
it('is idle by default', () => {
expect(getCancelButtonState({ armed: false, isPending: false })).toEqual({
label: 'Cancel',
variant: 'secondary',
animate: false,
});
});

it('flips to destructive with pulse when armed', () => {
expect(getCancelButtonState({ armed: true, isPending: false })).toEqual({
label: 'Click again to confirm',
variant: 'destructive',
animate: true,
});
});

it('shows the pending label while the request is in flight', () => {
// Pending should win over armed — the caller disarms before firing
// the mutation but the race between disarm + isPending flipping
// true shouldn't briefly show the armed label.
expect(getCancelButtonState({ armed: true, isPending: true })).toEqual({
label: 'Cancelling…',
variant: 'secondary',
animate: false,
});
expect(getCancelButtonState({ armed: false, isPending: true })).toEqual({
label: 'Cancelling…',
variant: 'secondary',
animate: false,
});
});
});

describe('shouldShowExecutionCancel', () => {
it('is false when there is no execution', () => {
expect(shouldShowExecutionCancel(null)).toBe(false);
expect(shouldShowExecutionCancel(undefined)).toBe(false);
});

it('is true for active statuses', () => {
const active: Execution['status'][] = [
'pending',
'running',
'waiting_approval',
'waiting_time',
'cancelling',
];
for (const status of active) {
expect(shouldShowExecutionCancel({ status })).toBe(true);
}
});

it('is false for terminal statuses', () => {
const terminal: Execution['status'][] = ['completed', 'failed', 'cancelled'];
for (const status of terminal) {
expect(shouldShowExecutionCancel({ status })).toBe(false);
}
});
});

it('builds a session link from a running session trace', () => {
const link = getSessionTraceLink(trace({
id: 'exec:scrape_yc:running:0',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,65 @@
import type { Execution, ExecutionApproval, ExecutionNode } from '@/api/executions';
import type { WorkflowNode } from '@valet/shared';

// Mirror of the terminal set from @/api/executions. Duplicated here so
// the model stays pure — importing @/api/executions at runtime pulls
// the whole app graph (router, react-query wiring) which breaks
// node-env vitest resolution. Keep this in sync with
// TERMINAL_EXECUTION_STATUSES in @/api/executions.ts.
const TERMINAL_EXECUTION_STATUSES = new Set<Execution['status']>([
'completed',
'failed',
'cancelled',
]);

export type ExecutionDisplayStatus = ExecutionNode['status'] | 'not_run';

/**
* Presentational mapping for the two-phase Cancel button.
*
* The button lives in three places (execution detail page, execution
* viewer summary pane, workflow-editor Test row). The armed-double-click
* state itself stays in each caller — this is just the label/variant/
* pulse mapping so all three sites render identically and can be unit-
* tested without a React renderer.
*
* States:
* - idle → 'Cancel', secondary
* - armed → 'Click again to confirm', destructive, animate
* - pending → 'Cancelling…', secondary (disabled by caller)
*/
export interface CancelButtonState {
label: string;
variant: 'secondary' | 'destructive';
animate: boolean;
}

export function getCancelButtonState({
armed,
isPending,
}: {
armed: boolean;
isPending: boolean;
}): CancelButtonState {
if (isPending) return { label: 'Cancelling…', variant: 'secondary', animate: false };
if (armed) return { label: 'Click again to confirm', variant: 'destructive', animate: true };
return { label: 'Cancel', variant: 'secondary', animate: false };
}

/**
* Should the Cancel button be visible for an execution?
*
* Mirrors the isActiveExecutionStatus check from @/api/executions but
* keeps this file free of runtime imports from that module (so the
* node-env vitest run can load it without pulling the router + query-
* client graph). Callers who don't need a nullable input should still
* prefer isActiveExecutionStatus directly.
*/
export function shouldShowExecutionCancel(execution: { status: Execution['status'] } | null | undefined): boolean {
if (!execution) return false;
return !TERMINAL_EXECUTION_STATUSES.has(execution.status);
}

export function buildExecutionNodeStateMap(nodes: ExecutionNode[]): Map<string, ExecutionNode> {
const latest = new Map<string, ExecutionNode>();
for (const node of nodes) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { Link } from '@tanstack/react-router';
import type { NodeProps } from '@xyflow/react';
import { ReactFlowProvider } from '@xyflow/react';
import type { Execution, ExecutionApproval, ExecutionNode } from '@/api/executions';
import { useCancelExecution } from '@/api/executions';
import { toastError, toastSuccess } from '@/hooks/use-toast';
import type { WorkflowDefinition, WorkflowNode } from '@valet/shared';
import { Canvas } from '@/components/ai-elements/canvas';
import { Controls } from '@/components/ai-elements/controls';
Expand Down Expand Up @@ -30,6 +32,7 @@ import {
buildTraceDetailSections,
formatReadableScalar,
formatExecutionDuration,
getCancelButtonState,
getExecutionDisplayStatus,
getNodeParametersForDisplay,
getReadableJsonItemTitle,
Expand All @@ -39,6 +42,7 @@ import {
getSessionTraceLink,
isRecord,
parseExecutionPayload,
shouldShowExecutionCancel,
type ParsedExecutionPayload,
type ReadableJsonTable,
type ExecutionDisplayStatus,
Expand Down Expand Up @@ -334,6 +338,43 @@ function ExecutionSummaryPane({
isRetryingExecution?: boolean;
onClose: () => void;
}) {
const cancel = useCancelExecution();

// Two-phase cancel — copied verbatim from the execution detail page
// (see routes/automation/executions/$executionId.tsx). First click
// arms, second confirms. Auto-disarms after 4s so a stray click
// doesn't leave the button in a dangerous state.
const [cancelArmed, setCancelArmed] = React.useState(false);
const isCancelable = shouldShowExecutionCancel(execution);
React.useEffect(() => {
if (!cancelArmed) return;
const timer = window.setTimeout(() => setCancelArmed(false), 4000);
return () => window.clearTimeout(timer);
}, [cancelArmed]);
React.useEffect(() => {
// Reset when the execution goes terminal — no point staying armed.
if (!isCancelable) setCancelArmed(false);
}, [isCancelable]);

const onCancel = async () => {
if (!cancelArmed) {
setCancelArmed(true);
return;
}
setCancelArmed(false);
try {
await cancel.mutateAsync({
executionId: execution.id,
data: { reason: 'Cancelled from workflow editor test run' },
});
toastSuccess('Execution cancelled');
} catch (err) {
toastError('Cancel failed', err instanceof Error ? err.message : 'unknown error');
}
};

const cancelButton = getCancelButtonState({ armed: cancelArmed, isPending: cancel.isPending });

return (
<div className="nodrag nopan nowheel absolute bottom-5 right-5 top-5 z-20 flex w-[min(400px,calc(100%-2.5rem))] flex-col overflow-hidden rounded-xl border border-neutral-200 bg-white shadow-2xl shadow-neutral-900/15 dark:border-neutral-800 dark:bg-neutral-950 dark:shadow-black/30">
<div className="flex shrink-0 items-center justify-between gap-3 border-b border-neutral-200 px-4 py-3 dark:border-neutral-800">
Expand All @@ -355,21 +396,40 @@ function ExecutionSummaryPane({
drawer grew past the viewport and nothing scrolled. */}
<div className="min-h-0 flex-1 overflow-y-auto">
<div className="space-y-4 p-4">
<div className="flex items-center justify-between gap-3">
<div className="flex items-center justify-between gap-2">
<ExecutionStatusPill status={execution.status} />
{onRetryExecution && (
<Button
type="button"
variant="secondary"
size="sm"
onClick={() => onRetryExecution(execution.id)}
disabled={isRetryingExecution}
className="border border-neutral-200 bg-white text-neutral-800 hover:bg-neutral-100 dark:border-neutral-700 dark:bg-neutral-900 dark:text-neutral-100 dark:hover:bg-neutral-800"
>
<RetryIcon />
{isRetryingExecution ? 'Retrying...' : 'Retry'}
</Button>
)}
<div className="flex items-center gap-2">
{isCancelable && (
<Button
type="button"
variant={cancelButton.variant}
size="sm"
onClick={onCancel}
disabled={cancel.isPending}
className={cn(
cancelButton.variant === 'secondary' &&
'border border-neutral-200 bg-white text-neutral-800 hover:bg-neutral-100 dark:border-neutral-700 dark:bg-neutral-900 dark:text-neutral-100 dark:hover:bg-neutral-800',
cancelButton.animate && 'animate-pulse',
)}
>
<CancelIcon />
{cancelButton.label}
</Button>
)}
{onRetryExecution && (
<Button
type="button"
variant="secondary"
size="sm"
onClick={() => onRetryExecution(execution.id)}
disabled={isRetryingExecution}
className="border border-neutral-200 bg-white text-neutral-800 hover:bg-neutral-100 dark:border-neutral-700 dark:bg-neutral-900 dark:text-neutral-100 dark:hover:bg-neutral-800"
>
<RetryIcon />
{isRetryingExecution ? 'Retrying...' : 'Retry'}
</Button>
)}
</div>
</div>
<div className="space-y-2 text-xs text-neutral-600 dark:text-neutral-400">
<KeyValue label="Started" value={formatExecutionTimestamp(execution.startedAt)} />
Expand Down Expand Up @@ -668,6 +728,16 @@ function RetryIcon() {
);
}

function CancelIcon() {
return (
<svg className="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<circle cx="12" cy="12" r="9" />
<path d="M15 9l-6 6" />
<path d="M9 9l6 6" />
</svg>
);
}

function StructuredPayloadBlock({
title,
payload,
Expand Down
Loading
Loading