mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-16 21:08:17 +00:00
* feat: Sort Modes and Mine Filter for the Agent Marketplace List
Adds two query parameters to `GET /api/agents`:
- `sort` — one of newest | oldest | popular | author, validated against
an allowlist since the value reaches a `$sort`/`$lookup` pipeline.
- `mine=1` — narrows the list to agents authored by the caller, applied
on top of the ACL-resolved accessible set rather than instead of it.
`newest`/`oldest` remain a plain `.find()` but now order on `createdAt`
instead of `updatedAt`. This endpoint refreshes S3 avatars through
`updateAgent`, which advances `updatedAt` — the very field the cursor
compared against — so an agent could cross a page boundary mid-scroll
and drop out of the caller's flattened list. Two indexes back the new
ordering.
`popular` counts favorites through an equality `$lookup` and validates
tenancy after the join. `author` resolves the same contact the card
renders — support_contact, then the user holding the OWNER ACL grant —
so the ordering matches what the reader actually sees. Both compute
their key inside the pipeline, so the cursor compares against the
computed field and the key is stripped before the rows are returned;
the response shape is unchanged.
Behaviour note: a request that sends no `sort` now comes back ordered by
`createdAt` descending rather than `updatedAt` descending.
* feat: Denser Agent Marketplace Grid with Sort and Mine Controls
Rebuilds the marketplace chrome around a denser grid. The hero block
gives way to a sticky header carrying the title, a live agent count and
a compact search field; category tabs become pills; and the grid follows
the available width instead of a fixed two-column layout, so a wide
window shows more than two agents per row.
Adds two controls to the category header, next to the category they act
on: a sort dropdown and an "only agents I created" switch. Both mirror
into the URL (`?sort=`, `?mine=1`) so a filtered view can be linked and
restored, and the default sort is omitted from the URL to keep it clean.
Switching the filter on inside Top Picks moves to All, where authored
agents can actually appear, since nothing writes `is_promoted` yet.
Since `popular` recomputes its count per request, pinning or unpinning
invalidates only the popular pages, and marks them stale rather than
refetching under a reader who is mid-scroll.
* feat: Agent Marketplace Refresh with Shared-Layout Detail Morph
Clicking an agent card now expands that card into the details dialog instead
of fading an unrelated panel over the grid, and the dialog contracts back into
the card it came from.
The morph is a framer-motion shared-layout handoff with `layoutCrossfade`
disabled, so the projection hides the relegated card nodes itself: the card
keeps its box, the grid never reflows, and no field is ever drawn twice. Card
and dialog keep genuinely different layouts and only the fields they share
travel — surface, avatar, name, category pill, creator row and the blurb.
The pill moves from the card's upper right to the dialog's upper left, the
avatar grows, the name zooms between the two type sizes, the creator moves out
of the footer to under the name, and the blurb is handed over at the dialog's
width so the surface's clip reveals the lines the card had no room for. The
dialog's own controls — close, "About this agent", Pin, Copy Link, Start Chat —
are introduced after the geometry is under way and leave the way they came in.
The dialog's content lives inside the morphing surface, whose sections are
projection nodes, so nothing stretches or spills outside the expanding box.
`layoutDependency` pins measurement to selection changes, which keeps the
virtualized grid's per-scroll rerenders from measuring every card. The page dim
is owned by the grid rather than the dialog's overlay so it can run its full
range across a contraction that outlives the dialog's mount, and the source
card is raised above its neighbours until the surface is home.
`OGDialogContent` gains `bare` and `forceMount` so a caller can own a dialog's
geometry and animation while Radix keeps focus trapping, Escape, the scroll
lock and the aria wiring. Reduced motion skips the morph and opens the dialog
outright; focus still returns to the card that opened it.
Also in the marketplace header: the admin settings trigger takes the bordered
`outline` variant so it matches the search field beside it, and the search
field's clear button declares its own colour instead of inheriting the
document's, which made the glyph invisible in dark mode.
* style: Square Off the Search Clear Button's Hover Fill
Its hover fill inherited the button recipe's `rounded-lg`, which on a 32px
square read as a pill inside the search field; `rounded-md` keeps the chip
subordinate to the field's own 8px corner.
* fix: Adjudicate Review Findings on the Marketplace Refresh
Four demonstrated defects from the review round on a10b31c0:
Surface radius came from a literal 16px repeated at both morph endpoints, so
`--theme-surface-radius` could not move the marketplace's corners even though
every other surface follows it. The card and dialog surfaces now carry
`rounded-theme-surface`, and the projection — which can only hold a corner
steady while it scales if it owns the radius as a number — is fed the resolved
token, read once per morph rather than per card or per frame.
The morph's page dim restated `bg-black/80` in feature code, duplicating an
appearance decision that belongs to the dialog primitive. `OriginalDialog` now
exports `DIALOG_SCRIM_CLASS` and both the Radix overlay and the grid's animated
backdrop consume it, so the scrim has one owner again. The scrim's colour is
still a literal in the primitive: making it a theme role changes every dialog
in the app and is not this PR's to decide.
`ErrorDisplay` narrowed on `Error` and kept only `message`, but an `AxiosError`
*is* an `Error`, so `response.status`, `response.data` and `code` — the fields
the classification runs on — were discarded for every real request failure. A
500 was therefore labelled non-transient `generic` with automatic recovery
disabled, and 404s rendered as errors instead of the neutral empty state. Only
a bare string needs wrapping now. Its regression test delivers the failure the
way axios does, as an `Error` instance, which the previous object-literal
fixtures never exercised.
`useAutoRetry.retryNow` did not cancel the pending backoff: resetting `attempt`
to 0 while it was already 0 is a no-op, so the effect never re-ran, its timer
stayed armed, and the scheduled attempt still fired after a manual or
connectivity-driven retry had gone out — a duplicate request that also spent a
backoff step. The schedule is now a value that changes on every retry, so each
one cancels and restarts it.
* fix: Keep a Morphed Card's Corner on the Radius Token
The resolved radius was handed to the surfaces only for the duration of a
morph. The projection keeps a `borderRadius` once it owns it, so dropping the
value on the way out left a morphed card pinned to whatever the theme was when
it was opened, and a later theme change moved every corner in the grid except
that one. The list resolves the token once for all its cards instead and
re-resolves it when the theme rewrites the root.
* perf: Page the Marketplace's Popular and Author Sorts in the Database
Two demonstrated defects from the review round on a10b31c0.
`sort=popular` loaded every accessible agent into application memory on every
page, queried favorites for that complete id set, sorted the whole array in
JavaScript and then kept the requested slice, so a 32-item page scaled with the
whole marketplace and the next cursor repeated all of it. The ordering is now
split at the only place it can be: agents somebody favorited, which is at most
as large as the favorites themselves, and the count-0 tail, which is ordered by
`_id` alone and therefore pages as an indexed range scan with the limit applied
by the database. The favorite counts no longer carry a marketplace-sized `$in`,
and the count key is per tenant, so a missing and an explicitly null `tenantId`
are one tenant rather than two.
Measured on 300 accessible agents, 4 of them favorited, `limit: 10`: page one
returned 314 documents to the process before and 19 after, page two the same
314 before and 19 after. Walking the whole list at `limit: 7` produces the
identical id order in both implementations.
The `author` pipeline joined the owner ACL entry and the owner user in order to
sort by the resolved display name, projected neither, and left
`getListAgentsHandler` to await `attachOwnerContacts`, which queried the same
ACL entries and the same users again for the page it had just ordered. The
pipeline now resolves `owner_contact` on exactly the tiers
`resolveAgentOwnerContact` applies — a support contact means no owner contact,
and without a joined owner account there is none either, even with a
denormalized `authorName` — and marks the row. `attachOwnerContacts` skips
marked rows, strips the marker, and so performs no query at all for an
author-sorted page.
`$$REMOVE` is rejected by DocumentDB, so "no contact" arrives as an explicit
null the list method drops before the row leaves.
The dropped popular-sort test asserted that a row deleted between the candidate
scan and the full fetch still yielded a usable cursor; it drove that state by
mocking `Agent.find` for one call, which the single ordered segment no longer
performs.
* fix: Keep Throttled Loads Recovering and the Skeleton on the Radius Token
Two findings from the review round on cdb91f4.
The marketplace query deliberately retries a 408 and a 429 twice
(`data-provider/Agents/queries.ts`) and leaves the longer backoff to the error
card, but the card classified both as `generic`, where `autoRetry` is false —
so a throttled or timed-out load stopped recovering after those two attempts
even though every layer above had called it retryable. A 408 now takes the
`timeout` copy that already describes it, and a 429 gets its own transient
kind rather than borrowing "Server Error" for a status the server answered
deliberately.
`GridSkeleton`'s placeholder card kept `rounded-2xl` while the real card moved
to `rounded-theme-surface`, so under any theme that sets a different surface
radius the corners jumped the moment the skeleton was replaced.
* fix: Read the Author Sort's Owner From Agent ACL Entries
The author sort joined every ACL entry sharing the agent's _id and picked the earliest full-bit user entry, so a REMOTE_AGENT owner entry left behind by an ownership transfer decided both the sort key and owner_contact. attachOwnerContacts counts only AGENT entries, so an author-sorted row could name a different owner than the same agent's card in any other sort mode. The filter now asserts the resource type.
* chore: Drop the Marketplace Strings the Refresh Orphaned
The rewritten grid, card and error card no longer render the old detail panel's copy, so com_agents_description_card, com_agents_error_loading, com_agents_error_searching, com_agents_results_for and com_agents_see_more had no reader left and the unused-i18n-keys static check failed. Only the English file is edited; the other locales are automated.
* fix: Recover on Window Focus and Move the Marketplace Query Contract Into packages/api
Three findings from the review at 9f59cad8.\n\nThe list query's sort allowlist and mine normalization were behavior in a CJS controller, which api/ is not supposed to hold; resolveMarketplaceListQuery now owns the contract in packages/api beside AgentSortOption, and v1.js keeps the call.\n\nuseAutoRetry promised recovery when the view is looked at again but only listened for visibilitychange, so a window that lost and regained focus with the tab still visible never recovered - terminal once the backoff was spent. It now also tracks focus/blur, counted once per activation so a tab switch that fires both events retries once.\n\nThe aggregation predicate helpers returned Record<string, unknown>, which the repository prohibits for new code and which accepts any misspelled operator; they return a concrete expression union instead.
* fix: Move Owner-Contact Resolution Out of the CJS Service and Open Mine Links on All
`api/server/services/Agents/ownerContact.js` had grown the resolved-row filtering, the
marker cleanup and the owner ACL pipeline, all behaviour, inside `/api`. The service is
now the wiring the boundary asks for: `attachAgentOwnerContacts`
(`packages/api/src/agents/ownerContact.ts`) takes its database reads from the caller, and
the owner query itself is a data-schemas method, `getFirstOwnerIdsByResource`, beside the
`OWNER_ACL_PERMISSION_BITS` the marketplace's author sort already resolves against. The
aggregation casts stringified ids, because `$match` does no schema casting and a caller
outside data-schemas has no Mongoose ObjectId to hand it.
A restored or shared `/agents?mine=1` carries no path category, so it resolved to
`promoted` and answered the caller's own agents with the near-always-empty
promoted-and-mine intersection; turning the same filter on from Top Picks navigates to
`/agents/all`. It now defaults to `all` whenever the filter is on, so both routes to the
intent agree.
The conversation-starter buttons dropped their hard-coded `rounded-xl`, so they take the
shared `Button`'s shape like the dialog's other controls instead of mixing two.
`e2e/specs/mock/scenarios/` carries one tagged Playwright test per acceptance scenario:
sorting and paging, the mine filter and its link, failure recovery, and the card-to-dialog
morph, its focus return, its single scrim and its radius.
* feat: Morph the Agent Description Word by Word and Retime the Whole Transition
The card clamps the description to three lines and the dialog shows all of it,
so handing the paragraph over as one block slid the card's wrapping into place
and then swapped it for the dialog's. Every word the card showed now travels
from where that paragraph wrapped it to where this one does, and the lines the
clamp hid fade in where they land. The words are written to directly through CSS
transitions rather than re-rendered: a description is hundreds of independently
positioned spans, the compositor can carry them without a frame of JavaScript
each, and a transition can be interrupted mid-flight where a keyframe animation
restarts. Assistive technology still reads the copy once, from a flat string;
the spans are decoration and are hidden from it.
The identity block moved into the scroll region, the contact took the old
Pin/Copy Link corner, and those two controls moved next to Start Chat. Title and
description centre on the avatar while the copy is shorter than it, and top-align
once it outgrows it - pure CSS, no measurement.
Timings collapse onto one clock. A single ease-out-cubic and one open budget
drive the surface, the page dim, the identity fields and the words, so nothing
reads as a second animation that happens to have been started alongside the
first:
open 300ms surface, identity fields, dim
words 210ms (0.7 of the open: a word crosses a fraction of the box's
distance, and sliding copy cannot be read)
close 280ms 70ms handover, then a 210ms contraction
word return 70ms the whole handover; nothing else is moving on the way back
The close is two phases because the surface cannot contract until this dialog
unmounts and gives it back. Only the handover is spent with the box still, so it
stays short, and the dim now leaves on the click rather than on the unmount -
that is what answers the click while the geometry is still waiting. The dim
ramps linearly across each direction: an ease-out on an alpha spends two thirds
of its range in the first third of its time, and a scrim at 80% black already
looks black at half of it, so the page read as fully dim while the box was still
growing.
The words move and only move - no blur, no per-word delay, no scaling. A word
broken across two lines has no single box to fly from, so it is left to the
fade, and a paragraph showing different copy than the card (a background refresh
can land one) is refused outright rather than flying every word in from the
wrong place. Reopening inside the handover turns the words around instead of
leaving them parked in the card's wrapping.
* fix: Keep the Loaded Rows Mounted While the Marketplace Retries
A failure or an empty result was rendered in place of the list. With pages
already loaded that collapsed the list's scrollable height, so the browser
clamped the scroll position to the shorter document, and the remount that
followed a recovery ran the layout effect again and started the list at the
top: a transient cursor-page failure sent someone browsing deep in the
marketplace back to the first row.
The rows now stay mounted and the placeholder follows them, which also means
the end of the list stays reachable while a failure is held — so paging is
suspended until it clears, leaving the retry and its backoff to the error card
instead of re-requesting the page that just failed on the next scroll.
* test: State the Morph and Retry Scenarios as What the Reader Sees
Two scenario assertions described the implementation rather than the behaviour.
The detail-dialog description is now painted per word beside one screen-reader
copy of the same text, so matching the copy exactly resolved to both nodes. The
scenario asserts the paragraph that carries the description instead of counting
the nodes that spell it out.
The retry scenario pinned the scroll position to the pixel, which moves by
whatever the card rendered below the list occupies. It now anchors on the row
the reader had reached still being on screen, with the position staying deep
rather than clamped back to the first row.
* fix: Show the Retry Instead of a Skeleton, and Keep Cursors Readable
Two failures a marketplace reader could hit.
A held failure has no data of its own, so the retry that clears it made the
list pending again and filled the viewport with skeleton cards above the error
card. The card's status, countdown and action ended up below the fold, so the
recovery the card was reporting was the one thing not on screen. The skeleton
is now suppressed while a failure is held: the card owns the waiting state for
the request it describes.
The sort cursor carries `primary` and `secondary`, which an instance predating
sort modes cannot read - it reads `updatedAt` and `_id`, builds an Invalid Date
from their absence, and the query Mongo rejects surfaces as a 500 in the middle
of someone's scroll during a rolling deployment. Cursors now carry that pair as
well, describing the same row, so an older instance continues its own
updated-time ordering from where the page ended. The popular mode built its
cursor from a synthetic row, so it now carries the projected document instead.
* fix: Keep a Cursor Readable Only by a Server That Implements Its Order
Four review findings, and one rule behind three of them: state belongs to
whoever owns it, and a cursor belongs to the ordering it describes.
A sort cursor carried a legacy `updatedAt`/`_id` pair unconditionally, so an
older instance reached during a rolling deployment could parse a cursor from
`oldest`, `popular` or `author` and resume its own `updatedAt` walk from a
boundary row that ordering never produced - skipping agents and repeating
others. The pair is now emitted only for `recent`, whose `updatedAt` descending
plus `_id` ascending order is exactly what the legacy decoder implements. Every
other sort omits it and an old instance rejects the cursor outright, which is
the same argument the surrounding comment already made about not inventing a
date.
Marketplace avatars were refreshed from a separate newest-sorted query capped at
1,000 rows, run before the page the caller actually asked for. A user with more
accessible S3-backed agents than that cap saw broken avatars on every
`oldest`, `popular` or `author` page, and the 30-minute cache suppressed the
next attempt. The requested page is now queried first and its own uncovered
S3-backed rows are refreshed; the cache records which ids it covered, so an
entry written for one page no longer stands in for rows it never touched. The
selection, the cap and the cache merge live in `packages/api/src/agents`, with
the controller reduced to the call.
The detail dialog reached into `~/store` to clear the conversations a
multi-conversation session left open. That state is the app's, not the
marketplace's, so `MarketplaceProvider` performs the reset and the dialog asks
for it through the host context; the hook throws rather than defaulting to a
no-op, because a silent miss is the bug it exists to prevent.
With rows kept mounted, a failed background or cursor page put its retry card at
the end of a list several viewports tall - a marketplace that had quietly
stopped loading looked healthy. The card is now pinned to the bottom of the
scroll frame while rows exist, so its status, countdown, retry and reload link
are on screen wherever the reader is; with no rows there is nothing to pin it
over and it remains the whole of the page.
Two findings are rejected rather than patched. Popularity pagination recomputes
counts per request, so an agent that gains favourites mid-walk can cross above
the cursor and be missed; the walk is stable within a count, and backward drift
is deduplicated by the client. Making it exact requires a ranking snapshot, and
the favourites subdocument carries no per-favourite timestamp to snapshot from
(`packages/data-schemas/src/schema/user.ts:163-171`), so the fix is the
materialized counter tracked in berry-13/LibreChat#11; the guarantee is now
stated in the method instead of implied. Author sorting computes its key from
the ACL and user joins, so its cursor predicate cannot move ahead of them
without a stored sortable owner key - a schema change with a backfill, not a
pipeline reordering.
* docs: Track the Popularity Walk's Skipped Row as Its Own Issue\n\nThe method pointed only at the materialised-counter issue, which tracks the cost\nof recounting favourites per page. The row an upward drift drops from the rest of\nthe walk is a correctness problem that survives whether or not the cost is ever\naddressed, so it is tracked separately and the comment cites both: what can be\nmissed, and what pinning a ranking would take.
* fix: Let a Cursor Be Read by the Version That Implements Its Order
The previous round gated cursor *encoding* so only `recent` emits the legacy
`updatedAt`/`_id` pair, and left decoding rejecting it. That breaks the opposite
rollout direction: a page served by an older instance, followed by a request
reaching this one, produced an unreadable cursor, so the walk restarted at page
one - and `fetchAllAgentPages` concatenates without cycle detection, so
alternating instances can loop without finishing. Decoding now accepts the
legacy pair for `recent`, whose ordering this version implements, and still
rejects it for the sorts whose ordering it does not. The invariant is the same
one, read from the other side.
Refreshing a presigned avatar URL went through a timestamped update, so
maintenance advanced `updatedAt` - the sort key of the default walk - and an
agent below an active cursor could cross above it and vanish from the rest of
that walk. Avatar writes now go through `updateAgentAvatar`, which sets the
avatar alone with timestamps disabled.
The avatar orchestration the last round left in the controller - the
page-coverage cache decision, the refresh failure policy, the cache merge and
the persistence call - moved to `packages/api/src/agents/avatars.ts` with the
cache, the refresh and the update injected. The CJS controller holds the wiring
and one call.
On the client, the retry card was pinned to the bottom of the scroll frame and
rendered after the whole list, so it was visible but last in keyboard order:
`handleKeyDown` mounts and focuses each next card, so reaching Retry meant
traversing every loaded agent. It now renders before the rows and pins to the
top of the frame. A bottom pin cannot survive the move - sticky bottom only
holds an element whose flow position is below the viewport - so the pin
direction follows the DOM order rather than the reverse.
Two more from the same reading. `keepPreviousData` leaves the previous scope's
pages in `data` while a replacement loads or fails, and the failure branch
bypasses the pending guard, so a failed "My agents" request could render its
error over clickable agents from the scope the user had left; those rows are no
longer treated as current. And because a virtual row is keyed by its first
agent, a refetch that reorders the list unmounts the focused card: focus is now
restored to the same agent, and only when the unmount is what dropped it.
* fix: Make a Cursor Name Its Ordering, and Refuse the Ones It Cannot Honor
Third round on the same seam, so this stops patching it. A cursor now names the
ordering it was produced under, and is honored only by a reader that implements
that ordering; one that cannot be honored is an error rather than a silent
restart. `recent` keeps emitting the legacy `updatedAt`/`_id` pair, so old
instances still read its cursors, and a legacy-only payload counts as the
`recent` ordering: usable there, a mismatch everywhere else. Decoding reports
usable, ordering-mismatch or unreadable; `getListAgentsByAccess` raises instead
of paging from the start, and the controller answers 409
`{"error":"cursor_ordering_mismatch"}` through a mapper in `packages/api`.
That closes the direction this round found: a first page served by an old
instance for `sort=newest` produced a cursor this version rejected, and the
rejection fell back to page one, so the infinite query appended a second first
page - duplicated and out of order. The client now treats the 409 as "this walk
came from another ordering", drops the pages it holds and refetches from the
first page in the ordering the user asked for, once per request signature so a
mixed-version deployment cannot loop.
The author sort ordered by raw display name, so `Zoe` came before `alice` in a
list whose whole purpose is alphabetical. It sorts on a `$toLower` key now, and
the cursor carries that same normalized value - otherwise the ordering and the
pagination boundary disagree about where the page ended.
Avatar refresh coverage was a flat id list under one renewing TTL, so a page
refreshed at minute 0 stayed marked covered until minute 59 if another page was
refreshed at minute 29, and the set grew for the length of the walk. Coverage is
now a per-id deadline map: an id is covered only while its own deadline holds,
expired ids are dropped on read and write, the retained set is bounded with
nearest-expiry eviction, and the entry's TTL follows the furthest deadline it
still holds.
On the client, the retry card was pinned but in flow, so it displaced every
loaded row by its own height when a late page failed and put them back on
recovery. It sits in a zero-height sticky host now, keeping the three
constraints that pull against each other: first in keyboard order, visible at
any scroll position, and no layout space. Both of the traps that shape it are
written down - a flex child stretches to its container's cross size, so the
card's background collapses without `items-start`, and the stacking level has
to clear the cards' own click overlay.
An agent removed from the list while its dialog was open kept Pin, Copy Link,
the starters and Start Chat live, so Start Chat could navigate to a deleted
agent and Pin could persist a stale id. Absence from the loaded pages is not
proof of deletion - paging and sorting move rows out of the window - so the
captured id is revalidated against the per-agent endpoint, which enforces
access; only 403 and 404 mark it unavailable, the dialog says so, and its
actions go with it. A transient failure leaves the agent actionable.
* fix: Version an Ordering When Its Comparison Changes
Normalizing the author sort changed what "ordered by creator name" means while
still calling that ordering `author`, so the immediately previous
implementation would accept a cursor from this head and resume under
case-sensitive comparison: page one ending at `alice` let a later page skip
`Zoe`, which compares before the cursor under the old rules. The ordering
identity now carries a version alongside the mode - `author` at 2, everything
else at 1 - matched exactly on decode, with an absent version read as 1 so
cursors already in flight keep working for every mode whose semantics did not
change. The rule is written where the version lives and where it is encoded:
bump it when a comparison changes, or an older reader resumes a walk under
semantics that no longer exist. `popular` and `recent` were audited and left at
1; their comparisons are untouched.
A next-page request answering `cursor_ordering_mismatch` reset the walk
correctly, but the grid had already filed that error as a next-page failure,
and it clears those only when the replacement holds more pages than the prefix
it replaced. A restart yields exactly one page, so the error card stayed up over
a perfectly good first page, and its retry called `fetchNextPage`, which does
nothing when that page has no cursor. The query layer now reports the reset it
performed, and the grid drops the held failure when that reset's page-one
request succeeds. Ordinary failures keep the hold-until-success rule that stops
the card from remounting and resetting its own backoff on every attempt.
The dialog revalidates the selected agent when its row leaves the loaded
window, and that request is authoritative - but the dialog kept rendering the
snapshot it opened with, so a refresh that both edited an agent and moved it out
of the window left a stale description and stale starters on screen, and a
starter could launch with text the owner had replaced. It now prefers the row
the list holds, then the revalidated agent, and keeps the snapshot only for the
case neither can answer.
While that check was in flight the action controls were unmounted, so focus on
Pin, Copy Link, Start Chat or a starter fell to a detached element outside the
modal and was not restored afterwards. They stay mounted and are marked
`aria-disabled` for the duration, which is also why they are not natively
disabled: disabling the focused element blurs it, reaching the same bug by
another route. `CopyLink` takes that state and guards its activation, so the
control keeps focus, announces as disabled, and cannot copy a link to an agent
whose existence is still being checked.
* fix: Put a Bumped Ordering's Boundary Where an Old Reader Cannot Find It
Versioning the ordering identity only protects a reader that knows to look at
the version. An instance deployed before versioning existed ignores unknown
fields and reads `primary`/`secondary` straight out of the payload, so an
author cursor from this version - whose boundary is a lowercased name - was
still resumable under the case-sensitive comparison it replaced: page one
ending at `alice` let that reader skip `Zoe`.
An ordering past version 1 now nests its boundary under `boundary`. A reader
that predates versioning finds no boundary it recognizes and fails closed
instead of walking the wrong comparison, and a reader that knows about versions
knows where to look. Version 1 keeps the flat shape, which is what keeps every
cursor already in flight readable across a deployment, and `recent` keeps its
legacy pair. A flat boundary claiming a version past 1 did not come from this
encoder, so it is unreadable rather than trusted.
Verified against the running API: an author page emits
`{sort, version: 2, boundary: {primary, secondary}}` with no top-level boundary
fields, the next page continues it with no overlap, and both a flattened
boundary and a version-1 author cursor answer 409 `cursor_ordering_mismatch`.
* fix: Let an Author Cursor Carry the Key the Database Ordered By
The author sort orders on `authorSortKey`, the `$toLower` of the display name,
and the row handed to the encoder already carries that key. The encoder
lowercased it a second time in JavaScript, which normalizes what the database
does not: `$toLower` is defined over ASCII and leaves `Émile` (U+00C9)
uppercase, so the boundary was written as `émile` (U+00E9) and the next page's
`$match` skipped every key in between - `Üwe` (U+00DC) disappeared from the
walk entirely, with `has_more` false and an empty page to show for it.
The computed key is now serialized as it stands. The ordering's comparison is
untouched - `$sort` still reads the same `$toLower` key - so the version stays
at 2: a cursor already in flight from the previous head decodes to the same
boundary it did before and resumes the same walk, rather than being refused for
an ordering change that did not happen.
Reproduced and verified in `agent.spec.ts`: two agents whose contact names are
`Émile` and `Üwe`, paged one at a time, lost the second row before this change
and both pages now return their row; 231 tests in that suite pass.
* fix: Give the Recovery Card Its Own Band Instead of the Rows' Space
The retry card was a zero-height sticky host painted over the list, so whatever
it covered was still focusable with nothing to show for it: a focus ring under
an opaque card is no focus ring, and on a narrow viewport the card covers the
first row entirely. Reproduced across desktop light, desktop dark and mobile -
the focused card's box intersected the card's box at the top of the list and
again halfway down it.
The host now takes the card's own measured height, so the rows begin below the
band rather than under it, and the scroll position absorbs that reserve: someone
reading deep in the list keeps the row they were on, and at the top - where
there is nothing to absorb it with - the rows are what moves, which is the point.
`scroll-padding-top` covers keyboard navigation, so a Tab into a row the card
would cover scrolls it clear, and a row the reader had already scrolled past is
pulled out from under the card when it takes focus. Only the focused card moves;
the reader's scroll position is otherwise left alone.
The card's height is measured rather than assumed because it grows with its
status, its countdown and its eventual reload link, and the reserve follows it.
Verified on this head with a rebuilt client: `@scenario:focused-card-stays-visible-under-the-retry`
fails before this change and passes after it in all three projects, with
`@scenario:pagination-failure-keeps-the-loaded-rows` and
`@scenario:retry-keeps-the-error-card-on-screen` still passing beside it -
the rows, their height, the reader's place and keyboard order are unchanged.
`client/src/components/Agents`: 13 suites / 155 tests pass; `npx tsc --noEmit` clean.
* fix: Keep the Grid Under an Open Dialog, and the Author Boundary a String
Three findings on one head, two of them variants of the same rule - a recovery
state must not take away what the reader is using.
The pending-results branch replaced the whole grid with the loading skeleton,
and the grid is what owns the detail dialog and the element focus returns to. A
refresh with no data of its own - a reset cache, a revalidation after the rows
were dropped - therefore tore an open dialog down mid-flight. The skeleton is
now one of the placeholders the grid renders *inside* itself, beside the
recovery card and the empty state, so the host stays mounted and the dialog
survives its own results being refetched.
A scope change is different: the grid is keyed on the query scope, so a
debounced search or a restored history entry legitimately remounts the rows and
the dialog goes with the list it belonged to. What must not go with it is the
focus it held: the browser drops focus on `document.body`, so the next Tab
starts at the top of the page rather than at the marketplace. The panel takes
focus in exactly that case - focus already elsewhere, the search field being
typed in, is left alone, because only `body` means nobody holds it.
The dialog also read the revalidated agent as the whole agent, and the per-agent
VIEW response carries no `category` (`api/server/controllers/agents/v1.js`), so
an agent that moved out of the loaded window lost its badge. The revalidated
fields are laid over the captured row instead: fresh where the endpoint speaks,
captured where it is silent.
Last, an author cursor's boundary was coerced with `String()`, and coercion is
not validation: a missing or non-string `primary` became the ordinary key
`'undefined'` and resumed the walk partway through the alphabet instead of
answering 409. The date and number modes fail on their own casts; the string
mode now requires a string.
Each is pinned by a regression that fails on the parent commit: the dialog
surviving a refresh and the panel taking focus back
(`AgentGrid.integration.spec.tsx`), the category surviving revalidation
(`VirtualizedAgentGrid.test.tsx`), and four non-string author boundaries
answering `unreadable` (`agent.spec.ts`). `client/src/components/Agents`:
13 suites / 157 tests pass; `packages/data-schemas` `agent.spec.ts`: 232 tests
pass; `npx tsc --noEmit` clean in both workspaces.
* fix: Merge an Avatar Refresh Into the Entry That Is There, Not the One It Read
Every list page for one user reads the refresh entry before its list query, then
spends the S3 round trips of a whole page before writing back. Two pages in
flight together therefore merge into the same snapshot, and the later write drops
the coverage and refreshed URLs the other one added, so the next response that
contains those agents presigns and persists them again.
The merge now re-reads the entry immediately before the write, which narrows the
overlap to that gap instead of the whole refresh. A read that fails keeps the
caller's snapshot, leaving the previous behaviour in place rather than losing the
refresh that just succeeded.
* docs: Say Which Default the Sort Contract Actually Describes
Both the shared type and the grid prop claimed the server falls back to `newest`
when a request omits `sort`. It does not: `resolveMarketplaceListQuery` leaves an
absent or unknown mode undefined, and `getListAgentsByAccess` then serves
`recent`, the most-recently-edited order the agent selector and the mention menu
depend on. `newest` is the marketplace's default, which is why the grid sends it
explicitly.
The grid now names the constant the dropdown already exports instead of
repeating the literal, so the marketplace default has one definition.
* fix: Keep Rich Agent Descriptions Rendering After the Marketplace Rewrite
The rewrite replaced the card and detail views that `Description` had just been
wired into, so an agent whose description is markup lost it: the card printed the
tags as text and the dialog no longer rendered the links or images at all.
The card strips the copy with `getPlainDescription`, which is what it showed
before and what the word morph can measure, since that morph walks text nodes.
The dialog renders markup through `Description` again and hands the paragraph
over whole rather than word by word, because there are no words to measure in a
sanitized fragment. A plain description still morphs.
* fix: Answer a Marketplace Failure Without Taking Away What Is in Use
Twelve findings over three rounds, and most of them are one rule: a recovery
state must not remove what the reader is holding, and a lever the code invents
belongs to whoever runs the deployment.
Focus, three times. The effect that takes focus back after a scope change fired
on the initial marketplace mount as well, because a fresh navigation also leaves
`document.body` focused - so arriving at the page started reading below the
heading, the search field and the filters. It now compares the scope key against
the previous render and never acts on the first one. A successful Retry removes
the recovery card with the focused button inside it; focus moves to the results
panel first, and only when it was inside the card, so a reader who has moved on
is not yanked back. And when the access check settles 403/404, the dialog's
actions are removed under the same rule: focus goes to the status that explains
why they are gone, which is now programmatically focusable, rather than to the
document.
A dialog opened after the owner edited an agent used to keep the cached copy
while re-enabling its actions, so a conversation starter could launch a chat with
text that had already been replaced. Both selected-agent branches now lay the
revalidated fields over the captured row through one helper - fresh where the
per-agent response speaks, captured where it is silent, which is why it is a
merge and not a replacement.
Two operator levers ship as configuration, each defaulting to today's behaviour:
`endpoints.agents.avatarRefresh.coverageLimit` for how many per-agent S3 refresh
deadlines one user's pages remember, and `interface.marketplace.retryDelaysMs`
for the recovery cadence - an empty sequence leaves only the manual Retry, which
is why the reload affordance goes with it. That closes berry-13/LibreChat#24,
which had deferred the retry policy.
The avatar path also stopped losing work and stopped overwriting owners. Two
pages refreshing the same user's avatars both read before either wrote, so the
later write dropped the other's coverage and both pages re-signed inside the
advertised window; merges for one key are serialized, with the re-read left in
the critical section because that is what makes separate processes converge. A
rejecting cache write used to discard URLs that had been signed successfully and
answer with the expired paths; it is best-effort now. And a viewer's in-flight
refresh could land after the owner replaced that avatar: `updateAgentAvatar`
takes the avatar the caller read and only writes while the stored one still
matches, with the skipped agent's stale URL left out of the response.
Two smaller ones. A malformed `popular` cursor carrying `-1` or `1.5` passed
validation and walked an incomplete or duplicated page instead of answering 409;
counts are discrete, so the boundary must be a non-negative integer. And a rich
description rendered inside the paragraph the plain text morphs in, which is
invalid nesting once the sanitized markup carries blocks of its own - the rich
branch is a block, and both share one set of motion props.
Last, `attachAgentOwnerContacts` took a Mongo `$in` filter and a projection
string, which put the storage engine in `packages/api`'s public contract. It now
takes owner ids, and `findOwnerContactUsers` in `packages/data-schemas` owns the
query.
Every fix is pinned by a regression that fails on the parent commit. Locally:
`client/src/components/Agents` 13 suites / 170 tests, `packages/api`
`src/agents/{avatars,ownerContact}` 29 tests, `packages/data-schemas`
`{agent,user}.methods` 330 tests, `api/server/controllers/agents/v1` 146 tests;
`npx tsc --noEmit` clean in `client`, `packages/api`, `packages/data-schemas` and
`packages/data-provider`.
* fix: Hand Focus Back When a Removal Takes It, Not When a Retry Starts
Recovery moved focus at the moment the request went out, which is the wrong
event: a retry that fails again leaves the card on screen, so the reader lost the
button they were still using. Focus is only in danger when the thing holding it
is removed - and the DOM says so plainly, because the browser drops focus on
`document.body` in that commit.
The grid now watches for that: one effect recovers focus when a scope change
remounted the rows or a cleared failure removed the recovery card, and only while
nobody holds focus. The card's retry goes back to being just a retry, and the
recovery band is the measured wrapper again, its bottom gap included.
Two regressions in `AgentGrid.integration.spec.tsx` pin the distinction: focus
lands on the results when a successful retry removes the focused button, and
stays on the button when the attempt fails again - the latter fails on the
previous commit, which yanked focus to the panel while the card was still there.
`@scenario:recovery-hands-focus-back-to-the-results` states it in a real browser,
where focus after a removal is the browser's decision rather than jsdom's.
`client/src/components/Agents`: 13 suites / 171 tests pass; `npx tsc --noEmit`
clean in `client` and `e2e`.
* style: Declare the Serialization Test's Cache as the Constant It Is
The forward reference the mock cache needed while it was assembled in two steps
is gone, so `let` only tripped `prefer-const` in CI's ESLint lane.
* fix: Bind a Cached Avatar URL, a Joined Owner and a Morph's Styles to What They Describe
Four defects from one round, each in a subsystem this branch introduced, and each
the same shape: a value was keyed by the thing it was near rather than the thing
it was about.
A signed URL belongs to an avatar, not to an agent. Coverage keyed on the agent
id alone meant that when an owner replaced one S3 image with another, the viewer's
page was skipped as covered and the controller pasted the cached URL for the old
file over the freshly loaded path - so that viewer kept seeing a removed avatar
for the rest of the window, while the owner saw the new one. Entries now carry the
filepath they were signed for, coverage only counts while that filepath is still
the one on the row, and a refresh pass records what it checked. Entries written
before the binding existed cannot be checked, so they are treated as uncovered
and signed again rather than replayed.
An owner belongs to a tenant. The author sort joins `aclentries` and `users` with
`$lookup`, which does not run the models' tenant middleware, so a stale or
imported principal id resolved to another tenant's user and that name came back as
`owner_contact` - a name the ordinary resolver, which goes through tenant-scoped
methods, never returns. Both joins now match the agent's tenant, with missing and
null treated as the one tenantless scope this file already uses for favourite
counts.
`support_contact` is `Schema.Types.Mixed`, and `$ifNull` passes a number or an
object straight into `$trim`, which rejects it and fails the whole aggregation. A
single malformed legacy row therefore turned every author-sorted page in that
scope into a 500, while `attachAgentOwnerContacts` shrugged the same value off.
Every display operand is now checked for BSON string type first, which leaves the
tier logic unchanged because it already rejects the empty string as a name.
A compositor hint belongs to the animation that needed it. When revalidated copy
arrived mid-morph, the previous effect's cleanup cancelled the settle timer and
the same-phase guard returned before clearing anything, so every reused word kept
`will-change: transform` and its transition for the lifetime of the dialog. One
cleanup now clears the spans it owns on every path - a same-phase change, a phase
change, an unmount - and the refreshed copy arrives at rest instead of replaying
an opening morph.
Two further reports on this round are accepted rather than fixed, with the
reasoning on their threads: the coverage merge is serialized per key inside a
process and not across replicas, because a dropped merge costs signing work the
next page redoes and never a wrong URL - the comment that claimed convergence now
says so - and the rolling-deployment window where a parent-version server ignores
`sort` and `mine` is transient, read-only and self-correcting, while the capability
handshake its remedy needs does not exist in this platform.
Each fix is pinned by a regression that fails on the parent commit:
`refreshes covered agents when their avatar filepath changes` and two siblings in
`packages/api/src/agents/avatars.spec.ts`, `does not resolve an owner user from
another tenant during author sorting` and `tolerates non-string support contact
values while sorting and paging` in `packages/data-schemas`, and `clears word
animation styles when refreshed copy changes during the morph` in
`AgentDetailContent.spec.tsx`. Locally: `client/src/components/Agents` 13 suites /
172 tests, `packages/api` avatars 26, `packages/data-schemas` agent + documentdb
298, `api/server/controllers/agents/v1` 146; `npx tsc --noEmit` clean in `client`,
`packages/api` and `packages/data-schemas`.
* fix: Cover the Path the Refresh Wrote, and Keep Pin Focusable While It Saves
Two findings, both about state that moved on while something kept pointing at
where it used to be.
Coverage recorded the filepath a refresh *started* from, while the write that
followed stored the newly signed one. The next page therefore loaded a row whose
path no coverage entry named, so a successful re-sign guaranteed another
per-agent pass and another cache write inside the window it had just claimed -
the opposite of what coverage is for. Coverage now names the path that was
persisted, because that is what a later page reads, and the cached URL keeps the
path the page in hand still carries, because that is the row it applies to. The
merge no longer requires those two to agree: they are different questions, and
insisting they match is what dropped the freshly signed URL.
A refresh that found nothing to change writes nothing, so its coverage keeps the
path the row already had; that case is now stated as its own test rather than
standing in for the one above.
Pin stayed a control while it worked. Activating it from the keyboard used to set
`disabled` on the button that had focus, and a disabled control leaves focus
navigation, so focus fell to the document until the favourite mutation settled.
It keeps `aria-disabled` and `aria-busy` with a guarded handler instead - the same
shape Copy link, Start chat and the starters already use - so the reader stays on
the control they pressed and a second Enter cannot queue a duplicate toggle.
Both are pinned by regressions that fail on the parent commit: `covers the path
it persisted, so the row it wrote is not signed again` in
`packages/api/src/agents/avatars.spec.ts` (two signing calls where one is
correct), and `keeps focus on Pin while the favorite mutation is busy and ignores
repeated activation` in `AgentDetailContent.spec.tsx` (focus on the document, no
`aria-disabled`). Locally: `client/src/components/Agents` 13 suites / 173 tests,
`packages/api` avatars 27, `api/server/controllers/agents/v1` 146; `npx tsc
--noEmit` clean in `client` and `packages/api`.
* fix: Join the Author's Owner the Way DocumentDB Can, and Leave Retry Focusable
Two findings, and the first is a compatibility rule this branch already carries as
an invariant. Scoping the author joins to the tenant used `$lookup` with
`let`/`pipeline`, which Amazon DocumentDB 5.0 rejects — this repository records
that in `prompt.getPromptGroup.spec.ts` — so selecting Author on such a
deployment would have failed the aggregation and answered 500. The joins are
plain `localField`/`foreignField` again, and the tenant scope is applied to the
joined arrays with `$filter` afterwards: the same isolation, expressed in
operators that survive the target. `documentdb.spec.ts` now fails if either
marketplace lookup goes back to the correlated form, so the next person to reach
for it is told by a test rather than by production.
The shared retry control had the focus fault the pin control just lost.
Activating Retry sets `isRetrying`, whose native `disabled` drops the focused
button out of focus navigation; when that attempt fails the card stays mounted,
the grid's handoff never runs — it only fires when a cleared failure removes the
card — and the reader is left with focus nowhere, beside a card they cannot Tab
into. `RetryableError` keeps the button focusable with `aria-disabled`,
`aria-busy` and a guarded handler, same label, spinner and dimming as before.
The marketplace's existing assertion that the control is `disabled` while
retrying pinned the mechanism rather than the behaviour, so it now states what a
reader gets: busy, still focusable, and a second press that does nothing.
`@scenario:recovery-hands-focus-back-to-the-results` covers both outcomes in a
real browser — focus stays on Retry when the attempt fails, and moves to the
results when the success removes the card — because jsdom blurs neither and that
is exactly how this escaped.
Pinned by `keeps marketplace author lookups in the DocumentDB-compatible form`
and `flags a correlated $lookup let/pipeline form` in
`packages/data-schemas/src/methods/documentdb.spec.ts`, which report four
offending stages on the parent commit, and by `keeps the retry control focusable
and blocks a second activation while retrying` in
`packages/client/src/components/RetryableError.spec.tsx`. Locally:
`packages/data-schemas` agent + documentdb 300 tests, `packages/client`
components + hooks 292, `client/src/components/Agents` 13 suites / 173 tests;
`npx tsc --noEmit` clean in `client`, `packages/client`, `packages/data-schemas`
and `e2e`.
* test: Ask Where Focus Is, Not Which Box It Sits In
The failed-attempt half of the recovery focus scenario asserted that focus was
inside the card's `role="alert"`, which the retry control has never been in: the
alert is the icon, title and detail, and the actions are its sibling, so the
assertion described the DOM rather than the behaviour and failed on all three
projects.
It now asks the only question that matters - the control the reader pressed still
has focus - and lets whichever attempt lands next, theirs or the card's backoff,
be the removal that hands focus to the results.
* test: Count the Morph's Scrim by the Class Both Layers Carry
The base moved OGDialog's scrim from a literal `bg-black/80` to the
`surface-overlay` role, so the morph's backdrop follows it through the shared
constant. The scenario counted layers by the old literal and by black channels,
which after the move would have found no scrim at all, and could only ever have
caught a duplicate dim in the themes whose overlay is black.
It now counts the class the overlay and the morph's backdrop both carry, and
treats any full-viewport layer at alpha 0.3 or above as a second dim, so the
light theme's gray scrim is covered by the same assertion.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFLKexs5HyzqT6H8B9oQqJ
* fix: Keep the Avatar Cache Contract in packages/api, and the Grid Mounted
The list controller was reading the avatar cache entry itself: it checked that a
cached value carried both a filepath and a url, that the row still named S3, and
that the filepath still matched, then wrote the signed URL onto the row. That is
behaviour in a CJS file under /api, and it split the cache contract across two
layers, so a later change to the entry shape would have had to be made in both.
`applyCachedAvatarUrl` now owns that decision beside the code that writes the
entry, and the controller passes the entry through.
The grid was keyed on the active category. Its own scope key already carries the
category, so the key only forced a remount that the scope change was about to
handle anyway, and it took the open detail dialog and its focus-return target
with it. The replacement grid starts with an empty previousScopeKeyRef, so it
reads its first render as a mount rather than a scope change and never hands
focus back, leaving it on the document.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFLKexs5HyzqT6H8B9oQqJ
* fix: Supply the Marketplace Host From the Shell, and Order Two Keys by What Reads Them
The marketplace provider took the app's conversation reset from `~/store` itself.
Wrapping that in a context did not make it a host boundary, because the feature
was still the side reaching for shell state, and the feature could not have moved
to its own workspace without the conversation store coming along. The route now
builds the reset and passes it in, and the provider only carries it. The base did
not have this coupling; it arrived with the host context.
The favourites index led with `favorites.agentId`, a multikey field the popular
sort only ever tests for existence. With it first, the count could not seek into
the caller's tenant and scanned favourites across all of them, which is the work
proportional to the whole corpus that a page is supposed to avoid. Tenant first
bounds it.
The author aggregation compared ACL timestamps through raw field paths. The
resolver it has to agree with sorts the same three keys, where a missing field
reads as null, but a missing field path in a comparison expression is undefined,
which BSON orders below null. An imported entry that omitted `grantedAt` would
therefore win outright and hand the author page a different owner than every
other list order. The timestamps are now read through `$ifNull`.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFLKexs5HyzqT6H8B9oQqJ
---------
Co-authored-by: hoangtrongthai-dtvn <thai.hoang2@dac-datatech.vn>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
(cherry picked from commit 18c48f6ff7)
Original-PR: https://github.com/LibreChat-AI/LibreChat/pull/15798
5267 lines
176 KiB
JavaScript
5267 lines
176 KiB
JavaScript
const mongoose = require('mongoose');
|
|
const express = require('express');
|
|
const request = require('supertest');
|
|
const { nanoid } = require('nanoid');
|
|
const { v4: uuidv4 } = require('uuid');
|
|
const { AgentSortCursorError, createModels, tenantStorage } = require('@librechat/data-schemas');
|
|
const {
|
|
Tools,
|
|
SkillsScope,
|
|
FileSources,
|
|
Permissions,
|
|
PermissionBits,
|
|
PermissionTypes,
|
|
PrincipalModel,
|
|
PrincipalType,
|
|
ResourceType,
|
|
actionDelimiter,
|
|
} = require('librechat-data-provider');
|
|
const { MongoMemoryServer } = require('mongodb-memory-server');
|
|
|
|
// Only mock the dependencies that are not database-related
|
|
jest.mock('~/server/services/Config', () => ({
|
|
getCachedTools: jest.fn().mockResolvedValue({
|
|
web_search: true,
|
|
execute_code: true,
|
|
file_search: true,
|
|
}),
|
|
}));
|
|
|
|
jest.mock('~/server/services/Files/strategies', () => ({
|
|
getStrategyFunctions: jest.fn(),
|
|
}));
|
|
|
|
jest.mock('~/server/services/Files/images/avatar', () => ({
|
|
resizeAvatar: jest.fn(),
|
|
}));
|
|
|
|
jest.mock('sharp', () =>
|
|
jest.fn(() => ({
|
|
metadata: jest.fn().mockResolvedValue({}),
|
|
toFormat: jest.fn().mockReturnThis(),
|
|
toBuffer: jest.fn().mockResolvedValue(Buffer.alloc(0)),
|
|
})),
|
|
);
|
|
|
|
jest.mock('@librechat/api', () => ({
|
|
...jest.requireActual('@librechat/api'),
|
|
mergeDeploymentSkillIds: jest.fn((ids) => ids),
|
|
refreshS3Url: jest.fn(),
|
|
}));
|
|
|
|
jest.mock('~/server/services/Files/process', () => ({
|
|
filterFile: jest.fn(),
|
|
}));
|
|
|
|
jest.mock('~/server/services/PermissionService', () => ({
|
|
findAccessibleResources: jest.fn().mockResolvedValue([]),
|
|
findPubliclyAccessibleResources: jest.fn().mockResolvedValue([]),
|
|
getResourcePermissionsMap: jest.fn().mockResolvedValue(new Map()),
|
|
grantPermission: jest.fn(),
|
|
hasPublicPermission: jest.fn().mockResolvedValue(false),
|
|
}));
|
|
|
|
jest.mock('~/models', () => {
|
|
const mongoose = require('mongoose');
|
|
const { createMethods } = require('@librechat/data-schemas');
|
|
const methods = createMethods(mongoose, {
|
|
removeAllPermissions: jest.fn().mockResolvedValue(undefined),
|
|
});
|
|
return {
|
|
...methods,
|
|
getCategoriesWithCounts: jest.fn(),
|
|
deleteFileByFilter: jest.fn(),
|
|
};
|
|
});
|
|
|
|
// Mock cache for S3 avatar refresh tests
|
|
const mockCache = {
|
|
get: jest.fn(),
|
|
set: jest.fn(),
|
|
delete: jest.fn(),
|
|
};
|
|
jest.mock('~/cache', () => ({
|
|
getLogStores: jest.fn(() => mockCache),
|
|
}));
|
|
|
|
const {
|
|
createAgent: createAgentHandler,
|
|
getAgent: getAgentHandler,
|
|
getAgentVersions: getAgentVersionsHandler,
|
|
duplicateAgent: duplicateAgentHandler,
|
|
revertAgentVersion: revertAgentVersionHandler,
|
|
updateAgent: updateAgentHandler,
|
|
getListAgents: getListAgentsHandler,
|
|
} = require('./v1');
|
|
|
|
const {
|
|
findAccessibleResources,
|
|
findPubliclyAccessibleResources,
|
|
getResourcePermissionsMap,
|
|
} = require('~/server/services/PermissionService');
|
|
|
|
const {
|
|
CONTENT_TRAVERSAL_MAX_DEPTH,
|
|
createAgentManagementAuth,
|
|
createAgentManagementCreateHandler,
|
|
createAgentManagementDeleteHandler,
|
|
createAgentManagementReadHandlers,
|
|
createAgentManagementUpdateHandler,
|
|
mergeDeploymentSkillIds,
|
|
refreshS3Url,
|
|
} = require('@librechat/api');
|
|
const { grantPermission } = require('~/server/services/PermissionService');
|
|
const { hasCapability } = require('~/server/middleware/roles/capabilities');
|
|
const db = require('~/models');
|
|
|
|
/**
|
|
* @type {import('mongoose').Model<import('@librechat/data-schemas').IAgent>}
|
|
*/
|
|
let Agent;
|
|
let AclEntry;
|
|
let User;
|
|
|
|
const OWNER_PERMISSION_BITS =
|
|
PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE | PermissionBits.SHARE;
|
|
|
|
const createOwner = (overrides = {}) =>
|
|
User.create({
|
|
name: 'Agent Owner',
|
|
email: `owner-${nanoid(8)}@example.com`,
|
|
provider: 'local',
|
|
emailVerified: true,
|
|
...overrides,
|
|
});
|
|
|
|
const createOverflowingActionValue = () => {
|
|
const root = { visible: 'safe visible value' };
|
|
let current = root;
|
|
for (let depth = 0; depth < CONTENT_TRAVERSAL_MAX_DEPTH; depth++) {
|
|
current.nested = {};
|
|
current = current.nested;
|
|
}
|
|
current.nested = { hidden: 'BLOCK-HIDDEN' };
|
|
return root;
|
|
};
|
|
|
|
const grantAgentOwner = ({ agent, owner, grantedAt = new Date() }) =>
|
|
AclEntry.create({
|
|
principalType: PrincipalType.USER,
|
|
principalModel: PrincipalModel.USER,
|
|
principalId: owner._id,
|
|
resourceType: ResourceType.AGENT,
|
|
resourceId: agent._id,
|
|
permBits: OWNER_PERMISSION_BITS,
|
|
grantedBy: owner._id,
|
|
grantedAt,
|
|
});
|
|
|
|
describe('Agent Controllers - Mass Assignment Protection', () => {
|
|
let mongoServer;
|
|
let mockReq;
|
|
let mockRes;
|
|
|
|
beforeAll(async () => {
|
|
mongoServer = await MongoMemoryServer.create();
|
|
const mongoUri = mongoServer.getUri();
|
|
await mongoose.connect(mongoUri);
|
|
createModels(mongoose);
|
|
Agent = mongoose.models.Agent;
|
|
AclEntry = mongoose.models.AclEntry;
|
|
User = mongoose.models.User;
|
|
}, 20000);
|
|
|
|
afterAll(async () => {
|
|
await mongoose.disconnect();
|
|
await mongoServer.stop();
|
|
});
|
|
|
|
beforeEach(async () => {
|
|
await Agent.deleteMany({});
|
|
await AclEntry.deleteMany({});
|
|
await User.deleteMany({});
|
|
await mongoose.models.File.deleteMany({});
|
|
|
|
// Reset all mocks
|
|
jest.clearAllMocks();
|
|
mergeDeploymentSkillIds.mockImplementation((ids) => ids);
|
|
|
|
// Setup mock request and response objects
|
|
mockReq = {
|
|
user: {
|
|
id: new mongoose.Types.ObjectId().toString(),
|
|
role: 'USER',
|
|
},
|
|
body: {},
|
|
params: {},
|
|
query: {},
|
|
app: {
|
|
locals: {
|
|
fileStrategy: 'local',
|
|
},
|
|
},
|
|
};
|
|
|
|
mockRes = {
|
|
status: jest.fn().mockReturnThis(),
|
|
json: jest.fn().mockReturnThis(),
|
|
};
|
|
});
|
|
|
|
describe('createAgentHandler', () => {
|
|
test('removes programmatic tool options when Code Interpreter capability is disabled', async () => {
|
|
mockReq.body = {
|
|
name: 'Invalid Programmatic Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: [Tools.execute_code, 'search_mcp_example'],
|
|
tool_options: {
|
|
search_mcp_example: { allowed_callers: ['code_execution'] },
|
|
},
|
|
};
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(201);
|
|
expect(mockRes.json.mock.calls[0][0].tool_options).toEqual({});
|
|
});
|
|
|
|
test('rejects a stateful environment excluded by deployment policy', async () => {
|
|
mockReq.config = {
|
|
endpoints: {
|
|
agents: {
|
|
statefulCodeSessions: { allowedEnvironments: ['user'] },
|
|
},
|
|
},
|
|
};
|
|
mockReq.body = {
|
|
name: 'Disallowed Stateful Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
stateful_code_sessions: true,
|
|
stateful_code_environment: 'conversation',
|
|
};
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(403);
|
|
expect(await Agent.countDocuments()).toBe(0);
|
|
});
|
|
|
|
test('rejects an unconfigured code environment id', async () => {
|
|
mockReq.config = {
|
|
endpoints: {
|
|
agents: {
|
|
statefulCodeSessions: {
|
|
allowedEnvironments: ['user'],
|
|
environments: [
|
|
{
|
|
id: 'configured-vm',
|
|
name: 'Configured VM',
|
|
type: 'attached',
|
|
baseURL: 'https://code.example.com/v1',
|
|
default: true,
|
|
},
|
|
],
|
|
},
|
|
},
|
|
},
|
|
};
|
|
mockReq.body = {
|
|
name: 'Invalid Environment Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
stateful_code_sessions: true,
|
|
code_environment_id: 'missing-vm',
|
|
};
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
expect(await Agent.countDocuments()).toBe(0);
|
|
});
|
|
|
|
test('rejects a pairing-only control plane as a code environment id', async () => {
|
|
mockReq.config = {
|
|
endpoints: {
|
|
agents: {
|
|
statefulCodeSessions: {
|
|
allowedEnvironments: ['user'],
|
|
environments: [
|
|
{
|
|
id: 'personal-workers',
|
|
name: 'Personal workers',
|
|
type: 'attached',
|
|
baseURL: 'https://code.example.com/v1',
|
|
pairing: {
|
|
allowPrincipalWorkers: true,
|
|
tokenEnv: 'CODE_BRIDGE_ADMIN_TOKEN',
|
|
},
|
|
},
|
|
],
|
|
},
|
|
},
|
|
},
|
|
};
|
|
mockReq.body = {
|
|
name: 'Invalid Control Plane Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
stateful_code_sessions: true,
|
|
code_environment_id: 'personal-workers',
|
|
};
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
expect(await Agent.countDocuments()).toBe(0);
|
|
});
|
|
|
|
test('rejects a workspace default without an explicit attached environment', async () => {
|
|
mockReq.config = {
|
|
endpoints: {
|
|
agents: {
|
|
statefulCodeSessions: {
|
|
allowedEnvironments: ['user'],
|
|
environments: [
|
|
{
|
|
id: 'default-vm',
|
|
name: 'Default VM',
|
|
type: 'attached',
|
|
baseURL: 'https://code.example.com/v1',
|
|
default: true,
|
|
},
|
|
],
|
|
},
|
|
},
|
|
},
|
|
};
|
|
mockReq.body = {
|
|
name: 'Unbound Workspace Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
code_workspace_id: 'project-a',
|
|
};
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
expect(mockRes.json).toHaveBeenCalledWith({
|
|
error: 'Code workspace defaults require an explicit attached code environment',
|
|
});
|
|
expect(await Agent.countDocuments()).toBe(0);
|
|
});
|
|
|
|
test('rejects a workspace default for a managed environment', async () => {
|
|
mockReq.config = {
|
|
endpoints: {
|
|
agents: {
|
|
statefulCodeSessions: {
|
|
allowedEnvironments: ['user'],
|
|
environments: [
|
|
{
|
|
id: 'managed-runtime',
|
|
name: 'Managed Runtime',
|
|
type: 'managed',
|
|
baseURL: 'https://code.example.com/v1',
|
|
},
|
|
],
|
|
},
|
|
},
|
|
},
|
|
};
|
|
mockReq.body = {
|
|
name: 'Managed Workspace Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
code_environment_id: 'managed-runtime',
|
|
code_workspace_id: 'project-a',
|
|
};
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
expect(mockRes.json).toHaveBeenCalledWith({
|
|
error: 'Code workspace defaults require an explicit attached code environment',
|
|
});
|
|
expect(await Agent.countDocuments()).toBe(0);
|
|
});
|
|
|
|
test('should block configured agent instruction content before persistence', async () => {
|
|
mockReq.config = {
|
|
filters: {
|
|
agentInstructions: {
|
|
pii: {
|
|
starterPatterns: ['sk_prefix'],
|
|
},
|
|
},
|
|
},
|
|
};
|
|
mockReq.body = {
|
|
name: 'Filtered Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
instructions: 'Use sk-private-token for requests',
|
|
};
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
expect(mockRes.json).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
error: 'content_filter_block',
|
|
source: 'agent_instruction',
|
|
field: 'instructions',
|
|
}),
|
|
);
|
|
await expect(Agent.countDocuments()).resolves.toBe(0);
|
|
});
|
|
|
|
test('should create agent with allowed fields only', async () => {
|
|
const validData = {
|
|
name: 'Test Agent',
|
|
description: 'A test agent',
|
|
instructions: 'Be helpful',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: ['web_search'],
|
|
model_parameters: { temperature: 0.7 },
|
|
tool_resources: {
|
|
file_search: { file_ids: ['file1', 'file2'] },
|
|
},
|
|
};
|
|
|
|
mockReq.body = validData;
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(201);
|
|
expect(mockRes.json).toHaveBeenCalled();
|
|
|
|
const createdAgent = mockRes.json.mock.calls[0][0];
|
|
expect(createdAgent.name).toBe('Test Agent');
|
|
expect(createdAgent.description).toBe('A test agent');
|
|
expect(createdAgent.provider).toBe('openai');
|
|
expect(createdAgent.model).toBe('gpt-4');
|
|
expect(createdAgent.author.toString()).toBe(mockReq.user.id);
|
|
expect(createdAgent.tools).toContain('web_search');
|
|
|
|
// Verify in database
|
|
const agentInDb = await Agent.findOne({ id: createdAgent.id });
|
|
expect(agentInDb).toBeDefined();
|
|
expect(agentInDb.name).toBe('Test Agent');
|
|
expect(agentInDb.author.toString()).toBe(mockReq.user.id);
|
|
});
|
|
|
|
test('management creation can be updated and read through the authenticated management API', async () => {
|
|
const tenantId = `tenant-${nanoid(8)}`;
|
|
const clientId = `client-${nanoid(8)}`;
|
|
const principal = await tenantStorage.run({ tenantId }, () => createOwner());
|
|
const userId = principal._id.toString();
|
|
const getRoleByName = jest.fn().mockResolvedValue({
|
|
permissions: {
|
|
[PermissionTypes.AGENTS]: {
|
|
[Permissions.USE]: true,
|
|
[Permissions.CREATE]: true,
|
|
},
|
|
},
|
|
});
|
|
grantPermission.mockImplementation(
|
|
async ({ principalType, principalId, resourceType, resourceId, grantedBy }) =>
|
|
AclEntry.create({
|
|
principalType,
|
|
principalModel: PrincipalModel.USER,
|
|
principalId,
|
|
resourceType,
|
|
resourceId,
|
|
permBits: OWNER_PERMISSION_BITS,
|
|
grantedBy,
|
|
grantedAt: new Date(),
|
|
}),
|
|
);
|
|
const auth = createAgentManagementAuth({
|
|
findUser: db.findUser,
|
|
isPrincipalActive: jest.fn().mockResolvedValue(true),
|
|
getAppConfig: jest.fn().mockResolvedValue({
|
|
endpoints: {
|
|
agents: {
|
|
managementApi: {
|
|
auth: {
|
|
oidc: {
|
|
enabled: true,
|
|
audience: 'agent-management',
|
|
issuer: 'https://issuer.example.com/',
|
|
},
|
|
clients: [{ clientId, tenantId, userId }],
|
|
},
|
|
},
|
|
},
|
|
},
|
|
}),
|
|
verifyAccessToken: jest.fn().mockResolvedValue({
|
|
azp: clientId,
|
|
sub: `${clientId}@clients`,
|
|
exp: Math.floor(Date.now() / 1000) + 300,
|
|
}),
|
|
});
|
|
const create = createAgentManagementCreateHandler({
|
|
getRoleByName,
|
|
createAgent: createAgentHandler,
|
|
});
|
|
const checkAgentPermission = async ({
|
|
userId: accessibleUserId,
|
|
resourceType,
|
|
resourceId,
|
|
requiredPermission,
|
|
}) =>
|
|
(await AclEntry.exists({
|
|
principalId: accessibleUserId,
|
|
resourceType,
|
|
resourceId,
|
|
permBits: { $bitsAllSet: requiredPermission },
|
|
})) != null;
|
|
const hasCapability = jest.fn().mockResolvedValue(false);
|
|
const reads = createAgentManagementReadHandlers({
|
|
getRoleByName,
|
|
getAgentWithVersionCount: db.getAgentWithVersionCount,
|
|
getAgentManagementListByAccess: db.getAgentManagementListByAccess,
|
|
findAccessibleResources: async ({ userId: accessibleUserId, resourceType }) =>
|
|
AclEntry.distinct('resourceId', {
|
|
principalId: accessibleUserId,
|
|
resourceType,
|
|
permBits: { $bitsAllSet: PermissionBits.EDIT },
|
|
}),
|
|
checkPermission: checkAgentPermission,
|
|
hasCapability,
|
|
});
|
|
const update = createAgentManagementUpdateHandler({
|
|
getRoleByName,
|
|
getAgentWithVersionCount: db.getAgentWithVersionCount,
|
|
checkPermission: checkAgentPermission,
|
|
hasCapability,
|
|
updateAgent: updateAgentHandler,
|
|
});
|
|
const remove = createAgentManagementDeleteHandler({
|
|
getRoleByName,
|
|
getAgentWithVersionCount: db.getAgentWithVersionCount,
|
|
checkPermission: checkAgentPermission,
|
|
hasCapability,
|
|
deleteAgent: db.deleteAgent,
|
|
});
|
|
const app = express();
|
|
app.use(express.json());
|
|
app.use('/api/agents/v1/agents', auth);
|
|
app.post('/api/agents/v1/agents', (req, res) => {
|
|
req.config = {};
|
|
return create(req, res);
|
|
});
|
|
app.get('/api/agents/v1/agents', reads.list);
|
|
app.get('/api/agents/v1/agents/:id', reads.get);
|
|
app.patch('/api/agents/v1/agents/:id', (req, res) => {
|
|
req.config = {};
|
|
return update(req, res);
|
|
});
|
|
app.delete('/api/agents/v1/agents/:id', remove);
|
|
|
|
const createdResponse = await request(app)
|
|
.post('/api/agents/v1/agents')
|
|
.set('Authorization', 'Bearer valid-token')
|
|
.send({
|
|
name: 'Managed Agent',
|
|
description: 'Description that remains unchanged',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
avatar: { filepath: 'avatars/managed.png', source: 'local' },
|
|
conversation_starters: ['Help me get started'],
|
|
});
|
|
|
|
expect(createdResponse.status).toBe(201);
|
|
expect(createdResponse.body).toEqual(
|
|
expect.objectContaining({
|
|
id: expect.stringMatching(/^agent_/),
|
|
name: 'Managed Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
version: 1,
|
|
}),
|
|
);
|
|
expect(createdResponse.body).not.toHaveProperty('_id');
|
|
expect(createdResponse.body).not.toHaveProperty('author');
|
|
expect(createdResponse.body).not.toHaveProperty('tenantId');
|
|
|
|
const [retrievedResponse, listedResponse] = await Promise.all([
|
|
request(app)
|
|
.get(`/api/agents/v1/agents/${createdResponse.body.id}`)
|
|
.set('Authorization', 'Bearer valid-token'),
|
|
request(app).get('/api/agents/v1/agents').set('Authorization', 'Bearer valid-token'),
|
|
]);
|
|
|
|
expect(retrievedResponse.status).toBe(200);
|
|
expect(retrievedResponse.body).toEqual(createdResponse.body);
|
|
expect(listedResponse.status).toBe(200);
|
|
expect(listedResponse.body.data).toEqual([createdResponse.body]);
|
|
|
|
const otherTenantId = `tenant-${nanoid(8)}`;
|
|
const currentTenantGraphId = `agent_${nanoid()}`;
|
|
const otherTenantGraphId = `agent_${nanoid()}`;
|
|
await tenantStorage.run({ tenantId }, async () => {
|
|
await Agent.create({
|
|
id: currentTenantGraphId,
|
|
name: 'Current tenant graph',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: principal._id,
|
|
edges: [{ from: '', to: createdResponse.body.id, edgeType: 'handoff' }],
|
|
});
|
|
await User.updateOne(
|
|
{ _id: principal._id },
|
|
{ $set: { favorites: [{ agentId: createdResponse.body.id }] } },
|
|
);
|
|
});
|
|
const otherTenantPrincipal = await tenantStorage.run(
|
|
{ tenantId: otherTenantId },
|
|
async () => {
|
|
const owner = await createOwner();
|
|
await Agent.create({
|
|
id: createdResponse.body.id,
|
|
name: 'Other tenant Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: owner._id,
|
|
});
|
|
await Agent.create({
|
|
id: otherTenantGraphId,
|
|
name: 'Other tenant graph',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: owner._id,
|
|
edges: [{ from: '', to: createdResponse.body.id, edgeType: 'handoff' }],
|
|
});
|
|
await User.updateOne(
|
|
{ _id: owner._id },
|
|
{ $set: { favorites: [{ agentId: createdResponse.body.id }] } },
|
|
);
|
|
return owner;
|
|
},
|
|
);
|
|
|
|
const updatedResponse = await request(app)
|
|
.patch(`/api/agents/v1/agents/${createdResponse.body.id}`)
|
|
.set('Authorization', 'Bearer valid-token')
|
|
.send({
|
|
name: 'Updated Managed Agent',
|
|
avatar: null,
|
|
conversation_starters: [],
|
|
});
|
|
|
|
expect(updatedResponse.status).toBe(200);
|
|
expect(updatedResponse.body).toEqual(
|
|
expect.objectContaining({
|
|
id: createdResponse.body.id,
|
|
name: 'Updated Managed Agent',
|
|
description: 'Description that remains unchanged',
|
|
avatar: null,
|
|
conversation_starters: [],
|
|
version: 2,
|
|
}),
|
|
);
|
|
expect(updatedResponse.body).not.toHaveProperty('_id');
|
|
expect(updatedResponse.body).not.toHaveProperty('author');
|
|
expect(updatedResponse.body).not.toHaveProperty('tenantId');
|
|
|
|
const retrievedAfterUpdate = await request(app)
|
|
.get(`/api/agents/v1/agents/${createdResponse.body.id}`)
|
|
.set('Authorization', 'Bearer valid-token');
|
|
expect(retrievedAfterUpdate.status).toBe(200);
|
|
expect(retrievedAfterUpdate.body).toEqual(updatedResponse.body);
|
|
|
|
const created = await Agent.collection.findOne({
|
|
id: createdResponse.body.id,
|
|
tenantId,
|
|
});
|
|
const otherTenantAgent = await Agent.collection.findOne({
|
|
id: createdResponse.body.id,
|
|
tenantId: otherTenantId,
|
|
});
|
|
expect(created.tenantId).toBe(tenantId);
|
|
expect(created.author.toString()).toBe(userId);
|
|
expect(created.name).toBe('Updated Managed Agent');
|
|
expect(created.description).toBe('Description that remains unchanged');
|
|
expect(created.avatar).toBeNull();
|
|
expect(created.conversation_starters).toEqual([]);
|
|
expect(created.versions).toHaveLength(2);
|
|
expect(otherTenantAgent.name).toBe('Other tenant Agent');
|
|
expect(grantPermission).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
principalType: PrincipalType.USER,
|
|
principalId: userId,
|
|
resourceType: ResourceType.AGENT,
|
|
}),
|
|
);
|
|
|
|
const deletedResponse = await request(app)
|
|
.delete(`/api/agents/v1/agents/${createdResponse.body.id}`)
|
|
.set('Authorization', 'Bearer valid-token');
|
|
expect(deletedResponse.status).toBe(200);
|
|
expect(deletedResponse.body).toEqual({ id: createdResponse.body.id, deleted: true });
|
|
|
|
const [retrievedAfterDelete, repeatedDelete] = await Promise.all([
|
|
request(app)
|
|
.get(`/api/agents/v1/agents/${createdResponse.body.id}`)
|
|
.set('Authorization', 'Bearer valid-token'),
|
|
request(app)
|
|
.delete(`/api/agents/v1/agents/${createdResponse.body.id}`)
|
|
.set('Authorization', 'Bearer valid-token'),
|
|
]);
|
|
expect(retrievedAfterDelete.status).toBe(404);
|
|
expect(repeatedDelete.status).toBe(404);
|
|
await expect(Agent.exists({ id: createdResponse.body.id, tenantId })).resolves.toBeNull();
|
|
await expect(
|
|
Agent.exists({ id: createdResponse.body.id, tenantId: otherTenantId }),
|
|
).resolves.not.toBeNull();
|
|
await expect(
|
|
Agent.exists({
|
|
id: currentTenantGraphId,
|
|
tenantId,
|
|
'edges.to': createdResponse.body.id,
|
|
}),
|
|
).resolves.toBeNull();
|
|
await expect(
|
|
Agent.exists({
|
|
id: otherTenantGraphId,
|
|
tenantId: otherTenantId,
|
|
'edges.to': createdResponse.body.id,
|
|
}),
|
|
).resolves.not.toBeNull();
|
|
await expect(
|
|
User.exists({
|
|
_id: principal._id,
|
|
tenantId,
|
|
'favorites.agentId': createdResponse.body.id,
|
|
}),
|
|
).resolves.toBeNull();
|
|
await expect(
|
|
User.exists({
|
|
_id: otherTenantPrincipal._id,
|
|
tenantId: otherTenantId,
|
|
'favorites.agentId': createdResponse.body.id,
|
|
}),
|
|
).resolves.not.toBeNull();
|
|
});
|
|
|
|
test('management creation rejects caller-controlled ownership', async () => {
|
|
const handler = createAgentManagementCreateHandler({
|
|
getRoleByName: jest.fn().mockResolvedValue({
|
|
permissions: {
|
|
[PermissionTypes.AGENTS]: {
|
|
[Permissions.USE]: true,
|
|
[Permissions.CREATE]: true,
|
|
},
|
|
},
|
|
}),
|
|
createAgent: createAgentHandler,
|
|
});
|
|
mockReq.user.tenantId = 'tenant-a';
|
|
mockReq.body = {
|
|
name: 'Managed Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: new mongoose.Types.ObjectId().toString(),
|
|
};
|
|
|
|
await handler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
expect(await Agent.countDocuments()).toBe(0);
|
|
});
|
|
|
|
test('should reject creation with unauthorized fields (mass assignment protection)', async () => {
|
|
const maliciousData = {
|
|
// Required fields
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
name: 'Malicious Agent',
|
|
|
|
// Unauthorized fields that should be stripped
|
|
author: new mongoose.Types.ObjectId().toString(), // Should not be able to set author
|
|
authorName: 'Hacker', // Should be stripped
|
|
versions: [], // Should be stripped
|
|
_id: new mongoose.Types.ObjectId(), // Should be stripped
|
|
id: 'custom_agent_id', // Should be overridden
|
|
createdAt: new Date('2020-01-01'), // Should be stripped
|
|
updatedAt: new Date('2020-01-01'), // Should be stripped
|
|
};
|
|
|
|
mockReq.body = maliciousData;
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(201);
|
|
|
|
const createdAgent = mockRes.json.mock.calls[0][0];
|
|
|
|
// Verify unauthorized fields were not set
|
|
expect(createdAgent.author.toString()).toBe(mockReq.user.id); // Should be the request user, not the malicious value
|
|
expect(createdAgent.authorName).toBeUndefined();
|
|
expect(createdAgent.versions).toHaveLength(1); // Should have exactly 1 version from creation
|
|
expect(createdAgent.id).not.toBe('custom_agent_id'); // Should have generated ID
|
|
expect(createdAgent.id).toMatch(/^agent_/); // Should have proper prefix
|
|
|
|
// Verify timestamps are recent (not the malicious dates)
|
|
const createdTime = new Date(createdAgent.createdAt).getTime();
|
|
const now = Date.now();
|
|
expect(now - createdTime).toBeLessThan(5000); // Created within last 5 seconds
|
|
|
|
// Verify in database
|
|
const agentInDb = await Agent.findOne({ id: createdAgent.id });
|
|
expect(agentInDb.author.toString()).toBe(mockReq.user.id);
|
|
expect(agentInDb.authorName).toBeUndefined();
|
|
});
|
|
|
|
test('should validate required fields', async () => {
|
|
const invalidData = {
|
|
name: 'Missing Required Fields',
|
|
// Missing provider and model
|
|
};
|
|
|
|
mockReq.body = invalidData;
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
expect(mockRes.json).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
error: 'Invalid request data',
|
|
details: expect.any(Array),
|
|
}),
|
|
);
|
|
|
|
// Verify nothing was created in database
|
|
const count = await Agent.countDocuments();
|
|
expect(count).toBe(0);
|
|
});
|
|
|
|
test('should handle tool_resources validation', async () => {
|
|
const dataWithInvalidToolResources = {
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
name: 'Agent with Tool Resources',
|
|
tool_resources: {
|
|
// Valid resources
|
|
file_search: {
|
|
file_ids: ['file1', 'file2'],
|
|
vector_store_ids: ['vs1'],
|
|
},
|
|
execute_code: {
|
|
file_ids: ['file3'],
|
|
},
|
|
// Invalid resource (should be stripped by schema)
|
|
invalid_resource: {
|
|
file_ids: ['file4'],
|
|
},
|
|
},
|
|
};
|
|
|
|
mockReq.body = dataWithInvalidToolResources;
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(201);
|
|
|
|
const createdAgent = mockRes.json.mock.calls[0][0];
|
|
expect(createdAgent.tool_resources).toBeDefined();
|
|
expect(createdAgent.tool_resources.file_search).toBeDefined();
|
|
expect(createdAgent.tool_resources.execute_code).toBeDefined();
|
|
expect(createdAgent.tool_resources.invalid_resource).toBeUndefined(); // Should be stripped
|
|
|
|
// Verify in database
|
|
const agentInDb = await Agent.findOne({ id: createdAgent.id });
|
|
expect(agentInDb.tool_resources.invalid_resource).toBeUndefined();
|
|
});
|
|
|
|
test('should strip runtime file records before persisting an agent', async () => {
|
|
mockReq.body = {
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
name: 'Agent with forged runtime file',
|
|
tool_resources: {
|
|
execute_code: {
|
|
files: [
|
|
{
|
|
file_id: 'forged-file',
|
|
filepath: '/etc/passwd',
|
|
source: FileSources.local,
|
|
},
|
|
],
|
|
},
|
|
},
|
|
};
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(201);
|
|
const createdAgent = mockRes.json.mock.calls[0][0];
|
|
expect(createdAgent.tool_resources?.execute_code?.files).toBeUndefined();
|
|
|
|
const agentInDb = await Agent.findOne({ id: createdAgent.id }).lean();
|
|
expect(agentInDb.tool_resources?.execute_code?.files).toBeUndefined();
|
|
expect(agentInDb.versions[0].tool_resources?.execute_code?.files).toBeUndefined();
|
|
});
|
|
|
|
test('should strip file_ids not owned by the creator from tool_resources', async () => {
|
|
const File = mongoose.models.File;
|
|
|
|
const ownedFileId = `file_${uuidv4()}`;
|
|
const otherFileId = `file_${uuidv4()}`;
|
|
await File.create({
|
|
file_id: ownedFileId,
|
|
user: mockReq.user.id,
|
|
filename: `${ownedFileId}.txt`,
|
|
filepath: `/tmp/${ownedFileId}`,
|
|
object: 'file',
|
|
type: 'text/plain',
|
|
bytes: 1,
|
|
source: FileSources.local,
|
|
});
|
|
await File.create({
|
|
file_id: otherFileId,
|
|
user: new mongoose.Types.ObjectId(),
|
|
filename: `${otherFileId}.txt`,
|
|
filepath: `/tmp/${otherFileId}`,
|
|
object: 'file',
|
|
type: 'text/plain',
|
|
bytes: 1,
|
|
source: FileSources.local,
|
|
});
|
|
|
|
mockReq.body = {
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
name: 'Agent with Files',
|
|
tool_resources: {
|
|
file_search: { file_ids: [ownedFileId, otherFileId] },
|
|
},
|
|
};
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(201);
|
|
const createdAgent = mockRes.json.mock.calls[0][0];
|
|
expect(createdAgent.tool_resources.file_search.file_ids).toEqual([ownedFileId]);
|
|
});
|
|
|
|
test('hydrates owned file_ids before fail-close agent resource inspection', async () => {
|
|
const File = mongoose.models.File;
|
|
const ownedFileId = `file_${uuidv4()}`;
|
|
await File.create({
|
|
file_id: ownedFileId,
|
|
user: mockReq.user.id,
|
|
filename: `${ownedFileId}.txt`,
|
|
filepath: `/tmp/${ownedFileId}`,
|
|
text: 'safe extracted text',
|
|
object: 'file',
|
|
type: 'text/plain',
|
|
bytes: 1,
|
|
source: FileSources.local,
|
|
});
|
|
mockReq.config = {
|
|
filters: {
|
|
files: {
|
|
pii: {
|
|
fields: ['extracted_text'],
|
|
uninspectable: 'block',
|
|
},
|
|
},
|
|
},
|
|
};
|
|
mockReq.body = {
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
name: 'Agent with inspected files',
|
|
tool_resources: {
|
|
file_search: { file_ids: [ownedFileId] },
|
|
},
|
|
};
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(201);
|
|
expect(mockRes.json.mock.calls[0][0].tool_resources.file_search.file_ids).toEqual([
|
|
ownedFileId,
|
|
]);
|
|
});
|
|
|
|
test('blocks agent creation when hydrated resource text matches file policy', async () => {
|
|
const File = mongoose.models.File;
|
|
const ownedFileId = `file_${uuidv4()}`;
|
|
await File.create({
|
|
file_id: ownedFileId,
|
|
user: mockReq.user.id,
|
|
filename: `${ownedFileId}.txt`,
|
|
filepath: `/tmp/${ownedFileId}`,
|
|
text: 'PRIVATE-CANONICAL-CONTEXT',
|
|
object: 'file',
|
|
type: 'text/plain',
|
|
bytes: 1,
|
|
source: FileSources.local,
|
|
});
|
|
mockReq.config = {
|
|
filters: {
|
|
files: {
|
|
pii: {
|
|
fields: ['extracted_text'],
|
|
starterPatterns: [],
|
|
customPatterns: [
|
|
{
|
|
id: 'private-canonical-context',
|
|
label: 'private canonical context',
|
|
regex: 'PRIVATE-CANONICAL-CONTEXT',
|
|
},
|
|
],
|
|
uninspectable: 'block',
|
|
},
|
|
},
|
|
},
|
|
};
|
|
mockReq.body = {
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
name: 'Agent with blocked files',
|
|
tool_resources: {
|
|
file_search: { file_ids: [ownedFileId] },
|
|
},
|
|
};
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
expect(mockRes.json).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
error: 'content_filter_block',
|
|
source: 'file',
|
|
field: 'extracted_text',
|
|
}),
|
|
);
|
|
await expect(Agent.countDocuments()).resolves.toBe(0);
|
|
});
|
|
|
|
test('canonicalizes hydrated tool resource files before create persistence', async () => {
|
|
const File = mongoose.models.File;
|
|
const ownedFileId = `file_${uuidv4()}`;
|
|
const otherFileId = `file_${uuidv4()}`;
|
|
await File.create({
|
|
file_id: ownedFileId,
|
|
user: mockReq.user.id,
|
|
filename: `${ownedFileId}.txt`,
|
|
filepath: `/tmp/${ownedFileId}`,
|
|
object: 'file',
|
|
type: 'text/plain',
|
|
bytes: 1,
|
|
source: FileSources.local,
|
|
});
|
|
await File.create({
|
|
file_id: otherFileId,
|
|
user: new mongoose.Types.ObjectId(),
|
|
filename: `${otherFileId}.txt`,
|
|
filepath: `/tmp/${otherFileId}`,
|
|
object: 'file',
|
|
type: 'text/plain',
|
|
bytes: 1,
|
|
source: FileSources.local,
|
|
});
|
|
mockReq.body = {
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
name: 'Agent with Hydrated Files',
|
|
tool_resources: {
|
|
execute_code: {
|
|
files: [
|
|
{ file_id: ownedFileId, filename: 'PRIVATE-SENTINEL' },
|
|
{ file_id: otherFileId, metadata: { codeEnvRef: { file_id: 'untrusted' } } },
|
|
],
|
|
},
|
|
},
|
|
};
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(201);
|
|
const createdAgent = mockRes.json.mock.calls[0][0];
|
|
expect(createdAgent.tool_resources.execute_code.file_ids).toEqual([ownedFileId]);
|
|
expect(createdAgent.tool_resources.execute_code.files).toBeUndefined();
|
|
expect(JSON.stringify(createdAgent)).not.toContain('PRIVATE-SENTINEL');
|
|
expect(JSON.stringify(createdAgent)).not.toContain('untrusted');
|
|
});
|
|
|
|
test('should handle support_contact with empty strings', async () => {
|
|
const dataWithEmptyContact = {
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
name: 'Agent with Empty Contact',
|
|
support_contact: {
|
|
name: '',
|
|
email: '',
|
|
},
|
|
};
|
|
|
|
mockReq.body = dataWithEmptyContact;
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(201);
|
|
|
|
const createdAgent = mockRes.json.mock.calls[0][0];
|
|
expect(createdAgent.name).toBe('Agent with Empty Contact');
|
|
expect(createdAgent.support_contact).toBeDefined();
|
|
expect(createdAgent.support_contact.name).toBe('');
|
|
expect(createdAgent.support_contact.email).toBe('');
|
|
});
|
|
|
|
test('should handle support_contact with valid email', async () => {
|
|
const dataWithValidContact = {
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
name: 'Agent with Valid Contact',
|
|
support_contact: {
|
|
name: 'Support Team',
|
|
email: 'support@example.com',
|
|
},
|
|
};
|
|
|
|
mockReq.body = dataWithValidContact;
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(201);
|
|
|
|
const createdAgent = mockRes.json.mock.calls[0][0];
|
|
expect(createdAgent.support_contact).toBeDefined();
|
|
expect(createdAgent.support_contact.name).toBe('Support Team');
|
|
expect(createdAgent.support_contact.email).toBe('support@example.com');
|
|
});
|
|
|
|
test('should reject support_contact with invalid email', async () => {
|
|
const dataWithInvalidEmail = {
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
name: 'Agent with Invalid Email',
|
|
support_contact: {
|
|
name: 'Support',
|
|
email: 'not-an-email',
|
|
},
|
|
};
|
|
|
|
mockReq.body = dataWithInvalidEmail;
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
expect(mockRes.json).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
error: 'Invalid request data',
|
|
details: expect.arrayContaining([
|
|
expect.objectContaining({
|
|
path: ['support_contact', 'email'],
|
|
}),
|
|
]),
|
|
}),
|
|
);
|
|
});
|
|
|
|
test('should handle avatar validation', async () => {
|
|
const dataWithAvatar = {
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
name: 'Agent with Avatar',
|
|
avatar: {
|
|
filepath: 'https://example.com/avatar.png',
|
|
source: 's3',
|
|
},
|
|
};
|
|
|
|
mockReq.body = dataWithAvatar;
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(201);
|
|
|
|
const createdAgent = mockRes.json.mock.calls[0][0];
|
|
expect(createdAgent.avatar).toEqual({
|
|
filepath: 'https://example.com/avatar.png',
|
|
source: 's3',
|
|
});
|
|
});
|
|
|
|
test('should remove empty strings from model_parameters (Issue Fix)', async () => {
|
|
// This tests the fix for empty strings being sent to API instead of being omitted
|
|
// When a user clears a numeric field (like max_tokens), it should be removed, not sent as ""
|
|
const dataWithEmptyModelParams = {
|
|
provider: 'azureOpenAI',
|
|
model: 'gpt-4',
|
|
name: 'Agent with Empty Model Params',
|
|
model_parameters: {
|
|
temperature: 0.7, // Valid number - should be preserved
|
|
max_tokens: '', // Empty string - should be removed
|
|
maxContextTokens: '', // Empty string - should be removed
|
|
topP: 0, // Zero value - should be preserved (not treated as empty)
|
|
frequency_penalty: '', // Empty string - should be removed
|
|
},
|
|
};
|
|
|
|
mockReq.body = dataWithEmptyModelParams;
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(201);
|
|
|
|
const createdAgent = mockRes.json.mock.calls[0][0];
|
|
expect(createdAgent.model_parameters).toBeDefined();
|
|
// Valid numbers should be preserved
|
|
expect(createdAgent.model_parameters.temperature).toBe(0.7);
|
|
expect(createdAgent.model_parameters.topP).toBe(0);
|
|
// Empty strings should be removed
|
|
expect(createdAgent.model_parameters.max_tokens).toBeUndefined();
|
|
expect(createdAgent.model_parameters.maxContextTokens).toBeUndefined();
|
|
expect(createdAgent.model_parameters.frequency_penalty).toBeUndefined();
|
|
|
|
// Verify in database
|
|
const agentInDb = await Agent.findOne({ id: createdAgent.id });
|
|
expect(agentInDb.model_parameters.temperature).toBe(0.7);
|
|
expect(agentInDb.model_parameters.topP).toBe(0);
|
|
expect(agentInDb.model_parameters.max_tokens).toBeUndefined();
|
|
expect(agentInDb.model_parameters.maxContextTokens).toBeUndefined();
|
|
});
|
|
|
|
test('should drop non-numeric strings and coerce numeric strings in model_parameters', async () => {
|
|
// Regression test for #12920: a stray placeholder string ("System") persisted
|
|
// into max_tokens was forwarded to the provider, causing a 400
|
|
const dataWithCorruptModelParams = {
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
name: 'Agent with Corrupt Model Params',
|
|
model_parameters: {
|
|
max_tokens: 'System',
|
|
maxContextTokens: '256000',
|
|
fileTokenLimit: 256000,
|
|
useResponsesApi: true,
|
|
},
|
|
};
|
|
|
|
mockReq.body = dataWithCorruptModelParams;
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(201);
|
|
|
|
const createdAgent = mockRes.json.mock.calls[0][0];
|
|
expect(createdAgent.model_parameters.max_tokens).toBeUndefined();
|
|
expect(createdAgent.model_parameters.maxContextTokens).toBe(256000);
|
|
expect(createdAgent.model_parameters.fileTokenLimit).toBe(256000);
|
|
expect(createdAgent.model_parameters.useResponsesApi).toBe(true);
|
|
|
|
const agentInDb = await Agent.findOne({ id: createdAgent.id });
|
|
expect(agentInDb.model_parameters.max_tokens).toBeUndefined();
|
|
expect(agentInDb.model_parameters.maxContextTokens).toBe(256000);
|
|
});
|
|
|
|
test('should handle invalid avatar format', async () => {
|
|
const dataWithInvalidAvatar = {
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
name: 'Agent with Invalid Avatar',
|
|
avatar: 'just-a-string', // Invalid format
|
|
};
|
|
|
|
mockReq.body = dataWithInvalidAvatar;
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
expect(mockRes.json).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
error: 'Invalid request data',
|
|
}),
|
|
);
|
|
});
|
|
});
|
|
|
|
describe('getAgentHandler', () => {
|
|
test('should return the safe Responses API flag in the basic VIEW response', async () => {
|
|
const agent = await Agent.create({
|
|
id: `agent_${uuidv4()}`,
|
|
name: 'Azure Agent',
|
|
description: 'Uses Responses API',
|
|
provider: 'azureOpenAI',
|
|
model: 'gpt-5.5',
|
|
author: mockReq.user.id,
|
|
model_parameters: {
|
|
useResponsesApi: true,
|
|
temperature: 0.7,
|
|
apiKey: 'secret-value',
|
|
},
|
|
});
|
|
|
|
mockReq.params = { id: agent.id };
|
|
|
|
await getAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(200);
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.model_parameters).toEqual({ useResponsesApi: true });
|
|
expect(response.model_parameters.temperature).toBeUndefined();
|
|
expect(response.model_parameters.apiKey).toBeUndefined();
|
|
});
|
|
|
|
test('should return owner_contact from the first ACL owner when support_contact is missing', async () => {
|
|
const owner = await createOwner({
|
|
name: 'Primary Owner',
|
|
email: 'primary.owner@example.com',
|
|
});
|
|
const agent = await Agent.create({
|
|
id: `agent_${uuidv4()}`,
|
|
name: 'Owner Contact Agent',
|
|
description: 'Uses owner fallback',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: owner._id,
|
|
});
|
|
await grantAgentOwner({ agent, owner });
|
|
|
|
mockReq.params = { id: agent.id };
|
|
|
|
await getAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(200);
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.owner_contact).toEqual({ name: 'Primary Owner' });
|
|
expect(response.owner_contact).not.toHaveProperty('email');
|
|
});
|
|
|
|
test('should omit owner_contact when the owner name and username are the account email', async () => {
|
|
const email = 'sso.owner@example.com';
|
|
const owner = await createOwner({ name: email, username: email, email });
|
|
const agent = await Agent.create({
|
|
id: `agent_${uuidv4()}`,
|
|
name: 'SSO Owner Agent',
|
|
description: 'Owner has email-shaped name from SSO fallback',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: owner._id,
|
|
});
|
|
await grantAgentOwner({ agent, owner });
|
|
|
|
mockReq.params = { id: agent.id };
|
|
|
|
await getAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(200);
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.owner_contact).toBeUndefined();
|
|
});
|
|
|
|
test('should not return owner_contact when support_contact is present', async () => {
|
|
const owner = await createOwner({
|
|
name: 'Primary Owner',
|
|
email: 'primary.owner@example.com',
|
|
});
|
|
const agent = await Agent.create({
|
|
id: `agent_${uuidv4()}`,
|
|
name: 'Support Contact Agent',
|
|
description: 'Uses support contact',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: owner._id,
|
|
support_contact: { name: 'Support Team', email: 'support@example.com' },
|
|
});
|
|
await grantAgentOwner({ agent, owner });
|
|
|
|
mockReq.params = { id: agent.id };
|
|
|
|
await getAgentHandler(mockReq, mockRes);
|
|
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.support_contact).toEqual({
|
|
name: 'Support Team',
|
|
email: 'support@example.com',
|
|
});
|
|
expect(response.owner_contact).toBeUndefined();
|
|
});
|
|
|
|
test('should include conversation_starters in the basic VIEW response', async () => {
|
|
const starters = ['Summarize this page', 'What can you do?'];
|
|
const agent = await Agent.create({
|
|
id: `agent_${uuidv4()}`,
|
|
name: 'Starter Agent',
|
|
description: 'Exposes conversation starters',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: mockReq.user.id,
|
|
conversation_starters: starters,
|
|
});
|
|
|
|
mockReq.params = { id: agent.id };
|
|
|
|
await getAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(200);
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.conversation_starters).toEqual(starters);
|
|
});
|
|
});
|
|
|
|
describe('getAgentVersionsHandler', () => {
|
|
test('returns the version history and excludes it from the basic VIEW response', async () => {
|
|
const agent = await Agent.create({
|
|
id: `agent_${uuidv4()}`,
|
|
name: 'Versioned Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: mockReq.user.id,
|
|
versions: [
|
|
{ name: 'V1', provider: 'openai', model: 'gpt-4', updatedAt: new Date() },
|
|
{ name: 'V2', provider: 'openai', model: 'gpt-4', updatedAt: new Date() },
|
|
],
|
|
});
|
|
mockReq.params = { id: agent.id };
|
|
|
|
await getAgentHandler(mockReq, mockRes);
|
|
const basicResponse = mockRes.json.mock.calls[0][0];
|
|
expect(basicResponse.versions).toBeUndefined();
|
|
expect(basicResponse.version).toBe(2);
|
|
|
|
mockRes.json.mockClear();
|
|
await getAgentVersionsHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(200);
|
|
const versions = mockRes.json.mock.calls[0][0];
|
|
expect(Array.isArray(versions)).toBe(true);
|
|
expect(versions).toHaveLength(2);
|
|
expect(versions.map((v) => v.name)).toEqual(['V1', 'V2']);
|
|
});
|
|
|
|
test('returns 404 when the agent does not exist', async () => {
|
|
mockReq.params = { id: `agent_${uuidv4()}` };
|
|
|
|
await getAgentVersionsHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(404);
|
|
});
|
|
});
|
|
|
|
describe('updateAgentHandler', () => {
|
|
let existingAgentId;
|
|
let existingAgentAuthorId;
|
|
|
|
beforeEach(async () => {
|
|
// Create an existing agent for update tests
|
|
existingAgentAuthorId = new mongoose.Types.ObjectId();
|
|
const agent = await Agent.create({
|
|
id: `agent_${uuidv4()}`,
|
|
name: 'Original Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-3.5-turbo',
|
|
author: existingAgentAuthorId,
|
|
description: 'Original description',
|
|
versions: [
|
|
{
|
|
name: 'Original Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-3.5-turbo',
|
|
description: 'Original description',
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
},
|
|
],
|
|
});
|
|
existingAgentId = agent.id;
|
|
});
|
|
|
|
test('should update agent with allowed fields only', async () => {
|
|
mockReq.user.id = existingAgentAuthorId.toString(); // Set as author
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = {
|
|
name: 'Updated Agent',
|
|
description: 'Updated description',
|
|
model: 'gpt-4',
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).not.toHaveBeenCalledWith(400);
|
|
expect(mockRes.status).not.toHaveBeenCalledWith(403);
|
|
expect(mockRes.json).toHaveBeenCalled();
|
|
|
|
const updatedAgent = mockRes.json.mock.calls[0][0];
|
|
expect(updatedAgent.name).toBe('Updated Agent');
|
|
expect(updatedAgent.description).toBe('Updated description');
|
|
expect(updatedAgent.model).toBe('gpt-4');
|
|
expect(updatedAgent.author).toBe(existingAgentAuthorId.toString());
|
|
|
|
// Verify in database
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
|
expect(agentInDb.name).toBe('Updated Agent');
|
|
});
|
|
|
|
test('removes newly added programmatic options when Code Interpreter capability is disabled', async () => {
|
|
await Agent.updateOne(
|
|
{ id: existingAgentId },
|
|
{ tools: [Tools.execute_code, 'search_mcp_example'] },
|
|
);
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = {
|
|
tool_options: {
|
|
search_mcp_example: { allowed_callers: ['code_execution'] },
|
|
},
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).not.toHaveBeenCalledWith(400);
|
|
expect(mockRes.json.mock.calls[0][0].tool_options).toEqual({});
|
|
});
|
|
|
|
test('removes programmatic callers when Code Interpreter is disabled', async () => {
|
|
await Agent.updateOne(
|
|
{ id: existingAgentId },
|
|
{
|
|
tools: [Tools.execute_code, 'search_mcp_example'],
|
|
tool_options: {
|
|
search_mcp_example: {
|
|
allowed_callers: ['code_execution'],
|
|
defer_loading: true,
|
|
},
|
|
},
|
|
},
|
|
);
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = { tools: ['search_mcp_example'] };
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).not.toHaveBeenCalledWith(400);
|
|
expect(mockRes.json.mock.calls[0][0].tool_options).toEqual({
|
|
search_mcp_example: { defer_loading: true },
|
|
});
|
|
});
|
|
|
|
test('allows unrelated edits to a legacy inconsistent agent', async () => {
|
|
await Agent.updateOne(
|
|
{ id: existingAgentId },
|
|
{
|
|
tools: ['search_mcp_example'],
|
|
tool_options: {
|
|
search_mcp_example: { allowed_callers: ['code_execution'] },
|
|
},
|
|
},
|
|
);
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = { description: 'Still saveable' };
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).not.toHaveBeenCalledWith(400);
|
|
expect(mockRes.json.mock.calls[0][0].description).toBe('Still saveable');
|
|
});
|
|
|
|
test('allows detaching a programmatic tool from a legacy inconsistent agent', async () => {
|
|
await Agent.updateOne(
|
|
{ id: existingAgentId },
|
|
{
|
|
tools: ['search_mcp_example'],
|
|
tool_options: {
|
|
search_mcp_example: { allowed_callers: ['code_execution'] },
|
|
},
|
|
},
|
|
);
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = { tools: [] };
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).not.toHaveBeenCalledWith(400);
|
|
expect(mockRes.json.mock.calls[0][0].tools).toEqual([]);
|
|
expect(mockRes.json.mock.calls[0][0].tool_options).toEqual({});
|
|
});
|
|
|
|
test('allows clearing programmatic options from a legacy inconsistent agent', async () => {
|
|
await Agent.updateOne(
|
|
{ id: existingAgentId },
|
|
{
|
|
tools: ['search_mcp_example'],
|
|
tool_options: {
|
|
search_mcp_example: { allowed_callers: ['code_execution'] },
|
|
},
|
|
},
|
|
);
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = { tool_options: {} };
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).not.toHaveBeenCalledWith(400);
|
|
expect(mockRes.json.mock.calls[0][0].tool_options).toEqual({});
|
|
});
|
|
|
|
test('removes all newly submitted programmatic options from a legacy agent', async () => {
|
|
await Agent.updateOne(
|
|
{ id: existingAgentId },
|
|
{
|
|
tools: ['search_mcp_example', 'lookup_mcp_example'],
|
|
tool_options: {
|
|
search_mcp_example: { allowed_callers: ['code_execution'] },
|
|
},
|
|
},
|
|
);
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = {
|
|
tool_options: {
|
|
search_mcp_example: { allowed_callers: ['code_execution'] },
|
|
lookup_mcp_example: { allowed_callers: ['code_execution'] },
|
|
},
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).not.toHaveBeenCalledWith(400);
|
|
expect(mockRes.json.mock.calls[0][0].tool_options).toEqual({});
|
|
});
|
|
|
|
test('rejects selecting a stateful environment excluded by deployment policy', async () => {
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.config = {
|
|
endpoints: {
|
|
agents: {
|
|
statefulCodeSessions: { allowedEnvironments: ['user'] },
|
|
},
|
|
},
|
|
};
|
|
mockReq.body = {
|
|
stateful_code_sessions: true,
|
|
stateful_code_environment: 'conversation',
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(403);
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
|
expect(agentInDb.stateful_code_sessions).not.toBe(true);
|
|
});
|
|
|
|
test('rejects updating an agent to an unconfigured code environment id', async () => {
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.config = {
|
|
endpoints: {
|
|
agents: {
|
|
statefulCodeSessions: {
|
|
allowedEnvironments: ['user'],
|
|
environments: [],
|
|
},
|
|
},
|
|
},
|
|
};
|
|
mockReq.body = { code_environment_id: 'missing-vm' };
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
|
expect(agentInDb.code_environment_id).toBeUndefined();
|
|
});
|
|
|
|
test('allows a workspace-only update for an existing attached environment', async () => {
|
|
await Agent.updateOne({ id: existingAgentId }, { code_environment_id: 'attached-vm' });
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.config = {
|
|
endpoints: {
|
|
agents: {
|
|
statefulCodeSessions: {
|
|
allowedEnvironments: ['user'],
|
|
environments: [
|
|
{
|
|
id: 'attached-vm',
|
|
name: 'Attached VM',
|
|
type: 'attached',
|
|
baseURL: 'https://bridge.example.com/v1',
|
|
},
|
|
],
|
|
},
|
|
},
|
|
},
|
|
};
|
|
mockReq.body = { code_workspace_id: 'project-a' };
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).not.toHaveBeenCalledWith(400);
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
|
expect(agentInDb.code_environment_id).toBe('attached-vm');
|
|
expect(agentInDb.code_workspace_id).toBe('project-a');
|
|
});
|
|
|
|
test('rejects a workspace-only update without an attached environment', async () => {
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.config = {
|
|
endpoints: {
|
|
agents: {
|
|
statefulCodeSessions: {
|
|
allowedEnvironments: ['user'],
|
|
environments: [
|
|
{
|
|
id: 'default-vm',
|
|
name: 'Default VM',
|
|
type: 'attached',
|
|
baseURL: 'https://bridge.example.com/v1',
|
|
default: true,
|
|
},
|
|
],
|
|
},
|
|
},
|
|
},
|
|
};
|
|
mockReq.body = { code_workspace_id: 'project-a' };
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
|
expect(agentInDb.code_workspace_id).toBeUndefined();
|
|
});
|
|
|
|
test('allows disabling stateful sessions after the configured environment is removed', async () => {
|
|
await Agent.updateOne(
|
|
{ id: existingAgentId },
|
|
{
|
|
stateful_code_sessions: true,
|
|
code_environment_id: 'removed-vm',
|
|
code_workspace_id: 'project-a',
|
|
},
|
|
);
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.config = {
|
|
endpoints: {
|
|
agents: {
|
|
statefulCodeSessions: {
|
|
allowedEnvironments: ['user'],
|
|
environments: [],
|
|
},
|
|
},
|
|
},
|
|
};
|
|
mockReq.body = {
|
|
stateful_code_sessions: false,
|
|
code_environment_id: 'removed-vm',
|
|
code_workspace_id: 'project-a',
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).not.toHaveBeenCalledWith(400);
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
|
expect(agentInDb.stateful_code_sessions).toBe(false);
|
|
expect(agentInDb.code_environment_id).toBe('removed-vm');
|
|
expect(agentInDb.code_workspace_id).toBe('project-a');
|
|
});
|
|
|
|
test('restores the deployment-default code environment', async () => {
|
|
await Agent.updateOne(
|
|
{ id: existingAgentId },
|
|
{
|
|
stateful_code_sessions: true,
|
|
code_environment_id: 'attached-vm',
|
|
code_workspace_id: 'project-a',
|
|
},
|
|
);
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.config = {
|
|
endpoints: {
|
|
agents: {
|
|
statefulCodeSessions: {
|
|
allowedEnvironments: ['user'],
|
|
environments: [
|
|
{
|
|
id: 'attached-vm',
|
|
name: 'Attached VM',
|
|
type: 'attached',
|
|
baseURL: 'https://bridge.example.com/v1',
|
|
default: true,
|
|
},
|
|
],
|
|
},
|
|
},
|
|
},
|
|
};
|
|
mockReq.body = { code_environment_id: null };
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).not.toHaveBeenCalledWith(400);
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
|
expect(agentInDb.code_environment_id).toBeUndefined();
|
|
expect(agentInDb.code_workspace_id).toBe('');
|
|
});
|
|
|
|
test('clears a configured Git identity', async () => {
|
|
await Agent.updateOne(
|
|
{ id: existingAgentId },
|
|
{ git_identity: { name: 'Coding Agent', email: 'agent@example.com' } },
|
|
);
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = { git_identity: null };
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
|
expect(agentInDb.git_identity).toBeUndefined();
|
|
});
|
|
|
|
test('allows unrelated edits to an existing scope after policy is tightened', async () => {
|
|
await Agent.updateOne(
|
|
{ id: existingAgentId },
|
|
{ stateful_code_sessions: true, stateful_code_environment: 'conversation' },
|
|
);
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.config = {
|
|
endpoints: {
|
|
agents: {
|
|
statefulCodeSessions: { allowedEnvironments: ['user'] },
|
|
},
|
|
},
|
|
};
|
|
mockReq.body = {
|
|
name: 'Still editable',
|
|
stateful_code_sessions: true,
|
|
stateful_code_environment: 'conversation',
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).not.toHaveBeenCalledWith(403);
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
|
expect(agentInDb.name).toBe('Still editable');
|
|
expect(agentInDb.stateful_code_environment).toBe('conversation');
|
|
});
|
|
|
|
test('rejects reactivating code execution with a retained disallowed scope', async () => {
|
|
await Agent.updateOne(
|
|
{ id: existingAgentId },
|
|
{
|
|
tools: [],
|
|
stateful_code_sessions: true,
|
|
stateful_code_environment: 'conversation',
|
|
},
|
|
);
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.config = {
|
|
endpoints: {
|
|
agents: {
|
|
statefulCodeSessions: { allowedEnvironments: ['user'] },
|
|
},
|
|
},
|
|
};
|
|
mockReq.body = { tools: [Tools.execute_code] };
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(403);
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
|
expect(agentInDb.tools).not.toContain(Tools.execute_code);
|
|
});
|
|
|
|
test('rejects graph topology that becomes invalid after self-placeholder rewrite', async () => {
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.config = {
|
|
endpoints: { agents: { capabilities: ['subagents'] } },
|
|
};
|
|
mockReq.body = {
|
|
subagents: {
|
|
enabled: true,
|
|
allowSelf: false,
|
|
graphs: [
|
|
{
|
|
type: 'collapsed_team',
|
|
name: 'Collapsed team',
|
|
description: 'Becomes invalid after placeholder replacement',
|
|
agent_ids: ['', existingAgentId],
|
|
edges: [{ from: '', to: existingAgentId, edgeType: 'direct' }],
|
|
entry_agent_id: '',
|
|
result_agent_id: existingAgentId,
|
|
},
|
|
],
|
|
},
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
expect(mockRes.json).toHaveBeenCalledWith(
|
|
expect.objectContaining({ error: 'Invalid request data' }),
|
|
);
|
|
});
|
|
|
|
test('should sanitize corrupt numeric model_parameters on update', async () => {
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = {
|
|
name: 'Healed Agent',
|
|
model_parameters: {
|
|
max_tokens: 'System',
|
|
maxContextTokens: 256000,
|
|
temperature: '0.7',
|
|
},
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.json).toHaveBeenCalled();
|
|
|
|
const updatedAgent = mockRes.json.mock.calls[0][0];
|
|
expect(updatedAgent.model_parameters.max_tokens).toBeUndefined();
|
|
expect(updatedAgent.model_parameters.maxContextTokens).toBe(256000);
|
|
expect(updatedAgent.model_parameters.temperature).toBe(0.7);
|
|
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
|
expect(agentInDb.model_parameters.max_tokens).toBeUndefined();
|
|
expect(agentInDb.model_parameters.maxContextTokens).toBe(256000);
|
|
});
|
|
|
|
test('should reject update with unauthorized fields (mass assignment protection)', async () => {
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = {
|
|
name: 'Updated Name',
|
|
|
|
// Unauthorized fields that should be stripped
|
|
author: new mongoose.Types.ObjectId().toString(), // Should not be able to change author
|
|
authorName: 'Hacker', // Should be stripped
|
|
id: 'different_agent_id', // Should be stripped
|
|
_id: new mongoose.Types.ObjectId(), // Should be stripped
|
|
versions: [], // Should be stripped
|
|
createdAt: new Date('2020-01-01'), // Should be stripped
|
|
updatedAt: new Date('2020-01-01'), // Should be stripped
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.json).toHaveBeenCalled();
|
|
|
|
const updatedAgent = mockRes.json.mock.calls[0][0];
|
|
|
|
// Verify unauthorized fields were not changed
|
|
expect(updatedAgent.author).toBe(existingAgentAuthorId.toString()); // Should not have changed
|
|
expect(updatedAgent.authorName).toBeUndefined();
|
|
expect(updatedAgent.id).toBe(existingAgentId); // Should not have changed
|
|
expect(updatedAgent.name).toBe('Updated Name'); // Only this should have changed
|
|
|
|
// Verify in database
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
|
expect(agentInDb.author.toString()).toBe(existingAgentAuthorId.toString());
|
|
expect(agentInDb.id).toBe(existingAgentId);
|
|
});
|
|
|
|
test('should allow admin to update any agent', async () => {
|
|
const adminUserId = new mongoose.Types.ObjectId().toString();
|
|
mockReq.user.id = adminUserId;
|
|
mockReq.user.role = 'ADMIN'; // Set as admin
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = {
|
|
name: 'Admin Update',
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).not.toHaveBeenCalledWith(403);
|
|
expect(mockRes.json).toHaveBeenCalled();
|
|
|
|
const updatedAgent = mockRes.json.mock.calls[0][0];
|
|
expect(updatedAgent.name).toBe('Admin Update');
|
|
});
|
|
|
|
test('should allow an editor to add their own file but not another user file', async () => {
|
|
const File = mongoose.models.File;
|
|
const adminUserId = new mongoose.Types.ObjectId().toString();
|
|
const authorFileId = `file_${uuidv4()}`;
|
|
const adminFileId = `file_${uuidv4()}`;
|
|
|
|
await File.create({
|
|
file_id: authorFileId,
|
|
user: existingAgentAuthorId,
|
|
filename: `${authorFileId}.txt`,
|
|
filepath: `/tmp/${authorFileId}`,
|
|
object: 'file',
|
|
type: 'text/plain',
|
|
bytes: 1,
|
|
source: FileSources.local,
|
|
});
|
|
await File.create({
|
|
file_id: adminFileId,
|
|
user: adminUserId,
|
|
filename: `${adminFileId}.txt`,
|
|
filepath: `/tmp/${adminFileId}`,
|
|
object: 'file',
|
|
type: 'text/plain',
|
|
bytes: 1,
|
|
source: FileSources.local,
|
|
});
|
|
|
|
mockReq.user.id = adminUserId;
|
|
mockReq.user.role = 'ADMIN';
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = {
|
|
tool_resources: {
|
|
file_search: { file_ids: [authorFileId, adminFileId] },
|
|
},
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId }).lean();
|
|
expect(agentInDb.tool_resources.file_search.file_ids).toEqual([adminFileId]);
|
|
});
|
|
|
|
test('should validate tool_resources in updates', async () => {
|
|
// Back these ids with real File docs so the orphan-pruning added for
|
|
// issue #12776 does not strip them — this test is about OCR conversion
|
|
// and schema filtering, not file existence.
|
|
const File = mongoose.models.File;
|
|
for (const id of ['ocr1', 'ocr2', 'img1']) {
|
|
await File.create({
|
|
file_id: id,
|
|
user: existingAgentAuthorId,
|
|
filename: `${id}.txt`,
|
|
filepath: `/tmp/${id}`,
|
|
object: 'file',
|
|
type: 'text/plain',
|
|
bytes: 1,
|
|
source: FileSources.local,
|
|
});
|
|
}
|
|
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = {
|
|
tool_resources: {
|
|
/** Legacy conversion from `ocr` to `context` */
|
|
ocr: {
|
|
file_ids: ['ocr1', 'ocr2'],
|
|
},
|
|
execute_code: {
|
|
file_ids: ['img1'],
|
|
},
|
|
// Invalid tool resource
|
|
invalid_tool: {
|
|
file_ids: ['invalid'],
|
|
},
|
|
},
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.json).toHaveBeenCalled();
|
|
|
|
const updatedAgent = mockRes.json.mock.calls[0][0];
|
|
expect(updatedAgent.tool_resources).toBeDefined();
|
|
expect(updatedAgent.tool_resources.ocr).toBeUndefined();
|
|
expect(updatedAgent.tool_resources.context).toBeDefined();
|
|
expect(updatedAgent.tool_resources.execute_code).toBeDefined();
|
|
expect(updatedAgent.tool_resources.invalid_tool).toBeUndefined();
|
|
});
|
|
|
|
test('canonicalizes hydrated tool resource files before update persistence', async () => {
|
|
const File = mongoose.models.File;
|
|
const ownedFileId = `file_${uuidv4()}`;
|
|
const otherFileId = `file_${uuidv4()}`;
|
|
await File.create({
|
|
file_id: ownedFileId,
|
|
user: existingAgentAuthorId,
|
|
filename: `${ownedFileId}.txt`,
|
|
filepath: `/tmp/${ownedFileId}`,
|
|
object: 'file',
|
|
type: 'text/plain',
|
|
bytes: 1,
|
|
source: FileSources.local,
|
|
});
|
|
await File.create({
|
|
file_id: otherFileId,
|
|
user: new mongoose.Types.ObjectId(),
|
|
filename: `${otherFileId}.txt`,
|
|
filepath: `/tmp/${otherFileId}`,
|
|
object: 'file',
|
|
type: 'text/plain',
|
|
bytes: 1,
|
|
source: FileSources.local,
|
|
});
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = {
|
|
tool_resources: {
|
|
execute_code: {
|
|
files: [
|
|
{ file_id: ownedFileId, filename: 'PRIVATE-SENTINEL' },
|
|
{ file_id: otherFileId, metadata: { codeEnvRef: { file_id: 'untrusted' } } },
|
|
],
|
|
},
|
|
},
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId }).lean();
|
|
expect(agentInDb.tool_resources.execute_code.file_ids).toEqual([ownedFileId]);
|
|
expect(agentInDb.tool_resources.execute_code.files).toBeUndefined();
|
|
expect(JSON.stringify(agentInDb)).not.toContain('PRIVATE-SENTINEL');
|
|
expect(JSON.stringify(agentInDb)).not.toContain('untrusted');
|
|
});
|
|
|
|
test('should strip runtime file records before persisting an update', async () => {
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = {
|
|
tool_resources: {
|
|
execute_code: {
|
|
files: [
|
|
{
|
|
file_id: 'forged-file',
|
|
filepath: '/etc/passwd',
|
|
source: FileSources.local,
|
|
},
|
|
],
|
|
},
|
|
},
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.json).toHaveBeenCalled();
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId }).lean();
|
|
expect(agentInDb.tool_resources.execute_code.files).toBeUndefined();
|
|
const latestVersion = agentInDb.versions[agentInDb.versions.length - 1];
|
|
expect(latestVersion.tool_resources.execute_code.files).toBeUndefined();
|
|
});
|
|
|
|
test('should remove empty strings from model_parameters during update (Issue Fix)', async () => {
|
|
// First create an agent with valid model_parameters
|
|
await Agent.updateOne(
|
|
{ id: existingAgentId },
|
|
{
|
|
model_parameters: {
|
|
temperature: 0.5,
|
|
max_tokens: 1000,
|
|
maxContextTokens: 2000,
|
|
},
|
|
},
|
|
);
|
|
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
// Simulate user clearing the fields (sends empty strings)
|
|
mockReq.body = {
|
|
model_parameters: {
|
|
temperature: 0.7, // Change to new value
|
|
max_tokens: '', // Clear this field (should be removed, not sent as "")
|
|
maxContextTokens: '', // Clear this field (should be removed, not sent as "")
|
|
},
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.json).toHaveBeenCalled();
|
|
|
|
const updatedAgent = mockRes.json.mock.calls[0][0];
|
|
expect(updatedAgent.model_parameters).toBeDefined();
|
|
// Valid number should be updated
|
|
expect(updatedAgent.model_parameters.temperature).toBe(0.7);
|
|
// Empty strings should be removed, not sent as ""
|
|
expect(updatedAgent.model_parameters.max_tokens).toBeUndefined();
|
|
expect(updatedAgent.model_parameters.maxContextTokens).toBeUndefined();
|
|
|
|
// Verify in database
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
|
expect(agentInDb.model_parameters.temperature).toBe(0.7);
|
|
expect(agentInDb.model_parameters.max_tokens).toBeUndefined();
|
|
expect(agentInDb.model_parameters.maxContextTokens).toBeUndefined();
|
|
});
|
|
|
|
test('should return 404 for non-existent agent', async () => {
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = `agent_${uuidv4()}`; // Non-existent ID
|
|
mockReq.body = {
|
|
name: 'Update Non-existent',
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(404);
|
|
expect(mockRes.json).toHaveBeenCalledWith({ error: 'Agent not found' });
|
|
});
|
|
|
|
test('should include version field in update response', async () => {
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = {
|
|
name: 'Updated with Version Check',
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.json).toHaveBeenCalled();
|
|
const updatedAgent = mockRes.json.mock.calls[0][0];
|
|
|
|
// Verify version field is included and is a number
|
|
expect(updatedAgent).toHaveProperty('version');
|
|
expect(typeof updatedAgent.version).toBe('number');
|
|
expect(updatedAgent.version).toBeGreaterThanOrEqual(1);
|
|
|
|
// Verify in database
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
|
expect(updatedAgent.version).toBe(agentInDb.versions.length);
|
|
});
|
|
|
|
test('should allow resetting avatar when value is explicitly null', async () => {
|
|
await Agent.updateOne(
|
|
{ id: existingAgentId },
|
|
{
|
|
avatar: {
|
|
filepath: 'https://example.com/avatar.png',
|
|
source: 's3',
|
|
},
|
|
},
|
|
);
|
|
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = {
|
|
avatar: null,
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
const updatedAgent = mockRes.json.mock.calls[0][0];
|
|
expect(updatedAgent.avatar).toBeNull();
|
|
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
|
expect(agentInDb.avatar).toBeNull();
|
|
});
|
|
|
|
test('should ignore avatar field when value is undefined', async () => {
|
|
const originalAvatar = {
|
|
filepath: 'https://example.com/original.png',
|
|
source: 's3',
|
|
};
|
|
await Agent.updateOne({ id: existingAgentId }, { avatar: originalAvatar });
|
|
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = {
|
|
avatar: undefined,
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
|
expect(agentInDb.avatar.filepath).toBe(originalAvatar.filepath);
|
|
expect(agentInDb.avatar.source).toBe(originalAvatar.source);
|
|
});
|
|
|
|
test('should not bump version when no mutable fields change', async () => {
|
|
const existingAgent = await Agent.findOne({ id: existingAgentId });
|
|
const originalVersionCount = existingAgent.versions.length;
|
|
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = {
|
|
avatar: undefined,
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
|
expect(agentInDb.versions.length).toBe(originalVersionCount);
|
|
});
|
|
|
|
test('should handle validation errors properly', async () => {
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = {
|
|
model_parameters: 'invalid-not-an-object', // Should be an object
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
expect(mockRes.json).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
error: 'Invalid request data',
|
|
details: expect.any(Array),
|
|
}),
|
|
);
|
|
});
|
|
|
|
describe('orphan file_id pruning (issue #12776)', () => {
|
|
const File = () => mongoose.models.File;
|
|
|
|
const createFileDoc = async (file_id, userId) =>
|
|
File().create({
|
|
file_id,
|
|
user: userId,
|
|
filename: `${file_id}.txt`,
|
|
filepath: `/tmp/${file_id}`,
|
|
object: 'file',
|
|
type: 'text/plain',
|
|
bytes: 1,
|
|
source: FileSources.local,
|
|
});
|
|
|
|
beforeEach(async () => {
|
|
await File().deleteMany({});
|
|
});
|
|
|
|
test('strips orphan file_ids from incoming tool_resources before persisting', async () => {
|
|
const keeper = `file_${uuidv4()}`;
|
|
const orphan = `file_${uuidv4()}`;
|
|
await createFileDoc(keeper, existingAgentAuthorId);
|
|
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = {
|
|
tool_resources: {
|
|
file_search: { file_ids: [keeper, orphan] },
|
|
},
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId }).lean();
|
|
expect(agentInDb.tool_resources.file_search.file_ids).toEqual([keeper]);
|
|
});
|
|
|
|
test('leaves tool_resources alone when the update omits it', async () => {
|
|
const orphan = `file_${uuidv4()}`;
|
|
await Agent.updateOne(
|
|
{ id: existingAgentId },
|
|
{ $set: { tool_resources: { file_search: { file_ids: [orphan] } } } },
|
|
);
|
|
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = { name: 'Unrelated Rename' };
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId }).lean();
|
|
expect(agentInDb.name).toBe('Unrelated Rename');
|
|
// Save-time pruning is intentionally scoped to tool_resources updates.
|
|
// The delete-time fix and migration script cover the untouched case.
|
|
expect(agentInDb.tool_resources.file_search.file_ids).toEqual([orphan]);
|
|
});
|
|
|
|
test('prunes incoming file_ids when the file ownership check fails', async () => {
|
|
const db = require('~/models');
|
|
jest.spyOn(db, 'getFiles').mockRejectedValueOnce(new Error('transient DB error'));
|
|
|
|
const orphan = `file_${uuidv4()}`;
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = {
|
|
name: 'Save Succeeds',
|
|
tool_resources: { file_search: { file_ids: [orphan] } },
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).not.toHaveBeenCalledWith(500);
|
|
expect(mockRes.json).toHaveBeenCalled();
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId }).lean();
|
|
expect(agentInDb.name).toBe('Save Succeeds');
|
|
expect(agentInDb.tool_resources.file_search.file_ids).toEqual([]);
|
|
});
|
|
|
|
test('strips file_ids owned by another user from incoming tool_resources', async () => {
|
|
const keeper = `file_${uuidv4()}`;
|
|
const otherUsersFile = `file_${uuidv4()}`;
|
|
await createFileDoc(keeper, existingAgentAuthorId);
|
|
await createFileDoc(otherUsersFile, new mongoose.Types.ObjectId());
|
|
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = {
|
|
tool_resources: {
|
|
file_search: { file_ids: [keeper, otherUsersFile] },
|
|
},
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId }).lean();
|
|
expect(agentInDb.tool_resources.file_search.file_ids).toEqual([keeper]);
|
|
});
|
|
|
|
test('preserves existing attached file_ids owned by another user', async () => {
|
|
const authorFile = `file_${uuidv4()}`;
|
|
const editorFile = `file_${uuidv4()}`;
|
|
const editorId = new mongoose.Types.ObjectId();
|
|
await createFileDoc(authorFile, existingAgentAuthorId);
|
|
await createFileDoc(editorFile, editorId);
|
|
await Agent.updateOne(
|
|
{ id: existingAgentId },
|
|
{ $set: { tool_resources: { file_search: { file_ids: [editorFile] } } } },
|
|
);
|
|
|
|
mockReq.user.id = existingAgentAuthorId.toString();
|
|
mockReq.params.id = existingAgentId;
|
|
mockReq.body = {
|
|
tool_resources: {
|
|
file_search: { file_ids: [authorFile, editorFile] },
|
|
},
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
const agentInDb = await Agent.findOne({ id: existingAgentId }).lean();
|
|
expect(agentInDb.tool_resources.file_search.file_ids).toEqual([authorFile, editorFile]);
|
|
});
|
|
});
|
|
});
|
|
|
|
describe('tool_resources ownership pruning in alternate write paths', () => {
|
|
const createFileDoc = (file_id, userId) =>
|
|
mongoose.models.File.create({
|
|
file_id,
|
|
user: userId,
|
|
filename: `${file_id}.txt`,
|
|
filepath: `/tmp/${file_id}`,
|
|
object: 'file',
|
|
type: 'text/plain',
|
|
bytes: 1,
|
|
source: FileSources.local,
|
|
});
|
|
const createActionSpec = (operationId) =>
|
|
JSON.stringify({
|
|
openapi: '3.0.0',
|
|
info: { title: 'Filtered Action', version: '1.0.0' },
|
|
servers: [{ url: 'https://api.example.com' }],
|
|
paths: {
|
|
'/lookup': {
|
|
get: {
|
|
operationId,
|
|
description: 'Look up a record',
|
|
responses: {
|
|
200: { description: 'Success' },
|
|
},
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
test('duplicateAgentHandler should block cloned content before action or agent writes', async () => {
|
|
const sourceAuthorId = new mongoose.Types.ObjectId();
|
|
const cloneAuthorId = new mongoose.Types.ObjectId();
|
|
const sourceAgent = await Agent.create({
|
|
id: `agent_${uuidv4()}`,
|
|
name: 'Source Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: sourceAuthorId,
|
|
instructions: 'Use sk-private-token for requests',
|
|
});
|
|
const db = require('~/models');
|
|
jest.spyOn(db, 'getActions').mockResolvedValueOnce([
|
|
{
|
|
action_id: 'source-action',
|
|
metadata: { domain: 'api.example.com' },
|
|
},
|
|
]);
|
|
const updateActionSpy = jest.spyOn(db, 'updateAction');
|
|
const createAgentSpy = jest.spyOn(db, 'createAgent');
|
|
|
|
mockReq.config = {
|
|
filters: {
|
|
agentInstructions: {
|
|
pii: {
|
|
starterPatterns: ['sk_prefix'],
|
|
},
|
|
},
|
|
},
|
|
};
|
|
mockReq.user.id = cloneAuthorId.toString();
|
|
mockReq.params.id = sourceAgent.id;
|
|
|
|
await duplicateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response).toEqual(
|
|
expect.objectContaining({
|
|
error: 'content_filter_block',
|
|
source: 'agent_instruction',
|
|
field: 'instructions',
|
|
}),
|
|
);
|
|
expect(JSON.stringify(response)).not.toContain('sk-private-token');
|
|
expect(updateActionSpy).not.toHaveBeenCalled();
|
|
expect(createAgentSpy).not.toHaveBeenCalled();
|
|
await expect(Agent.countDocuments()).resolves.toBe(1);
|
|
});
|
|
|
|
test('duplicateAgentHandler should block sanitized action metadata before any writes', async () => {
|
|
const sourceAuthorId = new mongoose.Types.ObjectId();
|
|
const cloneAuthorId = new mongoose.Types.ObjectId();
|
|
const sourceAgent = await Agent.create({
|
|
id: `agent_${uuidv4()}`,
|
|
name: 'Source Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: sourceAuthorId,
|
|
});
|
|
const db = require('~/models');
|
|
jest.spyOn(db, 'getActions').mockResolvedValueOnce([
|
|
{
|
|
action_id: 'source-action',
|
|
metadata: {
|
|
domain: 'api.example.com',
|
|
api_key: 'REMOVED-BEFORE-INSPECTION',
|
|
auth: {
|
|
authorization_url: 'https://auth.example.test/BLOCK-AUTH',
|
|
},
|
|
},
|
|
},
|
|
]);
|
|
const updateActionSpy = jest.spyOn(db, 'updateAction');
|
|
const createAgentSpy = jest.spyOn(db, 'createAgent');
|
|
|
|
mockReq.config = {
|
|
filters: {
|
|
actionMetadata: {
|
|
pii: {
|
|
fields: ['authorization_url'],
|
|
starterPatterns: [],
|
|
customPatterns: [
|
|
{
|
|
id: 'submitted-content',
|
|
label: 'submitted content',
|
|
regex: 'BLOCK-[A-Z]+',
|
|
},
|
|
],
|
|
},
|
|
},
|
|
},
|
|
};
|
|
mockReq.user.id = cloneAuthorId.toString();
|
|
mockReq.params.id = sourceAgent.id;
|
|
|
|
await duplicateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response).toEqual(
|
|
expect.objectContaining({
|
|
error: 'content_filter_block',
|
|
source: 'action_metadata',
|
|
field: 'authorization_url',
|
|
}),
|
|
);
|
|
expect(JSON.stringify(response)).not.toContain('BLOCK-AUTH');
|
|
expect(JSON.stringify(response)).not.toContain('REMOVED-BEFORE-INSPECTION');
|
|
expect(updateActionSpy).not.toHaveBeenCalled();
|
|
expect(createAgentSpy).not.toHaveBeenCalled();
|
|
await expect(Agent.countDocuments()).resolves.toBe(1);
|
|
});
|
|
|
|
test('duplicateAgentHandler should fail closed on oversized protected action metadata', async () => {
|
|
const sourceAuthorId = new mongoose.Types.ObjectId();
|
|
const cloneAuthorId = new mongoose.Types.ObjectId();
|
|
const sourceAgent = await Agent.create({
|
|
id: `agent_${uuidv4()}`,
|
|
name: 'Source Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: sourceAuthorId,
|
|
});
|
|
const db = require('~/models');
|
|
jest.spyOn(db, 'getActions').mockResolvedValueOnce([
|
|
{
|
|
action_id: 'source-action',
|
|
metadata: {
|
|
domain: 'api.example.com',
|
|
raw_spec: createOverflowingActionValue(),
|
|
},
|
|
},
|
|
]);
|
|
const updateActionSpy = jest.spyOn(db, 'updateAction');
|
|
const createAgentSpy = jest.spyOn(db, 'createAgent');
|
|
|
|
mockReq.config = {
|
|
filters: {
|
|
actionMetadata: {
|
|
pii: {
|
|
fields: ['raw_spec'],
|
|
starterPatterns: [],
|
|
customPatterns: [
|
|
{
|
|
id: 'protected-content',
|
|
label: 'protected content',
|
|
regex: 'BLOCK-NOT-PRESENT',
|
|
},
|
|
],
|
|
},
|
|
},
|
|
},
|
|
};
|
|
mockReq.user.id = cloneAuthorId.toString();
|
|
mockReq.params.id = sourceAgent.id;
|
|
|
|
await duplicateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
expect(mockRes.json).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
error: 'content_filter_uninspectable',
|
|
}),
|
|
);
|
|
expect(updateActionSpy).not.toHaveBeenCalled();
|
|
expect(createAgentSpy).not.toHaveBeenCalled();
|
|
await expect(Agent.countDocuments()).resolves.toBe(1);
|
|
});
|
|
|
|
test('duplicateAgentHandler should inspect stored action function definitions before writes', async () => {
|
|
const sourceAuthorId = new mongoose.Types.ObjectId();
|
|
const cloneAuthorId = new mongoose.Types.ObjectId();
|
|
const sourceAgent = await Agent.create({
|
|
id: `agent_${uuidv4()}`,
|
|
name: 'Source Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: sourceAuthorId,
|
|
});
|
|
const db = require('~/models');
|
|
jest.spyOn(db, 'getActions').mockResolvedValueOnce([
|
|
{
|
|
action_id: 'source-action',
|
|
metadata: {
|
|
domain: 'api.example.com',
|
|
raw_spec: createActionSpec('BLOCK-TOOL'),
|
|
},
|
|
},
|
|
]);
|
|
const updateActionSpy = jest.spyOn(db, 'updateAction');
|
|
const createAgentSpy = jest.spyOn(db, 'createAgent');
|
|
|
|
mockReq.config = {
|
|
filters: {
|
|
agentInstructions: {
|
|
pii: {
|
|
fields: ['name'],
|
|
starterPatterns: [],
|
|
customPatterns: [
|
|
{
|
|
id: 'submitted-content',
|
|
label: 'submitted content',
|
|
regex: 'BLOCK-[A-Z]+',
|
|
},
|
|
],
|
|
},
|
|
},
|
|
},
|
|
};
|
|
mockReq.user.id = cloneAuthorId.toString();
|
|
mockReq.params.id = sourceAgent.id;
|
|
|
|
await duplicateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response).toEqual(
|
|
expect.objectContaining({
|
|
error: 'content_filter_block',
|
|
source: 'agent_instruction',
|
|
field: 'name',
|
|
}),
|
|
);
|
|
expect(JSON.stringify(response)).not.toContain('BLOCK-TOOL');
|
|
expect(updateActionSpy).not.toHaveBeenCalled();
|
|
expect(createAgentSpy).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test('duplicateAgentHandler should prune file_ids not owned by the clone author', async () => {
|
|
const sourceAuthorId = new mongoose.Types.ObjectId();
|
|
const cloneAuthorId = new mongoose.Types.ObjectId();
|
|
const sourceFileId = `file_${uuidv4()}`;
|
|
const cloneAuthorFileId = `file_${uuidv4()}`;
|
|
|
|
await createFileDoc(sourceFileId, sourceAuthorId);
|
|
await createFileDoc(cloneAuthorFileId, cloneAuthorId);
|
|
const sourceAgent = await Agent.create({
|
|
id: `agent_${uuidv4()}`,
|
|
name: 'Source Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: sourceAuthorId,
|
|
tool_resources: {
|
|
context: {
|
|
files: [
|
|
{ file_id: sourceFileId, filename: 'source.txt' },
|
|
{ file_id: cloneAuthorFileId, filename: 'clone.txt' },
|
|
],
|
|
},
|
|
},
|
|
});
|
|
|
|
const db = require('~/models');
|
|
jest.spyOn(db, 'getActions').mockResolvedValueOnce([]);
|
|
|
|
mockReq.user.id = cloneAuthorId.toString();
|
|
mockReq.params.id = sourceAgent.id;
|
|
|
|
await duplicateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(201);
|
|
const { agent } = mockRes.json.mock.calls[0][0];
|
|
expect(agent.author.toString()).toBe(cloneAuthorId.toString());
|
|
expect(agent.tool_resources.context.file_ids).toEqual([cloneAuthorFileId]);
|
|
expect(agent.tool_resources.context.files).toBeUndefined();
|
|
});
|
|
|
|
test('revertAgentVersionHandler should block selected content before persistence', async () => {
|
|
const agentAuthorId = new mongoose.Types.ObjectId();
|
|
const agent = await Agent.create({
|
|
id: `agent_${uuidv4()}`,
|
|
name: 'Current Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: agentAuthorId,
|
|
instructions: 'Current allowed instructions',
|
|
versions: [
|
|
{
|
|
name: 'Historical Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
instructions: 'Use sk-private-token for requests',
|
|
},
|
|
],
|
|
});
|
|
const db = require('~/models');
|
|
const updateAgentSpy = jest.spyOn(db, 'updateAgent');
|
|
|
|
mockReq.config = {
|
|
filters: {
|
|
agentInstructions: {
|
|
pii: {
|
|
starterPatterns: ['sk_prefix'],
|
|
},
|
|
},
|
|
},
|
|
};
|
|
mockReq.user.id = agentAuthorId.toString();
|
|
mockReq.params.id = agent.id;
|
|
mockReq.body = { version_index: 0 };
|
|
|
|
await revertAgentVersionHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response).toEqual(
|
|
expect.objectContaining({
|
|
error: 'content_filter_block',
|
|
source: 'agent_instruction',
|
|
field: 'instructions',
|
|
}),
|
|
);
|
|
expect(JSON.stringify(response)).not.toContain('sk-private-token');
|
|
expect(updateAgentSpy).not.toHaveBeenCalled();
|
|
const agentInDb = await Agent.findOne({ id: agent.id }).lean();
|
|
expect(agentInDb.name).toBe('Current Agent');
|
|
expect(agentInDb.instructions).toBe('Current allowed instructions');
|
|
});
|
|
|
|
test('revertAgentVersionHandler should block reactivated action metadata before persistence', async () => {
|
|
const agentAuthorId = new mongoose.Types.ObjectId();
|
|
const agent = await Agent.create({
|
|
id: `agent_${uuidv4()}`,
|
|
name: 'Current Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: agentAuthorId,
|
|
versions: [
|
|
{
|
|
name: 'Historical Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
actions: [`api.example.com${actionDelimiter}source-action`],
|
|
},
|
|
],
|
|
});
|
|
const db = require('~/models');
|
|
jest.spyOn(db, 'getActions').mockResolvedValueOnce([
|
|
{
|
|
action_id: 'source-action',
|
|
agent_id: agent.id,
|
|
metadata: {
|
|
domain: 'api.example.com',
|
|
auth: {
|
|
authorization_url: 'https://auth.example.test/BLOCK-AUTH',
|
|
},
|
|
},
|
|
},
|
|
]);
|
|
const updateAgentSpy = jest.spyOn(db, 'updateAgent');
|
|
|
|
mockReq.config = {
|
|
filters: {
|
|
actionMetadata: {
|
|
pii: {
|
|
fields: ['authorization_url'],
|
|
starterPatterns: [],
|
|
customPatterns: [
|
|
{
|
|
id: 'submitted-content',
|
|
label: 'submitted content',
|
|
regex: 'BLOCK-[A-Z]+',
|
|
},
|
|
],
|
|
},
|
|
},
|
|
},
|
|
};
|
|
mockReq.user.id = agentAuthorId.toString();
|
|
mockReq.params.id = agent.id;
|
|
mockReq.body = { version_index: 0 };
|
|
|
|
await revertAgentVersionHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response).toEqual(
|
|
expect.objectContaining({
|
|
error: 'content_filter_block',
|
|
source: 'action_metadata',
|
|
field: 'authorization_url',
|
|
}),
|
|
);
|
|
expect(JSON.stringify(response)).not.toContain('BLOCK-AUTH');
|
|
expect(updateAgentSpy).not.toHaveBeenCalled();
|
|
const agentInDb = await Agent.findOne({ id: agent.id }).lean();
|
|
expect(agentInDb.name).toBe('Current Agent');
|
|
expect(agentInDb.actions).toBeUndefined();
|
|
});
|
|
|
|
test('revertAgentVersionHandler should inspect reactivated action function definitions', async () => {
|
|
const agentAuthorId = new mongoose.Types.ObjectId();
|
|
const agent = await Agent.create({
|
|
id: `agent_${uuidv4()}`,
|
|
name: 'Current Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: agentAuthorId,
|
|
versions: [
|
|
{
|
|
name: 'Historical Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
actions: [`api.example.com${actionDelimiter}source-action`],
|
|
},
|
|
],
|
|
});
|
|
const db = require('~/models');
|
|
jest.spyOn(db, 'getActions').mockResolvedValueOnce([
|
|
{
|
|
action_id: 'source-action',
|
|
agent_id: agent.id,
|
|
metadata: {
|
|
domain: 'api.example.com',
|
|
raw_spec: createActionSpec('BLOCK-TOOL'),
|
|
},
|
|
},
|
|
]);
|
|
const updateAgentSpy = jest.spyOn(db, 'updateAgent');
|
|
|
|
mockReq.config = {
|
|
filters: {
|
|
agentInstructions: {
|
|
pii: {
|
|
fields: ['name'],
|
|
starterPatterns: [],
|
|
customPatterns: [
|
|
{
|
|
id: 'submitted-content',
|
|
label: 'submitted content',
|
|
regex: 'BLOCK-[A-Z]+',
|
|
},
|
|
],
|
|
},
|
|
},
|
|
},
|
|
};
|
|
mockReq.user.id = agentAuthorId.toString();
|
|
mockReq.params.id = agent.id;
|
|
mockReq.body = { version_index: 0 };
|
|
|
|
await revertAgentVersionHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response).toEqual(
|
|
expect.objectContaining({
|
|
error: 'content_filter_block',
|
|
source: 'agent_instruction',
|
|
field: 'name',
|
|
}),
|
|
);
|
|
expect(JSON.stringify(response)).not.toContain('BLOCK-TOOL');
|
|
expect(updateAgentSpy).not.toHaveBeenCalled();
|
|
const agentInDb = await Agent.findOne({ id: agent.id }).lean();
|
|
expect(agentInDb.name).toBe('Current Agent');
|
|
expect(agentInDb.actions).toBeUndefined();
|
|
});
|
|
|
|
test('revertAgentVersionHandler should canonicalize and prune target-only file_ids', async () => {
|
|
const agentAuthorId = new mongoose.Types.ObjectId();
|
|
const otherUserId = new mongoose.Types.ObjectId();
|
|
const ownedFileId = `file_${uuidv4()}`;
|
|
const currentSharedFileId = `file_${uuidv4()}`;
|
|
const targetOnlyFileId = `file_${uuidv4()}`;
|
|
const orphanFileId = `file_${uuidv4()}`;
|
|
|
|
await createFileDoc(ownedFileId, agentAuthorId);
|
|
await createFileDoc(currentSharedFileId, otherUserId);
|
|
await createFileDoc(targetOnlyFileId, otherUserId);
|
|
const agent = await Agent.create({
|
|
id: `agent_${uuidv4()}`,
|
|
name: 'Current Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: agentAuthorId,
|
|
tool_resources: {
|
|
file_search: { file_ids: [currentSharedFileId] },
|
|
},
|
|
versions: [
|
|
{
|
|
name: 'Historical Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tool_resources: {
|
|
file_search: {
|
|
files: [
|
|
{ file_id: ownedFileId, filename: 'owned.txt' },
|
|
{ file_id: currentSharedFileId, filename: 'already-attached.txt' },
|
|
{ file_id: targetOnlyFileId, filename: 'target-only.txt' },
|
|
{ file_id: orphanFileId, filename: 'missing.txt' },
|
|
],
|
|
},
|
|
},
|
|
},
|
|
],
|
|
});
|
|
|
|
mockReq.user.id = agentAuthorId.toString();
|
|
mockReq.params.id = agent.id;
|
|
mockReq.body = { version_index: 0 };
|
|
|
|
await revertAgentVersionHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.json).toHaveBeenCalled();
|
|
const agentInDb = await Agent.findOne({ id: agent.id }).lean();
|
|
expect(agentInDb.tool_resources.file_search.file_ids).toEqual([
|
|
ownedFileId,
|
|
currentSharedFileId,
|
|
]);
|
|
expect(agentInDb.tool_resources.file_search.files).toBeUndefined();
|
|
});
|
|
|
|
test('duplicateAgentHandler removes programmatic options without Code Interpreter', async () => {
|
|
const sourceAgent = await Agent.create({
|
|
id: `agent_${uuidv4()}`,
|
|
name: 'Legacy Programmatic Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: mockReq.user.id,
|
|
tools: ['search_mcp_example'],
|
|
tool_options: {
|
|
search_mcp_example: { allowed_callers: ['code_execution'] },
|
|
},
|
|
});
|
|
const db = require('~/models');
|
|
jest.spyOn(db, 'getActions').mockResolvedValueOnce([]);
|
|
mockReq.params.id = sourceAgent.id;
|
|
|
|
await duplicateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(201);
|
|
expect(mockRes.json.mock.calls[0][0].agent.tool_options).toEqual({});
|
|
});
|
|
|
|
test('duplicateAgentHandler preserves a disabled stale workspace binding', async () => {
|
|
const sourceAgent = await Agent.create({
|
|
id: `agent_${uuidv4()}`,
|
|
name: 'Disabled BYOM Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: mockReq.user.id,
|
|
stateful_code_sessions: false,
|
|
code_environment_id: 'removed-vm',
|
|
code_workspace_id: 'project-a',
|
|
});
|
|
jest.spyOn(db, 'getActions').mockResolvedValueOnce([]);
|
|
mockReq.config = {
|
|
endpoints: {
|
|
agents: {
|
|
statefulCodeSessions: { environments: [] },
|
|
},
|
|
},
|
|
};
|
|
mockReq.params.id = sourceAgent.id;
|
|
|
|
await duplicateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(201);
|
|
expect(mockRes.json.mock.calls[0][0].agent).toEqual(
|
|
expect.objectContaining({
|
|
stateful_code_sessions: false,
|
|
code_environment_id: 'removed-vm',
|
|
code_workspace_id: 'project-a',
|
|
}),
|
|
);
|
|
});
|
|
|
|
test('duplicateAgentHandler rejects an active stale workspace binding', async () => {
|
|
const sourceAgent = await Agent.create({
|
|
id: `agent_${uuidv4()}`,
|
|
name: 'Active BYOM Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: mockReq.user.id,
|
|
stateful_code_sessions: true,
|
|
code_environment_id: 'removed-vm',
|
|
code_workspace_id: 'project-a',
|
|
});
|
|
mockReq.config = {
|
|
endpoints: {
|
|
agents: {
|
|
statefulCodeSessions: { environments: [] },
|
|
},
|
|
},
|
|
};
|
|
mockReq.params.id = sourceAgent.id;
|
|
|
|
await duplicateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
expect(mockRes.json).toHaveBeenCalledWith({
|
|
error: 'Code workspace defaults require an explicit attached code environment',
|
|
});
|
|
});
|
|
|
|
test('revertAgentVersionHandler removes restored programmatic options without Code Interpreter', async () => {
|
|
const agent = await Agent.create({
|
|
id: `agent_${uuidv4()}`,
|
|
name: 'Current Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: mockReq.user.id,
|
|
versions: [
|
|
{
|
|
name: 'Legacy Programmatic Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: ['search_mcp_example'],
|
|
tool_options: {
|
|
search_mcp_example: { allowed_callers: ['code_execution'] },
|
|
},
|
|
},
|
|
],
|
|
});
|
|
mockReq.params.id = agent.id;
|
|
mockReq.body = { version_index: 0 };
|
|
|
|
await revertAgentVersionHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.json).toHaveBeenCalled();
|
|
expect(mockRes.json.mock.calls[0][0].tool_options).toEqual({});
|
|
});
|
|
|
|
test('revertAgentVersionHandler restores a disabled stale workspace binding', async () => {
|
|
const agent = await Agent.create({
|
|
id: `agent_${uuidv4()}`,
|
|
name: 'Current Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: mockReq.user.id,
|
|
versions: [
|
|
{
|
|
name: 'Disabled Historical BYOM Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
stateful_code_sessions: false,
|
|
code_environment_id: 'removed-vm',
|
|
code_workspace_id: 'project-a',
|
|
},
|
|
],
|
|
});
|
|
mockReq.config = {
|
|
endpoints: {
|
|
agents: {
|
|
statefulCodeSessions: { environments: [] },
|
|
},
|
|
},
|
|
};
|
|
mockReq.params.id = agent.id;
|
|
mockReq.body = { version_index: 0 };
|
|
|
|
await revertAgentVersionHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).not.toHaveBeenCalledWith(400);
|
|
const persisted = await Agent.findOne({ id: agent.id }).lean();
|
|
expect(persisted).toEqual(
|
|
expect.objectContaining({
|
|
stateful_code_sessions: false,
|
|
code_environment_id: 'removed-vm',
|
|
code_workspace_id: 'project-a',
|
|
}),
|
|
);
|
|
});
|
|
|
|
test('revertAgentVersionHandler rejects a stale binding that inherits active sessions', async () => {
|
|
const agent = await Agent.create({
|
|
id: `agent_${uuidv4()}`,
|
|
name: 'Current Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: mockReq.user.id,
|
|
stateful_code_sessions: true,
|
|
versions: [
|
|
{
|
|
name: 'Historical BYOM Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
code_environment_id: 'removed-vm',
|
|
code_workspace_id: 'project-a',
|
|
},
|
|
],
|
|
});
|
|
mockReq.config = {
|
|
endpoints: {
|
|
agents: {
|
|
statefulCodeSessions: { environments: [] },
|
|
},
|
|
},
|
|
};
|
|
mockReq.params.id = agent.id;
|
|
mockReq.body = { version_index: 0 };
|
|
|
|
await revertAgentVersionHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
expect(mockRes.json).toHaveBeenCalledWith({
|
|
error: 'Code workspace defaults require an explicit attached code environment',
|
|
});
|
|
});
|
|
|
|
test('revertAgentVersionHandler does not update unchanged tool options', async () => {
|
|
const agent = await Agent.create({
|
|
id: `agent_${uuidv4()}`,
|
|
name: 'Current Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: mockReq.user.id,
|
|
versions: [
|
|
{
|
|
name: 'Historical Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tool_options: {},
|
|
},
|
|
],
|
|
});
|
|
const db = require('~/models');
|
|
const updateAgentSpy = jest.spyOn(db, 'updateAgent');
|
|
mockReq.params.id = agent.id;
|
|
mockReq.body = { version_index: 0 };
|
|
|
|
await revertAgentVersionHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.json).toHaveBeenCalled();
|
|
expect(updateAgentSpy).not.toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
describe('Mass Assignment Attack Scenarios', () => {
|
|
test('should prevent setting system fields during creation', async () => {
|
|
const systemFields = {
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
name: 'System Fields Test',
|
|
|
|
// System fields that should never be settable by users
|
|
__v: 99,
|
|
_id: new mongoose.Types.ObjectId(),
|
|
versions: [
|
|
{
|
|
name: 'Fake Version',
|
|
provider: 'fake',
|
|
model: 'fake-model',
|
|
},
|
|
],
|
|
};
|
|
|
|
mockReq.body = systemFields;
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(201);
|
|
|
|
const createdAgent = mockRes.json.mock.calls[0][0];
|
|
|
|
// Verify system fields were not affected
|
|
expect(createdAgent.__v).not.toBe(99);
|
|
expect(createdAgent.versions).toHaveLength(1); // Should only have the auto-created version
|
|
expect(createdAgent.versions[0].name).toBe('System Fields Test'); // From actual creation
|
|
expect(createdAgent.versions[0].provider).toBe('openai'); // From actual creation
|
|
|
|
// Verify in database
|
|
const agentInDb = await Agent.findOne({ id: createdAgent.id });
|
|
expect(agentInDb.__v).not.toBe(99);
|
|
});
|
|
|
|
test('should prevent author hijacking', async () => {
|
|
const originalAuthorId = new mongoose.Types.ObjectId();
|
|
const attackerId = new mongoose.Types.ObjectId();
|
|
|
|
// Admin creates an agent
|
|
mockReq.user.id = originalAuthorId.toString();
|
|
mockReq.user.role = 'ADMIN';
|
|
mockReq.body = {
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
name: 'Admin Agent',
|
|
author: attackerId.toString(), // Trying to set different author
|
|
};
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(201);
|
|
|
|
const createdAgent = mockRes.json.mock.calls[0][0];
|
|
|
|
// Author should be the actual user, not the attempted value
|
|
expect(createdAgent.author.toString()).toBe(originalAuthorId.toString());
|
|
expect(createdAgent.author.toString()).not.toBe(attackerId.toString());
|
|
|
|
// Verify in database
|
|
const agentInDb = await Agent.findOne({ id: createdAgent.id });
|
|
expect(agentInDb.author.toString()).toBe(originalAuthorId.toString());
|
|
});
|
|
|
|
test('should strip unknown fields to prevent future vulnerabilities', async () => {
|
|
mockReq.body = {
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
name: 'Future Proof Test',
|
|
|
|
// Unknown fields that might be added in future
|
|
superAdminAccess: true,
|
|
bypassAllChecks: true,
|
|
internalFlag: 'secret',
|
|
futureFeature: 'exploit',
|
|
};
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(201);
|
|
|
|
const createdAgent = mockRes.json.mock.calls[0][0];
|
|
|
|
// Verify unknown fields were stripped
|
|
expect(createdAgent.superAdminAccess).toBeUndefined();
|
|
expect(createdAgent.bypassAllChecks).toBeUndefined();
|
|
expect(createdAgent.internalFlag).toBeUndefined();
|
|
expect(createdAgent.futureFeature).toBeUndefined();
|
|
|
|
// Also check in database
|
|
const agentInDb = await Agent.findOne({ id: createdAgent.id }).lean();
|
|
expect(agentInDb.superAdminAccess).toBeUndefined();
|
|
expect(agentInDb.bypassAllChecks).toBeUndefined();
|
|
expect(agentInDb.internalFlag).toBeUndefined();
|
|
expect(agentInDb.futureFeature).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
describe('getListAgentsHandler - Security Tests', () => {
|
|
let userA, userB;
|
|
let agentA1, agentA2, agentA3, agentB1;
|
|
|
|
beforeEach(async () => {
|
|
await Agent.deleteMany({});
|
|
jest.clearAllMocks();
|
|
|
|
// Create two test users
|
|
userA = new mongoose.Types.ObjectId();
|
|
userB = new mongoose.Types.ObjectId();
|
|
|
|
// Create agents for User A
|
|
agentA1 = await Agent.create({
|
|
id: `agent_${nanoid(12)}`,
|
|
name: 'Agent A1',
|
|
description: 'User A agent 1',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: userA,
|
|
versions: [
|
|
{
|
|
name: 'Agent A1',
|
|
description: 'User A agent 1',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
},
|
|
],
|
|
});
|
|
|
|
agentA2 = await Agent.create({
|
|
id: `agent_${nanoid(12)}`,
|
|
name: 'Agent A2',
|
|
description: 'User A agent 2',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: userA,
|
|
versions: [
|
|
{
|
|
name: 'Agent A2',
|
|
description: 'User A agent 2',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
},
|
|
],
|
|
});
|
|
|
|
agentA3 = await Agent.create({
|
|
id: `agent_${nanoid(12)}`,
|
|
name: 'Agent A3',
|
|
description: 'User A agent 3',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: userA,
|
|
category: 'productivity',
|
|
versions: [
|
|
{
|
|
name: 'Agent A3',
|
|
description: 'User A agent 3',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
category: 'productivity',
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
},
|
|
],
|
|
});
|
|
|
|
// Create an agent for User B
|
|
agentB1 = await Agent.create({
|
|
id: `agent_${nanoid(12)}`,
|
|
name: 'Agent B1',
|
|
description: 'User B agent 1',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: userB,
|
|
versions: [
|
|
{
|
|
name: 'Agent B1',
|
|
description: 'User B agent 1',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
},
|
|
],
|
|
});
|
|
});
|
|
test('maps cursor contract failures to HTTP 409 without restarting the walk', async () => {
|
|
const listSpy = jest
|
|
.spyOn(db, 'getListAgentsByAccess')
|
|
.mockRejectedValue(new AgentSortCursorError('ordering-mismatch'));
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(409);
|
|
expect(mockRes.json).toHaveBeenCalledWith({ error: 'cursor_ordering_mismatch' });
|
|
expect(mockRes.status).not.toHaveBeenCalledWith(500);
|
|
listSpy.mockRestore();
|
|
});
|
|
|
|
test('lets a manage:agents role discover unshared agents by search', async () => {
|
|
await db.grantCapability({
|
|
principalType: PrincipalType.ROLE,
|
|
principalId: 'LIST_MANAGER_TEST',
|
|
capability: SystemCapabilities.MANAGE_AGENTS,
|
|
});
|
|
mockReq.user = {
|
|
id: userB.toString(),
|
|
role: 'LIST_MANAGER_TEST',
|
|
idOnTheSource: null,
|
|
};
|
|
mockReq.query.search = 'A2';
|
|
findAccessibleResources.mockResolvedValue([]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
expect(await hasCapability(mockReq.user, SystemCapabilities.MANAGE_AGENTS)).toBe(true);
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.data.map((agent) => agent.id)).toEqual([agentA2.id]);
|
|
expect(response.data[0].isEditable).toBe(true);
|
|
expect(findAccessibleResources).toHaveBeenCalledWith(
|
|
expect.objectContaining({ resourceType: ResourceType.AGENT }),
|
|
);
|
|
});
|
|
|
|
test('restricts a manager to the authenticated tenant even without ambient tenant context', async () => {
|
|
const tenantA = `tenant-a-${uuidv4()}`;
|
|
const tenantB = `tenant-b-${uuidv4()}`;
|
|
const name = 'Tenant-Scoped Discovery';
|
|
const agentInA = await tenantStorage.run({ tenantId: tenantA }, () =>
|
|
Agent.create({
|
|
id: `agent_${nanoid(12)}`,
|
|
name,
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: userA,
|
|
}),
|
|
);
|
|
await tenantStorage.run({ tenantId: tenantB }, () =>
|
|
Agent.create({
|
|
id: `agent_${nanoid(12)}`,
|
|
name,
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: userB,
|
|
}),
|
|
);
|
|
await db.grantCapability({
|
|
principalType: PrincipalType.ROLE,
|
|
principalId: 'LIST_TENANT_MANAGER',
|
|
capability: SystemCapabilities.MANAGE_AGENTS,
|
|
});
|
|
mockReq.user = {
|
|
id: userB.toString(),
|
|
role: 'LIST_TENANT_MANAGER',
|
|
idOnTheSource: null,
|
|
tenantId: tenantA,
|
|
};
|
|
mockReq.query.search = name;
|
|
findAccessibleResources.mockResolvedValue([]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
expect(mockCache.get).toHaveBeenCalledWith(
|
|
`${userB.toString()}:${tenantA}:agents_avatar_refresh`,
|
|
);
|
|
expect(mockRes.json.mock.calls[0][0].data.map((agent) => agent.id)).toEqual([agentInA.id]);
|
|
|
|
mockRes.json.mockClear();
|
|
mockReq.user.tenantId = undefined;
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
expect(mockRes.json.mock.calls[0][0].data).toHaveLength(0);
|
|
});
|
|
|
|
test('should return empty list when user has no accessible agents', async () => {
|
|
// User B has no permissions and no owned agents
|
|
mockReq.user.id = userB.toString();
|
|
findAccessibleResources.mockResolvedValue([]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
expect(findAccessibleResources).toHaveBeenCalledWith({
|
|
userId: userB.toString(),
|
|
role: 'USER',
|
|
resourceType: 'agent',
|
|
requiredPermissions: 1, // VIEW permission
|
|
});
|
|
|
|
expect(mockRes.json).toHaveBeenCalledWith({
|
|
object: 'list',
|
|
data: [],
|
|
first_id: null,
|
|
last_id: null,
|
|
has_more: false,
|
|
after: null,
|
|
});
|
|
});
|
|
|
|
test('should not return other users agents when accessibleIds is empty', async () => {
|
|
// User B trying to see agents with no permissions
|
|
mockReq.user.id = userB.toString();
|
|
findAccessibleResources.mockResolvedValue([]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.data).toHaveLength(0);
|
|
|
|
// Verify User A's agents are not included
|
|
const agentIds = response.data.map((a) => a.id);
|
|
expect(agentIds).not.toContain(agentA1.id);
|
|
expect(agentIds).not.toContain(agentA2.id);
|
|
expect(agentIds).not.toContain(agentA3.id);
|
|
});
|
|
|
|
test('should only return agents user has access to', async () => {
|
|
// User B has access to one of User A's agents
|
|
mockReq.user.id = userB.toString();
|
|
findAccessibleResources.mockResolvedValue([agentA1._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.data).toHaveLength(1);
|
|
expect(response.data[0].id).toBe(agentA1.id);
|
|
expect(response.data[0].name).toBe('Agent A1');
|
|
});
|
|
|
|
test('should return owner_contact for list agents missing support_contact', async () => {
|
|
const owner = await createOwner({
|
|
_id: userA,
|
|
name: 'List Owner',
|
|
email: 'list.owner@example.com',
|
|
});
|
|
await grantAgentOwner({ agent: agentA1, owner });
|
|
|
|
mockReq.user.id = userB.toString();
|
|
findAccessibleResources.mockResolvedValue([agentA1._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.data[0].owner_contact).toEqual({ name: 'List Owner' });
|
|
expect(response.data[0].owner_contact).not.toHaveProperty('email');
|
|
});
|
|
|
|
test('should use the first ACL owner when an agent has multiple owners', async () => {
|
|
const firstOwner = await createOwner({
|
|
name: 'First Owner',
|
|
email: 'first.owner@example.com',
|
|
});
|
|
const secondOwner = await createOwner({
|
|
name: 'Second Owner',
|
|
email: 'second.owner@example.com',
|
|
});
|
|
await grantAgentOwner({
|
|
agent: agentA1,
|
|
owner: secondOwner,
|
|
grantedAt: new Date('2024-02-01T00:00:00.000Z'),
|
|
});
|
|
await grantAgentOwner({
|
|
agent: agentA1,
|
|
owner: firstOwner,
|
|
grantedAt: new Date('2024-01-01T00:00:00.000Z'),
|
|
});
|
|
|
|
mockReq.user.id = userB.toString();
|
|
findAccessibleResources.mockResolvedValue([agentA1._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.data[0].owner_contact).toEqual({ name: 'First Owner' });
|
|
});
|
|
|
|
test('should omit owner_contact when no owner user can be resolved', async () => {
|
|
mockReq.user.id = userB.toString();
|
|
findAccessibleResources.mockResolvedValue([agentA1._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.data[0].owner_contact).toBeUndefined();
|
|
});
|
|
|
|
test('should mark isEditable per agent on a VIEW-scoped list', async () => {
|
|
mockReq.user.id = userA.toString();
|
|
mockReq.query = { requiredPermission: String(PermissionBits.VIEW) };
|
|
/** VIEW reaches all three; the EDIT lookup only reaches agentA1. */
|
|
findAccessibleResources.mockImplementation(({ resourceType, requiredPermissions }) => {
|
|
if (resourceType === 'agent' && requiredPermissions === PermissionBits.EDIT) {
|
|
return Promise.resolve([agentA1._id]);
|
|
}
|
|
if (resourceType === 'agent') {
|
|
return Promise.resolve([agentA1._id, agentA2._id, agentA3._id]);
|
|
}
|
|
return Promise.resolve([]);
|
|
});
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
const byId = Object.fromEntries(
|
|
mockRes.json.mock.calls[0][0].data.map((a) => [a.id, a.isEditable]),
|
|
);
|
|
expect(byId[agentA1.id]).toBe(true);
|
|
expect(byId[agentA2.id]).toBe(false);
|
|
expect(byId[agentA3.id]).toBe(false);
|
|
});
|
|
|
|
test('should forward idOnTheSource to every ACL lookup', async () => {
|
|
/** Without it `getUserPrincipals` reads the user document once per lookup, so the
|
|
* handler pays an extra `User.findById` for each permission it resolves. */
|
|
mockReq.user.id = userA.toString();
|
|
mockReq.user.idOnTheSource = 'external-oid-1';
|
|
findAccessibleResources.mockResolvedValue([agentA1._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
expect(findAccessibleResources.mock.calls.length).toBeGreaterThan(1);
|
|
for (const [args] of findAccessibleResources.mock.calls) {
|
|
expect(args.idOnTheSource).toBe('external-oid-1');
|
|
}
|
|
});
|
|
|
|
test('should mark every agent editable when the request is already EDIT-scoped', async () => {
|
|
mockReq.user.id = userA.toString();
|
|
mockReq.query = { requiredPermission: String(PermissionBits.EDIT) };
|
|
findAccessibleResources.mockResolvedValue([agentA1._id, agentA2._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.data.every((a) => a.isEditable === true)).toBe(true);
|
|
/** No extra EDIT lookup: an EDIT-scoped match is editable by definition. */
|
|
const editCalls = findAccessibleResources.mock.calls.filter(
|
|
([args]) =>
|
|
args.resourceType === 'agent' && args.requiredPermissions === PermissionBits.EDIT,
|
|
);
|
|
expect(editCalls).toHaveLength(1);
|
|
});
|
|
|
|
test('should return only expected safe list fields for VIEW callers', async () => {
|
|
const hiddenSkillId = new mongoose.Types.ObjectId();
|
|
await Agent.findByIdAndUpdate(agentA1._id, {
|
|
avatar: { filepath: '/avatars/a1.png', source: FileSources.local },
|
|
category: 'general',
|
|
support_contact: { name: 'Support', email: 'support@example.com' },
|
|
is_promoted: true,
|
|
instructions: 'private system instructions',
|
|
tools: ['execute_code'],
|
|
actions: ['example.com::action'],
|
|
model_parameters: { temperature: 0.7 },
|
|
tool_resources: { file_search: { file_ids: ['file-1'] } },
|
|
tool_options: { execute_code: { defer_loading: true } },
|
|
subagents: { enabled: true, agent_ids: [agentA2.id] },
|
|
edges: [{ from: agentA1.id, to: agentA2.id }],
|
|
skills_enabled: true,
|
|
skills: [hiddenSkillId.toString()],
|
|
});
|
|
|
|
mockReq.user.id = userB.toString();
|
|
mockReq.query.requiredPermission = String(PermissionBits.VIEW);
|
|
findAccessibleResources.mockImplementation(({ resourceType }) => {
|
|
if (resourceType === ResourceType.AGENT) {
|
|
return Promise.resolve([agentA1._id]);
|
|
}
|
|
if (resourceType === ResourceType.SKILL) {
|
|
return Promise.resolve([]);
|
|
}
|
|
return Promise.resolve([]);
|
|
});
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
const agent = response.data[0];
|
|
expect(Object.keys(agent).sort()).toEqual(
|
|
[
|
|
'_id',
|
|
'agent_ids',
|
|
'author',
|
|
'avatar',
|
|
'category',
|
|
'conversation_starters',
|
|
'description',
|
|
'edges',
|
|
'id',
|
|
'isEditable',
|
|
'is_promoted',
|
|
'name',
|
|
'subagents',
|
|
'support_contact',
|
|
'tools',
|
|
'updatedAt',
|
|
].sort(),
|
|
);
|
|
expect(agent).toEqual(
|
|
expect.objectContaining({
|
|
id: agentA1.id,
|
|
name: 'Agent A1',
|
|
description: 'User A agent 1',
|
|
author: userA.toString(),
|
|
category: 'general',
|
|
is_promoted: true,
|
|
tools: ['execute_code'],
|
|
edges: [{ from: agentA1.id, to: agentA2.id }],
|
|
subagents: { enabled: true, agent_ids: [agentA2.id] },
|
|
}),
|
|
);
|
|
});
|
|
|
|
test('should return multiple accessible agents', async () => {
|
|
// User B has access to multiple agents
|
|
mockReq.user.id = userB.toString();
|
|
findAccessibleResources.mockResolvedValue([agentA1._id, agentA3._id, agentB1._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.data).toHaveLength(3);
|
|
|
|
const agentIds = response.data.map((a) => a.id);
|
|
expect(agentIds).toContain(agentA1.id);
|
|
expect(agentIds).toContain(agentA3.id);
|
|
expect(agentIds).toContain(agentB1.id);
|
|
expect(agentIds).not.toContain(agentA2.id);
|
|
});
|
|
|
|
test('should apply category filter correctly with ACL', async () => {
|
|
// User has access to all agents but filters by category
|
|
mockReq.user.id = userB.toString();
|
|
mockReq.query.category = 'productivity';
|
|
findAccessibleResources.mockResolvedValue([agentA1._id, agentA2._id, agentA3._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.data).toHaveLength(1);
|
|
expect(response.data[0].id).toBe(agentA3.id);
|
|
expect(response.data[0].category).toBe('productivity');
|
|
});
|
|
|
|
test('should apply search filter correctly with ACL', async () => {
|
|
// User has access to multiple agents but searches for specific one
|
|
mockReq.user.id = userB.toString();
|
|
mockReq.query.search = 'A2';
|
|
findAccessibleResources.mockResolvedValue([agentA1._id, agentA2._id, agentA3._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.data).toHaveLength(1);
|
|
expect(response.data[0].id).toBe(agentA2.id);
|
|
});
|
|
|
|
test('should handle pagination with ACL filtering', async () => {
|
|
// Create more agents for pagination testing
|
|
const moreAgents = [];
|
|
for (let i = 4; i <= 10; i++) {
|
|
const agent = await Agent.create({
|
|
id: `agent_${nanoid(12)}`,
|
|
name: `Agent A${i}`,
|
|
description: `User A agent ${i}`,
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: userA,
|
|
versions: [
|
|
{
|
|
name: `Agent A${i}`,
|
|
description: `User A agent ${i}`,
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
},
|
|
],
|
|
});
|
|
moreAgents.push(agent);
|
|
}
|
|
|
|
// User has access to all agents
|
|
const allAgentIds = [agentA1, agentA2, agentA3, ...moreAgents].map((a) => a._id);
|
|
mockReq.user.id = userB.toString();
|
|
mockReq.query.limit = '5';
|
|
findAccessibleResources.mockResolvedValue(allAgentIds);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.data).toHaveLength(5);
|
|
expect(response.has_more).toBe(true);
|
|
expect(response.after).toBeTruthy();
|
|
});
|
|
|
|
test('should mark publicly accessible agents', async () => {
|
|
// User has access to agents, some are public
|
|
mockReq.user.id = userB.toString();
|
|
findAccessibleResources.mockResolvedValue([agentA1._id, agentA2._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([agentA2._id]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.data).toHaveLength(2);
|
|
|
|
const publicAgent = response.data.find((a) => a.id === agentA2.id);
|
|
const privateAgent = response.data.find((a) => a.id === agentA1.id);
|
|
|
|
expect(publicAgent.isPublic).toBe(true);
|
|
expect(privateAgent.isPublic).toBeUndefined();
|
|
});
|
|
|
|
test('should handle requiredPermission parameter', async () => {
|
|
// Test with different permission levels
|
|
mockReq.user.id = userB.toString();
|
|
mockReq.query.requiredPermission = '15'; // FULL_ACCESS
|
|
findAccessibleResources.mockResolvedValue([agentA1._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
expect(findAccessibleResources).toHaveBeenCalledWith({
|
|
userId: userB.toString(),
|
|
role: 'USER',
|
|
resourceType: 'agent',
|
|
requiredPermissions: 15,
|
|
});
|
|
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.data).toHaveLength(1);
|
|
});
|
|
|
|
test('should return only viewer-accessible skill scope for VIEW list callers', async () => {
|
|
const visibleSkillId = new mongoose.Types.ObjectId();
|
|
const hiddenSkillId = new mongoose.Types.ObjectId();
|
|
await Agent.findByIdAndUpdate(agentA1._id, {
|
|
skills_enabled: true,
|
|
skills: [visibleSkillId.toString(), hiddenSkillId.toString()],
|
|
});
|
|
|
|
mockReq.user.id = userB.toString();
|
|
mockReq.query.requiredPermission = String(PermissionBits.VIEW);
|
|
findAccessibleResources.mockImplementation(({ resourceType }) => {
|
|
if (resourceType === ResourceType.AGENT) {
|
|
return Promise.resolve([agentA1._id]);
|
|
}
|
|
if (resourceType === ResourceType.SKILL) {
|
|
return Promise.resolve([visibleSkillId]);
|
|
}
|
|
return Promise.resolve([]);
|
|
});
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.data).toHaveLength(1);
|
|
expect(response.data[0].skills_enabled).toBe(true);
|
|
expect(response.data[0].skills).toEqual([visibleSkillId.toString()]);
|
|
expect(response.data[0].skills).not.toContain(hiddenSkillId.toString());
|
|
});
|
|
|
|
test('should omit skill scope for VIEW list callers with no accessible configured skills', async () => {
|
|
const hiddenSkillId = new mongoose.Types.ObjectId();
|
|
await Agent.findByIdAndUpdate(agentA1._id, {
|
|
skills_enabled: true,
|
|
skills: [hiddenSkillId.toString()],
|
|
});
|
|
|
|
mockReq.user.id = userB.toString();
|
|
mockReq.query.requiredPermission = String(PermissionBits.VIEW);
|
|
findAccessibleResources.mockImplementation(({ resourceType }) => {
|
|
if (resourceType === ResourceType.AGENT) {
|
|
return Promise.resolve([agentA1._id]);
|
|
}
|
|
if (resourceType === ResourceType.SKILL) {
|
|
return Promise.resolve([]);
|
|
}
|
|
return Promise.resolve([]);
|
|
});
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.data).toHaveLength(1);
|
|
expect(response.data[0].skills).toBeUndefined();
|
|
expect(response.data[0].skills_enabled).toBeUndefined();
|
|
});
|
|
|
|
test('should preserve deployment skill scope for VIEW list callers', async () => {
|
|
const deploymentSkillId = new mongoose.Types.ObjectId();
|
|
await Agent.findByIdAndUpdate(agentA1._id, {
|
|
skills_enabled: true,
|
|
skills: [deploymentSkillId.toString()],
|
|
});
|
|
|
|
mockReq.user.id = userB.toString();
|
|
mockReq.query.requiredPermission = String(PermissionBits.VIEW);
|
|
findAccessibleResources.mockImplementation(({ resourceType }) => {
|
|
if (resourceType === ResourceType.AGENT) {
|
|
return Promise.resolve([agentA1._id]);
|
|
}
|
|
return Promise.resolve([]);
|
|
});
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
mergeDeploymentSkillIds.mockImplementation((ids) => [...ids, deploymentSkillId]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.data).toHaveLength(1);
|
|
expect(response.data[0].skills_enabled).toBe(true);
|
|
expect(response.data[0].skills).toEqual([deploymentSkillId.toString()]);
|
|
});
|
|
|
|
test('should preserve enabled skill scope for VIEW list callers with an empty allowlist', async () => {
|
|
await Agent.findByIdAndUpdate(agentA1._id, {
|
|
skills_enabled: true,
|
|
skills: [],
|
|
});
|
|
|
|
mockReq.user.id = userB.toString();
|
|
mockReq.query.requiredPermission = String(PermissionBits.VIEW);
|
|
findAccessibleResources.mockImplementation(({ resourceType }) => {
|
|
if (resourceType === ResourceType.AGENT) {
|
|
return Promise.resolve([agentA1._id]);
|
|
}
|
|
if (resourceType === ResourceType.SKILL) {
|
|
return Promise.resolve([]);
|
|
}
|
|
return Promise.resolve([]);
|
|
});
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.data).toHaveLength(1);
|
|
expect(response.data[0].skills).toBeUndefined();
|
|
expect(response.data[0].skills_enabled).toBe(true);
|
|
});
|
|
|
|
test('should preserve an enabled empty catalog for VIEW list callers', async () => {
|
|
await Agent.findByIdAndUpdate(agentA1._id, {
|
|
skills_enabled: false,
|
|
skill_authoring_enabled: true,
|
|
skills_scope: SkillsScope.none,
|
|
skills: [],
|
|
});
|
|
|
|
mockReq.user.id = userB.toString();
|
|
mockReq.query.requiredPermission = String(PermissionBits.VIEW);
|
|
findAccessibleResources.mockImplementation(({ resourceType }) => {
|
|
if (resourceType === ResourceType.AGENT) {
|
|
return Promise.resolve([agentA1._id]);
|
|
}
|
|
return Promise.resolve([]);
|
|
});
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.data).toHaveLength(1);
|
|
expect(response.data[0].skills).toBeUndefined();
|
|
expect(response.data[0].skills_enabled).toBeUndefined();
|
|
expect(response.data[0].skill_authoring_enabled).toBe(true);
|
|
expect(response.data[0].skills_scope).toBeUndefined();
|
|
});
|
|
|
|
test('should return raw skill configuration for EDIT list callers', async () => {
|
|
const visibleSkillId = new mongoose.Types.ObjectId();
|
|
const hiddenSkillId = new mongoose.Types.ObjectId();
|
|
await Agent.findByIdAndUpdate(agentA1._id, {
|
|
skills_enabled: true,
|
|
skills: [visibleSkillId.toString(), hiddenSkillId.toString()],
|
|
});
|
|
|
|
mockReq.user.id = userB.toString();
|
|
mockReq.query.requiredPermission = String(PermissionBits.EDIT);
|
|
findAccessibleResources.mockResolvedValue([agentA1._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.data).toHaveLength(1);
|
|
expect(response.data[0].skills_enabled).toBe(true);
|
|
expect(response.data[0].skills).toEqual([
|
|
visibleSkillId.toString(),
|
|
hiddenSkillId.toString(),
|
|
]);
|
|
expect(findAccessibleResources).not.toHaveBeenCalledWith(
|
|
expect.objectContaining({ resourceType: ResourceType.SKILL }),
|
|
);
|
|
});
|
|
|
|
test('should handle promoted filter with ACL', async () => {
|
|
// Create a promoted agent
|
|
const promotedAgent = await Agent.create({
|
|
id: `agent_${nanoid(12)}`,
|
|
name: 'Promoted Agent',
|
|
description: 'A promoted agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: userA,
|
|
is_promoted: true,
|
|
versions: [
|
|
{
|
|
name: 'Promoted Agent',
|
|
description: 'A promoted agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
is_promoted: true,
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
},
|
|
],
|
|
});
|
|
|
|
mockReq.user.id = userB.toString();
|
|
mockReq.query.promoted = '1';
|
|
findAccessibleResources.mockResolvedValue([agentA1._id, agentA2._id, promotedAgent._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.data).toHaveLength(1);
|
|
expect(response.data[0].id).toBe(promotedAgent.id);
|
|
expect(response.data[0].is_promoted).toBe(true);
|
|
});
|
|
|
|
test('should handle errors gracefully', async () => {
|
|
mockReq.user.id = userB.toString();
|
|
findAccessibleResources.mockRejectedValue(new Error('Permission service error'));
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(500);
|
|
expect(mockRes.json).toHaveBeenCalledWith({
|
|
error: 'Permission service error',
|
|
});
|
|
});
|
|
|
|
test('should respect combined filters with ACL', async () => {
|
|
// Create agents with specific attributes
|
|
const productivityPromoted = await Agent.create({
|
|
id: `agent_${nanoid(12)}`,
|
|
name: 'Productivity Pro',
|
|
description: 'A promoted productivity agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: userA,
|
|
category: 'productivity',
|
|
is_promoted: true,
|
|
versions: [
|
|
{
|
|
name: 'Productivity Pro',
|
|
description: 'A promoted productivity agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
category: 'productivity',
|
|
is_promoted: true,
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
},
|
|
],
|
|
});
|
|
|
|
mockReq.user.id = userB.toString();
|
|
mockReq.query.category = 'productivity';
|
|
mockReq.query.promoted = '1';
|
|
findAccessibleResources.mockResolvedValue([
|
|
agentA1._id,
|
|
agentA2._id,
|
|
agentA3._id,
|
|
productivityPromoted._id,
|
|
]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.data).toHaveLength(1);
|
|
expect(response.data[0].id).toBe(productivityPromoted.id);
|
|
expect(response.data[0].category).toBe('productivity');
|
|
expect(response.data[0].is_promoted).toBe(true);
|
|
});
|
|
});
|
|
|
|
describe('S3 Avatar Refresh', () => {
|
|
let userA, userB;
|
|
let agentWithS3Avatar, agentWithLocalAvatar, agentOwnedByOther;
|
|
|
|
beforeEach(async () => {
|
|
await Agent.deleteMany({});
|
|
jest.clearAllMocks();
|
|
|
|
// Reset cache mock
|
|
mockCache.get.mockResolvedValue(false);
|
|
mockCache.set.mockResolvedValue(undefined);
|
|
|
|
userA = new mongoose.Types.ObjectId();
|
|
userB = new mongoose.Types.ObjectId();
|
|
|
|
// Create agent with S3 avatar owned by userA
|
|
agentWithS3Avatar = await Agent.create({
|
|
id: `agent_${nanoid(12)}`,
|
|
name: 'Agent with S3 Avatar',
|
|
description: 'Has S3 avatar',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: userA,
|
|
avatar: {
|
|
source: FileSources.s3,
|
|
filepath: 'old-s3-path.jpg',
|
|
},
|
|
versions: [
|
|
{
|
|
name: 'Agent with S3 Avatar',
|
|
description: 'Has S3 avatar',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
},
|
|
],
|
|
});
|
|
|
|
// Create agent with local avatar owned by userA
|
|
agentWithLocalAvatar = await Agent.create({
|
|
id: `agent_${nanoid(12)}`,
|
|
name: 'Agent with Local Avatar',
|
|
description: 'Has local avatar',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: userA,
|
|
avatar: {
|
|
source: 'local',
|
|
filepath: 'local-path.jpg',
|
|
},
|
|
versions: [
|
|
{
|
|
name: 'Agent with Local Avatar',
|
|
description: 'Has local avatar',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
},
|
|
],
|
|
});
|
|
|
|
// Create agent with S3 avatar owned by userB
|
|
agentOwnedByOther = await Agent.create({
|
|
id: `agent_${nanoid(12)}`,
|
|
name: 'Agent Owned By Other',
|
|
description: 'Owned by userB',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: userB,
|
|
avatar: {
|
|
source: FileSources.s3,
|
|
filepath: 'other-s3-path.jpg',
|
|
},
|
|
versions: [
|
|
{
|
|
name: 'Agent Owned By Other',
|
|
description: 'Owned by userB',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
},
|
|
],
|
|
});
|
|
});
|
|
|
|
test('should skip avatar refresh if cache already covers the page', async () => {
|
|
/* Coverage is only coverage while it names the filepath it was taken for: a cached
|
|
URL for a replaced avatar is a link to a file the agent no longer shows. */
|
|
mockCache.get.mockResolvedValue({
|
|
urlCache: {},
|
|
coveredIds: [agentWithS3Avatar.id],
|
|
coveredFilepaths: { [agentWithS3Avatar.id]: 'old-s3-path.jpg' },
|
|
});
|
|
findAccessibleResources.mockResolvedValue([agentWithS3Avatar._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
const mockReq = {
|
|
user: { id: userA.toString(), role: 'USER' },
|
|
query: {},
|
|
};
|
|
const mockRes = {
|
|
status: jest.fn().mockReturnThis(),
|
|
json: jest.fn().mockReturnThis(),
|
|
};
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
// Should not call refreshS3Url when cache hit
|
|
expect(refreshS3Url).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test('does not treat a manager page cache as an ACL-wide refresh after role downgrade', async () => {
|
|
mockCache.get.mockResolvedValue({ urlCache: {}, scope: 'page' });
|
|
findAccessibleResources.mockResolvedValue([agentWithS3Avatar._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
refreshS3Url.mockResolvedValue('refreshed-after-downgrade.jpg');
|
|
const mockReq = { user: { id: userA.toString(), role: 'USER' }, query: {} };
|
|
const mockRes = { status: jest.fn().mockReturnThis(), json: jest.fn().mockReturnThis() };
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
expect(refreshS3Url).toHaveBeenCalledTimes(1);
|
|
expect(mockRes.json.mock.calls[0][0].data[0].avatar.filepath).toBe(
|
|
'refreshed-after-downgrade.jpg',
|
|
);
|
|
});
|
|
|
|
test('should refresh and persist S3 avatars on cache miss', async () => {
|
|
mockCache.get.mockResolvedValue(false);
|
|
findAccessibleResources.mockResolvedValue([agentWithS3Avatar._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
refreshS3Url.mockResolvedValue('new-s3-path.jpg');
|
|
|
|
const mockReq = {
|
|
user: { id: userA.toString(), role: 'USER' },
|
|
query: {},
|
|
};
|
|
const mockRes = {
|
|
status: jest.fn().mockReturnThis(),
|
|
json: jest.fn().mockReturnThis(),
|
|
};
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
// Verify S3 URL was refreshed
|
|
expect(refreshS3Url).toHaveBeenCalled();
|
|
|
|
// Verify cache was set with urlCache map, not a plain boolean
|
|
expect(mockCache.set).toHaveBeenCalledWith(
|
|
expect.any(String),
|
|
expect.objectContaining({ urlCache: expect.any(Object) }),
|
|
expect.any(Number),
|
|
);
|
|
|
|
// Verify response was returned
|
|
expect(mockRes.json).toHaveBeenCalled();
|
|
});
|
|
|
|
test('should load the requested page before refreshing its avatars', async () => {
|
|
const db = require('~/models');
|
|
const order = [];
|
|
refreshS3Url.mockImplementation(async () => {
|
|
order.push('avatar-refresh');
|
|
return 'new-s3-path.jpg';
|
|
});
|
|
const listSpy = jest.spyOn(db, 'getListAgentsByAccess').mockImplementation(async (params) => {
|
|
order.push('list-query');
|
|
if (params.includeSkillConfig) {
|
|
return {
|
|
object: 'list',
|
|
data: [agentWithS3Avatar.toObject()],
|
|
has_more: false,
|
|
after: null,
|
|
};
|
|
}
|
|
return { object: 'list', data: [], has_more: false, after: null };
|
|
});
|
|
mockCache.get.mockResolvedValue(false);
|
|
findAccessibleResources.mockResolvedValue([agentWithS3Avatar._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
const mockReq = { user: { id: userA.toString(), role: 'USER' }, query: {} };
|
|
const mockRes = { status: jest.fn().mockReturnThis(), json: jest.fn().mockReturnThis() };
|
|
|
|
try {
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
expect(order).toEqual(['list-query', 'avatar-refresh']);
|
|
} finally {
|
|
listSpy.mockRestore();
|
|
refreshS3Url.mockReset();
|
|
}
|
|
});
|
|
|
|
test('should serve the refreshed filepath in the same response on cache miss', async () => {
|
|
const agentId = agentWithS3Avatar.id;
|
|
mockCache.get.mockResolvedValue(false);
|
|
findAccessibleResources.mockResolvedValue([agentWithS3Avatar._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
refreshS3Url.mockResolvedValue('new-s3-path.jpg');
|
|
|
|
const mockReq = {
|
|
user: { id: userA.toString(), role: 'USER' },
|
|
query: {},
|
|
};
|
|
const mockRes = {
|
|
status: jest.fn().mockReturnThis(),
|
|
json: jest.fn().mockReturnThis(),
|
|
};
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
const responseData = mockRes.json.mock.calls[0][0];
|
|
const agent = responseData.data.find((a) => a.id === agentId);
|
|
/** The refresh runs alongside the list query, so the refreshed path must reach the
|
|
* response through `urlCache` rather than through what the list query read. */
|
|
expect(agent.avatar.filepath).toBe('new-s3-path.jpg');
|
|
});
|
|
|
|
test('should keep the page query unfiltered while selecting only S3 rows for refresh', async () => {
|
|
const db = require('~/models');
|
|
const listSpy = jest.spyOn(db, 'getListAgentsByAccess');
|
|
mockCache.get.mockResolvedValue(false);
|
|
findAccessibleResources.mockResolvedValue([agentWithLocalAvatar._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
const mockReq = {
|
|
user: { id: userA.toString(), role: 'USER' },
|
|
query: {},
|
|
};
|
|
const mockRes = {
|
|
status: jest.fn().mockReturnThis(),
|
|
json: jest.fn().mockReturnThis(),
|
|
};
|
|
|
|
try {
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
expect(listSpy).toHaveBeenCalledTimes(1);
|
|
expect(listSpy).toHaveBeenCalledWith(
|
|
expect.objectContaining({ includeSkillConfig: true, otherParams: {} }),
|
|
);
|
|
expect(refreshS3Url).not.toHaveBeenCalled();
|
|
const responseData = mockRes.json.mock.calls[0][0];
|
|
const agent = responseData.data.find((a) => a.id === agentWithLocalAvatar.id);
|
|
expect(agent.avatar.filepath).toBe('local-path.jpg');
|
|
} finally {
|
|
listSpy.mockRestore();
|
|
}
|
|
});
|
|
|
|
test('should refresh avatars for all accessible agents (VIEW permission)', async () => {
|
|
mockCache.get.mockResolvedValue(false);
|
|
// User A has access to both their own agent and userB's agent
|
|
findAccessibleResources.mockResolvedValue([agentWithS3Avatar._id, agentOwnedByOther._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
refreshS3Url.mockResolvedValue('new-path.jpg');
|
|
|
|
const mockReq = {
|
|
user: { id: userA.toString(), role: 'USER' },
|
|
query: {},
|
|
};
|
|
const mockRes = {
|
|
status: jest.fn().mockReturnThis(),
|
|
json: jest.fn().mockReturnThis(),
|
|
};
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
// Should be called for both agents - any user with VIEW access can refresh
|
|
expect(refreshS3Url).toHaveBeenCalledTimes(2);
|
|
});
|
|
|
|
test('should skip non-S3 avatars', async () => {
|
|
mockCache.get.mockResolvedValue(false);
|
|
findAccessibleResources.mockResolvedValue([agentWithLocalAvatar._id, agentWithS3Avatar._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
refreshS3Url.mockResolvedValue('new-path.jpg');
|
|
|
|
const mockReq = {
|
|
user: { id: userA.toString(), role: 'USER' },
|
|
query: {},
|
|
};
|
|
const mockRes = {
|
|
status: jest.fn().mockReturnThis(),
|
|
json: jest.fn().mockReturnThis(),
|
|
};
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
// Should only be called for S3 avatar agent
|
|
expect(refreshS3Url).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
test('should not update if S3 URL unchanged', async () => {
|
|
mockCache.get.mockResolvedValue(false);
|
|
findAccessibleResources.mockResolvedValue([agentWithS3Avatar._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
// Return the same path - no update needed
|
|
refreshS3Url.mockResolvedValue('old-s3-path.jpg');
|
|
|
|
const mockReq = {
|
|
user: { id: userA.toString(), role: 'USER' },
|
|
query: {},
|
|
};
|
|
const mockRes = {
|
|
status: jest.fn().mockReturnThis(),
|
|
json: jest.fn().mockReturnThis(),
|
|
};
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
// Verify refreshS3Url was called
|
|
expect(refreshS3Url).toHaveBeenCalled();
|
|
|
|
// Response should still be returned
|
|
expect(mockRes.json).toHaveBeenCalled();
|
|
});
|
|
|
|
test('should handle S3 refresh errors gracefully', async () => {
|
|
mockCache.get.mockResolvedValue(false);
|
|
findAccessibleResources.mockResolvedValue([agentWithS3Avatar._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
refreshS3Url.mockRejectedValue(new Error('S3 error'));
|
|
|
|
const mockReq = {
|
|
user: { id: userA.toString(), role: 'USER' },
|
|
query: {},
|
|
};
|
|
const mockRes = {
|
|
status: jest.fn().mockReturnThis(),
|
|
json: jest.fn().mockReturnThis(),
|
|
};
|
|
|
|
// Should not throw - handles error gracefully
|
|
await expect(getListAgentsHandler(mockReq, mockRes)).resolves.not.toThrow();
|
|
|
|
// Response should still be returned
|
|
expect(mockRes.json).toHaveBeenCalled();
|
|
});
|
|
|
|
test('should process agents in batches', async () => {
|
|
mockCache.get.mockResolvedValue(false);
|
|
|
|
// Create 25 agents (should be processed in batches of 20)
|
|
const manyAgents = [];
|
|
for (let i = 0; i < 25; i++) {
|
|
const agent = await Agent.create({
|
|
id: `agent_${nanoid(12)}`,
|
|
name: `Agent ${i}`,
|
|
description: `Agent ${i} description`,
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: userA,
|
|
avatar: {
|
|
source: FileSources.s3,
|
|
filepath: `path${i}.jpg`,
|
|
},
|
|
versions: [
|
|
{
|
|
name: `Agent ${i}`,
|
|
description: `Agent ${i} description`,
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
},
|
|
],
|
|
});
|
|
manyAgents.push(agent);
|
|
}
|
|
|
|
const allAgentIds = manyAgents.map((a) => a._id);
|
|
findAccessibleResources.mockResolvedValue(allAgentIds);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
refreshS3Url.mockImplementation((avatar) =>
|
|
Promise.resolve(avatar.filepath.replace('.jpg', '-new.jpg')),
|
|
);
|
|
|
|
const mockReq = {
|
|
user: { id: userA.toString(), role: 'USER' },
|
|
query: {},
|
|
};
|
|
const mockRes = {
|
|
status: jest.fn().mockReturnThis(),
|
|
json: jest.fn().mockReturnThis(),
|
|
};
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
// All 25 should be processed
|
|
expect(refreshS3Url).toHaveBeenCalledTimes(25);
|
|
});
|
|
|
|
test('should skip agents without id or author', async () => {
|
|
mockCache.get.mockResolvedValue(false);
|
|
|
|
// Create agent without proper id field (edge case)
|
|
const agentWithoutId = await Agent.create({
|
|
id: `agent_${nanoid(12)}`,
|
|
name: 'Agent without ID field',
|
|
description: 'Testing',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
author: userA,
|
|
avatar: {
|
|
source: FileSources.s3,
|
|
filepath: 'test-path.jpg',
|
|
},
|
|
versions: [
|
|
{
|
|
name: 'Agent without ID field',
|
|
description: 'Testing',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
},
|
|
],
|
|
});
|
|
|
|
findAccessibleResources.mockResolvedValue([agentWithoutId._id, agentWithS3Avatar._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
refreshS3Url.mockResolvedValue('new-path.jpg');
|
|
|
|
const mockReq = {
|
|
user: { id: userA.toString(), role: 'USER' },
|
|
query: {},
|
|
};
|
|
const mockRes = {
|
|
status: jest.fn().mockReturnThis(),
|
|
json: jest.fn().mockReturnThis(),
|
|
};
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
// Should still complete without errors
|
|
expect(mockRes.json).toHaveBeenCalled();
|
|
});
|
|
|
|
test('should refresh rows on a non-default page ordering beyond the old warm-up cap', async () => {
|
|
const db = require('~/models');
|
|
const accessibleIds = [
|
|
agentWithS3Avatar._id,
|
|
...Array.from({ length: 1000 }, () => new mongoose.Types.ObjectId()),
|
|
];
|
|
const listSpy = jest.spyOn(db, 'getListAgentsByAccess').mockImplementation(async (params) => {
|
|
if (!params.includeSkillConfig) {
|
|
return { object: 'list', data: [], has_more: false, after: null };
|
|
}
|
|
return {
|
|
object: 'list',
|
|
data: [agentWithS3Avatar.toObject()],
|
|
has_more: false,
|
|
after: null,
|
|
};
|
|
});
|
|
mockCache.get.mockResolvedValue(false);
|
|
findAccessibleResources.mockResolvedValue(accessibleIds);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
refreshS3Url.mockResolvedValue('oldest-page-presigned-url.jpg');
|
|
|
|
const mockReq = {
|
|
user: { id: userA.toString(), role: 'USER' },
|
|
query: { sort: 'oldest', limit: '32' },
|
|
};
|
|
const mockRes = {
|
|
status: jest.fn().mockReturnThis(),
|
|
json: jest.fn().mockReturnThis(),
|
|
};
|
|
|
|
try {
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
expect(listSpy).toHaveBeenCalledTimes(1);
|
|
expect(listSpy).toHaveBeenCalledWith(expect.objectContaining({ sort: 'oldest' }));
|
|
expect(refreshS3Url).toHaveBeenCalledTimes(1);
|
|
const responseData = mockRes.json.mock.calls[0][0];
|
|
expect(responseData.data[0].avatar.filepath).toBe('oldest-page-presigned-url.jpg');
|
|
} finally {
|
|
listSpy.mockRestore();
|
|
}
|
|
});
|
|
|
|
test('should treat legacy boolean cache entry as a miss and run refresh', async () => {
|
|
// Simulate a cache entry written by the pre-fix code
|
|
mockCache.get.mockResolvedValue(true);
|
|
findAccessibleResources.mockResolvedValue([agentWithS3Avatar._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
refreshS3Url.mockResolvedValue('new-s3-path.jpg');
|
|
|
|
const mockReq = {
|
|
user: { id: userA.toString(), role: 'USER' },
|
|
query: {},
|
|
};
|
|
const mockRes = {
|
|
status: jest.fn().mockReturnThis(),
|
|
json: jest.fn().mockReturnThis(),
|
|
};
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
// Boolean true fails the shape guard, so refresh must run
|
|
expect(refreshS3Url).toHaveBeenCalled();
|
|
// Cache is overwritten with the proper format
|
|
expect(mockCache.set).toHaveBeenCalledWith(
|
|
expect.any(String),
|
|
expect.objectContaining({ urlCache: expect.any(Object) }),
|
|
expect.any(Number),
|
|
);
|
|
});
|
|
|
|
test('should apply cached urlCache filepath to paginated response on cache hit', async () => {
|
|
const agentId = agentWithS3Avatar.id;
|
|
const cachedUrl = 'cached-presigned-url.jpg';
|
|
|
|
mockCache.get.mockResolvedValue({
|
|
urlCache: { [agentId]: { filepath: 'old-s3-path.jpg', url: cachedUrl } },
|
|
coveredIds: { [agentId]: Date.now() + 30 * 60 * 1000 },
|
|
coveredFilepaths: { [agentId]: 'old-s3-path.jpg' },
|
|
});
|
|
findAccessibleResources.mockResolvedValue([agentWithS3Avatar._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
|
|
const mockReq = {
|
|
user: { id: userA.toString(), role: 'USER' },
|
|
query: {},
|
|
};
|
|
const mockRes = {
|
|
status: jest.fn().mockReturnThis(),
|
|
json: jest.fn().mockReturnThis(),
|
|
};
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
expect(refreshS3Url).not.toHaveBeenCalled();
|
|
|
|
const responseData = mockRes.json.mock.calls[0][0];
|
|
const agent = responseData.data.find((a) => a.id === agentId);
|
|
// Cached URL is served, not the stale DB value 'old-s3-path.jpg'
|
|
expect(agent.avatar.filepath).toBe(cachedUrl);
|
|
});
|
|
|
|
test('should refresh page rows absent from a prior cache coverage entry', async () => {
|
|
mockCache.get.mockResolvedValue({ urlCache: {}, coveredIds: [] });
|
|
findAccessibleResources.mockResolvedValue([agentWithS3Avatar._id]);
|
|
findPubliclyAccessibleResources.mockResolvedValue([]);
|
|
refreshS3Url.mockResolvedValue('new-s3-path.jpg');
|
|
|
|
const mockReq = {
|
|
user: { id: userA.toString(), role: 'USER' },
|
|
query: {},
|
|
};
|
|
const mockRes = {
|
|
status: jest.fn().mockReturnThis(),
|
|
json: jest.fn().mockReturnThis(),
|
|
};
|
|
|
|
await getListAgentsHandler(mockReq, mockRes);
|
|
|
|
expect(refreshS3Url).toHaveBeenCalledTimes(1);
|
|
const responseData = mockRes.json.mock.calls[0][0];
|
|
const agent = responseData.data.find((a) => a.id === agentWithS3Avatar.id);
|
|
expect(agent.avatar.filepath).toBe('new-s3-path.jpg');
|
|
});
|
|
});
|
|
|
|
describe('Edge ACL validation', () => {
|
|
let targetAgent;
|
|
|
|
beforeEach(async () => {
|
|
targetAgent = await Agent.create({
|
|
id: `agent_${nanoid()}`,
|
|
author: new mongoose.Types.ObjectId().toString(),
|
|
name: 'Target Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: [],
|
|
});
|
|
});
|
|
test('createAgentHandler should return 403 when user lacks VIEW on an edge-referenced agent', async () => {
|
|
const permMap = new Map();
|
|
getResourcePermissionsMap.mockResolvedValueOnce(permMap);
|
|
|
|
mockReq.body = {
|
|
name: 'Attacker Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
edges: [{ from: '', to: targetAgent.id, edgeType: 'handoff' }],
|
|
};
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(403);
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.agent_ids).toContain(targetAgent.id);
|
|
});
|
|
|
|
test('createAgentHandler should reject a missing graph-subagent member', async () => {
|
|
const missingMemberId = 'agent_missing_graph_member';
|
|
mockReq.config = {
|
|
endpoints: { agents: { capabilities: ['subagents'] } },
|
|
};
|
|
mockReq.body = {
|
|
name: 'Graph Parent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
subagents: {
|
|
enabled: true,
|
|
allowSelf: false,
|
|
graphs: [
|
|
{
|
|
type: 'research_team',
|
|
name: 'Research team',
|
|
description: 'Researches before answering',
|
|
agent_ids: [targetAgent.id, missingMemberId],
|
|
edges: [{ from: targetAgent.id, to: missingMemberId, edgeType: 'direct' }],
|
|
entry_agent_id: targetAgent.id,
|
|
result_agent_id: missingMemberId,
|
|
},
|
|
],
|
|
},
|
|
};
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
expect(mockRes.json).toHaveBeenCalledWith({
|
|
error: 'One or more agents referenced in subagents do not exist',
|
|
agent_ids: [missingMemberId],
|
|
});
|
|
});
|
|
|
|
test('createAgentHandler should rewrite a graph self placeholder to the generated ID', async () => {
|
|
mockReq.config = {
|
|
endpoints: { agents: { capabilities: ['subagents'] } },
|
|
};
|
|
mockReq.body = {
|
|
name: 'Self Graph Parent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
subagents: {
|
|
enabled: true,
|
|
graphs: [
|
|
{
|
|
type: 'self_review',
|
|
name: 'Self review',
|
|
description: 'Runs the new agent in an isolated context',
|
|
agent_ids: [''],
|
|
edges: [],
|
|
entry_agent_id: '',
|
|
result_agent_id: '',
|
|
},
|
|
],
|
|
},
|
|
};
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(201);
|
|
const createdAgent = mockRes.json.mock.calls[0][0];
|
|
expect(createdAgent.subagents.graphs[0]).toMatchObject({
|
|
agent_ids: [createdAgent.id],
|
|
entry_agent_id: createdAgent.id,
|
|
result_agent_id: createdAgent.id,
|
|
});
|
|
});
|
|
|
|
test('createAgentHandler should succeed when user has VIEW on all edge-referenced agents', async () => {
|
|
const permMap = new Map([[targetAgent._id.toString(), 1]]);
|
|
getResourcePermissionsMap.mockResolvedValueOnce(permMap);
|
|
|
|
mockReq.body = {
|
|
name: 'Legit Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
edges: [{ from: '', to: targetAgent.id, edgeType: 'handoff' }],
|
|
};
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(201);
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.edges).toEqual([
|
|
{ from: response.id, to: targetAgent.id, edgeType: 'handoff' },
|
|
]);
|
|
});
|
|
|
|
test('createAgentHandler should reject a non-existent handoff target', async () => {
|
|
mockReq.body = {
|
|
name: 'Dangling Edge Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
edges: [{ from: '', to: 'agent_missing_target', edgeType: 'handoff' }],
|
|
};
|
|
|
|
await createAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
expect(mockRes.json).toHaveBeenCalledWith({
|
|
error: 'One or more agents referenced in edges do not exist',
|
|
agent_ids: ['agent_missing_target'],
|
|
});
|
|
});
|
|
|
|
test('updateAgentHandler should return 403 when user lacks VIEW on an edge-referenced agent', async () => {
|
|
const ownedAgent = await Agent.create({
|
|
id: `agent_${nanoid()}`,
|
|
author: mockReq.user.id,
|
|
name: 'Owned Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: [],
|
|
});
|
|
|
|
const permMap = new Map([[ownedAgent._id.toString(), PermissionBits.VIEW]]);
|
|
getResourcePermissionsMap.mockResolvedValueOnce(permMap);
|
|
|
|
mockReq.params = { id: ownedAgent.id };
|
|
mockReq.body = {
|
|
edges: [{ from: ownedAgent.id, to: targetAgent.id, edgeType: 'handoff' }],
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(403);
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.agent_ids).toContain(targetAgent.id);
|
|
expect(response.agent_ids).not.toContain(ownedAgent.id);
|
|
});
|
|
|
|
test('updateAgentHandler should repair a legacy empty handoff source', async () => {
|
|
const ownedAgent = await Agent.create({
|
|
id: `agent_${nanoid()}`,
|
|
author: mockReq.user.id,
|
|
name: 'Legacy Router',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: [],
|
|
edges: [{ from: '', to: targetAgent.id, edgeType: 'handoff' }],
|
|
});
|
|
getResourcePermissionsMap.mockResolvedValueOnce(
|
|
new Map([
|
|
[ownedAgent._id.toString(), PermissionBits.VIEW],
|
|
[targetAgent._id.toString(), PermissionBits.VIEW],
|
|
]),
|
|
);
|
|
|
|
mockReq.params = { id: ownedAgent.id };
|
|
mockReq.body = {
|
|
edges: [{ from: '', to: targetAgent.id, edgeType: 'handoff' }],
|
|
};
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).not.toHaveBeenCalledWith(400);
|
|
expect(mockRes.json).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
edges: [{ from: ownedAgent.id, to: targetAgent.id, edgeType: 'handoff' }],
|
|
}),
|
|
);
|
|
const persisted = await Agent.findOne({ id: ownedAgent.id }).lean();
|
|
expect(persisted.edges).toEqual([
|
|
{ from: ownedAgent.id, to: targetAgent.id, edgeType: 'handoff' },
|
|
]);
|
|
});
|
|
|
|
test('updateAgentHandler should succeed when edges field is absent from payload', async () => {
|
|
const ownedAgent = await Agent.create({
|
|
id: `agent_${nanoid()}`,
|
|
author: mockReq.user.id,
|
|
name: 'Owned Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: [],
|
|
});
|
|
|
|
mockReq.params = { id: ownedAgent.id };
|
|
mockReq.body = { name: 'Renamed Agent' };
|
|
|
|
await updateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).not.toHaveBeenCalledWith(403);
|
|
const response = mockRes.json.mock.calls[0][0];
|
|
expect(response.name).toBe('Renamed Agent');
|
|
});
|
|
|
|
test('duplicateAgentHandler should move current and legacy handoff sources to the clone', async () => {
|
|
const sourceAgentId = `agent_${nanoid()}`;
|
|
const secondTarget = await Agent.create({
|
|
id: `agent_${nanoid()}`,
|
|
author: new mongoose.Types.ObjectId().toString(),
|
|
name: 'Second Target Agent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: [],
|
|
});
|
|
const sourceAgent = await Agent.create({
|
|
id: sourceAgentId,
|
|
author: mockReq.user.id,
|
|
name: 'Legacy Clone Source',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: [],
|
|
edges: [
|
|
{ from: sourceAgentId, to: targetAgent.id, edgeType: 'handoff' },
|
|
{ from: '', to: secondTarget.id, edgeType: 'handoff' },
|
|
],
|
|
});
|
|
getResourcePermissionsMap.mockResolvedValueOnce(
|
|
new Map([
|
|
[targetAgent._id.toString(), PermissionBits.VIEW],
|
|
[secondTarget._id.toString(), PermissionBits.VIEW],
|
|
]),
|
|
);
|
|
jest.spyOn(require('~/models'), 'getActions').mockResolvedValueOnce([]);
|
|
|
|
mockReq.params = { id: sourceAgent.id };
|
|
|
|
await duplicateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(201);
|
|
const { agent } = mockRes.json.mock.calls[0][0];
|
|
expect(agent.edges).toEqual([
|
|
{ from: agent.id, to: targetAgent.id, edgeType: 'handoff' },
|
|
{ from: agent.id, to: secondTarget.id, edgeType: 'handoff' },
|
|
]);
|
|
});
|
|
|
|
test('duplicateAgentHandler should rewrite and allow a graph-team self member', async () => {
|
|
const sourceAgentId = `agent_${nanoid()}`;
|
|
await Agent.create({
|
|
id: sourceAgentId,
|
|
author: mockReq.user.id,
|
|
name: 'Self Graph Clone Source',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: [],
|
|
subagents: {
|
|
enabled: true,
|
|
allowSelf: false,
|
|
graphs: [
|
|
{
|
|
type: 'self_team',
|
|
name: 'Self team',
|
|
description: 'Contains the parent and a worker',
|
|
agent_ids: [sourceAgentId, targetAgent.id],
|
|
edges: [{ from: sourceAgentId, to: targetAgent.id, edgeType: 'direct' }],
|
|
entry_agent_id: sourceAgentId,
|
|
result_agent_id: targetAgent.id,
|
|
},
|
|
],
|
|
},
|
|
});
|
|
getResourcePermissionsMap.mockResolvedValueOnce(
|
|
new Map([[targetAgent._id.toString(), PermissionBits.VIEW]]),
|
|
);
|
|
jest.spyOn(require('~/models'), 'getActions').mockResolvedValueOnce([]);
|
|
mockReq.config = { endpoints: { agents: { capabilities: ['subagents'] } } };
|
|
mockReq.params = { id: sourceAgentId };
|
|
|
|
await duplicateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(201);
|
|
const { agent } = mockRes.json.mock.calls[0][0];
|
|
expect(agent.subagents.graphs[0]).toMatchObject({
|
|
agent_ids: [agent.id, targetAgent.id],
|
|
edges: [{ from: agent.id, to: targetAgent.id, edgeType: 'direct' }],
|
|
entry_agent_id: agent.id,
|
|
result_agent_id: targetAgent.id,
|
|
});
|
|
});
|
|
|
|
test('duplicateAgentHandler should return 400 for a missing handoff target', async () => {
|
|
const missingTargetId = `agent_${nanoid()}`;
|
|
const sourceAgent = await Agent.create({
|
|
id: `agent_${nanoid()}`,
|
|
author: mockReq.user.id,
|
|
name: 'Stale Clone Source',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: [],
|
|
edges: [{ from: '', to: missingTargetId, edgeType: 'handoff' }],
|
|
});
|
|
|
|
mockReq.params = { id: sourceAgent.id };
|
|
|
|
await duplicateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
expect(mockRes.json).toHaveBeenCalledWith({
|
|
error: 'One or more agents referenced in edges do not exist',
|
|
agent_ids: [missingTargetId],
|
|
});
|
|
expect(await Agent.countDocuments()).toBe(2);
|
|
});
|
|
|
|
test('duplicateAgentHandler should return 403 without VIEW access to a handoff target', async () => {
|
|
const sourceAgentId = `agent_${nanoid()}`;
|
|
const sourceAgent = await Agent.create({
|
|
id: sourceAgentId,
|
|
author: mockReq.user.id,
|
|
name: 'Restricted Clone Source',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: [],
|
|
edges: [{ from: sourceAgentId, to: targetAgent.id, edgeType: 'handoff' }],
|
|
});
|
|
getResourcePermissionsMap.mockResolvedValueOnce(new Map());
|
|
|
|
mockReq.params = { id: sourceAgent.id };
|
|
|
|
await duplicateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(403);
|
|
expect(mockRes.json).toHaveBeenCalledWith({
|
|
error: 'You do not have access to one or more agents referenced in edges',
|
|
agent_ids: [targetAgent.id],
|
|
});
|
|
expect(await Agent.countDocuments()).toBe(2);
|
|
});
|
|
|
|
test('duplicateAgentHandler should return 403 without VIEW access to a graph-subagent member', async () => {
|
|
const sourceAgent = await Agent.create({
|
|
id: `agent_${nanoid()}`,
|
|
author: mockReq.user.id,
|
|
name: 'Restricted Graph Clone Source',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: [],
|
|
subagents: {
|
|
enabled: true,
|
|
allowSelf: false,
|
|
graphs: [
|
|
{
|
|
type: 'restricted_team',
|
|
name: 'Restricted team',
|
|
description: 'Contains a restricted member',
|
|
agent_ids: [targetAgent.id],
|
|
edges: [],
|
|
entry_agent_id: targetAgent.id,
|
|
result_agent_id: targetAgent.id,
|
|
},
|
|
],
|
|
},
|
|
});
|
|
getResourcePermissionsMap.mockResolvedValueOnce(new Map());
|
|
mockReq.config = { endpoints: { agents: { capabilities: ['subagents'] } } };
|
|
mockReq.params = { id: sourceAgent.id };
|
|
|
|
await duplicateAgentHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(403);
|
|
expect(mockRes.json).toHaveBeenCalledWith({
|
|
error: 'You do not have access to one or more agents referenced in subagents',
|
|
agent_ids: [targetAgent.id],
|
|
});
|
|
expect(await Agent.countDocuments()).toBe(2);
|
|
});
|
|
|
|
test('revertAgentVersionHandler should clear handoffs when the historical version has none', async () => {
|
|
const agentId = `agent_${nanoid()}`;
|
|
await Agent.create({
|
|
id: agentId,
|
|
author: mockReq.user.id,
|
|
name: 'Current Router',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: [],
|
|
edges: [{ from: agentId, to: targetAgent.id, edgeType: 'handoff' }],
|
|
versions: [
|
|
{
|
|
name: 'Historical Router',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: [],
|
|
},
|
|
],
|
|
});
|
|
|
|
mockReq.params = { id: agentId };
|
|
mockReq.body = { version_index: 0 };
|
|
|
|
await revertAgentVersionHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).not.toHaveBeenCalledWith(400);
|
|
const persisted = await Agent.findOne({ id: agentId }).lean();
|
|
expect(persisted.name).toBe('Historical Router');
|
|
expect(persisted.edges).toEqual([]);
|
|
});
|
|
|
|
test('revertAgentVersionHandler should restore accessible historical handoffs', async () => {
|
|
const agentId = `agent_${nanoid()}`;
|
|
const sourceAgent = await Agent.create({
|
|
id: agentId,
|
|
author: mockReq.user.id,
|
|
name: 'Current Router',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: [],
|
|
edges: [],
|
|
versions: [
|
|
{
|
|
name: 'Historical Router',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: [],
|
|
edges: [{ from: '', to: targetAgent.id, edgeType: 'handoff' }],
|
|
},
|
|
],
|
|
});
|
|
getResourcePermissionsMap.mockResolvedValueOnce(
|
|
new Map([
|
|
[sourceAgent._id.toString(), PermissionBits.VIEW],
|
|
[targetAgent._id.toString(), PermissionBits.VIEW],
|
|
]),
|
|
);
|
|
|
|
mockReq.params = { id: agentId };
|
|
mockReq.body = { version_index: 0 };
|
|
|
|
await revertAgentVersionHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).not.toHaveBeenCalledWith(400);
|
|
expect(mockRes.status).not.toHaveBeenCalledWith(403);
|
|
const persisted = await Agent.findOne({ id: agentId }).lean();
|
|
expect(persisted.name).toBe('Historical Router');
|
|
expect(persisted.edges).toEqual([{ from: agentId, to: targetAgent.id, edgeType: 'handoff' }]);
|
|
});
|
|
|
|
test('revertAgentVersionHandler should return 400 before restoring a missing handoff target', async () => {
|
|
const agentId = `agent_${nanoid()}`;
|
|
const missingTargetId = `agent_${nanoid()}`;
|
|
await Agent.create({
|
|
id: agentId,
|
|
author: mockReq.user.id,
|
|
name: 'Current Router',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: [],
|
|
versions: [
|
|
{
|
|
name: 'Stale Historical Router',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: [],
|
|
edges: [{ from: agentId, to: missingTargetId, edgeType: 'handoff' }],
|
|
},
|
|
],
|
|
});
|
|
|
|
mockReq.params = { id: agentId };
|
|
mockReq.body = { version_index: 0 };
|
|
|
|
await revertAgentVersionHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
expect(mockRes.json).toHaveBeenCalledWith({
|
|
error: 'One or more agents referenced in edges do not exist',
|
|
agent_ids: [missingTargetId],
|
|
});
|
|
const persisted = await Agent.findOne({ id: agentId }).lean();
|
|
expect(persisted.name).toBe('Current Router');
|
|
});
|
|
|
|
test('revertAgentVersionHandler should return 400 before restoring a missing graph-subagent member', async () => {
|
|
const agentId = `agent_${nanoid()}`;
|
|
const missingMemberId = `agent_${nanoid()}`;
|
|
await Agent.create({
|
|
id: agentId,
|
|
author: mockReq.user.id,
|
|
name: 'Current Graph Parent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: [],
|
|
versions: [
|
|
{
|
|
name: 'Historical Graph Parent',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: [],
|
|
subagents: {
|
|
enabled: true,
|
|
allowSelf: false,
|
|
graphs: [
|
|
{
|
|
type: 'missing_team',
|
|
name: 'Missing team',
|
|
description: 'Contains a deleted member',
|
|
agent_ids: [missingMemberId],
|
|
edges: [],
|
|
entry_agent_id: missingMemberId,
|
|
result_agent_id: missingMemberId,
|
|
},
|
|
],
|
|
},
|
|
},
|
|
],
|
|
});
|
|
mockReq.config = { endpoints: { agents: { capabilities: ['subagents'] } } };
|
|
mockReq.params = { id: agentId };
|
|
mockReq.body = { version_index: 0 };
|
|
|
|
await revertAgentVersionHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(400);
|
|
expect(mockRes.json).toHaveBeenCalledWith({
|
|
error: 'One or more agents referenced in subagents do not exist',
|
|
agent_ids: [missingMemberId],
|
|
});
|
|
const persisted = await Agent.findOne({ id: agentId }).lean();
|
|
expect(persisted.name).toBe('Current Graph Parent');
|
|
});
|
|
|
|
test('revertAgentVersionHandler should return 403 before restoring a restricted handoff target', async () => {
|
|
const agentId = `agent_${nanoid()}`;
|
|
const sourceAgent = await Agent.create({
|
|
id: agentId,
|
|
author: mockReq.user.id,
|
|
name: 'Current Router',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: [],
|
|
versions: [
|
|
{
|
|
name: 'Restricted Historical Router',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: [],
|
|
edges: [{ from: agentId, to: targetAgent.id, edgeType: 'handoff' }],
|
|
},
|
|
],
|
|
});
|
|
getResourcePermissionsMap.mockResolvedValueOnce(
|
|
new Map([[sourceAgent._id.toString(), PermissionBits.VIEW]]),
|
|
);
|
|
|
|
mockReq.params = { id: agentId };
|
|
mockReq.body = { version_index: 0 };
|
|
|
|
await revertAgentVersionHandler(mockReq, mockRes);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(403);
|
|
expect(mockRes.json).toHaveBeenCalledWith({
|
|
error: 'You do not have access to one or more agents referenced in edges',
|
|
agent_ids: [targetAgent.id],
|
|
});
|
|
const persisted = await Agent.findOne({ id: agentId }).lean();
|
|
expect(persisted.name).toBe('Current Router');
|
|
});
|
|
});
|
|
});
|