mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-02 20:17:17 +00:00
* ♻️ refactor: Take Typed Criteria, Not Mongo Filters, for Actions and Assistants `createActionMethods` and `createAssistantMethods` accepted `FilterQuery<T>`, putting Mongoose's query language in the package's public surface: every caller wrote raw Mongo, and no engine other than Mongo could satisfy the signatures. Both now take domain criteria — `ActionQuery` and `AssistantQuery` — naming concepts rather than stored fields, with an array meaning "any of these". A per-domain field map translates them, so `FilterQuery` survives only inside the two translators. `buildFilter` throws on a criterion the field map does not cover. Callers in `api/` are JavaScript and get no compile-time checking, and the server sets `strictQuery`, under which a silently dropped criterion widens the filter instead of narrowing it — an unscoped `findOne` returns an arbitrary document rather than none. Failing closed is the only safe default. `AssistantQuery.avatarFilepath` covers the avatar-authorization lookup, which queries a nested path no plain field name reaches. No behaviour change: every migrated call site produces the same filter as before. * 🧪 test: Update Avatar Authorization Assertion to Typed Criteria `validateImages.spec.js` asserted the old `{ 'avatar.filepath': { $in: [...] } }` call shape for `getAssistant`. The earlier sweep matched on `action_id`, `agent_id` and `assistant_id`, none of which appear in a dotted avatar path, so this one assertion was missed. The `getAgent` assertions in the same file keep the filter shape — that method still takes a `FilterQuery`. * 🔒 fix: Reject Unknown Criteria Before Omitting Undefined Ones `buildFilter` skipped a criterion whose value was `undefined` before checking it against the field map, so a JavaScript caller misspelling a key that happened to carry `undefined` — `deleteActions({ agent_id: maybeId })` — produced `{}` and reached `deleteMany` unscoped. That is the exact failure the guard exists to prevent, defeated by the order of the two checks. Validate every key first, then apply the undefined-omission rule. The lookup is an own-property check so inherited names cannot resolve through the field map's prototype: `{ toString: 'x' }` previously found `Function.prototype.toString`, passed the truthiness test, and wrote a garbage filter key instead of throwing. A recognized criterion left `undefined` is still omitted, so optional parameters keep working. * 🔒 fix: Reject Query Fragments as Criteria and Keep the Translator Internal Three review findings on the criteria translator, all of the same shape: the guard was narrower than the surface it protects. Criterion values are now validated as scalars or lists of scalars. `matchAny` copied any non-array through unchanged, so a JavaScript caller could pass `{ agentId: { $ne: null } }` and have the operator land verbatim in the filter — the fail-open case the field map exists to close. `null` is rejected too; it would have matched documents missing the field entirely. `matchAny`, `buildFilter` and `FieldMap` are no longer re-exported from the package barrel. They emit Mongo, and shipping them as public API undercut the point of the change; they were reachable as `require('@librechat/data-schemas') .buildFilter`. `OneOrMany` moves to `types/query` because the domain query types reference it and it names no engine — which also drops the `types` -> `utils` import. `loadActionSets` names `ActionQuery` through `import()` so the JSDoc type actually resolves.
234 lines
6.3 KiB
JavaScript
234 lines
6.3 KiB
JavaScript
const { duplicateAgent } = require('../v1');
|
|
const { getAgent, createAgent, getActions } = require('~/models');
|
|
const { nanoid } = require('nanoid');
|
|
|
|
jest.mock('~/models');
|
|
jest.mock('nanoid');
|
|
|
|
describe('duplicateAgent', () => {
|
|
let req, res;
|
|
|
|
beforeEach(() => {
|
|
req = {
|
|
params: { id: 'agent_123' },
|
|
user: { id: 'user_456' },
|
|
};
|
|
res = {
|
|
status: jest.fn().mockReturnThis(),
|
|
json: jest.fn(),
|
|
};
|
|
jest.clearAllMocks();
|
|
});
|
|
|
|
it('should duplicate an agent successfully', async () => {
|
|
const mockAgent = {
|
|
id: 'agent_123',
|
|
name: 'Test Agent',
|
|
description: 'Test Description',
|
|
instructions: 'Test Instructions',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: ['file_search'],
|
|
actions: [],
|
|
author: 'user_789',
|
|
versions: [{ name: 'Test Agent', version: 1 }],
|
|
__v: 0,
|
|
};
|
|
|
|
const mockNewAgent = {
|
|
id: 'agent_new_123',
|
|
name: 'Test Agent (1/2/23, 12:34)',
|
|
description: 'Test Description',
|
|
instructions: 'Test Instructions',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: ['file_search'],
|
|
actions: [],
|
|
author: 'user_456',
|
|
versions: [
|
|
{
|
|
name: 'Test Agent (1/2/23, 12:34)',
|
|
description: 'Test Description',
|
|
instructions: 'Test Instructions',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: ['file_search'],
|
|
actions: [],
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
},
|
|
],
|
|
};
|
|
|
|
getAgent.mockResolvedValue(mockAgent);
|
|
getActions.mockResolvedValue([]);
|
|
nanoid.mockReturnValue('new_123');
|
|
createAgent.mockResolvedValue(mockNewAgent);
|
|
|
|
await duplicateAgent(req, res);
|
|
|
|
expect(getAgent).toHaveBeenCalledWith({ id: 'agent_123' });
|
|
expect(getActions).toHaveBeenCalledWith({ agentId: 'agent_123' }, true);
|
|
expect(createAgent).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
id: 'agent_new_123',
|
|
author: 'user_456',
|
|
name: expect.stringContaining('Test Agent ('),
|
|
description: 'Test Description',
|
|
instructions: 'Test Instructions',
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
tools: ['file_search'],
|
|
actions: [],
|
|
}),
|
|
);
|
|
|
|
expect(createAgent).toHaveBeenCalledWith(
|
|
expect.not.objectContaining({
|
|
versions: expect.anything(),
|
|
__v: expect.anything(),
|
|
}),
|
|
);
|
|
|
|
expect(res.status).toHaveBeenCalledWith(201);
|
|
expect(res.json).toHaveBeenCalledWith({
|
|
agent: mockNewAgent,
|
|
actions: [],
|
|
});
|
|
});
|
|
|
|
it('should ensure duplicated agent has clean versions array without nested fields', async () => {
|
|
const mockAgent = {
|
|
id: 'agent_123',
|
|
name: 'Test Agent',
|
|
description: 'Test Description',
|
|
versions: [
|
|
{
|
|
name: 'Test Agent',
|
|
versions: [{ name: 'Nested' }],
|
|
__v: 1,
|
|
},
|
|
],
|
|
__v: 2,
|
|
};
|
|
|
|
const mockNewAgent = {
|
|
id: 'agent_new_123',
|
|
name: 'Test Agent (1/2/23, 12:34)',
|
|
description: 'Test Description',
|
|
versions: [
|
|
{
|
|
name: 'Test Agent (1/2/23, 12:34)',
|
|
description: 'Test Description',
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
},
|
|
],
|
|
};
|
|
|
|
getAgent.mockResolvedValue(mockAgent);
|
|
getActions.mockResolvedValue([]);
|
|
nanoid.mockReturnValue('new_123');
|
|
createAgent.mockResolvedValue(mockNewAgent);
|
|
|
|
await duplicateAgent(req, res);
|
|
|
|
expect(mockNewAgent.versions).toHaveLength(1);
|
|
|
|
const firstVersion = mockNewAgent.versions[0];
|
|
expect(firstVersion).not.toHaveProperty('versions');
|
|
expect(firstVersion).not.toHaveProperty('__v');
|
|
|
|
expect(mockNewAgent).not.toHaveProperty('__v');
|
|
|
|
expect(res.status).toHaveBeenCalledWith(201);
|
|
});
|
|
|
|
it('rewrites graph-team self references to the duplicated agent id', async () => {
|
|
getAgent.mockResolvedValue({
|
|
id: 'agent_123',
|
|
name: 'Graph parent',
|
|
subagents: {
|
|
enabled: true,
|
|
graphs: [
|
|
{
|
|
type: 'team',
|
|
name: 'Team',
|
|
description: 'A self-contained team',
|
|
agent_ids: ['agent_123', 'agent_member'],
|
|
edges: [{ from: ['agent_member'], to: 'agent_123', edgeType: 'direct' }],
|
|
entry_agent_id: 'agent_member',
|
|
result_agent_id: 'agent_123',
|
|
},
|
|
],
|
|
},
|
|
});
|
|
getActions.mockResolvedValue([]);
|
|
nanoid.mockReturnValue('new_123');
|
|
createAgent.mockResolvedValue({ id: 'agent_new_123' });
|
|
|
|
await duplicateAgent(req, res);
|
|
|
|
expect(createAgent).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
subagents: expect.objectContaining({
|
|
graphs: [
|
|
expect.objectContaining({
|
|
agent_ids: ['agent_new_123', 'agent_member'],
|
|
edges: [expect.objectContaining({ from: ['agent_member'], to: 'agent_new_123' })],
|
|
entry_agent_id: 'agent_member',
|
|
result_agent_id: 'agent_new_123',
|
|
}),
|
|
],
|
|
}),
|
|
}),
|
|
);
|
|
});
|
|
|
|
it('should return 404 if agent not found', async () => {
|
|
getAgent.mockResolvedValue(null);
|
|
|
|
await duplicateAgent(req, res);
|
|
|
|
expect(res.status).toHaveBeenCalledWith(404);
|
|
expect(res.json).toHaveBeenCalledWith({
|
|
error: 'Agent not found',
|
|
status: 'error',
|
|
});
|
|
});
|
|
|
|
it('should convert `tool_resources.ocr` to `tool_resources.context`', async () => {
|
|
const mockAgent = {
|
|
id: 'agent_123',
|
|
name: 'Test Agent',
|
|
tool_resources: {
|
|
ocr: { enabled: true, config: 'test' },
|
|
other: { should: 'not be copied' },
|
|
},
|
|
};
|
|
|
|
getAgent.mockResolvedValue(mockAgent);
|
|
getActions.mockResolvedValue([]);
|
|
nanoid.mockReturnValue('new_123');
|
|
createAgent.mockResolvedValue({ id: 'agent_new_123' });
|
|
|
|
await duplicateAgent(req, res);
|
|
|
|
expect(createAgent).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
tool_resources: {
|
|
context: { enabled: true, config: 'test' },
|
|
},
|
|
}),
|
|
);
|
|
});
|
|
|
|
it('should handle errors gracefully', async () => {
|
|
getAgent.mockRejectedValue(new Error('Database error'));
|
|
|
|
await duplicateAgent(req, res);
|
|
|
|
expect(res.status).toHaveBeenCalledWith(500);
|
|
expect(res.json).toHaveBeenCalledWith({ error: 'Database error' });
|
|
});
|
|
});
|