Skip to content

Commit a910b36

Browse files
committed
fix(folders): stop archived rows skewing sortOrder, hide them from admin, and cover the two untested modules
nextFolderSortOrder returned min - 1 over ALL rows including soft-deleted ones, so every delete ratcheted the floor further negative and never recovered — an archived folder at -400 forced the next new folder to -401 forever. Both minima (folders and child resources) now see only rows a user can still see, which is how the Files path has always worked. The admin workspace-folders endpoint counted and paginated soft-deleted folders, so an operator saw phantom folders and an inflated total, disagreeing with every user-facing list. Adds naming.test.ts and queries.test.ts. Both modules had zero tests and are mocked at every call site, so their bodies executed in no test anywhere. That left unasserted the two bug classes that caused real defects in the folder migration: the suffix sequence (must start at (1) and skip taken suffixes) and resourceType scoping on the id-keyed lookups, where a missing clause silently files a knowledge base under a table folder. Every assertion is mutation-checked. The first version of the sortOrder test was vacuous — for a root folder the parent condition is itself an isNull node, so a presence-only check passed with the soft-delete filter deleted; it now asserts the specific column.
1 parent 4793607 commit a910b36

6 files changed

Lines changed: 497 additions & 11 deletions

File tree

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
/**
2+
* @vitest-environment node
3+
*/
4+
import {
5+
createMockRequest,
6+
dbChainMockFns,
7+
queueTableRows,
8+
resetDbChainMock,
9+
schemaMock,
10+
} from '@sim/testing'
11+
import { beforeEach, describe, expect, it, vi } from 'vitest'
12+
13+
/**
14+
* The route composes `withAdminAuthParams`, so auth is bypassed by making that wrapper a
15+
* passthrough — the assertions here are about query construction, not the auth gate.
16+
*/
17+
vi.mock('@/app/api/v1/admin/middleware', () => ({
18+
withAdminAuthParams: (handler: unknown) => handler,
19+
}))
20+
21+
import { GET } from '@/app/api/v1/admin/workspaces/[id]/folders/route'
22+
23+
const WORKSPACE_ID = 'ws-1'
24+
const routeContext = { params: Promise.resolve({ id: WORKSPACE_ID }) }
25+
26+
function listRequest() {
27+
return createMockRequest(
28+
'GET',
29+
undefined,
30+
{},
31+
`http://localhost:3000/api/v1/admin/workspaces/${WORKSPACE_ID}/folders?limit=50&offset=0`
32+
)
33+
}
34+
35+
/** Flattens the nested `and(...)` objects the drizzle operator mocks produce. */
36+
function flattenConditions(condition: unknown): Array<Record<string, unknown>> {
37+
if (!condition || typeof condition !== 'object') return []
38+
const node = condition as Record<string, unknown>
39+
if (node.type === 'and' && Array.isArray(node.conditions)) {
40+
return node.conditions.flatMap(flattenConditions)
41+
}
42+
return [node]
43+
}
44+
45+
describe('admin workspace folders GET', () => {
46+
beforeEach(() => {
47+
vi.clearAllMocks()
48+
resetDbChainMock()
49+
})
50+
51+
/**
52+
* Both the count and the page must exclude soft-deleted folders. Without the filter an operator
53+
* inspecting a workspace sees folders that live in Recently Deleted and an inflated total, and
54+
* this endpoint disagrees with every user-facing folder list — all of which filter `deletedAt`.
55+
*/
56+
it('excludes soft-deleted folders from both the count and the page', async () => {
57+
queueTableRows(schemaMock.workspace, [{ id: WORKSPACE_ID }])
58+
queueTableRows(schemaMock.folder, [{ total: 0 }])
59+
queueTableRows(schemaMock.folder, [])
60+
61+
await GET(listRequest(), routeContext)
62+
63+
// Calls: [0] workspace lookup, then the count and page share one prebuilt condition.
64+
const folderWheres = dbChainMockFns.where.mock.calls.slice(1).map(([where]) => where)
65+
expect(folderWheres.length).toBeGreaterThanOrEqual(2)
66+
for (const where of folderWheres) {
67+
// Asserted on the COLUMN: `resourceType`/`workspaceId` are eq nodes, so a bare
68+
// "some isNull exists" check could pass on an unrelated clause.
69+
expect(
70+
flattenConditions(where).some(
71+
(node) => node.type === 'isNull' && node.column === schemaMock.folder.deletedAt
72+
)
73+
).toBe(true)
74+
}
75+
})
76+
77+
it('still scopes to the workspace and to workflow folders', async () => {
78+
queueTableRows(schemaMock.workspace, [{ id: WORKSPACE_ID }])
79+
queueTableRows(schemaMock.folder, [{ total: 0 }])
80+
queueTableRows(schemaMock.folder, [])
81+
82+
await GET(listRequest(), routeContext)
83+
84+
const where = dbChainMockFns.where.mock.calls[1]?.[0]
85+
const nodes = flattenConditions(where)
86+
expect(nodes.some((n) => n.type === 'eq' && n.right === WORKSPACE_ID)).toBe(true)
87+
expect(nodes.some((n) => n.type === 'eq' && n.right === 'workflow')).toBe(true)
88+
})
89+
})

apps/sim/app/api/v1/admin/workspaces/[id]/folders/route.ts

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
import { db } from '@sim/db'
1414
import { folder as folderTable, workspace } from '@sim/db/schema'
1515
import { createLogger } from '@sim/logger'
16-
import { and, count, eq } from 'drizzle-orm'
16+
import { and, count, eq, isNull } from 'drizzle-orm'
1717
import { adminV1ListWorkspaceFoldersContract } from '@/lib/api/contracts/v1/admin'
1818
import { parseRequest } from '@/lib/api/server'
1919
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
@@ -46,19 +46,24 @@ export const GET = withRouteHandler(
4646
return notFoundResponse('Workspace')
4747
}
4848

49+
/**
50+
* Soft-deleted folders are excluded. Without this the count and the page both include rows
51+
* sitting in Recently Deleted, so an operator inspecting a workspace sees phantom folders
52+
* and an inflated total — and the two disagree with every user-facing folder list, all of
53+
* which filter on `deletedAt`.
54+
*/
55+
const activeWorkflowFolders = and(
56+
eq(folderTable.workspaceId, workspaceId),
57+
eq(folderTable.resourceType, 'workflow'),
58+
isNull(folderTable.deletedAt)
59+
)
60+
4961
const [countResult, folders] = await Promise.all([
50-
db
51-
.select({ total: count() })
52-
.from(folderTable)
53-
.where(
54-
and(eq(folderTable.workspaceId, workspaceId), eq(folderTable.resourceType, 'workflow'))
55-
),
62+
db.select({ total: count() }).from(folderTable).where(activeWorkflowFolders),
5663
db
5764
.select()
5865
.from(folderTable)
59-
.where(
60-
and(eq(folderTable.workspaceId, workspaceId), eq(folderTable.resourceType, 'workflow'))
61-
)
66+
.where(activeWorkflowFolders)
6267
.orderBy(folderTable.sortOrder, folderTable.name)
6368
.limit(limit)
6469
.offset(offset),

apps/sim/lib/folders/lifecycle.test.ts

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,16 @@ import { createFolder, deleteFolder, restoreFolder, updateFolder } from '@/lib/f
6767

6868
const CHILD_TABLE = { name: 'child_table' }
6969

70+
/** Flattens the nested `and(...)` objects the drizzle operator mocks produce. */
71+
function flattenConditions(condition: unknown): Array<Record<string, unknown>> {
72+
if (!condition || typeof condition !== 'object') return []
73+
const node = condition as Record<string, unknown>
74+
if (node.type === 'and' && Array.isArray(node.conditions)) {
75+
return node.conditions.flatMap(flattenConditions)
76+
}
77+
return [node]
78+
}
79+
7080
/** Stand-in for the per-resource config; each test declares only the deltas it exercises. */
7181
function setConfig(overrides: Record<string, unknown> = {}) {
7282
resourceConfig.current = {
@@ -230,6 +240,43 @@ describe('createFolder', () => {
230240
expect(dbChainMockFns.values).toHaveBeenCalledWith(expect.objectContaining({ sortOrder: -3 }))
231241
})
232242

243+
it('ignores soft-deleted folders and resources when picking the new sortOrder', async () => {
244+
/**
245+
* `min - 1` means archived rows would ratchet the floor further negative on every delete and
246+
* never recover. Both minima must therefore see only rows a user can still see. Asserted on
247+
* the WHERE clauses because the mock returns whatever is queued regardless of the filter, so
248+
* an assertion on the resulting sortOrder alone would pass without either clause.
249+
*/
250+
setConfig({
251+
resourceType: 'workflow',
252+
countKey: 'workflows',
253+
sortOrderColumn: 'child.sortOrder',
254+
})
255+
queueTableRows(schemaMock.folder, [{ minSortOrder: 0 }])
256+
queueTableRows(CHILD_TABLE, [{ minSortOrder: 0 }])
257+
dbChainMockFns.returning.mockResolvedValueOnce([folderRow({ sortOrder: -1 })])
258+
259+
await createFolder({ ...baseCreate, resourceType: 'workflow' })
260+
261+
const [folderWhere, childWhere] = dbChainMockFns.where.mock.calls
262+
.slice(0, 2)
263+
.map(([where]) => where)
264+
265+
// Assert on the specific COLUMN, not merely that some isNull exists: for a root folder the
266+
// parent condition is itself `isNull(parentId)`, so a presence-only check passes with the
267+
// soft-delete filter deleted. That made the first version of this test vacuous.
268+
expect(
269+
flattenConditions(folderWhere).some(
270+
(node) => node.type === 'isNull' && node.column === schemaMock.folder.deletedAt
271+
)
272+
).toBe(true)
273+
expect(
274+
flattenConditions(childWhere).some(
275+
(node) => node.type === 'isNull' && node.column === 'child.archivedAt'
276+
)
277+
).toBe(true)
278+
})
279+
233280
it('starts at zero when the folder is the first thing in its location', async () => {
234281
queueTableRows(schemaMock.folder, [{ minSortOrder: null }])
235282
dbChainMockFns.returning.mockResolvedValueOnce([folderRow()])

apps/sim/lib/folders/lifecycle.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,14 +128,22 @@ export async function nextFolderSortOrder(
128128
? eq(folderTable.parentId, parentId)
129129
: isNull(folderTable.parentId)
130130

131+
/**
132+
* Soft-deleted rows are excluded from both minima. This function returns `min - 1` to put a
133+
* new folder at the top, so counting archived rows lets every delete ratchet the floor further
134+
* negative and never recover — an archived folder at -400 forces the next new folder to -401
135+
* forever. Only rows a user can actually see should influence the ordering. The Files path
136+
* (`workspace-file-folder-manager`) has always filtered this way.
137+
*/
131138
const folderMinPromise = tx
132139
.select({ minSortOrder: min(folderTable.sortOrder) })
133140
.from(folderTable)
134141
.where(
135142
and(
136143
eq(folderTable.workspaceId, workspaceId),
137144
eq(folderTable.resourceType, resourceType),
138-
folderParentCondition
145+
folderParentCondition,
146+
isNull(folderTable.deletedAt)
139147
)
140148
)
141149

@@ -147,6 +155,7 @@ export async function nextFolderSortOrder(
147155
and(
148156
eq(config.workspaceColumn, workspaceId),
149157
parentId ? eq(config.folderIdColumn, parentId) : isNull(config.folderIdColumn),
158+
isNull(config.deletedColumn),
150159
config.scope
151160
)
152161
)
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
/**
2+
* @vitest-environment node
3+
*/
4+
import { describe, expect, it } from 'vitest'
5+
import { deduplicateFolderName } from '@/lib/folders/naming'
6+
7+
interface SelectCall {
8+
where: unknown
9+
}
10+
11+
/**
12+
* Chainable stand-in for the injectable `tx`. `deduplicateFolderName` awaits after `.where()`,
13+
* so the sibling rows are returned there and the condition captured for inspection.
14+
*/
15+
function makeTx(siblingNames: string[]) {
16+
const selectCalls: SelectCall[] = []
17+
const tx = {
18+
select: () => ({
19+
from: () => ({
20+
where: (where: unknown) => {
21+
selectCalls.push({ where })
22+
return Promise.resolve(siblingNames.map((name) => ({ name })))
23+
},
24+
}),
25+
}),
26+
}
27+
return { tx: tx as never, selectCalls }
28+
}
29+
30+
/** Flattens the nested `and(...)` objects the drizzle operator mocks produce. */
31+
function flattenConditions(condition: unknown): Array<Record<string, unknown>> {
32+
if (!condition || typeof condition !== 'object') return []
33+
const node = condition as Record<string, unknown>
34+
if (node.type === 'and' && Array.isArray(node.conditions)) {
35+
return node.conditions.flatMap(flattenConditions)
36+
}
37+
return [node]
38+
}
39+
40+
function hasCondition(
41+
condition: unknown,
42+
predicate: (node: Record<string, unknown>) => boolean
43+
): boolean {
44+
return flattenConditions(condition).some(predicate)
45+
}
46+
47+
/**
48+
* The suffix shape is a cross-surface contract: the client's `nextUntitledFolderName` and
49+
* migration 0272's backfill both produce `"<name> (N)"` starting at (1). A server-side drift
50+
* either collides on `folder_workspace_resource_parent_name_active_unique` (23505 on a path the
51+
* user cannot retry) or renders a folder named differently depending on how it was created.
52+
* Nothing asserted this before — every caller mocks this module out.
53+
*/
54+
describe('deduplicateFolderName', () => {
55+
it('returns the requested name untouched when no sibling holds it', async () => {
56+
const { tx } = makeTx(['Other', 'Reports (1)'])
57+
58+
expect(await deduplicateFolderName(tx, 'ws-1', null, 'Reports', 'workflow')).toBe('Reports')
59+
})
60+
61+
it('starts the suffix at (1), not (2)', async () => {
62+
// A loop seeded at 2 — the shape of a bug already fixed twice in this feature — yields
63+
// "Reports (2)" here and silently diverges from the client and the migration.
64+
const { tx } = makeTx(['Reports'])
65+
66+
expect(await deduplicateFolderName(tx, 'ws-1', null, 'Reports', 'workflow')).toBe('Reports (1)')
67+
})
68+
69+
it('skips suffixes already taken rather than returning a colliding name', async () => {
70+
const { tx } = makeTx(['Reports', 'Reports (1)', 'Reports (2)'])
71+
72+
expect(await deduplicateFolderName(tx, 'ws-1', null, 'Reports', 'workflow')).toBe('Reports (3)')
73+
})
74+
75+
it('fills a gap in the suffix sequence instead of appending past it', async () => {
76+
const { tx } = makeTx(['Reports', 'Reports (2)'])
77+
78+
expect(await deduplicateFolderName(tx, 'ws-1', null, 'Reports', 'workflow')).toBe('Reports (1)')
79+
})
80+
81+
it('treats a name that only differs by suffix as a distinct base', async () => {
82+
// 'Reports (1)' is taken, but the request is for 'Reports (1)' itself — its first free
83+
// variant is 'Reports (1) (1)', not 'Reports (2)'.
84+
const { tx } = makeTx(['Reports (1)'])
85+
86+
expect(await deduplicateFolderName(tx, 'ws-1', null, 'Reports (1)', 'workflow')).toBe(
87+
'Reports (1) (1)'
88+
)
89+
})
90+
91+
/**
92+
* The sibling query defines the namespace the suffix is chosen within. Every clause below
93+
* mirrors one column of the partial unique index — dropping any of them counts the wrong rows
94+
* and either inflates the suffix or picks a name that is already taken.
95+
*/
96+
describe('sibling scoping', () => {
97+
it('scopes to workspace, resourceType, root parent, and active rows', async () => {
98+
const { tx, selectCalls } = makeTx([])
99+
100+
await deduplicateFolderName(tx, 'ws-1', null, 'Reports', 'knowledge_base')
101+
102+
expect(selectCalls).toHaveLength(1)
103+
const { where } = selectCalls[0]
104+
expect(hasCondition(where, (n) => n.type === 'eq' && n.right === 'ws-1')).toBe(true)
105+
// Without this a knowledge-base folder would count table folders as siblings.
106+
expect(hasCondition(where, (n) => n.type === 'eq' && n.right === 'knowledge_base')).toBe(true)
107+
// Root scope must be IS NULL, not eq(null), which matches nothing in SQL.
108+
expect(hasCondition(where, (n) => n.type === 'isNull')).toBe(true)
109+
})
110+
111+
it('scopes to the given parent when nested', async () => {
112+
const { tx, selectCalls } = makeTx([])
113+
114+
await deduplicateFolderName(tx, 'ws-1', 'parent-1', 'Reports', 'workflow')
115+
116+
expect(
117+
hasCondition(selectCalls[0].where, (n) => n.type === 'eq' && n.right === 'parent-1')
118+
).toBe(true)
119+
})
120+
121+
it('excludes soft-deleted siblings so an archived name is reusable', async () => {
122+
// The unique index is partial (WHERE deleted_at IS NULL), so counting archived siblings
123+
// would suffix a name that is actually free.
124+
const { tx, selectCalls } = makeTx([])
125+
126+
await deduplicateFolderName(tx, 'ws-1', null, 'Reports', 'workflow')
127+
128+
expect(
129+
flattenConditions(selectCalls[0].where).filter((n) => n.type === 'isNull')
130+
).toHaveLength(2)
131+
})
132+
})
133+
})

0 commit comments

Comments
 (0)