Skip to content

Add tenant-scoped folders to Media - #1419

Open
busbyk wants to merge 9 commits into
mainfrom
media-folders-tenant-scoped
Open

busbyk wants to merge 9 commits into
mainfrom
media-folders-tenant-scoped

Conversation

@busbyk

@busbyk busbyk commented Oct 19, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Editors can organize Media into folders in the admin (the SAC use case in #307: Bios/, Blog Images/), and each avalanche center sees and uses only its own folders.

Payload generates a single payload-folders collection with no tenant field, readable and writable by any logged-in user. This PR makes it tenant-scoped through the root folders config's collectionOverrides. ADR 023 explains each piece. Payload marks folders beta, so re-check folder browsing after Payload upgrades.

This replaces #1147 (Add tenant-scoped folder organization to Media), which was far behind main and scoped only the folder list views.

Payload patch: Folder column

Payload's Folder list column (FolderTableCellClient in @payloadcms/ui) had two problems that showed up on the preview:

  • Slow: each row fetched its folder in its own request, and rows with no folder fetched the whole folder list. A 10-row Media page sent 10 extra requests, about 1.7s each on the preview.
  • Stale after bulk edit: the cell kept the first folder name it loaded, so after Edit → Folder → Save the column showed the old folder until a full reload.

patches/@[email protected] rewrites that one file. It loads every row's folder in one batched request (the loader relationship columns already use), skips the request for rows with no folder, and shows the row's current folder after a refresh. __tests__/client/patches/folderTableCell.client.test.tsx covers all three.

This follows the same pattern as #1253 — Patch Payload to parse multipart saves that arrive without Content-Length: report it upstream, open the fix as a PR against Payload's 3.x branch, and delete the patch and its test once a Payload release includes it.

  • TODO: file the upstream Payload issue (after discussing with the team)
  • TODO: file our follow-up issue to upstream the fix and drop the patch (after discussing with the team)

Folder pages are still slower than other admin pages on the preview (about 2.2s against 1.1–1.6s). Most of every admin page's time is Payload reloading the logged-in user about five times per request, which this PR doesn't change.

Related Issues

Fixes #307
Supersedes #1147

Key Changes

  • Tenant-scoped folders (src/collections/Folders/): tenant field, selected-tenant base filter, and access on Media permissions narrowed to the selected tenant. Without the narrowing, a SAC admin could list, rename and delete NWAC's folders over REST.
  • Server-side guards: validateFolderTenant (on folders and Media) refuses filing media in, or nesting a folder under, another center's folder, and moving filed media to another center. keepFolderTenant keeps a folder's tenant fixed.
  • No Browse by Folder. The root browseByFolder is off, which removes the nav button (it also showed on the dashboard) and the cross-collection /admin/browse-by-folder view. Media is the only folder-enabled collection, so Media → By Folder covers it. Turn it back on if Documents gets folders.
  • Folder column on Media. Payload's "Choose from existing" media picker has no folder browsing, so Folder is now a default Media column, and Filters → Folder narrows the picker to one folder. Default columns only apply to users who haven't saved their own column choice.
  • filterByTenantID: inside a folder, Payload loads contents through a join that can't query tenant.slug, so opening any folder threw QueryError. Media and folders now filter by tenant ID.
  • Bulk edit hides internal fields (src/plugins/disableBulkEditOfHiddenFields.ts): bulk edit offered Content Hash, Blur Data Url, Prefix and _objectKey, and bulk-changing Prefix or _objectKey would break file URLs. Fields hidden from the admin are now excluded everywhere, so Media's bulk edit offers Avalanche Center, Alt and Folder.
  • Deprovisioning: folders are deleted with their tenant. A separate commit adds stationPages, galleries and form-submissions, which were missing, so deleting any tenant failed on main.
  • Payload patch for the Folder column (patches/@[email protected], registered in package.json / pnpm-lock.yaml): one batched folder lookup per page instead of one per row, and the column follows bulk edits. See Payload patch: Folder column.
  • Seed, MCP, migration: a "Brand" folder per center; folders excluded from MCP; additive add_media_folders migration.

How to test

  1. rm -f dev.db*, pnpm seed, and log in as [email protected] / localpass.
  2. Media → By Folder shows only SAC's "Brand" folder. Create a folder, open it, and move a media item into it from the item's No Folder button.
  3. Bulk filing: in All Media, select several items → Edit → Folder → pick a folder → Save. The Folder column shows the new folder as soon as the drawer closes, without a reload.
  4. As [email protected] with NWAC selected, only NWAC's folders show in Media → By Folder. The nav has no Browse by Folder button, and /admin/browse-by-folder returns 404.
  5. As the SAC admin, open a biography, remove the Photo, and click Choose from existing: the picker shows a Folder column, and Filters → Folder → equals → Blog Images lists only that folder's images.
  6. As the SAC admin in the browser console: /api/payload-folders lists only SAC folders, PATCH/DELETE on an NWAC folder returns 403, and PATCH /api/media/<id> with an NWAC folder returns 400.

pnpm test (2407 passing, including new folders, folderAccess, disableBulkEditOfHiddenFields and folderTableCell suites), tsc, lint, fallow:audit and drift:check pass. A Local API script on a seeded copy also confirmed every cross-tenant write is refused and deleting a tenant removes its folders cleanly.

Screenshots / Demo video

Demo: https://www.loom.com/share/e7193d714db84bc2b7f2283fea5ba2c2

Each center sees only its own folders

Super admin with NWAC selected: Media by folder
Super admin on NWAC, Media by folder

Filing a media item

Move-to-folder picker (SAC folders only)Inside SAC's Brand folder
Move-to-folder pickerSAC Brand folder contents

Bulk filing with Edit → Folder

Bulk edit fields (internals hidden)Folder picker in bulk editResult: three images in Blog Images
Bulk edit field listBulk edit folder pickerBlog Images folder after bulk edit

Migration Explanation

20261019_180035_add_media_folders is additive: it creates payload_folders and payload_folders_folder_type, and adds a nullable folder_id to media (plus a rel column on payload_locked_documents_rels). Existing media keeps working everywhere and starts unfiled; it appears under All Media, not at the root of By Folder.

migrate:create drops ON DELETE from ALTER ... REFERENCES, so it was added by hand to match push mode. down() then up() on a seeded copy kept every media row. The migrate:check warnings are only those ON DELETE clauses and the two ADD statements. Details are in the _explanation.md.

Future enhancements / Questions

  • The cross-tenant REST gap exists outside folders. byTenantRole returns true for the selected tenant, so a SAC admin can list other centers' redirects over REST, and REST creates accept an explicit foreign tenant. Fixed for folders only; the general fix deserves its own issue.
  • With no center selected, a super admin's By Folder shows every center's folders with nothing to tell them apart. A folder card shows only its name, and Payload offers no slot to label, explain, or hide the By Folder tab. Hiding the folders instead left an unexplained empty view, which was worse. Center admins always have a center selected.
  • Folders on Documents is the natural follow-up (folders: true, filterByTenantID, validateFolderTenant).

🤖 Generated with Claude Code


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need.

@github-actions

github-actions Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Migration Safety Check

Found 7 potential issues:

20261028_180035_add_media_folders.ts

Warning (line 10): DELETE keyword detected - review for data loss

FOREIGN KEY (\`parent_id\`) REFERENCES \`payload_folders\`(\`id\`) ON UPDATE no action ON DELETE cascade

Warning (line 27): DELETE keyword detected - review for data loss

FOREIGN KEY (\`tenant_id\`) REFERENCES \`tenants\`(\`id\`) ON UPDATE no action ON DELETE set null,

Warning (line 28): DELETE keyword detected - review for data loss

FOREIGN KEY (\`folder_id\`) REFERENCES \`payload_folders\`(\`id\`) ON UPDATE no action ON DELETE set null

Warning (line 45): DELETE keyword detected - review for data loss

sql`ALTER TABLE \`media\` ADD \`folder_id\` integer REFERENCES payload_folders(id) ON DELETE set null;`,

Warning (line 45): ALTER keyword detected - review for data loss

sql`ALTER TABLE \`media\` ADD \`folder_id\` integer REFERENCES payload_folders(id) ON DELETE set null;`,

Warning (line 49): DELETE keyword detected - review for data loss

sql`ALTER TABLE \`payload_locked_documents_rels\` ADD \`payload_folders_id\` integer REFERENCES payload_folders(id) ON DELETE cascade;`,

Warning (line 49): ALTER keyword detected - review for data loss

sql`ALTER TABLE \`payload_locked_documents_rels\` ADD \`payload_folders_id\` integer REFERENCES payload_folders(id) ON DELETE cascade;`,

Review these patterns and add backup/restore logic if needed. See docs/migration-safety.md for guidance.

@github-actions

Copy link
Copy Markdown
Contributor

@busbyk
busbyk force-pushed the media-folders-tenant-scoped branch from 6f9c9aa to 88ae737 Compare October 20, 2026 03:26
@busbyk
busbyk requested a review from rchlfryn October 20, 2026 03:56
@busbyk
busbyk force-pushed the media-folders-tenant-scoped branch from a3f9b83 to 1c1a485 Compare October 21, 2026 06:18
@busbyk
busbyk force-pushed the media-folders-tenant-scoped branch from 1c1a485 to b369b9c Compare October 23, 2026 18:49
@busbyk
busbyk force-pushed the media-folders-tenant-scoped branch from b369b9c to 50f4fc0 Compare October 25, 2026 07:16
busbyk and others added 4 commits October 28, 2026 22:51
Deleting a tenant failed on SQLite's NOT NULL constraint because these
three tenant-scoped collections were missing from the deprovision list.
Form submissions go before forms, which they reference.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Enables Payload's folders on Media and folds the generated
payload-folders collection into our tenancy through the root folders
config's collectionOverrides:

- a tenant field, and a selected-tenant base filter by tenant ID, which
  Payload's folder joins can query (they cannot query tenant.slug)
- folder access on Media permissions, narrowed to the selected tenant so
  the REST API cannot list or edit another center's folders
- validateFolderTenant on folders and Media, refusing a folder, parent
  folder or tenant change that would mix tenants; keepFolderTenant keeps
  a folder's tenant fixed
- folders deleted with their tenant, seeded as a Brand folder per center,
  and left out of the MCP server

ADR 026 records the design.

Fixes #307

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Payload's bulk edit skips only fields with a top-level `hidden`, not
`admin.hidden`, so Media offered Content Hash, Blur Data Url, Prefix and
the storage plugin's _objectKey. Changing Prefix or _objectKey in bulk
would break file URLs. A last-run plugin sets `admin.disableBulkEdit` on
every field hidden from the admin, including those other plugins add.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Folder cards show only a name, so with no center selected every center's same-named folders looked identical. Folders now match nothing until a center is selected. The cross-collection Browse by Folder view and its nav button are off, since Media is the only folder-enabled collection.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
busbyk and others added 5 commits October 28, 2026 22:52
Hiding folders until a center was selected left By Folder empty, which Payload gives no way to explain or hide. Revert to listing every center's folders. Add Folder to Media's default columns so the Choose-from-existing picker, which has no folder browsing, shows each item's folder.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The snapshot predated main's station-columns migration, so the next migrate:create would have re-emitted it.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Payload's Folder list column (FolderTableCellClient in @payloadcms/ui) fetched each row's folder in its own request, and rows with no folder fetched the whole folder list. On the preview a 10-row Media page sent 10 extra requests at about 1.7s each. The cell also kept the first folder name it loaded, so after a bulk Edit → Folder → Save the column showed the old folder until a full reload.

The patch loads every row's folder through the list's batched relationship loader (one request per page), skips the request for rows with no folder, and derives the shown folder from the row data, keeping a local value only for a move made from the cell itself. The code is unchanged in Payload 3.91.0, so delete the patch and its test once a Payload release includes the fix.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Main landed 20261027_230050_add_provider_curriculum, so the folders migration moves to 20261028_180035 and its snapshot carries the providers curriculum tables. migrate:create --skip-empty generates nothing.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

@rchlfryn rchlfryn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LG - bummer about not being able to expose the tenant name on the By Folder view. Claude suggested adding the tenant to the title but I don't think its worth it since only super admins see this view. And there is a fix with using the tenant dropdown. Hopefully Payload fixes this 🤷🏼‍♀️


## Conclusion

Additive only. Existing media keep `folder_id` null, which Payload shows at the root of the folder view. The `migrate:check` warnings are the `ON DELETE` clauses and the two `ALTER TABLE ... ADD` statements, which drop nothing. `migrate:create` omits `ON DELETE` on `ALTER ... REFERENCES`, so it was added by hand (`set null` on `media.folder_id`, `cascade` on the locked-documents rel) to match the schema push mode creates.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This says exsisting media shows “at the root of the folder view”. The PR description says it appears under All Media, not at the root of By Folder. Could this line say that? Worth getting right here, since this file is what we read later.

+ const populatedName = !moved && folderValue && typeof folderValue === 'object' ? folderValue.name : undefined;
+ const loadedFolder = fromFolderID ? documents?.[folderCollectionSlug]?.[fromFolderID] : undefined;
+ useEffect(() => {
+ if (moved || !fromFolderID || populatedName || loadedFolder !== undefined || typeof getRelationships !== 'function') {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this cell ever renders outside a RelationshipProvider, getRelationships is undefined. This early return then skips the request, and the name falls through to Loading... (line 67) with nothing left to resolve it. The list view and join tables provide the loader today. But folders are beta, and this is a patched copy that’ll be easy to forget. Could we fall back to the old single-folder fetch, or at least to folder:noFolder, when there’s no loader?

* Returns the ID of the tenant selected by the 'payload-tenant' cookie, or null when no tenant is
* selected or the slug has no tenant document.
*/
export async function getTenantIDFromCookie(req: PayloadRequest): Promise<number | null> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude comment I am unsure about using caching here:
Each call here queries the tenants table, and it now runs on every folder read/update/delete access check plus Media’s baseListFilter. Payload works out permissions on every admin page load, and since the DB is remote libSQL, each lookup is a round trip. You mentioned folder pages are already the slow ones.

Could we cache it on the request? Payload passes the same req to all of a request’s access checks, and the cookie can’t change mid-request. Since getAccessResults runs collections in parallel, cache the promise so concurrent checks share one query:

req.context.selectedTenantID ??= lookUpTenantID(req, tenantSlug)
return req.context.selectedTenantID as Promise<number | null>

tenantField’s beforeChange does the same slug→ID lookup and could use this too.

This branch was previously deployed

1 inactive deployment
Preview — 97ab816e Deployed Oct 29, 2026 by busbyk via build #3172
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Folder structure for Media

2 participants