mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-18 14:08:21 +00:00
* 🫀 feat: Let a Job Owner Keep a Silent Run Alive A generation job's idle clock advances only with emitted chunks, so a run that works without output for 20 minutes is reaped while it is still alive. touchJob refreshes the idle clock and the storage lifetimes an append would have extended, fenced on the generation epoch and limited to the replica that owns the runtime. * 🧶 refactor: Share One Fold From Child Frames to Content Parts readSubagentContent folded public child frames into content parts inline. The fold is now a synchronous function a second caller can use, so a frame can be folded and published without yielding in between. * 🏷️ feat: Mark the Generation Job of a Background Subagent Task Job metadata gains subagentTaskId and subagentParentConversationId, set only by the subagent task store. A marked job is a child-thread job, so it stays out of the active chat list, and isBackgroundChildJob tells it apart from an event-bound child, whose job the chat controller owns. * 🧵 feat: Run a Background Child as a Resumable Generation Job createChildGenerationHost opens a generation job keyed by the child thread id and feeds it the child's public step frames. Text deltas that queue behind a slow write merge instead of dropping, the terminal state is claimed before the caller persists and the final event is published only afterwards, and no stream failure can fail the child: the run and its result carry on without a live view. * 🪢 feat: Stream a Background Child Through Its Own Generation Job The subagent task store takes a childGenerations dependency. Once a child's thread and input row are durable it opens a job keyed by the thread id, feeds it each public frame, refreshes its idle clock on every lease renewal, and settles it around its own persistence, so a reader sees the final event only after the result row exists. A cancel, a failure and a job aborted from outside all end both the child and its stream. endpoints.agents.subagentActivity.generationJobs turns it off. A stream that cannot be opened or written never fails the child. * 🔌 feat: Give the Server's Task Store Its Child Stream The host wiring builds the child generation host from the generation job manager and hands it to the subagent task store, so a background child's stream is reachable in the running server. * 🚧 fix: Refuse Chat Abort and Steer on a Background Child's Job The chat abort route saves a user row and a partial response and upserts the conversation, and the steer route queues text only the chat controller drains. Both authorized on the job's owner alone, so either could act on a background child's job and write a chat-shaped history into a view-only thread, or accept a steer nothing would ever apply. Both now answer 409 for a job the subagent task store owns; the child is stopped and steered through its control endpoint. * 🧹 fix: Evict a Finished Job Before a Live One at Capacity The in-memory job store made room by deleting its oldest job whatever its status, so a full store could end a run somebody was still waiting on. It now takes the oldest finished job first. Also covers a job manager that shuts down while a background child runs: the child still persists its cancellation. * 🛰️ test: Read a Background Child's Stream From Another Replica Against real Redis: a second replica resumes with everything the child has streamed, receives only newer deltas live, then the final event; a child that streams past the manager's 5,000-event early buffer before anyone attaches still resumes whole on both replicas; and the owner's touch keeps a silent child's job alive. * 🧽 chore: Sort Imports in the Child Stream Files * 🧪 test: Expect the Child Stream Lever in the Activity Defaults * 📜 feat: Store What a Background Child Streamed as Standard Content (#18173) A child's result row carried its text and a bounded activity projection, not the content parts every agent message stores, so a reader had to rebuild the child's output from the projection. The row now also carries what the child streamed, on completion, failure and cancellation, in the standard shape. endpoints.agents.subagentActivity.generationContentBytes bounds it (4 MiB by default, 0 stores none). Content over the bound is left off, so the row always fits and keeps its text and projection as before. * 🛟 fix: Keep a Stalled or Failing Child Stream From Touching Its Child Four ways the stream could still reach the run it only observes. A frame that could not be copied threw into the child's own progress report. A job store that never answered held the child's start behind job creation and its result behind the terminal claim. And a stream that had stopped being written was never ended, so its job read as a live child for twenty minutes after the child finished. Frames are now copied defensively, opening and settling are bounded, a job that arrives after its child stopped waiting is ended, and a detached stream is still touched and still settled with its full final event. * 🧯 fix: Let a Child Stream Observe Its Run Without Ever Stopping It Review round 1. A failed Redis append retires the job's runtime by aborting its controller, and the child stream forwarded every abort of that controller to the task store as a cancellation. A stream-store outage therefore stopped the child's model and tool work. The stream no longer signals the child at all: deletion, shutdown and the control endpoint already stop a child through the task store, and an aborted, reaped or retired job now only ends the live view. The in-memory store's capacity eviction preferred any terminal job, including one that still owed persistence, a host action, a schedule reconciliation or a provider drain. Those are no longer treated as finished. The chat abort route's refusal for a background child's job moves out of the CJS route into createBackgroundChildAbortGuard, registered ahead of it. * ♻️ fix: Replace a Dead Background Child's Job on Its Thread A background child's job outlives an owner that crashed, or a settlement that could not reach the store, for up to twenty minutes. A continuation of the thread in that window was refused its own stream, because the dead job still read as live. The caller of open holds the thread's lease, so a background child's job still marked live there has lost its owner: it is replaced and its readers are told to refetch. A live job that is not a background child's, such as an event-bound child paused for approval, is still never replaced. * 🧱 fix: Fail the Abort Guard Closed and Budget Content Against the Whole Row Review round 2. The abort guard passed the request on when its job lookup failed, so a retried lookup in the route could run the chat-shaped abort on a child the guard never saw. A failed lookup now ends the request at the error boundary. A child's streamed content was checked against its own limit only. A result row also carries the text and the transcript, so content that passed the limit could push the document past MongoDB's 16 MiB and turn a successful child into a failed one. The content is now the optional field: it is left off whenever the row's large fields together would exceed the budget. Also accounts for the guard's job read in the two abort route specs that sequence it, and gives the limiter spec's api mock the guard. * 🪶 refactor: Settle a Child Stream Once and Fold a Frame It Cannot Copy The task store settles a child's stream on its outcome path and again in its cleanup. The second call made another terminal claim that could only lose; the stream now remembers that it claimed and only persists. A frame that cannot be copied is still folded from the original, so the stored content stays whole when the stream detaches over it. * 🧪 test: Cover the Child Stream's Failure Branches and the Content Fold The change-risk report showed the stream's fail-open branches untested: a terminal claim that lands after its wait, a claim or a final publish that throws, the settle timeout, the backlog limit, and a rejected touch. Each now has a case. The shared content fold gets direct cases for a closed step, a commentary phase and an applied steer.
1411 lines
52 KiB
JavaScript
1411 lines
52 KiB
JavaScript
/**
|
|
* Tests for the agent abort endpoint
|
|
*
|
|
* Tests the following fixes from PR #11462:
|
|
* 1. Authorization check - only job owner can abort
|
|
* 2. Early abort handling - skip save when no responseMessageId
|
|
* 3. Partial response saving - save message before returning
|
|
*/
|
|
|
|
const express = require('express');
|
|
const request = require('supertest');
|
|
|
|
const mockLogger = {
|
|
debug: jest.fn(),
|
|
warn: jest.fn(),
|
|
error: jest.fn(),
|
|
info: jest.fn(),
|
|
};
|
|
|
|
const mockGenerationJobManager = {
|
|
getJob: jest.fn(),
|
|
abortJob: jest.fn(),
|
|
getActiveJobIdsForUser: jest.fn(),
|
|
};
|
|
|
|
const mockSaveMessage = jest.fn();
|
|
const mockHasPersistedPrivateText = jest.fn();
|
|
const mockGetPrivateMessageTexts = jest.fn();
|
|
const mockSaveConvo = jest.fn();
|
|
const mockGetMessages = jest.fn(async () => [{ _id: 'existing-anchor' }]);
|
|
|
|
const mockRecordScheduleOutcome = jest.fn();
|
|
const mockBeginScheduledStop = jest.fn();
|
|
const mockAcknowledgeScheduledStopPersistence = jest.fn();
|
|
|
|
jest.mock('@librechat/data-schemas', () => ({
|
|
...jest.requireActual('@librechat/data-schemas'),
|
|
logger: mockLogger,
|
|
}));
|
|
|
|
jest.mock('@librechat/api', () => ({
|
|
...jest.requireActual('@librechat/api'),
|
|
isEnabled: jest.fn().mockReturnValue(false),
|
|
isAgentTriggerRequest: jest.fn(() => false),
|
|
captureScheduleFireContext: jest.fn((req) => {
|
|
req._isScheduledFire = false;
|
|
req._isManualScheduledFire = false;
|
|
}),
|
|
GenerationJobManager: mockGenerationJobManager,
|
|
}));
|
|
|
|
jest.mock('~/models', () => ({
|
|
initializeMessageBudget: jest.fn(),
|
|
initializeChannelStorageConfig: jest.fn(),
|
|
saveMessage: (...args) => mockSaveMessage(...args),
|
|
getPersistedPrivateTextId: async (...args) =>
|
|
(await mockHasPersistedPrivateText(...args)) ? 'protected-row-id' : null,
|
|
getPrivateMessageTexts: (...args) => mockGetPrivateMessageTexts(...args),
|
|
saveConvo: (...args) => mockSaveConvo(...args),
|
|
getMessages: (...args) => mockGetMessages(...args),
|
|
}));
|
|
|
|
jest.mock('~/server/services/Schedules', () => ({
|
|
recordScheduleOutcome: (...args) => mockRecordScheduleOutcome(...args),
|
|
beginScheduledStop: (...args) => mockBeginScheduledStop(...args),
|
|
acknowledgeScheduledStopPersistence: (...args) =>
|
|
mockAcknowledgeScheduledStopPersistence(...args),
|
|
}));
|
|
|
|
jest.mock('~/server/middleware', () => ({
|
|
uaParser: (req, res, next) => next(),
|
|
checkBan: (req, res, next) => next(),
|
|
requireJwtAuth: (req, res, next) => {
|
|
req.user = { id: 'test-user-123' };
|
|
next();
|
|
},
|
|
moderateText: (req, res, next) => next(),
|
|
agentEventUserLimiter: (req, res, next) => next(),
|
|
messageIpLimiter: (req, res, next) => next(),
|
|
configMiddleware: (req, res, next) => next(),
|
|
messageUserLimiter: (req, res, next) => next(),
|
|
requireTermsAcceptance: (req, res, next) => next(),
|
|
}));
|
|
|
|
// Mock the chat module - needs to be a router
|
|
jest.mock('~/server/routes/agents/chat', () => require('express').Router());
|
|
|
|
// Mock the v1 module - v1 is directly used as middleware
|
|
jest.mock('~/server/routes/agents/v1', () => ({
|
|
v1: require('express').Router(),
|
|
}));
|
|
jest.mock('~/server/routes/agents/management', () => require('express').Router());
|
|
|
|
// Import after mocks
|
|
const agentRoutes = require('~/server/routes/agents/index');
|
|
const { isUnpersistedPreliminaryParent } = require('@librechat/api');
|
|
|
|
describe('Agent Abort Endpoint', () => {
|
|
let app;
|
|
|
|
beforeAll(() => {
|
|
app = express();
|
|
app.use(express.json());
|
|
app.use((req, _res, next) => {
|
|
req.config = { endpoints: { agents: { checkpointer: { type: 'memory' } } } };
|
|
next();
|
|
});
|
|
app.use('/api/agents', agentRoutes);
|
|
});
|
|
|
|
beforeEach(() => {
|
|
jest.clearAllMocks();
|
|
mockGenerationJobManager.getJob.mockReset();
|
|
mockGenerationJobManager.abortJob.mockReset();
|
|
mockGenerationJobManager.getActiveJobIdsForUser.mockReset();
|
|
mockSaveMessage.mockReset();
|
|
mockSaveMessage.mockImplementation(async (_context, message) => message);
|
|
mockHasPersistedPrivateText.mockReset();
|
|
mockHasPersistedPrivateText.mockResolvedValue(true);
|
|
mockGetPrivateMessageTexts.mockReset();
|
|
mockGetPrivateMessageTexts.mockResolvedValue([]);
|
|
mockSaveConvo.mockReset();
|
|
mockSaveConvo.mockResolvedValue({});
|
|
mockRecordScheduleOutcome.mockReset();
|
|
mockRecordScheduleOutcome.mockResolvedValue(true);
|
|
mockBeginScheduledStop.mockReset();
|
|
mockBeginScheduledStop.mockResolvedValue(true);
|
|
mockAcknowledgeScheduledStopPersistence.mockReset();
|
|
mockAcknowledgeScheduledStopPersistence.mockResolvedValue(undefined);
|
|
});
|
|
|
|
describe('POST /chat/abort', () => {
|
|
describe('Authorization', () => {
|
|
it("should return 403 when user tries to abort another user's job", async () => {
|
|
const jobStreamId = 'test-stream-123';
|
|
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
metadata: { userId: 'other-user-456' },
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.send({ conversationId: jobStreamId });
|
|
|
|
expect(response.status).toBe(403);
|
|
expect(response.body).toEqual({ error: 'Unauthorized', generationProtocolVersion: 1 });
|
|
expect(mockLogger.warn).toHaveBeenCalledWith(
|
|
expect.stringContaining('Unauthorized abort attempt'),
|
|
);
|
|
expect(mockGenerationJobManager.abortJob).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('should allow abort when user owns the job', async () => {
|
|
const jobStreamId = 'test-stream-123';
|
|
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
metadata: { userId: 'test-user-123' },
|
|
});
|
|
|
|
mockGenerationJobManager.abortJob.mockResolvedValue({
|
|
success: true,
|
|
jobData: null,
|
|
content: [],
|
|
text: '',
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.send({ conversationId: jobStreamId });
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(response.body).toEqual({
|
|
success: true,
|
|
aborted: jobStreamId,
|
|
generationProtocolVersion: 1,
|
|
});
|
|
expect(response.headers['x-librechat-generation-protocol']).toBe('1');
|
|
expect(mockGenerationJobManager.abortJob).toHaveBeenCalledWith(
|
|
jobStreamId,
|
|
expect.objectContaining({ transformAbortContent: expect.any(Function) }),
|
|
);
|
|
});
|
|
|
|
it('should refuse to abort a background child job, which its task store owns', async () => {
|
|
const jobStreamId = 'child-thread-123';
|
|
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
metadata: {
|
|
userId: 'test-user-123',
|
|
subagentTaskId: 'task-1',
|
|
subagentParentConversationId: 'parent-1',
|
|
},
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.send({ conversationId: jobStreamId });
|
|
|
|
expect(response.status).toBe(409);
|
|
expect(response.body).toMatchObject({ code: 'CHILD_THREAD_READ_ONLY' });
|
|
expect(mockGenerationJobManager.abortJob).not.toHaveBeenCalled();
|
|
expect(mockSaveMessage).not.toHaveBeenCalled();
|
|
expect(mockSaveConvo).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("should answer 403, not 409, for another user's background child job", async () => {
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
metadata: { userId: 'other-user-456', subagentTaskId: 'task-1' },
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.send({ conversationId: 'child-thread-123' });
|
|
|
|
expect(response.status).toBe(403);
|
|
expect(mockGenerationJobManager.abortJob).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('should fail closed when job has no userId metadata', async () => {
|
|
const jobStreamId = 'test-stream-123';
|
|
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
metadata: {},
|
|
});
|
|
|
|
mockGenerationJobManager.abortJob.mockResolvedValue({
|
|
success: true,
|
|
jobData: null,
|
|
content: [],
|
|
text: '',
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.send({ conversationId: jobStreamId });
|
|
|
|
expect(response.status).toBe(403);
|
|
expect(response.body).toEqual({ error: 'Unauthorized', generationProtocolVersion: 1 });
|
|
expect(mockGenerationJobManager.abortJob).not.toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
describe('Early Abort Handling', () => {
|
|
it('should skip message saving when responseMessageId is missing (early abort)', async () => {
|
|
const jobStreamId = 'test-stream-123';
|
|
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
metadata: { userId: 'test-user-123', generationProtocolVersion: 2 },
|
|
});
|
|
|
|
mockGenerationJobManager.abortJob.mockResolvedValue({
|
|
success: true,
|
|
jobData: {
|
|
userMessage: { messageId: 'user-msg-123' },
|
|
// No responseMessageId - early abort before generation started
|
|
conversationId: jobStreamId,
|
|
},
|
|
content: [],
|
|
text: '',
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.set('X-LibreChat-Generation-Protocol', '2')
|
|
.send({ conversationId: jobStreamId, generationProtocolVersion: 2 });
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(mockSaveMessage).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('should skip message saving when userMessage is missing', async () => {
|
|
const jobStreamId = 'test-stream-123';
|
|
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
metadata: { userId: 'test-user-123' },
|
|
});
|
|
|
|
mockGenerationJobManager.abortJob.mockResolvedValue({
|
|
success: true,
|
|
jobData: {
|
|
// No userMessage
|
|
responseMessageId: 'response-msg-123',
|
|
conversationId: jobStreamId,
|
|
},
|
|
content: [],
|
|
text: '',
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.send({ conversationId: jobStreamId });
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(mockSaveMessage).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('should skip message saving when abort content is only an OAuth prompt', async () => {
|
|
const jobStreamId = 'test-stream-123';
|
|
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
metadata: { userId: 'test-user-123' },
|
|
});
|
|
|
|
mockGenerationJobManager.abortJob.mockResolvedValue({
|
|
success: true,
|
|
jobData: {
|
|
userMessage: { messageId: 'user-msg-123' },
|
|
responseMessageId: 'response-msg-456',
|
|
conversationId: jobStreamId,
|
|
},
|
|
content: [
|
|
{
|
|
type: 'tool_call',
|
|
tool_call: {
|
|
type: 'tool_call',
|
|
id: 'oauth-call-1',
|
|
name: 'oauth_mcp_Google-Workspace',
|
|
args: '',
|
|
auth: 'https://auth.example.com/oauth',
|
|
},
|
|
},
|
|
],
|
|
text: '',
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.send({ conversationId: jobStreamId });
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(mockSaveMessage).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('persists a created empty turn before FINAL so interrupt-and-send clears the parent fence', async () => {
|
|
const jobStreamId = 'test-stream-123';
|
|
const userMessageId = 'user-msg-123';
|
|
const preliminaryResponseId = `${userMessageId}_`;
|
|
const persistedMessages = new Map();
|
|
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
metadata: { userId: 'test-user-123', generationProtocolVersion: 2 },
|
|
});
|
|
|
|
const abortResult = {
|
|
success: true,
|
|
jobData: {
|
|
createdEventEmitted: true,
|
|
userMessage: {
|
|
messageId: userMessageId,
|
|
parentMessageId: 'older-response',
|
|
conversationId: jobStreamId,
|
|
text: 'Stop before the first model token.',
|
|
},
|
|
responseMessageId: preliminaryResponseId,
|
|
conversationId: jobStreamId,
|
|
endpoint: 'agents',
|
|
sender: 'TestAgent',
|
|
model: 'agent-1',
|
|
},
|
|
content: [],
|
|
text: '',
|
|
};
|
|
mockGenerationJobManager.abortJob.mockImplementation(async (_streamId, options) => {
|
|
await options.beforePublish(abortResult);
|
|
return abortResult;
|
|
});
|
|
mockSaveMessage.mockImplementation(async (_context, message) => {
|
|
persistedMessages.set(message.messageId, message);
|
|
return message;
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.set('X-LibreChat-Generation-Protocol', '2')
|
|
.send({ conversationId: jobStreamId, generationProtocolVersion: 2 });
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(mockSaveMessage).toHaveBeenNthCalledWith(
|
|
1,
|
|
expect.anything(),
|
|
expect.objectContaining({
|
|
messageId: userMessageId,
|
|
conversationId: jobStreamId,
|
|
isCreatedByUser: true,
|
|
}),
|
|
expect.objectContaining({ context: expect.stringContaining('user prerequisite') }),
|
|
);
|
|
expect(mockSaveMessage).toHaveBeenNthCalledWith(
|
|
2,
|
|
expect.anything(),
|
|
expect.objectContaining({
|
|
messageId: preliminaryResponseId,
|
|
parentMessageId: userMessageId,
|
|
conversationId: jobStreamId,
|
|
content: [],
|
|
text: '',
|
|
unfinished: true,
|
|
isCreatedByUser: false,
|
|
}),
|
|
expect.objectContaining({ context: expect.stringContaining('abort endpoint') }),
|
|
);
|
|
|
|
/** The row renders nothing, so a dot raised for it names a reply the user can never
|
|
* open and no acknowledgement could clear. */
|
|
expect(mockSaveConvo).not.toHaveBeenCalledWith(
|
|
expect.anything(),
|
|
expect.anything(),
|
|
expect.objectContaining({ stampReply: true }),
|
|
);
|
|
|
|
/** This is the exact server-side fence hit by the queued submission
|
|
* after the abort FINAL. It must observe the row written above rather
|
|
* than reject the drain solely because the stable id ends in `_`. */
|
|
await expect(
|
|
isUnpersistedPreliminaryParent({
|
|
userId: 'test-user-123',
|
|
conversationId: jobStreamId,
|
|
parentMessageId: preliminaryResponseId,
|
|
getMessages: async (filter) =>
|
|
persistedMessages.has(filter.messageId)
|
|
? [{ _id: `persisted:${filter.messageId}` }]
|
|
: [],
|
|
}),
|
|
).resolves.toBe(false);
|
|
});
|
|
|
|
/** A compaction's `userMessage` is the persisted leaf projected for
|
|
* identity only (`projectCompactionAnchor`), so upserting it would
|
|
* erase a user leaf's text or turn an assistant leaf into an empty
|
|
* user row: Stop writes only the aborted response. */
|
|
it('skips the anchor prerequisite when an aborted compaction persists its row', async () => {
|
|
const jobStreamId = 'test-stream-compact';
|
|
const anchorId = 'persisted-leaf-1';
|
|
const compactionRowId = 'compaction-response-1';
|
|
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
metadata: { userId: 'test-user-123', generationProtocolVersion: 2 },
|
|
});
|
|
|
|
const abortResult = {
|
|
success: true,
|
|
jobData: {
|
|
compact: true,
|
|
createdEventEmitted: true,
|
|
userMessage: {
|
|
messageId: anchorId,
|
|
parentMessageId: 'older-response',
|
|
conversationId: jobStreamId,
|
|
text: '',
|
|
},
|
|
responseMessageId: compactionRowId,
|
|
conversationId: jobStreamId,
|
|
endpoint: 'agents',
|
|
sender: 'TestAgent',
|
|
model: 'agent-1',
|
|
},
|
|
content: [
|
|
{
|
|
type: 'error',
|
|
error: JSON.stringify({ type: 'compaction_failed' }),
|
|
initiatedBy: 'user',
|
|
},
|
|
],
|
|
text: '',
|
|
};
|
|
mockGenerationJobManager.abortJob.mockImplementation(async (_streamId, options) => {
|
|
await options.beforePublish(abortResult);
|
|
return abortResult;
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.set('X-LibreChat-Generation-Protocol', '2')
|
|
.send({ conversationId: jobStreamId, generationProtocolVersion: 2 });
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(mockSaveMessage).toHaveBeenCalledTimes(1);
|
|
expect(mockSaveMessage).toHaveBeenCalledWith(
|
|
expect.anything(),
|
|
expect.objectContaining({
|
|
messageId: compactionRowId,
|
|
parentMessageId: anchorId,
|
|
unfinished: false,
|
|
isCreatedByUser: false,
|
|
}),
|
|
expect.objectContaining({ context: expect.stringContaining('abort endpoint') }),
|
|
);
|
|
});
|
|
|
|
/** Stop can win the race before the branch loaded, so the projected
|
|
* anchor names a row that was never written: a response persisted
|
|
* there would be orphaned on reload. */
|
|
it('persists nothing when the compaction anchor was never written', async () => {
|
|
mockGetMessages.mockResolvedValueOnce([]);
|
|
const jobStreamId = 'test-stream-compact-unanchored';
|
|
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
metadata: { userId: 'test-user-123', generationProtocolVersion: 2 },
|
|
});
|
|
|
|
const abortResult = {
|
|
success: true,
|
|
jobData: {
|
|
compact: true,
|
|
createdEventEmitted: true,
|
|
userMessage: {
|
|
messageId: 'never-persisted-leaf',
|
|
parentMessageId: 'older-response',
|
|
conversationId: jobStreamId,
|
|
text: '',
|
|
},
|
|
responseMessageId: 'compaction-response-2',
|
|
conversationId: jobStreamId,
|
|
endpoint: 'agents',
|
|
sender: 'TestAgent',
|
|
model: 'agent-1',
|
|
},
|
|
content: [
|
|
{
|
|
type: 'error',
|
|
error: JSON.stringify({ type: 'compaction_failed' }),
|
|
initiatedBy: 'user',
|
|
},
|
|
],
|
|
text: '',
|
|
};
|
|
let beforePublishError;
|
|
mockGenerationJobManager.abortJob.mockImplementation(async (_streamId, options) => {
|
|
try {
|
|
await options.beforePublish(abortResult);
|
|
} catch (error) {
|
|
/** The manager catches this failure and publishes a
|
|
* reconciliation frame instead of the normal FINAL. */
|
|
beforePublishError = error;
|
|
}
|
|
return abortResult;
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.set('X-LibreChat-Generation-Protocol', '2')
|
|
.send({ conversationId: jobStreamId, generationProtocolVersion: 2 });
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(mockSaveMessage).not.toHaveBeenCalled();
|
|
expect(beforePublishError).toBeInstanceOf(Error);
|
|
expect(beforePublishError.message).toContain('anchor unavailable');
|
|
});
|
|
});
|
|
|
|
describe('Partial Response Saving', () => {
|
|
it('does not overwrite a persisted protected user sidecar while stopping a run', async () => {
|
|
const conversationId = 'test-stream-123';
|
|
const userMessageId = 'protected-user-msg';
|
|
const privacyRevision = 'protected-revision';
|
|
const text = 'Email [EMAIL_1_protected]';
|
|
const abortResult = {
|
|
success: true,
|
|
jobData: {
|
|
userMessage: { messageId: userMessageId, privacyRevision, text },
|
|
responseMessageId: 'protected-response',
|
|
conversationId,
|
|
endpoint: 'agents',
|
|
},
|
|
content: [{ type: 'text', text: 'Partial answer' }],
|
|
text: 'Partial answer',
|
|
};
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
metadata: { userId: 'test-user-123' },
|
|
});
|
|
mockGenerationJobManager.abortJob.mockImplementation(async (_streamId, options) => {
|
|
await options.beforePublish(abortResult);
|
|
return abortResult;
|
|
});
|
|
|
|
const response = await request(app).post('/api/agents/chat/abort').send({ conversationId });
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(mockHasPersistedPrivateText).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
userId: 'test-user-123',
|
|
messageId: userMessageId,
|
|
conversationId,
|
|
privacyRevision,
|
|
text,
|
|
}),
|
|
);
|
|
expect(mockSaveMessage).toHaveBeenCalledTimes(1);
|
|
expect(mockSaveMessage).toHaveBeenCalledWith(
|
|
expect.anything(),
|
|
expect.objectContaining({ messageId: 'protected-response', isCreatedByUser: false }),
|
|
expect.anything(),
|
|
);
|
|
});
|
|
|
|
it('recovers an older revisionless job from its exact protected row without unsetting it', async () => {
|
|
const conversationId = 'test-stream-revisionless';
|
|
const userMessageId = 'protected-user';
|
|
const text = `Email [EMAIL_1_${'a'.repeat(32)}]`;
|
|
const abortResult = {
|
|
success: true,
|
|
jobData: {
|
|
createdEventEmitted: true,
|
|
userMessage: { messageId: userMessageId, text },
|
|
responseMessageId: 'protected-response',
|
|
conversationId,
|
|
endpoint: 'agents',
|
|
},
|
|
finalEvent: { requestMessage: { messageId: userMessageId, text } },
|
|
content: [],
|
|
text: '',
|
|
};
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
metadata: { userId: 'test-user-123' },
|
|
});
|
|
mockGenerationJobManager.abortJob.mockImplementation(async (_id, options) => {
|
|
await options.beforePublish(abortResult);
|
|
return abortResult;
|
|
});
|
|
mockSaveMessage.mockImplementationOnce(async (_ctx, message, metadata) => {
|
|
expect(metadata.insertOnly).toBe(true);
|
|
return { ...message, _id: 'protected-parent', privacyRevision: 'recovered-revision' };
|
|
});
|
|
|
|
const response = await request(app).post('/api/agents/chat/abort').send({ conversationId });
|
|
expect(response.status).toBe(200);
|
|
expect(mockGetPrivateMessageTexts).not.toHaveBeenCalled();
|
|
expect(mockHasPersistedPrivateText).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
userId: 'test-user-123',
|
|
conversationId,
|
|
messageId: userMessageId,
|
|
privacyRevision: 'recovered-revision',
|
|
text,
|
|
}),
|
|
);
|
|
expect(abortResult.finalEvent.requestMessage.privacyRevision).toBe('recovered-revision');
|
|
expect(mockSaveMessage).toHaveBeenCalledTimes(2);
|
|
expect(mockSaveMessage).toHaveBeenCalledWith(
|
|
expect.anything(),
|
|
expect.objectContaining({ messageId: 'protected-response' }),
|
|
expect.anything(),
|
|
);
|
|
});
|
|
|
|
it('should save partial response when both userMessage and responseMessageId exist', async () => {
|
|
const jobStreamId = 'test-stream-123';
|
|
const userMessageId = 'user-msg-123';
|
|
const responseMessageId = 'response-msg-456';
|
|
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
metadata: { userId: 'test-user-123' },
|
|
});
|
|
|
|
const abortResult = {
|
|
success: true,
|
|
jobData: {
|
|
userMessage: { messageId: userMessageId },
|
|
responseMessageId,
|
|
conversationId: jobStreamId,
|
|
sender: 'TestAgent',
|
|
endpoint: 'anthropic',
|
|
iconURL: 'https://example.com/spec-icon.png',
|
|
model: 'claude-3',
|
|
userSubmittedPaths: ['/content/0/tool_call/args'],
|
|
userSubmittedMessageFieldPaths: [
|
|
{ path: '/content/0/tool_call/output', field: 'decision_response' },
|
|
],
|
|
},
|
|
content: [{ type: 'text', text: 'Partial response...' }],
|
|
text: 'Partial response...',
|
|
};
|
|
mockGenerationJobManager.abortJob.mockImplementation(async (_streamId, options) => {
|
|
await options.beforePublish(abortResult);
|
|
return abortResult;
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.send({ conversationId: jobStreamId });
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(mockSaveMessage).toHaveBeenCalledWith(
|
|
expect.anything(),
|
|
expect.objectContaining({
|
|
messageId: responseMessageId,
|
|
parentMessageId: userMessageId,
|
|
conversationId: jobStreamId,
|
|
content: [{ type: 'text', text: 'Partial response...' }],
|
|
text: 'Partial response...',
|
|
sender: 'TestAgent',
|
|
endpoint: 'anthropic',
|
|
iconURL: 'https://example.com/spec-icon.png',
|
|
model: 'claude-3',
|
|
unfinished: true,
|
|
error: false,
|
|
isCreatedByUser: false,
|
|
userSubmittedPaths: ['/content/0/tool_call/args'],
|
|
userSubmittedMessageFieldPaths: [
|
|
{ path: '/content/0/tool_call/output', field: 'decision_response' },
|
|
],
|
|
user: 'test-user-123',
|
|
}),
|
|
expect.objectContaining({
|
|
context: 'api/server/routes/agents/index.js - abort endpoint',
|
|
}),
|
|
);
|
|
});
|
|
|
|
it('carries the context meta the run published onto the stopped response', async () => {
|
|
const contextMeta = {
|
|
calibrationRatio: 1.2,
|
|
encoding: 'claude',
|
|
fading: { v: 1, budgetTokens: 50_000, masked: true },
|
|
fadingTiers: [{ agentId: 'agent-a', v: 1, budgetTokens: 50_000, masked: true }],
|
|
};
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
metadata: { userId: 'test-user-123' },
|
|
});
|
|
const abortResult = {
|
|
success: true,
|
|
jobData: {
|
|
userMessage: { messageId: 'user-msg-123' },
|
|
responseMessageId: 'response-msg-456',
|
|
conversationId: 'test-stream-123',
|
|
contextMeta,
|
|
},
|
|
content: [{ type: 'text', text: 'Partial response...' }],
|
|
text: 'Partial response...',
|
|
};
|
|
mockGenerationJobManager.abortJob.mockImplementation(async (_streamId, options) => {
|
|
await options.beforePublish(abortResult);
|
|
return abortResult;
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.send({ conversationId: 'test-stream-123' });
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(mockSaveMessage).toHaveBeenCalledWith(
|
|
expect.anything(),
|
|
expect.objectContaining({ messageId: 'response-msg-456', contextMeta }),
|
|
expect.objectContaining({
|
|
context: 'api/server/routes/agents/index.js - abort endpoint',
|
|
}),
|
|
);
|
|
});
|
|
|
|
it('unsets context meta on the stopped response when the job has none', async () => {
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
metadata: { userId: 'test-user-123' },
|
|
});
|
|
const abortResult = {
|
|
success: true,
|
|
jobData: {
|
|
userMessage: { messageId: 'user-msg-123' },
|
|
responseMessageId: 'response-msg-456',
|
|
conversationId: 'test-stream-123',
|
|
},
|
|
content: [{ type: 'text', text: 'Partial response...' }],
|
|
text: 'Partial response...',
|
|
};
|
|
mockGenerationJobManager.abortJob.mockImplementation(async (_streamId, options) => {
|
|
await options.beforePublish(abortResult);
|
|
return abortResult;
|
|
});
|
|
|
|
await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.send({ conversationId: 'test-stream-123' });
|
|
|
|
const [, savedResponse] = mockSaveMessage.mock.calls.find(
|
|
([, message]) => message.messageId === 'response-msg-456',
|
|
);
|
|
expect(savedResponse.contextMeta).toBeNull();
|
|
});
|
|
|
|
it('stamps the aborted reply through an upsert so an early stop still lights the dot', async () => {
|
|
const jobStreamId = 'test-stream-123';
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
metadata: { userId: 'test-user-123' },
|
|
});
|
|
const abortResult = {
|
|
success: true,
|
|
jobData: {
|
|
userMessage: { messageId: 'user-msg-123' },
|
|
responseMessageId: 'response-msg-456',
|
|
conversationId: jobStreamId,
|
|
endpoint: 'anthropic',
|
|
model: 'claude-3',
|
|
},
|
|
content: [{ type: 'text', text: 'Partial response...' }],
|
|
text: 'Partial response...',
|
|
};
|
|
mockGenerationJobManager.abortJob.mockImplementation(async (_streamId, options) => {
|
|
await options.beforePublish(abortResult);
|
|
return abortResult;
|
|
});
|
|
mockSaveMessage.mockImplementation(async (_context, message) => ({
|
|
...message,
|
|
_id: `oid-${message.messageId}`,
|
|
}));
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.send({ conversationId: jobStreamId });
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(mockSaveConvo).toHaveBeenCalledWith(
|
|
expect.anything(),
|
|
expect.objectContaining({
|
|
conversationId: jobStreamId,
|
|
endpoint: 'anthropic',
|
|
model: 'claude-3',
|
|
}),
|
|
expect.objectContaining({
|
|
stampReply: true,
|
|
replyMessageId: 'response-msg-456',
|
|
/* Without these `saveConvo` reloads the whole history inside the abort barrier. */
|
|
appendMessageIds: ['oid-user-msg-123', 'oid-response-msg-456'],
|
|
}),
|
|
);
|
|
});
|
|
|
|
it('saves the aborted partial as temporary from job metadata, not the request body', async () => {
|
|
const jobStreamId = 'test-stream-123';
|
|
const expiredAt = new Date('2030-01-01T00:00:00.000Z');
|
|
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
metadata: { userId: 'test-user-123' },
|
|
});
|
|
|
|
// The job was a temporary chat; the stop button posts only conversationId.
|
|
const abortResult = {
|
|
success: true,
|
|
jobData: {
|
|
userMessage: { messageId: 'user-msg-123' },
|
|
responseMessageId: 'response-msg-456',
|
|
conversationId: jobStreamId,
|
|
isTemporary: true,
|
|
retentionExpiresAt: expiredAt.toISOString(),
|
|
},
|
|
content: [{ type: 'text', text: 'Partial...' }],
|
|
text: 'Partial...',
|
|
};
|
|
mockGenerationJobManager.abortJob.mockImplementation(async (_streamId, options) => {
|
|
await options.beforePublish(abortResult);
|
|
return abortResult;
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.send({ conversationId: jobStreamId }); // no isTemporary in body
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(mockSaveMessage).toHaveBeenCalledWith(
|
|
expect.objectContaining({ isTemporary: true, expiredAt }),
|
|
expect.anything(),
|
|
expect.anything(),
|
|
);
|
|
});
|
|
|
|
it('stamps a paused ask_user_question via transformAbortContent, before the final SSE emits', async () => {
|
|
const jobStreamId = 'test-stream-123';
|
|
const question = { question: 'Deploy where?', options: [{ label: 'Prod', value: 'prod' }] };
|
|
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
metadata: {
|
|
userId: 'test-user-123',
|
|
pendingAction: { payload: { type: 'ask_user_question', question } },
|
|
},
|
|
});
|
|
|
|
// abortJob applies the transform; capture it and echo the transformed
|
|
// content back as the result, mirroring the real (Redis) reconstruction
|
|
// where the ask tool_call arrives with empty args.
|
|
let capturedTransform;
|
|
mockGenerationJobManager.abortJob.mockImplementation(async (_streamId, options) => {
|
|
capturedTransform = options?.transformAbortContent;
|
|
const rawContent = [
|
|
{ type: 'tool_call', tool_call: { id: 'tc1', name: 'ask_user_question', args: '' } },
|
|
];
|
|
const content = capturedTransform
|
|
? capturedTransform(rawContent, {
|
|
pendingAction: { payload: { type: 'ask_user_question', question } },
|
|
})
|
|
: rawContent;
|
|
const result = {
|
|
success: true,
|
|
jobData: {
|
|
userMessage: { messageId: 'user-msg-123' },
|
|
responseMessageId: 'response-msg-456',
|
|
conversationId: jobStreamId,
|
|
},
|
|
content,
|
|
text: '',
|
|
};
|
|
await options?.beforePublish?.(result);
|
|
return result;
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.send({ conversationId: jobStreamId });
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(capturedTransform).toEqual(expect.any(Function));
|
|
// The saved (and, in prod, emitted) content carries the stamped args.
|
|
// saveMessage(reqLike, responseMessage, opts) — the message is arg #2.
|
|
const savedMessage = mockSaveMessage.mock.calls
|
|
.map(([, message]) => message)
|
|
.find((message) => message.isCreatedByUser === false);
|
|
const askPart = savedMessage.content.find(
|
|
(p) => p?.tool_call?.name === 'ask_user_question',
|
|
);
|
|
expect(JSON.parse(askPart.tool_call.args)).toMatchObject({ question: 'Deploy where?' });
|
|
});
|
|
|
|
it('preserves an accepted ask answer when abort wins during resume reconstruction', async () => {
|
|
const jobStreamId = 'test-stream-123';
|
|
const question = { question: 'Deploy where?', options: [{ label: 'Prod', value: 'prod' }] };
|
|
|
|
// The route reads the still-paused snapshot before resume wins. The
|
|
// manager must supply the newer, terminal-claim snapshot to the
|
|
// transform rather than letting this initial read go stale.
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
metadata: { userId: 'test-user-123' },
|
|
});
|
|
|
|
mockGenerationJobManager.abortJob.mockImplementation(async (_streamId, options) => {
|
|
const rawContent = [
|
|
{ type: 'tool_call', tool_call: { id: 'tc1', name: 'ask_user_question', args: '' } },
|
|
];
|
|
const content = options.transformAbortContent(rawContent, {
|
|
resolvedAskUserQuestions: [
|
|
{
|
|
request: question,
|
|
output: 'prod',
|
|
toolCallId: 'tc1',
|
|
},
|
|
],
|
|
});
|
|
const result = {
|
|
success: true,
|
|
jobData: {
|
|
userMessage: { messageId: 'user-msg-123' },
|
|
responseMessageId: 'response-msg-456',
|
|
conversationId: jobStreamId,
|
|
},
|
|
content,
|
|
text: '',
|
|
};
|
|
await options.beforePublish(result);
|
|
return result;
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.send({ conversationId: jobStreamId });
|
|
|
|
expect(response.status).toBe(200);
|
|
const savedMessage = mockSaveMessage.mock.calls
|
|
.map(([, message]) => message)
|
|
.find((message) => message.isCreatedByUser === false);
|
|
const askPart = savedMessage.content.find(
|
|
(part) => part?.tool_call?.name === 'ask_user_question',
|
|
);
|
|
expect(JSON.parse(askPart.tool_call.args)).toEqual(question);
|
|
expect(askPart.tool_call.output).toBe('prod');
|
|
expect(askPart.tool_call.progress).toBe(1);
|
|
});
|
|
|
|
it('does not stamp an ID-less legacy answer onto a later pending ask', async () => {
|
|
const jobStreamId = 'test-stream-123';
|
|
const priorQuestion = { question: 'Which environment?' };
|
|
const currentQuestion = { question: 'Approve deployment?' };
|
|
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
metadata: { userId: 'test-user-123' },
|
|
});
|
|
mockGenerationJobManager.abortJob.mockImplementation(async (_streamId, options) => {
|
|
const rawContent = [
|
|
{
|
|
type: 'tool_call',
|
|
tool_call: {
|
|
id: 'legacy-call',
|
|
name: 'ask_user_question',
|
|
args: JSON.stringify(priorQuestion),
|
|
output: 'staging',
|
|
},
|
|
},
|
|
{
|
|
type: 'tool_call',
|
|
tool_call: { id: 'current-call', name: 'ask_user_question', args: '' },
|
|
},
|
|
];
|
|
const content = options.transformAbortContent(rawContent, {
|
|
resolvedAskUserQuestions: [{ request: priorQuestion, output: 'staging' }],
|
|
pendingAction: {
|
|
payload: {
|
|
type: 'ask_user_question',
|
|
question: currentQuestion,
|
|
tool_call_id: 'current-call',
|
|
},
|
|
},
|
|
});
|
|
const result = {
|
|
success: true,
|
|
jobData: {
|
|
userMessage: { messageId: 'user-msg-123' },
|
|
responseMessageId: 'response-msg-456',
|
|
conversationId: jobStreamId,
|
|
},
|
|
content,
|
|
text: '',
|
|
};
|
|
await options.beforePublish(result);
|
|
return result;
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.send({ conversationId: jobStreamId });
|
|
|
|
expect(response.status).toBe(200);
|
|
const savedMessage = mockSaveMessage.mock.calls
|
|
.map(([, message]) => message)
|
|
.find((message) => message.isCreatedByUser === false);
|
|
const [priorAsk, currentAsk] = savedMessage.content;
|
|
expect(priorAsk.tool_call.output).toBe('staging');
|
|
expect(JSON.parse(priorAsk.tool_call.args)).toEqual(priorQuestion);
|
|
expect(currentAsk.tool_call.output).toBeUndefined();
|
|
expect(JSON.parse(currentAsk.tool_call.args)).toEqual(currentQuestion);
|
|
});
|
|
|
|
it('reconstructs an exact-ID prior answer alongside a later pending ask', async () => {
|
|
const jobStreamId = 'test-stream-123';
|
|
const priorQuestion = { question: 'Which environment?' };
|
|
const currentQuestion = { question: 'Approve deployment?' };
|
|
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
metadata: { userId: 'test-user-123' },
|
|
});
|
|
mockGenerationJobManager.abortJob.mockImplementation(async (_streamId, options) => {
|
|
const rawContent = [
|
|
{
|
|
type: 'tool_call',
|
|
tool_call: { id: 'prior-call', name: 'ask_user_question', args: '' },
|
|
},
|
|
{
|
|
type: 'tool_call',
|
|
tool_call: { id: 'current-call', name: 'ask_user_question', args: '' },
|
|
},
|
|
];
|
|
const content = options.transformAbortContent(rawContent, {
|
|
resolvedAskUserQuestions: [
|
|
{
|
|
request: priorQuestion,
|
|
output: 'staging',
|
|
toolCallId: 'prior-call',
|
|
},
|
|
],
|
|
pendingAction: {
|
|
payload: {
|
|
type: 'ask_user_question',
|
|
question: currentQuestion,
|
|
tool_call_id: 'current-call',
|
|
},
|
|
},
|
|
});
|
|
const result = {
|
|
success: true,
|
|
jobData: {
|
|
userMessage: { messageId: 'user-msg-123' },
|
|
responseMessageId: 'response-msg-456',
|
|
conversationId: jobStreamId,
|
|
},
|
|
content,
|
|
text: '',
|
|
};
|
|
await options.beforePublish(result);
|
|
return result;
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.send({ conversationId: jobStreamId });
|
|
|
|
expect(response.status).toBe(200);
|
|
const savedMessage = mockSaveMessage.mock.calls
|
|
.map(([, message]) => message)
|
|
.find((message) => message.isCreatedByUser === false);
|
|
const [priorAsk, currentAsk] = savedMessage.content;
|
|
expect(priorAsk.tool_call.output).toBe('staging');
|
|
expect(JSON.parse(priorAsk.tool_call.args)).toEqual(priorQuestion);
|
|
expect(currentAsk.tool_call.output).toBeUndefined();
|
|
expect(JSON.parse(currentAsk.tool_call.args)).toEqual(currentQuestion);
|
|
});
|
|
|
|
it('reconstructs an ID-less prior answer while a later tool approval is pending', async () => {
|
|
const jobStreamId = 'test-stream-123';
|
|
const priorQuestion = { question: 'Which environment?' };
|
|
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
metadata: { userId: 'test-user-123' },
|
|
});
|
|
mockGenerationJobManager.abortJob.mockImplementation(async (_streamId, options) => {
|
|
const rawContent = [
|
|
{
|
|
type: 'tool_call',
|
|
tool_call: { id: 'legacy-call', name: 'ask_user_question', args: '' },
|
|
},
|
|
];
|
|
const content = options.transformAbortContent(rawContent, {
|
|
resolvedAskUserQuestions: [{ request: priorQuestion, output: 'staging' }],
|
|
pendingAction: {
|
|
payload: {
|
|
type: 'tool_approval',
|
|
action_requests: [{ tool_call_id: 'tool-1' }],
|
|
review_configs: [],
|
|
},
|
|
},
|
|
});
|
|
const result = {
|
|
success: true,
|
|
jobData: {
|
|
userMessage: { messageId: 'user-msg-123' },
|
|
responseMessageId: 'response-msg-456',
|
|
conversationId: jobStreamId,
|
|
},
|
|
content,
|
|
text: '',
|
|
};
|
|
await options.beforePublish(result);
|
|
return result;
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.send({ conversationId: jobStreamId });
|
|
|
|
expect(response.status).toBe(200);
|
|
const savedMessage = mockSaveMessage.mock.calls
|
|
.map(([, message]) => message)
|
|
.find((message) => message.isCreatedByUser === false);
|
|
const [priorAsk] = savedMessage.content;
|
|
expect(priorAsk.tool_call.output).toBe('staging');
|
|
expect(JSON.parse(priorAsk.tool_call.args)).toEqual(priorQuestion);
|
|
});
|
|
|
|
it('should handle saveMessage errors gracefully', async () => {
|
|
const jobStreamId = 'test-stream-123';
|
|
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
metadata: { userId: 'test-user-123', generationProtocolVersion: 2 },
|
|
});
|
|
|
|
const abortResult = {
|
|
success: true,
|
|
jobData: {
|
|
userMessage: { messageId: 'user-msg-123' },
|
|
responseMessageId: 'response-msg-456',
|
|
conversationId: jobStreamId,
|
|
},
|
|
content: [{ type: 'text', text: 'Partial response...' }],
|
|
text: 'Partial response...',
|
|
};
|
|
mockGenerationJobManager.abortJob.mockImplementation(async (_streamId, options) => {
|
|
try {
|
|
await options.beforePublish(abortResult);
|
|
} catch {
|
|
return { ...abortResult, persistenceFailed: true };
|
|
}
|
|
return abortResult;
|
|
});
|
|
|
|
mockSaveMessage.mockRejectedValue(new Error('Database error'));
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.set('X-LibreChat-Generation-Protocol', '2')
|
|
.send({ conversationId: jobStreamId, generationProtocolVersion: 2 });
|
|
|
|
// Should still return success even if save fails
|
|
expect(response.status).toBe(200);
|
|
expect(response.body).toEqual({
|
|
success: true,
|
|
aborted: jobStreamId,
|
|
persistenceFailed: true,
|
|
generationProtocolVersion: 2,
|
|
});
|
|
expect(response.headers['x-librechat-generation-protocol']).toBe('2');
|
|
});
|
|
});
|
|
|
|
describe('Job Not Found', () => {
|
|
it('should reject an unfenced new-placeholder abort when paused and running jobs exist', async () => {
|
|
mockGenerationJobManager.getJob
|
|
.mockResolvedValueOnce({
|
|
status: 'requires_action',
|
|
metadata: { userId: 'test-user-123' },
|
|
})
|
|
.mockResolvedValueOnce({
|
|
status: 'running',
|
|
metadata: { userId: 'test-user-123' },
|
|
});
|
|
mockGenerationJobManager.getActiveJobIdsForUser.mockResolvedValue([
|
|
'paused-stream',
|
|
'running-stream',
|
|
]);
|
|
mockGenerationJobManager.abortJob.mockResolvedValue({
|
|
success: true,
|
|
jobData: null,
|
|
content: [],
|
|
text: '',
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.send({ conversationId: 'new' });
|
|
|
|
expect(response.status).toBe(409);
|
|
expect(response.body).toEqual({
|
|
code: 'AMBIGUOUS_ACTIVE_RUN',
|
|
generationProtocolVersion: 1,
|
|
});
|
|
expect(mockGenerationJobManager.abortJob).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('should abort an unambiguous paused fallback job', async () => {
|
|
mockGenerationJobManager.getJob.mockResolvedValueOnce({
|
|
status: 'requires_action',
|
|
metadata: { userId: 'test-user-123' },
|
|
});
|
|
mockGenerationJobManager.getActiveJobIdsForUser.mockResolvedValue(['paused-stream']);
|
|
mockGenerationJobManager.abortJob.mockResolvedValue({
|
|
success: true,
|
|
jobData: null,
|
|
content: [],
|
|
text: '',
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.send({ conversationId: 'new' });
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(response.body).toEqual({
|
|
success: true,
|
|
aborted: 'paused-stream',
|
|
generationProtocolVersion: 1,
|
|
});
|
|
expect(mockGenerationJobManager.abortJob).toHaveBeenCalledWith(
|
|
'paused-stream',
|
|
expect.objectContaining({ transformAbortContent: expect.any(Function) }),
|
|
);
|
|
});
|
|
|
|
it('should return 404 when job is not found', async () => {
|
|
mockGenerationJobManager.getJob.mockResolvedValue(null);
|
|
mockGenerationJobManager.getActiveJobIdsForUser.mockResolvedValue([]);
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.send({ conversationId: 'non-existent-job' });
|
|
|
|
expect(response.status).toBe(404);
|
|
expect(response.body).toEqual({
|
|
error: 'Job not found',
|
|
streamId: 'non-existent-job',
|
|
generationProtocolVersion: 1,
|
|
});
|
|
});
|
|
});
|
|
|
|
describe('Scheduled Stop persistence protocol', () => {
|
|
const scheduledJob = {
|
|
status: 'running',
|
|
createdAt: 111,
|
|
metadata: {
|
|
userId: 'test-user-123',
|
|
generationProtocolVersion: 2,
|
|
scheduleId: 's1',
|
|
scheduledFor: '2026-01-01T00:00:00.000Z',
|
|
conversationId: 'conv-1',
|
|
},
|
|
};
|
|
|
|
it('stamps the Stop before signalling abort, then acknowledges after persistence', async () => {
|
|
mockGenerationJobManager.getJob.mockResolvedValue(scheduledJob);
|
|
mockGenerationJobManager.abortJob.mockResolvedValue({
|
|
success: true,
|
|
jobData: { conversationId: 'conv-1' },
|
|
content: [],
|
|
text: '',
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.set('X-LibreChat-Generation-Protocol', '2')
|
|
.send({ conversationId: 'conv-1', generationProtocolVersion: 2 });
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(mockBeginScheduledStop).toHaveBeenCalledWith({
|
|
scheduleId: 's1',
|
|
scheduledFor: '2026-01-01T00:00:00.000Z',
|
|
});
|
|
// Stamp BEFORE the abort signal; acknowledgement AFTER it (persistence done).
|
|
expect(mockBeginScheduledStop.mock.invocationCallOrder[0]).toBeLessThan(
|
|
mockGenerationJobManager.abortJob.mock.invocationCallOrder[0],
|
|
);
|
|
// The ack also carries a terminal outcome to re-drive: the owner calls
|
|
// recordScheduleOutcome once, and if that call's Stop barrier deferred (slow
|
|
// beforePublish), nothing would settle the run where no reconciler is armed.
|
|
expect(mockAcknowledgeScheduledStopPersistence).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
scheduleId: 's1',
|
|
scheduledFor: '2026-01-01T00:00:00.000Z',
|
|
settle: expect.objectContaining({ status: 'interrupted' }),
|
|
}),
|
|
);
|
|
expect(mockGenerationJobManager.abortJob.mock.invocationCallOrder[0]).toBeLessThan(
|
|
mockAcknowledgeScheduledStopPersistence.mock.invocationCallOrder[0],
|
|
);
|
|
});
|
|
|
|
it('returns STOP_IN_PROGRESS and never signals a second abort when a Stop is already live', async () => {
|
|
mockGenerationJobManager.getJob.mockResolvedValue(scheduledJob);
|
|
mockBeginScheduledStop.mockResolvedValue('in_progress');
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.set('X-LibreChat-Generation-Protocol', '2')
|
|
.send({ conversationId: 'conv-1', generationProtocolVersion: 2 });
|
|
|
|
expect(response.status).toBe(409);
|
|
expect(response.body.code).toBe('STOP_IN_PROGRESS');
|
|
expect(mockGenerationJobManager.abortJob).not.toHaveBeenCalled();
|
|
expect(mockAcknowledgeScheduledStopPersistence).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('does NOT acknowledge when the abort persistence failed (run stays preserved)', async () => {
|
|
mockGenerationJobManager.getJob.mockResolvedValue(scheduledJob);
|
|
mockGenerationJobManager.abortJob.mockResolvedValue({
|
|
success: true,
|
|
persistenceFailed: true,
|
|
jobData: { conversationId: 'conv-1' },
|
|
content: [],
|
|
text: '',
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.set('X-LibreChat-Generation-Protocol', '2')
|
|
.send({ conversationId: 'conv-1', generationProtocolVersion: 2 });
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(response.body.persistenceFailed).toBe(true);
|
|
expect(mockBeginScheduledStop).toHaveBeenCalled();
|
|
expect(mockAcknowledgeScheduledStopPersistence).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('does not re-drive settlement for a PAUSED job, which settles explicitly', async () => {
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
...scheduledJob,
|
|
status: 'requires_action',
|
|
});
|
|
mockGenerationJobManager.abortJob.mockResolvedValue({
|
|
success: true,
|
|
jobData: { conversationId: 'conv-1' },
|
|
content: [],
|
|
text: '',
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.set('X-LibreChat-Generation-Protocol', '2')
|
|
.send({ conversationId: 'conv-1', generationProtocolVersion: 2 });
|
|
|
|
expect(response.status).toBe(200);
|
|
const ack = mockAcknowledgeScheduledStopPersistence.mock.calls[0][0];
|
|
expect(ack.settle).toBeUndefined();
|
|
// The paused path records its own outcome explicitly.
|
|
expect(mockRecordScheduleOutcome).toHaveBeenCalled();
|
|
});
|
|
|
|
it('leaves non-scheduled aborts untouched by the Stop protocol', async () => {
|
|
mockGenerationJobManager.getJob.mockResolvedValue({
|
|
status: 'running',
|
|
createdAt: 1,
|
|
metadata: { userId: 'test-user-123', generationProtocolVersion: 2 },
|
|
});
|
|
mockGenerationJobManager.abortJob.mockResolvedValue({
|
|
success: true,
|
|
jobData: { conversationId: 'conv-x' },
|
|
content: [],
|
|
text: '',
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post('/api/agents/chat/abort')
|
|
.set('X-LibreChat-Generation-Protocol', '2')
|
|
.send({ conversationId: 'conv-x', generationProtocolVersion: 2 });
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(mockBeginScheduledStop).not.toHaveBeenCalled();
|
|
expect(mockAcknowledgeScheduledStopPersistence).not.toHaveBeenCalled();
|
|
});
|
|
});
|
|
});
|
|
});
|