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
115 changes: 114 additions & 1 deletion apps/sim/app/api/workflows/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@ vi.mock('@/lib/workflows/defaults', () => ({

vi.mock('@/lib/workflows/persistence/utils', () => workflowsPersistenceUtilsMock)

import { POST } from '@/app/api/workflows/route'
import { listWorkflowsContract } from '@/lib/api/contracts/workflows'
import { cursorRoute, cursorScopeKey } from '@/lib/api/cursor-binding'
import { writeSortedCursor } from '@/app/api/v2/lib/response'
import { GET, POST } from '@/app/api/workflows/route'

describe('Workflows API Route - POST ordering', () => {
afterAll(() => {
Expand Down Expand Up @@ -103,3 +106,113 @@ describe('Workflows API Route - POST ordering', () => {
expect(dbChainMockFns.values).toHaveBeenCalledWith(expect.objectContaining({ sortOrder: 1 }))
})
})

/** One row of the workflow list, shaped as the `listColumns` projection. */
const workflowListRow = (id: string, sortOrder: number) => ({
id,
name: `Workflow ${id}`,
description: null,
workspaceId: 'ws-1',
folderId: null,
sortOrder,
createdAt: new Date(Date.UTC(2026, 0, 1, 0, sortOrder, 0)),
updatedAt: new Date(Date.UTC(2026, 0, 1, 0, sortOrder, 0)),
archivedAt: null,
locked: false,
forkSyncExcluded: false,
isDeployed: false,
})

describe('Workflows API Route - GET pagination', () => {
beforeEach(() => {
permissionsMockFns.mockWorkspaceExists.mockResolvedValue(true)
})

const getWorkflows = (searchParams: Record<string, string>) =>
GET(createMockRequest({ method: 'GET', url: '/api/workflows', searchParams }))

it('returns one page with nextCursor null when the workspace fits in a page', async () => {
queueTableRows(schemaMock.workflow, [workflowListRow('w-1', 1), workflowListRow('w-2', 2)])

const response = await getWorkflows({ workspaceId: 'ws-1' })
const data = await response.json()
expect(response.status).toBe(200)
expect(data.data).toHaveLength(2)
expect(data.nextCursor).toBeNull()
})

it('caps the page at limit and returns a cursor when more workflows remain', async () => {
const rows = Array.from({ length: 51 }, (_, i) => workflowListRow(`w-${i + 1}`, i + 1))
dbChainMockFns.limit.mockResolvedValueOnce(rows)

const response = await getWorkflows({ workspaceId: 'ws-1', limit: '50' })
const data = await response.json()
expect(response.status).toBe(200)
expect(data.data).toHaveLength(50)
expect(data.data[49].id).toBe('w-50')
expect(data.nextCursor).toEqual(expect.any(String))
})

/**
* A cursor minted under one scope must not resume under another: the keys
* name a position in the first scope's row set, and replaying them under a
* narrower filter would return a coherent page silently missing every match
* sorting before that position. The refusal happens at decode time, before
* the query runs — the same split the v2 workflow list test pins.
*
* A full page-two resume through `resumeKeyset` is deliberately not covered
* here: the mocked schema columns are plain strings, so the timestamp key's
* `column.getSQLType()` has nothing to call on (see `timestampKey.bind`).
* That path is covered at the SQL level by `lib/api/list-query.test.ts`
* (real drizzle columns) and needs a real Postgres read to prove end to end.
*/
it('refuses a cursor replayed under a different scope', async () => {
const rows = Array.from({ length: 3 }, (_, i) => workflowListRow(`w-${i + 1}`, i + 1))
dbChainMockFns.limit.mockResolvedValueOnce(rows)

const first = await getWorkflows({ workspaceId: 'ws-1', limit: '2' })
const firstData = await first.json()
expect(first.status).toBe(200)
expect(firstData.data).toHaveLength(2)
expect(firstData.nextCursor).toEqual(expect.any(String))

const replayed = await getWorkflows({
workspaceId: 'ws-1',
scope: 'archived',
cursor: firstData.nextCursor,
})
expect(replayed.status).toBe(400)
})

it('rejects a cursor that cannot be decoded', async () => {
const response = await getWorkflows({ workspaceId: 'ws-1', cursor: 'not-a-cursor' })
expect(response.status).toBe(400)
})

/**
* A cursor that decodes under the request's scope but carries keys that do
* not fit the position sort (three keys: sortOrder, createdAt, id) is a
* 400, not a 500: `resumeKeyset` throws an `OrchestrationError` for it,
* and the route maps that to a 400 around the paged read, mirroring the
* decode step. Minted with `writeSortedCursor` so the stamps are valid
* and only the key count is wrong.
*/
it('rejects a cursor whose keys do not fit the position sort', async () => {
const scope = cursorScopeKey(cursorRoute(listWorkflowsContract), {
workspaceId: 'ws-1',
scope: undefined,
})
const cursor = writeSortedCursor([1], 'position', 'asc', scope)
expect(cursor).toEqual(expect.any(String))

const response = await getWorkflows({ workspaceId: 'ws-1', cursor: cursor ?? '' })
expect(response.status).toBe(400)
})

it('rejects limit values outside 1-100', async () => {
for (const limit of ['0', '101', '2.5']) {
const response = await getWorkflows({ workspaceId: 'ws-1', limit })
expect(response.status).toBe(400)
}
})
})
65 changes: 60 additions & 5 deletions apps/sim/app/api/workflows/route.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
import { createLogger } from '@sim/logger'
import { assertFolderMutable, FolderLockedError } from '@sim/platform-authz/workflow'
import { type NextRequest, NextResponse } from 'next/server'
import { createWorkflowContract, workflowListQuerySchema } from '@/lib/api/contracts/workflows'
import {
createWorkflowContract,
listWorkflowsContract,
workflowListQuerySchema,
} from '@/lib/api/contracts/workflows'
import { cursorRoute, cursorScopeKey } from '@/lib/api/cursor-binding'
import type { CursorKey } from '@/lib/api/list-query'
import { parseRequest } from '@/lib/api/server'
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
import { OrchestrationError } from '@/lib/core/orchestration/types'
import { generateRequestId } from '@/lib/core/utils/request'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { captureServerEvent } from '@/lib/posthog/server'
import { performCreateWorkflow } from '@/lib/workflows/orchestration'
import { listWorkflowsForUser } from '@/lib/workflows/queries'
import { listWorkflowsPageForUser } from '@/lib/workflows/queries'
import { getUserEntityPermissions, workspaceExists } from '@/lib/workspaces/permissions/utils'
import { readSortedCursor, writeSortedCursor } from '@/app/api/v2/lib/response'
import { verifyWorkspaceMembership } from '@/app/api/workflows/utils'

const logger = createLogger('WorkflowAPI')
Expand All @@ -24,7 +32,30 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
{ status: 400 }
)
}
const { workspaceId, scope } = query.data
const { workspaceId, scope, limit, cursor } = query.data

// The list is keyset-paged in workspace (position) order. The cursor is
// stamped with the sort and filters it was minted under, so replaying it
// under different filters is a 400, not a page from a nonsense position.
// `scope` carries `.default('active')`, so it is always present on the
// parsed query; binding it unconditionally would put a constant in every
// fingerprint and reject every cursor minted before the field existed.
// Decoded before the handler body: `readSortedCursor` throws an
// `OrchestrationError`, which is not an `HttpError`, so letting it bubble
// would surface a bad cursor as a 500.
const workflowCursorScope = cursorScopeKey(cursorRoute(listWorkflowsContract), {
workspaceId,
scope: scope === 'active' ? undefined : scope,
})
let cursorKeys: CursorKey[] | undefined
try {
cursorKeys = readSortedCursor(cursor, 'position', 'asc', workflowCursorScope)
} catch (error) {
if (error instanceof OrchestrationError) {
return NextResponse.json({ error: error.message }, { status: 400 })
}
throw error
}

try {
const auth = await checkSessionOrInternalAuth(request, { requireWorkflowId: false })
Expand Down Expand Up @@ -58,9 +89,33 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
}
}

const workflows = await listWorkflowsForUser({ userId, workspaceId, scope })
// `resumeKeyset` throws an `OrchestrationError` for a cursor whose
// keys do not fit this sort, and that throw reaches here, not the
// decode step above — map it to a 400 the same way, so a bad cursor
// is never a 500. Anything else rethrows into the outer catch.
let page
try {
page = await listWorkflowsPageForUser({
userId,
workspaceId,
scope,
limit,
cursorKeys,
})
} catch (error) {
if (error instanceof OrchestrationError) {
return NextResponse.json({ error: error.message }, { status: 400 })
}
throw error
}

return NextResponse.json({ data: workflows }, { status: 200 })
return NextResponse.json(
{
data: page.data,
nextCursor: writeSortedCursor(page.nextCursorKeys, 'position', 'asc', workflowCursorScope),
},
{ status: 200 }
)
} catch (error: any) {
const elapsed = Date.now() - startTime
logger.error(`Workflow fetch error after ${elapsed}ms`, error)
Expand Down
10 changes: 10 additions & 0 deletions apps/sim/lib/api/contracts/workflows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
workspaceIdSchema,
} from '@/lib/api/contracts/primitives'
import { defineRouteContract } from '@/lib/api/contracts/types'
import { v2PaginationFields } from '@/lib/api/contracts/v2/shared'
import { MAX_WORKFLOW_EXECUTION_TIMEOUT_SECONDS } from '@/lib/billing/execution-timeout-defaults'
import { PRIVATE_SECRET_PROVENANCE_FIELD } from '@/lib/execution/private-tool-metadata'

Expand Down Expand Up @@ -238,6 +239,9 @@ export const workflowIdParamsSchema = z.object({
export const workflowListQuerySchema = z.object({
workspaceId: z.string().min(1).optional(),
scope: workflowScopeSchema.default('active'),
// Same page shape as the v2 workflow list: `limit` 1-100, default 50, and an
// opaque `cursor` minted by the previous page's `nextCursor`.
...v2PaginationFields(),
})

export type WorkflowListItem = z.output<typeof workflowListItemSchema>
Expand Down Expand Up @@ -719,6 +723,12 @@ export const listWorkflowsContract = defineRouteContract({
mode: 'json',
schema: z.object({
data: z.array(workflowListItemSchema),
nextCursor: z
.string()
.nullable()
.describe(
'Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages.'
),
}),
},
})
Expand Down
102 changes: 85 additions & 17 deletions apps/sim/lib/workflows/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,62 @@ function scopeCondition(
return and(base, isNull(workflow.archivedAt))
}

/** Keyset behind the workspace-ordered workflow list: manual position, then creation time, then id. */
const listWorkflowKeys = WORKFLOW_SORTS.position

interface FetchWorkflowListRowsInput {
userId: string
workspaceId?: string
scope: WorkflowListScope
limit?: number
cursorKeys?: CursorKey[]
}

/**
* Raw rows for {@link listWorkflowsForUser} and {@link listWorkflowsPageForUser}.
* With `limit`, reads one page past the cursor in workspace order (`limit + 1`)
* rows, so the caller can tell whether another page exists); without it, reads
* the whole set exactly as before. The paged read orders on the keyset
* expressions (millisecond-truncated `createdAt`) so the ordering is exactly
* the ordering a cursor can express — ordering on the raw column would
* re-admit the page's last row.
*/
async function fetchWorkflowListRows({
userId,
workspaceId,
scope,
limit,
cursorKeys,
}: FetchWorkflowListRowsInput): Promise<WorkflowListRow[]> {
const resumeAfter =
limit === undefined ? undefined : resumeKeyset(listWorkflowKeys, cursorKeys, 'asc')
const orderBy =
limit === undefined ? orderByClause : listOrderBy(keysetColumns(listWorkflowKeys), 'asc')

const selectPage = (where: SQL | undefined) => {
const query = db
.select(listColumns)
.from(workflow)
.where(where)
.orderBy(...orderBy)
return limit === undefined ? query : query.limit(limit + 1)
}

if (workspaceId) {
return selectPage(
and(scopeCondition(scope, eq(workflow.workspaceId, workspaceId)), resumeAfter)
)
}

const accessibleRows = await listAccessibleWorkspaceRowsForUser(userId, 'all')
const workspaceIds = accessibleRows.map((row) => row.workspace.id)
if (workspaceIds.length === 0) return []

return selectPage(
and(scopeCondition(scope, inArray(workflow.workspaceId, workspaceIds)), resumeAfter)
)
}

/**
* Lists workflows visible to a user as the contract wire shape, shared by the
* `GET /api/workflows` route and the workspace sidebar prefetch. Performs no auth
Expand All @@ -353,23 +409,35 @@ export async function listWorkflowsForUser({
workspaceId?: string
scope: WorkflowListScope
}): Promise<WorkflowListItem[]> {
if (workspaceId) {
const rows = await db
.select(listColumns)
.from(workflow)
.where(scopeCondition(scope, eq(workflow.workspaceId, workspaceId)))
.orderBy(...orderByClause)
return rows.map(toListItem)
}
const rows = await fetchWorkflowListRows({ userId, workspaceId, scope })
return rows.map(toListItem)
}

const accessibleRows = await listAccessibleWorkspaceRowsForUser(userId, 'all')
const workspaceIds = accessibleRows.map((row) => row.workspace.id)
if (workspaceIds.length === 0) return []
export interface WorkflowListPage {
data: WorkflowListItem[]
nextCursorKeys: CursorKey[] | null
}

const rows = await db
.select(listColumns)
.from(workflow)
.where(scopeCondition(scope, inArray(workflow.workspaceId, workspaceIds)))
.orderBy(...orderByClause)
return rows.map(toListItem)
/**
* One cursor page of the workflows visible to a user, in workspace order,
* for `GET /api/workflows`. Same rows and access rules as
* {@link listWorkflowsForUser}, but capped at `limit` rows past `cursorKeys`
* with the keys that resume the next page (`null` on the last page).
*/
export async function listWorkflowsPageForUser({
userId,
workspaceId,
scope,
limit,
cursorKeys,
}: {
userId: string
workspaceId?: string
scope: WorkflowListScope
limit: number
cursorKeys?: CursorKey[]
}): Promise<WorkflowListPage> {
const rows = await fetchWorkflowListRows({ userId, workspaceId, scope, limit, cursorKeys })
const page = keysetPage(listWorkflowKeys, rows, limit)
return { data: page.data.map(toListItem), nextCursorKeys: page.nextCursorKeys }
}