mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-16 13:00:55 +00:00
* 🎒 feat: Carry Project Context Across Conversations
* fix: fail a project attach whose upload hold cannot be released and keep file deletes independent of project cleanup
- Attaching a project file now fails, with nothing attached, when the file's
temporary upload hold cannot be released, instead of attaching a file that
can still expire.
- A failed project cleanup after a file delete is logged rather than failing a
delete that already happened, and a user-wide delete clears that user's
project references without reading every file first.
- Both resize handles share the orientation-aware grip, so a primary handle in
a vertical group renders a rotated grip like the alternate one.
* fix: treat an empty tenant id as no tenant in the project file picker
* fix: attach nothing when a project file is deleted while the attach is in flight
* fix: localize project file association failures instead of showing server text
* test: expect a localized reason for a rejected project file association
* fix: scope project file listing to the caller's tenant and name the file limit when attaching an existing file
- Listing a project's attached files now returns not found when the project
belongs to another tenant, matching the available-file listing and the
chat context resolver.
- Choosing an existing file for a full project now names the project file
limit instead of the generic attach error, like the upload path.
* fix: treat an empty tenant id as no tenant in every project tenant check
A caller whose tenant id is an empty string was refused its own tenantless
project when listing attached or available files, because the handlers
compared '' with null. The project handlers and the chat context resolver now
share one comparison that treats an empty tenant id as no tenant, the rule the
project file queries already follow.
* test: wait for the workspace layout swap and the mobile drawer before acting in the long-metadata spec
The desktop title was measured while the phone layout could still be the one
rendered, and the sidebar row menu was opened before the mobile drawer
committed its open state, which closes a menu opened ahead of it. The spec
now waits for the workspace's phone-only sidebar toggle to leave and for the
drawer to drop inert, the same drawer signal the agents helpers use.
* fix: keep the agent context fingerprint of a turn outside any project unchanged
Every turn now passes a project context key into the agent context
fingerprint, and a turn outside any project passed the no-project sentinel,
which changed the digest of every existing no-project checkpoint. An agent
event conversation written before this change then cold-started and reloaded
its history on its next event. The fingerprint now hashes the no-project key
as absent, so those checkpoints keep matching.
* test: load the long-metadata spec at phone width before driving the mobile drawer
The spec crossed back from desktop to phone width without a reload, which
leaves the drawer on the desktop toggle path whose delayed focus handoff to
the close button dismissed the row menu roughly 200ms after it opened. The
spec now reloads at phone width, as a phone arrives, and waits for the
drawer's own focus handoff before opening the menu.
283 lines
10 KiB
JavaScript
283 lines
10 KiB
JavaScript
const mockLogger = {
|
|
debug: jest.fn(),
|
|
warn: jest.fn(),
|
|
error: jest.fn(),
|
|
info: jest.fn(),
|
|
};
|
|
|
|
let activeTenantContext;
|
|
const mockTenantStorageRun = jest.fn(async (context, callback) => {
|
|
activeTenantContext = context;
|
|
try {
|
|
return await callback();
|
|
} finally {
|
|
activeTenantContext = undefined;
|
|
}
|
|
});
|
|
const mockSaveMessage = jest.fn();
|
|
const mockGetConvo = jest.fn();
|
|
const mockGetMessages = jest.fn();
|
|
const mockIsAgentTriggerPrincipalActive = jest.fn();
|
|
const mockFilterPersistableAbortContent = jest.fn((content) => content);
|
|
const mockCheckAndIncrementPendingRequest = jest.fn();
|
|
const mockDecrementPendingRequest = jest.fn();
|
|
const mockGenerationJobManager = {
|
|
createJob: jest.fn(),
|
|
emitError: jest.fn(),
|
|
completeJob: jest.fn(),
|
|
beginProviderExecution: jest.fn(),
|
|
markProviderExecutionDrained: jest.fn(),
|
|
getResumeState: jest.fn(),
|
|
getJobStore: jest.fn(),
|
|
updateMetadata: jest.fn(),
|
|
claimGeneration: jest.fn(),
|
|
releaseGeneration: jest.fn(),
|
|
hasJob: jest.fn(),
|
|
steering: {
|
|
closeAndDrain: jest.fn(),
|
|
park: jest.fn(),
|
|
},
|
|
};
|
|
|
|
jest.mock('@librechat/data-schemas', () => ({
|
|
logger: mockLogger,
|
|
tenantStorage: {
|
|
run: (...args) => mockTenantStorageRun(...args),
|
|
},
|
|
}));
|
|
|
|
jest.mock('@librechat/api', () => ({
|
|
getAgentErrorMetadata: (...args) =>
|
|
jest.requireActual('@librechat/api').getAgentErrorMetadata(...args),
|
|
sendEvent: jest.fn(),
|
|
persistedReasoningOverrideFields:
|
|
jest.requireActual('@librechat/api').persistedReasoningOverrideFields,
|
|
isScheduleFireRequest: jest.fn(() => false),
|
|
exemptFromConcurrencyLimiter: jest.fn(() => false),
|
|
toPendingSteer: jest.fn((item) => item),
|
|
isSteerPreemptSupported: jest.fn(() => true),
|
|
isSteerTerminalContinuationSupported: jest.fn(() => false),
|
|
buildRecoveredSteerPayload: jest.fn(() => null),
|
|
deleteAgentCheckpoint: jest.fn(),
|
|
getViolationInfo: jest.fn(() => ({
|
|
type: 'concurrent',
|
|
limit: 2,
|
|
pendingRequests: 3,
|
|
score: 1,
|
|
})),
|
|
buildMessageFiles: jest.fn(() => []),
|
|
resolveTitleTiming: jest.fn(() => 'immediate'),
|
|
createConvoPersistenceSignal: jest.requireActual('@librechat/api').createConvoPersistenceSignal,
|
|
recoverTurnMessageReference: jest.requireActual('@librechat/api').recoverTurnMessageReference,
|
|
resolveConversationAnchor: jest.requireActual('@librechat/api').resolveConversationAnchor,
|
|
resolveRunCodeWorkspaces: jest.requireActual('@librechat/api').resolveRunCodeWorkspaces,
|
|
shouldPersistCodeWorkspaceInitializationError:
|
|
jest.requireActual('@librechat/api').shouldPersistCodeWorkspaceInitializationError,
|
|
resolvePersistableCodeEnvironmentDecision: (...args) =>
|
|
jest.requireActual('@librechat/api').resolvePersistableCodeEnvironmentDecision(...args),
|
|
getSafeErrorMetadata: jest.requireActual('@librechat/api').getSafeErrorMetadata,
|
|
getSafeErrorText: jest.requireActual('@librechat/api').getSafeErrorText,
|
|
startAgentProjectContextResolution:
|
|
jest.requireActual('@librechat/api').startAgentProjectContextResolution,
|
|
assertChatProjectInstructions: jest.requireActual('@librechat/api').assertChatProjectInstructions,
|
|
getChatProjectTurnFailure: jest.requireActual('@librechat/api').getChatProjectTurnFailure,
|
|
GenerationJobManager: mockGenerationJobManager,
|
|
getReferencedQuotes: jest.fn(() => null),
|
|
cleanupMCPRequestContext: jest.fn(),
|
|
createMCPRequestContext: jest.fn(() => ({
|
|
connections: new Map(),
|
|
pending: new Map(),
|
|
cleanupStarted: false,
|
|
})),
|
|
getMCPRequestContext: jest.fn(() => ({
|
|
connections: new Map(),
|
|
pending: new Map(),
|
|
cleanupStarted: false,
|
|
})),
|
|
filterPersistableAbortContent: (...args) => mockFilterPersistableAbortContent(...args),
|
|
cleanupMCPRequestContextForReq: jest.fn(),
|
|
decrementPendingRequest: (...args) => mockDecrementPendingRequest(...args),
|
|
sanitizeMessageForTransmit: jest.fn((message) => message),
|
|
checkAndIncrementPendingRequest: (...args) => mockCheckAndIncrementPendingRequest(...args),
|
|
getAgentStartupTelemetry: jest.fn(() => undefined),
|
|
acceptAgentStartupTelemetry: jest.fn(),
|
|
isUnpersistedPreliminaryParent: jest.fn(async () => false),
|
|
createMCPRuntimeRequestBody: ({ messageId, conversationId, parentMessageId }) => ({
|
|
messageId,
|
|
conversationId,
|
|
parentMessageId,
|
|
}),
|
|
parseAgentEventActorDetachedCompletion: jest.fn(() => undefined),
|
|
}));
|
|
|
|
jest.mock('~/server/cleanup', () => ({
|
|
disposeClient: jest.fn(),
|
|
clientRegistry: null,
|
|
requestDataMap: {
|
|
set: jest.fn(),
|
|
},
|
|
}));
|
|
|
|
jest.mock('~/server/middleware', () => ({
|
|
handleAbortError: jest.fn(() => Promise.resolve()),
|
|
}));
|
|
|
|
jest.mock('~/cache', () => ({
|
|
logViolation: jest.fn(),
|
|
}));
|
|
|
|
jest.mock('~/models', () => ({
|
|
saveMessage: (...args) => mockSaveMessage(...args),
|
|
getMessages: (...args) => mockGetMessages(...args),
|
|
getConvo: (...args) => mockGetConvo(...args),
|
|
isAgentTriggerPrincipalActive: (...args) => mockIsAgentTriggerPrincipalActive(...args),
|
|
}));
|
|
|
|
const AgentController = require('../request');
|
|
|
|
describe('ResumableAgentController tenant context', () => {
|
|
beforeEach(() => {
|
|
jest.clearAllMocks();
|
|
activeTenantContext = undefined;
|
|
mockCheckAndIncrementPendingRequest.mockResolvedValue({ allowed: true });
|
|
mockDecrementPendingRequest.mockResolvedValue(undefined);
|
|
mockGetConvo.mockResolvedValue({ createdAt: '2026-07-31T00:00:00.000Z' });
|
|
mockGetMessages.mockResolvedValue([]);
|
|
mockIsAgentTriggerPrincipalActive.mockResolvedValue(true);
|
|
mockGenerationJobManager.updateMetadata.mockResolvedValue(undefined);
|
|
mockGenerationJobManager.emitError.mockResolvedValue(undefined);
|
|
mockGenerationJobManager.completeJob.mockResolvedValue(undefined);
|
|
mockGenerationJobManager.beginProviderExecution.mockResolvedValue(true);
|
|
mockGenerationJobManager.markProviderExecutionDrained.mockResolvedValue(true);
|
|
mockGenerationJobManager.claimGeneration.mockResolvedValue({ claimed: true });
|
|
mockGenerationJobManager.releaseGeneration.mockResolvedValue(undefined);
|
|
mockGenerationJobManager.hasJob.mockResolvedValue(true);
|
|
mockGenerationJobManager.steering.closeAndDrain.mockResolvedValue([]);
|
|
mockGenerationJobManager.steering.park.mockResolvedValue(undefined);
|
|
});
|
|
|
|
/**
|
|
* Drives the controller far enough to register the `allSubscribersLeft` handler,
|
|
* fires it, and returns the tenant context that was active during `saveMessage`.
|
|
*/
|
|
const partialContextMeta = {
|
|
calibrationRatio: 1.2,
|
|
encoding: 'claude',
|
|
fading: { v: 1, budgetTokens: 50_000, masked: true },
|
|
};
|
|
|
|
const firePartialDisconnect = async (
|
|
user,
|
|
jobRecord = { createdAt: 1000, contextMeta: partialContextMeta },
|
|
) => {
|
|
mockGetConvo.mockResolvedValue({
|
|
conversationId: 'conversation-123',
|
|
user: user.id,
|
|
tenantId: user.tenantId,
|
|
createdAt: '2026-07-31T00:00:00.000Z',
|
|
});
|
|
let allSubscribersLeftHandler;
|
|
mockGenerationJobManager.getJobStore.mockReturnValue({
|
|
getJob: jest.fn().mockResolvedValue(jobRecord),
|
|
});
|
|
mockGenerationJobManager.createJob.mockResolvedValue({
|
|
createdAt: 1000,
|
|
metadata: {
|
|
providerExecutionId: 'provider-segment-1',
|
|
providerDrained: true,
|
|
},
|
|
readyPromise: Promise.resolve(),
|
|
abortController: new AbortController(),
|
|
emitter: {
|
|
on: jest.fn((event, handler) => {
|
|
if (event === 'allSubscribersLeft') {
|
|
allSubscribersLeftHandler = handler;
|
|
}
|
|
}),
|
|
},
|
|
});
|
|
mockGenerationJobManager.getResumeState.mockResolvedValue({
|
|
conversationId: 'conversation-123',
|
|
responseMessageId: 'response-message',
|
|
userMessage: {
|
|
messageId: 'user-message',
|
|
},
|
|
});
|
|
|
|
let tenantSeenBySave;
|
|
mockSaveMessage.mockImplementation(async () => {
|
|
tenantSeenBySave = activeTenantContext;
|
|
return {};
|
|
});
|
|
|
|
const initializeClient = jest.fn().mockRejectedValue(new Error('stop after setup'));
|
|
const req = {
|
|
user,
|
|
body: {
|
|
text: 'Continue the analysis',
|
|
messageId: 'user-message',
|
|
parentMessageId: 'parent-message',
|
|
conversationId: 'conversation-123',
|
|
endpointOption: {
|
|
endpoint: 'agents',
|
|
modelOptions: { model: 'gpt-4.1' },
|
|
},
|
|
},
|
|
config: {},
|
|
};
|
|
const res = {
|
|
headersSent: true,
|
|
json: jest.fn(),
|
|
status: jest.fn(() => res),
|
|
};
|
|
|
|
await AgentController(req, res, jest.fn(), initializeClient, null);
|
|
expect(allSubscribersLeftHandler).toEqual(expect.any(Function));
|
|
|
|
await allSubscribersLeftHandler([{ type: 'text', text: 'Partial response' }]);
|
|
return tenantSeenBySave;
|
|
};
|
|
|
|
it('carries the context meta the run published onto the partial response saved on disconnect', async () => {
|
|
await firePartialDisconnect({ id: 'user-123', tenantId: 'tenant-a' });
|
|
|
|
expect(mockSaveMessage).toHaveBeenCalledWith(
|
|
expect.any(Object),
|
|
expect.objectContaining({
|
|
messageId: 'response-message',
|
|
unfinished: true,
|
|
contextMeta: partialContextMeta,
|
|
}),
|
|
expect.any(Object),
|
|
);
|
|
});
|
|
|
|
it('leaves context meta off the partial response when the job record belongs to another epoch', async () => {
|
|
await firePartialDisconnect(
|
|
{ id: 'user-123', tenantId: 'tenant-a' },
|
|
{ createdAt: 2000, contextMeta: partialContextMeta },
|
|
);
|
|
|
|
const [, savedMessage] = mockSaveMessage.mock.calls[0];
|
|
expect(savedMessage).not.toHaveProperty('contextMeta');
|
|
});
|
|
|
|
it('restores the authenticated tenant before saving a partial response on disconnect', async () => {
|
|
const tenantSeenBySave = await firePartialDisconnect({ id: 'user-123', tenantId: 'tenant-a' });
|
|
|
|
expect(mockTenantStorageRun).toHaveBeenCalledWith(
|
|
{ tenantId: 'tenant-a', userId: 'user-123' },
|
|
expect.any(Function),
|
|
);
|
|
expect(tenantSeenBySave).toEqual({ tenantId: 'tenant-a', userId: 'user-123' });
|
|
expect(mockSaveMessage).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it('saves the partial response without tenant context when the user has no tenant', async () => {
|
|
const tenantSeenBySave = await firePartialDisconnect({ id: 'user-123' });
|
|
|
|
expect(mockTenantStorageRun).not.toHaveBeenCalled();
|
|
expect(tenantSeenBySave).toBeUndefined();
|
|
expect(mockSaveMessage).toHaveBeenCalledTimes(1);
|
|
});
|
|
});
|