diff --git a/apps/sim/app/api/workflows/route.test.ts b/apps/sim/app/api/workflows/route.test.ts index 53ddf9390ee..dc99395b0e6 100644 --- a/apps/sim/app/api/workflows/route.test.ts +++ b/apps/sim/app/api/workflows/route.test.ts @@ -36,7 +36,7 @@ vi.mock('@/lib/workflows/defaults', () => ({ vi.mock('@/lib/workflows/persistence/utils', () => workflowsPersistenceUtilsMock) -import { POST } from '@/app/api/workflows/route' +import { GET, POST } from '@/app/api/workflows/route' describe('Workflows API Route - POST ordering', () => { afterAll(() => { @@ -103,3 +103,93 @@ 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) => + 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) + }) + + 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) + } + }) +}) diff --git a/apps/sim/app/api/workflows/route.ts b/apps/sim/app/api/workflows/route.ts index 6758f56c55d..2723504475c 100644 --- a/apps/sim/app/api/workflows/route.ts +++ b/apps/sim/app/api/workflows/route.ts @@ -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') @@ -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 }) @@ -58,9 +89,21 @@ export const GET = withRouteHandler(async (request: NextRequest) => { } } - const workflows = await listWorkflowsForUser({ userId, workspaceId, scope }) + const page = await listWorkflowsPageForUser({ + userId, + workspaceId, + scope, + limit, + cursorKeys, + }) - 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) diff --git a/apps/sim/lib/api/contracts/workflows.ts b/apps/sim/lib/api/contracts/workflows.ts index 5886725417c..8e43965914e 100644 --- a/apps/sim/lib/api/contracts/workflows.ts +++ b/apps/sim/lib/api/contracts/workflows.ts @@ -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' @@ -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 @@ -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.' + ), }), }, }) diff --git a/apps/sim/lib/workflows/queries.ts b/apps/sim/lib/workflows/queries.ts index 8a4b9a7a5b6..9b929753ec1 100644 --- a/apps/sim/lib/workflows/queries.ts +++ b/apps/sim/lib/workflows/queries.ts @@ -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 { + 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 @@ -353,23 +409,35 @@ export async function listWorkflowsForUser({ workspaceId?: string scope: WorkflowListScope }): Promise { - 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 { + const rows = await fetchWorkflowListRows({ userId, workspaceId, scope, limit, cursorKeys }) + const page = keysetPage(listWorkflowKeys, rows, limit) + return { data: page.data.map(toListItem), nextCursorKeys: page.nextCursorKeys } }