Skip to content
Open
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
Expand Up @@ -828,7 +828,8 @@ export const LogDetails = memo(function LogDetails({
<div className='flex items-center justify-between'>
<h2 className='text-[var(--text-primary)] text-sm'>Log Details</h2>
<div className='flex items-center gap-[1px]'>
{log.status === 'failed' &&
{onRetryExecution &&
log.status === 'failed' &&
(log.workflow?.id || log.workflowId) &&
log.trigger !== 'mothership' && (
<Tooltip.Root>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ function renderMenu(
props: Partial<{
log: WorkflowLogSummary
canCancelExecution: boolean
canRetryExecution: boolean
isCancelPending: boolean
cancelPendingExecutionId: string
}> = {}
Expand All @@ -100,6 +101,7 @@ function renderMenu(
position={{ x: 0, y: 0 }}
log={props.log ?? LOG}
canCancelExecution={props.canCancelExecution ?? true}
canRetryExecution={props.canRetryExecution ?? true}
isCancelPending={props.isCancelPending}
cancelPendingExecutionId={props.cancelPendingExecutionId}
isFilteredByThisWorkflow={false}
Expand Down Expand Up @@ -152,3 +154,11 @@ describe('LogRowContextMenu cancellation action', () => {
expect(findButton('Stopping…')?.disabled).toBe(true)
})
})

describe('LogRowContextMenu retry action', () => {
it('hides Retry without edit permission', () => {
renderMenu({ log: { ...LOG, status: 'failed' }, canRetryExecution: false })

expect(findButton('Retry')).toBeUndefined()
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ interface LogRowContextMenuProps {
onCancelExecution: () => void
onRetryExecution: () => void
canCancelExecution: boolean
canRetryExecution: boolean
isCancelPending?: boolean
cancelPendingExecutionId?: string
isRetryPending?: boolean
Expand All @@ -57,6 +58,7 @@ export const LogRowContextMenu = memo(function LogRowContextMenu({
onCancelExecution,
onRetryExecution,
canCancelExecution,
canRetryExecution,
isCancelPending = false,
cancelPendingExecutionId,
isRetryPending = false,
Expand All @@ -78,7 +80,8 @@ export const LogRowContextMenu = memo(function LogRowContextMenu({
(isCancelPending && cancelPendingExecutionId === log?.executionId)
const showCancelAction =
canCancelExecution && hasExecutionId && hasWorkflow && (isCancellable || isStopping)
const isRetryable = log?.status === 'failed' && hasWorkflow && log?.trigger !== 'mothership'
const isRetryable =
canRetryExecution && log?.status === 'failed' && hasWorkflow && log?.trigger !== 'mothership'

return (
<DropdownMenu open={isOpen} onOpenChange={(open) => !open && onClose()} modal={false}>
Expand Down
13 changes: 7 additions & 6 deletions apps/sim/app/workspace/[workspaceId]/logs/logs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -597,7 +597,7 @@ export default function Logs() {
}, [contextMenuLog])

const cancelExecution = useCancelExecution(workspaceId)
const retryExecution = useRetryExecution()
const retryExecution = useRetryExecution(workspaceId)

const handleCancelExecution = useCallback(async () => {
const workflowId = contextMenuLog?.workflow?.id || contextMenuLog?.workflowId
Expand All @@ -617,17 +617,17 @@ export default function Logs() {
async (log: WorkflowLogRow | null) => {
const workflowId = log?.workflow?.id || log?.workflowId
const executionId = log?.executionId
if (!workflowId || !executionId) return
if (!userPermissions.canEdit || !workflowId || !executionId) return

try {
await retryExecution.mutateAsync({ workflowId, executionId })
toast.success('Retry started')
} catch {
toast.error('Failed to retry execution')
} catch (error) {
toast.error(getErrorMessage(error, 'Failed to retry execution'))
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
[userPermissions.canEdit]
)

const handleRetryExecution = useCallback(() => {
Expand Down Expand Up @@ -862,7 +862,7 @@ export default function Logs() {
onNavigatePrev={handleNavigatePrev}
hasNext={selectedLogIndex >= 0 && selectedLogIndex < logs.length - 1}
hasPrev={selectedLogIndex > 0}
onRetryExecution={handleRetrySidebarExecution}
onRetryExecution={userPermissions.canEdit ? handleRetrySidebarExecution : undefined}
isRetryPending={retryExecution.isPending}
onActiveTabChange={handleActiveTabChange}
/>
Expand Down Expand Up @@ -1270,6 +1270,7 @@ export default function Logs() {
onCancelExecution={handleCancelExecution}
onRetryExecution={handleRetryExecution}
canCancelExecution={userPermissions.canEdit}
canRetryExecution={userPermissions.canEdit}
isCancelPending={cancelExecution.isPending}
cancelPendingExecutionId={cancelExecution.variables?.executionId}
isRetryPending={retryExecution.isPending}
Expand Down
157 changes: 155 additions & 2 deletions apps/sim/hooks/queries/logs.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

const { mockRequestJson } = vi.hoisted(() => ({
const { mockFetch, mockRequestJson } = vi.hoisted(() => ({
mockFetch: vi.fn(),
mockRequestJson: vi.fn(),
}))

Expand All @@ -16,7 +17,7 @@ vi.mock('@/lib/api/client/request', () => ({

import { getLogByExecutionIdContract } from '@/lib/api/contracts/logs'
import { cancelWorkflowExecutionContract } from '@/lib/api/contracts/workflows'
import { useCancelExecution } from '@/hooks/queries/logs'
import { useCancelExecution, useRetryExecution } from '@/hooks/queries/logs'

function renderHookWithClient<T>(useHook: () => T): {
result: () => T
Expand Down Expand Up @@ -198,3 +199,155 @@ describe('useCancelExecution', () => {
unmount()
})
})

function failedLogDetail(
children = [
{
id: 'failed-span',
name: 'Failed block',
type: 'function',
status: 'error',
blockId: 'failed-block',
},
]
) {
return {
data: {
executionData: {
workflowInput: { prompt: 'original input' },
traceSpans: [
{
id: 'workflow-execution',
name: 'Workflow Execution',
type: 'workflow',
status: 'error',
children,
},
],
},
},
}
}

function executionStream(events: object[]): ReadableStream<Uint8Array> {
return new ReadableStream({
start(controller) {
for (const event of events) {
controller.enqueue(new TextEncoder().encode(`data: ${JSON.stringify(event)}\n\n`))
}
controller.close()
},
})
}

describe('useRetryExecution', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.stubGlobal('fetch', mockFetch)
})

afterEach(() => {
vi.unstubAllGlobals()
})

it('starts the retry from the failed block using the source execution state', async () => {
mockRequestJson.mockResolvedValue(failedLogDetail())
mockFetch.mockResolvedValue({
ok: true,
body: executionStream([
{ type: 'execution:started', data: { startTime: '2026-08-31T00:00:00.000Z' } },
{ type: 'block:started', data: { blockId: 'different-block' } },
{ type: 'block:started', data: { blockId: 'failed-block' } },
]),
})

const { result, unmount } = renderHookWithClient(() => useRetryExecution('workspace-1'))

await act(async () => {
await result().mutateAsync({ workflowId: 'workflow-1', executionId: 'execution-1' })
})

expect(mockRequestJson).toHaveBeenCalledWith(getLogByExecutionIdContract, {
params: { executionId: 'execution-1' },
query: { workspaceId: 'workspace-1' },
signal: undefined,
})
expect(mockFetch).toHaveBeenCalledWith('/api/workflows/workflow-1/execute', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
inputFromExecutionId: 'execution-1',
triggerType: 'manual',
stream: true,
runFromBlock: { startBlockId: 'failed-block', executionId: 'execution-1' },
}),
})

unmount()
})

it('surfaces a streamed run-from-block validation error', async () => {
mockRequestJson.mockResolvedValue(failedLogDetail())
mockFetch.mockResolvedValue({
ok: true,
body: executionStream([
{ type: 'execution:started', data: { startTime: '2026-08-31T00:00:00.000Z' } },
{
type: 'execution:error',
data: { error: 'The failed block no longer exists in the current workflow' },
},
]),
})

const { result, unmount } = renderHookWithClient(() => useRetryExecution('workspace-1'))

await act(async () => {
await expect(
result().mutateAsync({ workflowId: 'workflow-1', executionId: 'execution-1' })
).rejects.toThrow('The failed block no longer exists in the current workflow')
})

unmount()
})

it('does not report success when the selected failed block never starts', async () => {
mockRequestJson.mockResolvedValue(failedLogDetail())
mockFetch.mockResolvedValue({
ok: true,
body: executionStream([
{ type: 'execution:started', data: { startTime: '2026-08-31T00:00:00.000Z' } },
{ type: 'execution:completed', data: { success: true } },
]),
})

const { result, unmount } = renderHookWithClient(() => useRetryExecution('workspace-1'))

await act(async () => {
await expect(
result().mutateAsync({ workflowId: 'workflow-1', executionId: 'execution-1' })
).rejects.toThrow('Retry execution ended before the failed block could start')
})

unmount()
})

it('does not execute when the source run has multiple terminating failures', async () => {
mockRequestJson.mockResolvedValue(
failedLogDetail([
{ id: 'failure-1', name: 'One', type: 'function', status: 'error', blockId: 'one' },
{ id: 'failure-2', name: 'Two', type: 'function', status: 'error', blockId: 'two' },
])
)

const { result, unmount } = renderHookWithClient(() => useRetryExecution('workspace-1'))

await act(async () => {
await expect(
result().mutateAsync({ workflowId: 'workflow-1', executionId: 'execution-1' })
).rejects.toThrow('multiple terminating failures')
})
expect(mockFetch).not.toHaveBeenCalled()

unmount()
})
})
47 changes: 42 additions & 5 deletions apps/sim/hooks/queries/logs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,11 @@ import {
type WorkflowStats,
} from '@/lib/api/contracts/logs'
import { cancelWorkflowExecutionContract } from '@/lib/api/contracts/workflows'
import { readSSEEvents } from '@/lib/core/utils/sse'
import { getEndDateFromTimeRange, getStartDateFromTimeRange } from '@/lib/logs/filters'
import { parseQuery, queryToApiParams } from '@/lib/logs/query-parser'
import { resolveRetryTarget } from '@/lib/logs/retry'
import type { ExecutionEvent } from '@/lib/workflows/executor/execution-events'
import type { TimeRange } from '@/stores/logs/filters/types'

export type { DashboardStatsResponse, WorkflowStats }
Expand Down Expand Up @@ -430,7 +433,7 @@ export function useCancelExecution(workspaceId: string) {
})
}

export function useRetryExecution() {
export function useRetryExecution(workspaceId: string) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async ({
Expand All @@ -440,6 +443,12 @@ export function useRetryExecution() {
workflowId: string
executionId: string
}) => {
const detail = await fetchLogByExecutionId(workspaceId, executionId)
const retryTarget = resolveRetryTarget(detail.executionData)
if (!retryTarget.success) {
throw new Error(retryTarget.error)
}

// boundary-raw-fetch: stream response, body is a ReadableStream consumed one chunk at a time
const res = await fetch(`/api/workflows/${workflowId}/execute`, {
method: 'POST',
Expand All @@ -448,16 +457,44 @@ export function useRetryExecution() {
inputFromExecutionId: executionId,
triggerType: 'manual',
stream: true,
runFromBlock: {
startBlockId: retryTarget.startBlockId,
executionId,
},
}),
})
if (!res.ok) {
const data = await res.json().catch(() => ({}))
throw new Error(data.error || 'Failed to retry execution')
}
const reader = res.body?.getReader()
if (reader) {
await reader.read()
reader.cancel()
if (!res.body) {
throw new Error('Retry execution did not return a stream')
}

const reader = res.body.getReader()
let retryStarted = false
try {
await readSSEEvents<ExecutionEvent>(reader, {
onEvent: (event) => {
if (event.type === 'execution:error') {
throw new Error(event.data.error)
}
if (event.type === 'block:started' && event.data.blockId === retryTarget.startBlockId) {
retryStarted = true
return true
}
if (event.type === 'execution:completed' || event.type === 'execution:paused') {
return true
}
},
})
} finally {
await reader.cancel().catch(() => undefined)
reader.releaseLock()
}

if (!retryStarted) {
throw new Error('Retry execution ended before the failed block could start')
}
return { started: true }
},
Expand Down
Loading
Loading