Skip to content

Commit e0b95cc

Browse files
committed
fix(resume): stop shipping the execution snapshot to the resume page
1 parent 0a19cdf commit e0b95cc

9 files changed

Lines changed: 155 additions & 34 deletions

File tree

‎apps/sim/app/(interfaces)/resume/[workflowId]/[executionId]/resume-page-client.tsx‎

Lines changed: 1 addition & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -106,22 +106,6 @@ function StatusBadge({ status }: { status: string }) {
106106
)
107107
}
108108

109-
function getBlockNameFromSnapshot(
110-
executionSnapshot: { snapshot?: string } | null | undefined,
111-
blockId: string | undefined
112-
): string | null {
113-
if (!executionSnapshot?.snapshot || !blockId) return null
114-
try {
115-
const parsed = JSON.parse(executionSnapshot.snapshot)
116-
const workflowState = parsed?.workflow
117-
if (!workflowState?.blocks || !Array.isArray(workflowState.blocks)) return null
118-
const block = workflowState.blocks.find((b: { id: string }) => b.id === blockId)
119-
return block?.metadata?.name || null
120-
} catch {
121-
return null
122-
}
123-
}
124-
125109
const DISPLAY_VALUE_PREVIEW_MAX_CHARS = 5000
126110

127111
function truncateForPreview(text: string): { text: string; truncated: boolean } {
@@ -697,13 +681,7 @@ export default function ResumeExecutionPage({
697681
selectedStatus === 'queued' ||
698682
(isHumanMode && hasInputFormat && (!isFormComplete || Object.keys(formErrors).length > 0))
699683

700-
const getBlockName = (pause: PausePointWithQueue) => {
701-
const pauseBlockId = pause.blockId || pause.triggerBlockId
702-
return (
703-
getBlockNameFromSnapshot(executionDetail?.executionSnapshot, pauseBlockId) ||
704-
'Human in the Loop'
705-
)
706-
}
684+
const getBlockName = (pause: PausePointWithQueue) => pause.blockName || 'Human in the Loop'
707685

708686
if (loadingExecution) {
709687
return (

‎apps/sim/app/api/resume/[workflowId]/[executionId]/route.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,4 +121,22 @@ describe('GET /api/resume/[workflowId]/[executionId]', () => {
121121
expect(response.status).toBe(403)
122122
expect(await response.json()).toEqual({ error: 'Insufficient workspace permissions' })
123123
})
124+
125+
it('leaves the execution snapshot out only when the resume page asks', async () => {
126+
const pageRead = await GET(
127+
createMockRequest(
128+
'GET',
129+
undefined,
130+
{},
131+
'http://localhost/api/resume/workflow-1/execution-1?includeSnapshot=false'
132+
),
133+
createRouteContext(params)
134+
)
135+
const apiRead = await GET(request(), createRouteContext(params))
136+
137+
const pageBody = await pageRead.json()
138+
expect(pageBody).not.toHaveProperty('executionSnapshot')
139+
expect(pageBody.pausePoints).toEqual(detail.pausePoints)
140+
expect((await apiRead.json()).executionSnapshot).toEqual(detail.executionSnapshot)
141+
})
124142
})

‎apps/sim/app/api/resume/[workflowId]/[executionId]/route.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { omit } from '@sim/utils/object'
12
import { resumeWorkflowExecutionContract } from '@/lib/api/contracts/workflows'
23
import { defineInternalJsonRoute, internalRateLimits } from '@/lib/api/server/routes'
34
import { internalWorkflowErrorPolicies, internalWorkflowReadAuth } from '@/lib/workflows/api'
@@ -15,14 +16,15 @@ export const GET = defineInternalJsonRoute({
1516
reason: 'Preserve existing authenticated resume-detail behavior',
1617
}),
1718
errorPolicy: internalWorkflowErrorPolicies.concealWorkflowAuthorization,
18-
mapInput: ({ params }) => ({
19+
mapInput: ({ params, query }) => ({
1920
workflowId: params.workflowId,
2021
executionId: params.executionId,
22+
includeSnapshot: query.includeSnapshot,
2123
}),
2224
useCase: readPausedWorkflowExecution,
2325
responseHeaders: () => ({ 'Cache-Control': 'private, no-store' }),
24-
present: (executionDetail) => ({
25-
...executionDetail,
26+
present: (executionDetail, { input }) => ({
27+
...(input.includeSnapshot ? executionDetail : omit(executionDetail, ['executionSnapshot'])),
2628
pausePoints: executionDetail.pausePoints.map((pausePoint) => ({ ...pausePoint })),
2729
queue: executionDetail.queue.map((queueEntry) => ({ ...queueEntry })),
2830
}),

‎apps/sim/hooks/queries/resume-execution.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,6 @@ export interface ResumeQueueEntrySummary {
4141

4242
export interface PausePointWithQueue {
4343
contextId: string
44-
triggerBlockId?: string
4544
blockId?: string
4645
response: any
4746
registeredAt: string
@@ -51,6 +50,7 @@ export interface PausePointWithQueue {
5150
resumeLinks?: ResumeLinks
5251
queuePosition?: number | null
5352
latestResumeEntry?: ResumeQueueEntrySummary | null
53+
blockName?: string
5454
parallelScope?: any
5555
loopScope?: any
5656
pauseKind?: 'human' | 'time'
@@ -73,7 +73,6 @@ export interface PausedExecutionSummary {
7373
}
7474

7575
export interface PausedExecutionDetail extends PausedExecutionSummary {
76-
executionSnapshot: any
7776
queue: ResumeQueueEntrySummary[]
7877
}
7978

@@ -118,6 +117,7 @@ export function useResumeExecutionDetail(workflowId: string, executionId: string
118117
queryFn: async ({ signal }): Promise<PausedExecutionDetail> => {
119118
const raw = await requestJson(resumeWorkflowExecutionContract, {
120119
params: { workflowId, executionId },
120+
query: { includeSnapshot: false },
121121
signal,
122122
})
123123
// double-cast-allowed: contract models pause points as z.record; the resume UI uses the richer PausedExecutionDetail interface

‎apps/sim/lib/api/contracts/workflows.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
} from '@sim/workflow-types/workflow'
77
import { z } from 'zod'
88
import {
9+
booleanQueryFlagSchema,
910
privateSecretProvenanceBundleSchema,
1011
requiredFieldSchema,
1112
workflowIdSchema,
@@ -442,6 +443,15 @@ export const resumeExecutionParamsSchema = z.object({
442443
executionId: z.string().min(1),
443444
})
444445

446+
/**
447+
* `includeSnapshot=false` leaves out the execution snapshot, which carries every
448+
* block's output and can run to many megabytes. The resume page asks for that;
449+
* API callers keep the documented default of receiving it.
450+
*/
451+
export const resumeExecutionQuerySchema = z.object({
452+
includeSnapshot: booleanQueryFlagSchema.optional().default(true),
453+
})
454+
445455
export const resumeExecutionContextParamsSchema = z.object({
446456
workflowId: z.string().min(1),
447457
executionId: z.string().min(1),
@@ -959,9 +969,12 @@ export const resumeWorkflowExecutionContract = defineRouteContract({
959969
method: 'GET',
960970
path: '/api/resume/[workflowId]/[executionId]',
961971
params: resumeExecutionParamsSchema,
972+
query: resumeExecutionQuerySchema,
962973
response: {
963974
mode: 'json',
964-
schema: pausedWorkflowExecutionDetailSchema,
975+
schema: pausedWorkflowExecutionDetailSchema.extend({
976+
executionSnapshot: z.unknown().optional(),
977+
}),
965978
},
966979
})
967980

‎apps/sim/lib/workflows/application/read-paused-workflow-execution.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import { PauseResumeManager } from '@/lib/workflows/executor/human-in-the-loop-m
77
export interface ReadPausedWorkflowExecutionInput {
88
workflowId: string
99
executionId: string
10+
/** Whether the presenting surface returns the execution snapshot; the read loads it either way. */
11+
includeSnapshot?: boolean
1012
}
1113

1214
export const readPausedWorkflowExecution = defineAuthorizedWorkflowUseCase({
@@ -19,6 +21,6 @@ export const readPausedWorkflowExecution = defineAuthorizedWorkflowUseCase({
1921
executionId: input.executionId,
2022
})
2123
if (!detail) throw new OrchestrationError('not_found', 'Paused execution not found')
22-
return detail
24+
return PauseResumeManager.namePausePoints(detail)
2325
},
2426
})

‎apps/sim/lib/workflows/executor/human-in-the-loop-manager.ts‎

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ import type {
8080
import { hasExecutionResult } from '@/executor/utils/errors'
8181
import { filterOutputForLog } from '@/executor/utils/output-filter'
8282
import { projectResolvedSecretDiagnosticError } from '@/executor/utils/resolved-secret-content-projection'
83+
import { extractBaseBlockId } from '@/executor/utils/subflow-node-id-codec'
8384
import type { SerializedConnection } from '@/serializer/types'
8485

8586
/**
@@ -396,6 +397,8 @@ interface ResumeQueueEntrySummary {
396397
interface PausePointWithQueue extends PausePoint {
397398
queuePosition?: number | null
398399
latestResumeEntry?: ResumeQueueEntrySummary | null
400+
/** The paused block's name from the snapshot's workflow, set by {@link PauseResumeManager.namePausePoints}. */
401+
blockName?: string
399402
}
400403

401404
interface PausedExecutionSummary {
@@ -3608,12 +3611,13 @@ export class PauseResumeManager {
36083611
contextId: string
36093612
}): Promise<PauseContextDetail | null> {
36103613
const { workflowId, executionId, contextId } = options
3611-
const detail = await PauseResumeManager.getPausedExecutionDetail({ workflowId, executionId })
3614+
const loaded = await PauseResumeManager.getPausedExecutionDetail({ workflowId, executionId })
36123615

3613-
if (!detail) {
3616+
if (!loaded) {
36143617
return null
36153618
}
36163619

3620+
const detail = omit(PauseResumeManager.namePausePoints(loaded), ['executionSnapshot'])
36173621
const pausePoint = detail.pausePoints.find((point) => point.contextId === contextId)
36183622
if (!pausePoint) {
36193623
return null
@@ -3628,7 +3632,7 @@ export class PauseResumeManager {
36283632
// are already returned via `pausePoint` below; strip them from
36293633
// `execution.pausePoints` so a large HITL payload isn't duplicated in full
36303634
// within the same response.
3631-
const execution: PausedExecutionDetail = {
3635+
const execution: PausedExecutionSummary = {
36323636
...detail,
36333637
pausePoints: detail.pausePoints.map(({ display, inputFields, ...point }) =>
36343638
point.response ? { ...point, response: { ...point.response, data: undefined } } : point
@@ -3643,6 +3647,35 @@ export class PauseResumeManager {
36433647
}
36443648
}
36453649

3650+
/**
3651+
* Names each pause point after its block in the snapshot's serialized workflow.
3652+
* The snapshot carries every block's output and can run to many megabytes, so
3653+
* readers resolve names here once instead of shipping the snapshot to a client.
3654+
*/
3655+
static namePausePoints<T extends PausedExecutionDetail>(detail: T): T {
3656+
const blockNames = new Map<string, string>()
3657+
try {
3658+
const workflow = toRecord(toRecord(JSON.parse(detail.executionSnapshot.snapshot)).workflow)
3659+
for (const block of Array.isArray(workflow.blocks) ? workflow.blocks : []) {
3660+
if (!isRecordLike(block) || typeof block.id !== 'string') continue
3661+
const name = toRecord(block.metadata).name
3662+
if (typeof name === 'string' && name) blockNames.set(block.id, name)
3663+
}
3664+
} catch (error) {
3665+
logger.warn('Could not read block names from paused execution snapshot', {
3666+
executionId: detail.executionId,
3667+
error: toError(error).message,
3668+
})
3669+
}
3670+
return {
3671+
...detail,
3672+
pausePoints: detail.pausePoints.map((point) => {
3673+
const blockName = blockNames.get(extractBaseBlockId(point.blockId ?? point.contextId))
3674+
return blockName ? { ...point, blockName } : point
3675+
}),
3676+
}
3677+
}
3678+
36463679
static async processQueuedResumes(parentExecutionId: string, workflowId: string): Promise<void> {
36473680
let pendingEntry: {
36483681
entry: typeof resumeQueue.$inferSelect

‎apps/sim/lib/workflows/executor/pause-persistence.integration.ts‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import { db } from '@sim/db'
77
import {
88
pausedExecutions,
9+
permissions,
910
user,
1011
workflow,
1112
workflowDeploymentVersion,
@@ -24,6 +25,7 @@ import {
2425
} from '@/lib/billing/core/attribution'
2526
import { LoggingSession } from '@/lib/logs/execution/logging-session'
2627
import type { WorkflowState } from '@/lib/logs/types'
28+
import { readPausedWorkflowExecution } from '@/lib/workflows/application/read-paused-workflow-execution'
2729
import {
2830
getWorkflowExecutionStatus,
2931
readPausedRunPoints,
@@ -154,6 +156,13 @@ beforeAll(async () => {
154156
ownerId: ids.owner,
155157
billedAccountUserId: ids.owner,
156158
})
159+
await db.insert(permissions).values({
160+
id: generateId(),
161+
entityType: 'workspace',
162+
entityId: ids.workspace,
163+
userId: ids.owner,
164+
permissionType: 'admin',
165+
})
157166
await db.insert(workflow).values({
158167
id: ids.workflow,
159168
userId: ids.owner,
@@ -175,6 +184,7 @@ afterAll(async () => {
175184
await db
176185
.delete(workflowExecutionSnapshots)
177186
.where(eq(workflowExecutionSnapshots.workflowId, ids.workflow))
187+
await db.delete(permissions).where(eq(permissions.entityId, ids.workspace))
178188
await deleteWorkspaceFixture(db, eq(workspace.id, ids.workspace))
179189
await db.delete(user).where(eq(user.id, ids.owner))
180190
})
@@ -496,3 +506,65 @@ describe('readPausedRunPoints', () => {
496506
})
497507
})
498508
})
509+
510+
describe('resume page reads', () => {
511+
/** Gives the published snapshot a workflow naming the paused block, as a real run's carries. */
512+
async function nameApprovalBlockInSnapshot(executionId: string) {
513+
const [row] = await db
514+
.select({ executionSnapshot: pausedExecutions.executionSnapshot })
515+
.from(pausedExecutions)
516+
.where(eq(pausedExecutions.executionId, executionId))
517+
const seed = row.executionSnapshot as { snapshot: string; triggerIds: string[] }
518+
const snapshot = {
519+
...JSON.parse(seed.snapshot),
520+
workflow: { blocks: [{ id: CONTEXT_ID, metadata: { name: 'Approval' } }] },
521+
}
522+
await db
523+
.update(pausedExecutions)
524+
.set({ executionSnapshot: { ...seed, snapshot: JSON.stringify(snapshot) } })
525+
.where(eq(pausedExecutions.executionId, executionId))
526+
}
527+
528+
it('names every parallel branch point from the snapshot and keeps the snapshot out of the pause context', async () => {
529+
const registry = registryWithResolvedSecret()
530+
const executionId = await publishPausedRun([
531+
humanBranchPoint(0, registry),
532+
humanBranchPoint(1, registry),
533+
])
534+
await nameApprovalBlockInSnapshot(executionId)
535+
536+
const detail = await readPausedWorkflowExecution.execute({
537+
principal: { kind: 'session', userId: ids.owner, sessionId: generateId() },
538+
input: { workflowId: ids.workflow, executionId },
539+
})
540+
const context = await PauseResumeManager.getPauseContextDetail({
541+
workflowId: ids.workflow,
542+
executionId,
543+
contextId: BRANCH_IDS[1],
544+
})
545+
546+
expect(detail.pausePoints.map((point) => point.blockName)).toEqual(['Approval', 'Approval'])
547+
expect(context?.pausePoint.blockName).toBe('Approval')
548+
expect(context?.execution.pausePoints.map((point) => point.blockName)).toEqual([
549+
'Approval',
550+
'Approval',
551+
])
552+
expect(JSON.stringify(context)).not.toContain(SNAPSHOT_SENTINEL)
553+
})
554+
555+
it('falls back to no block name when the snapshot cannot be read', async () => {
556+
const executionId = await publishPausedRun([humanBranchPoint(0, registryWithResolvedSecret())])
557+
await db
558+
.update(pausedExecutions)
559+
.set({ executionSnapshot: { snapshot: '{not json', triggerIds: [] } })
560+
.where(eq(pausedExecutions.executionId, executionId))
561+
562+
const context = await PauseResumeManager.getPauseContextDetail({
563+
workflowId: ids.workflow,
564+
executionId,
565+
contextId: BRANCH_IDS[0],
566+
})
567+
568+
expect(context?.pausePoint).not.toHaveProperty('blockName')
569+
})
570+
})

‎packages/testing/src/mocks/human-in-the-loop-manager.mock.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ const pauseResumeManagerMockFns = {
5858
mockGetPausedExecutionById: vi.fn(),
5959
mockGetPausedExecutionDetail: vi.fn(),
6060
mockGetPauseContextDetail: vi.fn(),
61+
mockNamePausePoints: vi.fn(<T>(detail: T): T => detail),
6162
mockProcessQueuedResumes: vi.fn(),
6263
}
6364

@@ -69,9 +70,10 @@ const pauseResumeManagerMockFns = {
6970
* `ResumeAdmissionError` (non-retryable) on mismatch.
7071
* - `mockUpdateResumeOutputInAggregationBuffers` rewrites the paused loop/parallel output in place.
7172
* - `mockComputeEarliestResumeAt` returns the earliest valid `time` pause `resumeAt` (or `null`).
73+
* - `mockNamePausePoints` returns the detail it was given, so a mocked detail reads back as-is.
7274
*
7375
* `mockCreateResumeAttemptTimeoutController` and `mockExtractResumeBillingAttributionFromSnapshot`
74-
* are bare, as is every `PauseResumeManager` static (`mockProcessQueuedResumes`,
76+
* are bare, as is every other `PauseResumeManager` static (`mockProcessQueuedResumes`,
7577
* `mockStartResumeExecution`, `mockGetPausedExecutionDetail`, …).
7678
*
7779
* @example
@@ -221,6 +223,7 @@ export const humanInTheLoopManagerMock = {
221223
getPausedExecutionById: pauseResumeManagerMockFns.mockGetPausedExecutionById,
222224
getPausedExecutionDetail: pauseResumeManagerMockFns.mockGetPausedExecutionDetail,
223225
getPauseContextDetail: pauseResumeManagerMockFns.mockGetPauseContextDetail,
226+
namePausePoints: pauseResumeManagerMockFns.mockNamePausePoints,
224227
processQueuedResumes: pauseResumeManagerMockFns.mockProcessQueuedResumes,
225228
},
226229
}

0 commit comments

Comments
 (0)