mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-20 23:13:35 +00:00
🪵 fix: Explain Failed Attachment Copies and Subagent Start-Up Failures (#17398)
* 🪵 fix: Explain Failed Attachment Copies and Subagent Start-Up Failures The attachments .gitignore and import failure warnings logged only a bare error type: getSafeErrorMetadata reads `status`, which a workspace tool error does not carry. They now log the request outcome, upstream status and the worker's error code, never a body or host path. A worker that reports the folder missing (one that predates LibreChat-AI/code-interpreter#360 on a root registered by path alone) is reported to the user as needing an update. A subagent that could not start was logged only as the SDK's `unknown` resolution cause. The run now passes onSubagentResolutionFailure, which logs the underlying cause chain (name, code, status, redacted message) and names an MCP server that needs re-authentication. A detached child thread shows the SDK's model-facing start-up message instead of a generic failure, and its failure log carries the task id, resolution cause and a redacted error in place of the raw stack. * 🪵 fix: Log Only Trusted Error Text and Recognize the Legacy Missing-Path Reply - Cause chains keep a message only for errors whose text LibreChat or the SDK composes (MCP authentication errors, SubagentResolutionError, CodeWorkspaceSelectionError); every other link logs name, code and status. Child-thread failures log stack frames without the message line instead of redacted error text. - A retryable MCP refresh or rejection is logged as a sign-in failure a retry may clear, not as one that needs re-authentication. - A worker's missing attachments folder relayed by an older Code API as INVALID_PATH "Workspace path does not exist" is also reported as unsupported, through the shared isWorkspacePathMissing check. * 🪵 fix: Log Frames Only From a Verified Stack and Keep OpenID Out of MCP - Stack frames are read only after the stack's own name: message header, and only when that header still matches the error, so a message line shaped like a frame is never logged. - OpenIDReauthRequiredError alone is no longer reported as an MCP sign-in failure: model and endpoint headers raise it too.
This commit is contained in:
parent
38c96a5e3a
commit
3ccdd252f9
9 changed files with 604 additions and 13 deletions
|
|
@ -1,4 +1,5 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { logger } from '@librechat/data-schemas';
|
||||
import { Tools, FileContext } from 'librechat-data-provider';
|
||||
import { Constants as AgentConstants } from '@librechat/agents';
|
||||
import type { TFile, TurnFileConsumers, CodeWorkspaceOperation } from 'librechat-data-provider';
|
||||
|
|
@ -40,18 +41,25 @@ type WorkspaceRequest = {
|
|||
* In-memory stand-in for the Code API and its attached worker, implementing the
|
||||
* `import_file` contract: stored objects are copied by reference, a same-digest file is left
|
||||
* unchanged, a different file at the path is a conflict, `write_file` is create-only, and
|
||||
* `read_file` returns what is stored.
|
||||
* `read_file` returns what is stored. With `missingParents`, it is a worker that predates
|
||||
* LibreChat-AI/code-interpreter#360 on a root registered by path alone: a write or import into a
|
||||
* folder that does not exist yet is `NOT_FOUND`, because that worker never creates one.
|
||||
*/
|
||||
function createFakeWorker({
|
||||
objects = new Map<string, string>(),
|
||||
delayMs = 0,
|
||||
denyWrites = false,
|
||||
truncateReads = false,
|
||||
missingParents = false,
|
||||
legacyCodeApi = false,
|
||||
}: {
|
||||
objects?: Map<string, string>;
|
||||
delayMs?: number;
|
||||
denyWrites?: boolean;
|
||||
truncateReads?: boolean;
|
||||
missingParents?: boolean;
|
||||
/** A Code API that predates `NOT_FOUND` relays it as `INVALID_PATH` with the same message. */
|
||||
legacyCodeApi?: boolean;
|
||||
} = {}) {
|
||||
const files = new Map<string, string>();
|
||||
const requests: WorkspaceRequest[] = [];
|
||||
|
|
@ -87,6 +95,13 @@ function createFakeWorker({
|
|||
if (denyWrites) {
|
||||
return reply(403, { code: 'WRITE_DISABLED', error: 'File writes are disabled' });
|
||||
}
|
||||
const folder = key.slice(0, key.lastIndexOf('/') + 1);
|
||||
if (missingParents && ![...files.keys()].some((path) => path.startsWith(folder))) {
|
||||
return reply(422, {
|
||||
code: legacyCodeApi ? 'INVALID_PATH' : 'NOT_FOUND',
|
||||
error: 'Workspace path does not exist',
|
||||
});
|
||||
}
|
||||
if (request.operation === 'write_file') {
|
||||
if (files.has(key) && request.overwrite === false) {
|
||||
return reply(409, { code: 'EDIT_CONFLICT', error: 'Workspace file already exists' });
|
||||
|
|
@ -703,6 +718,67 @@ describe('primeWorkspaceAttachments', () => {
|
|||
expect(worker.files.get('root:.librechat/attachments/report.pdf')).toBe('pdf');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['NOT_FOUND', false],
|
||||
['INVALID_PATH', true],
|
||||
])(
|
||||
'tells the user to update a worker that cannot create the attachments folder (%s)',
|
||||
async (upstreamCode, legacyCodeApi) => {
|
||||
const warn = jest.spyOn(logger, 'warn');
|
||||
const worker = createFakeWorker({ missingParents: true, legacyCodeApi });
|
||||
const { deps, records } = createDeps(worker);
|
||||
const file = remember(chatFile('report.pdf', 'pdf', worker.objects));
|
||||
const agent = agentWith(attachedContext(), [file]);
|
||||
|
||||
await primeWorkspaceAttachments({ agents: [agent], deps });
|
||||
|
||||
expect(worker.requests.map((request) => request.operation)).toEqual(['write_file']);
|
||||
expect(worker.files.size).toBe(0);
|
||||
expect(agent.dynamicToolContextMap?.[Tools.execute_code]).toContain(
|
||||
"report.pdf (attached by user): this machine's LibreChat worker cannot receive attachments yet; updating the worker enables it",
|
||||
);
|
||||
expect(records.every((record) => record.copy == null)).toBe(true);
|
||||
expect(warn).toHaveBeenCalledWith(
|
||||
'[workspaceAttachments] Could not create .librechat/attachments/.gitignore in workspace primary: unsupported',
|
||||
{
|
||||
type: 'WorkspaceToolHttpError',
|
||||
reason: 'rejected',
|
||||
upstreamStatus: 422,
|
||||
upstreamCode,
|
||||
},
|
||||
);
|
||||
warn.mockRestore();
|
||||
},
|
||||
);
|
||||
|
||||
it('logs the worker code of a refused import without its message', async () => {
|
||||
const warn = jest.spyOn(logger, 'warn');
|
||||
const worker = createFakeWorker();
|
||||
const { deps } = createDeps(worker);
|
||||
const file = remember(chatFile('report.pdf', 'pdf', worker.objects));
|
||||
const agent = agentWith(attachedContext(), [file]);
|
||||
|
||||
await primeWorkspaceAttachments({
|
||||
agents: [agent],
|
||||
deps: { ...deps, digestFile: async () => ({ sha256: sha('other bytes'), bytes: 3 }) },
|
||||
});
|
||||
|
||||
expect(agent.dynamicToolContextMap?.[Tools.execute_code]).toContain(
|
||||
'report.pdf (attached by user): copying it to this machine failed',
|
||||
);
|
||||
expect(warn).toHaveBeenCalledWith(
|
||||
`[workspaceAttachments] Import of file ${file.file.file_id} into workspace primary failed: failed`,
|
||||
{
|
||||
type: 'WorkspaceToolHttpError',
|
||||
reason: 'rejected',
|
||||
upstreamStatus: 422,
|
||||
upstreamCode: 'INVALID_REQUEST',
|
||||
},
|
||||
);
|
||||
expect(JSON.stringify(warn.mock.calls)).not.toContain('source mismatch');
|
||||
warn.mockRestore();
|
||||
});
|
||||
|
||||
it('reports a worker-side write refusal instead of a path', async () => {
|
||||
const worker = createFakeWorker({ denyWrites: true });
|
||||
const { deps } = createDeps(worker);
|
||||
|
|
|
|||
|
|
@ -33,6 +33,7 @@ import {
|
|||
import { codeExecutionAuthHeaders, getCodeExecutionRouteKey } from '~/agents/execution';
|
||||
import { isAttachedFileWriteDenied } from '~/agents/hitl/byom';
|
||||
import { getSafeErrorMetadata } from '~/utils/errors';
|
||||
import { isWorkspacePathMissing } from './paths';
|
||||
|
||||
/** Workspace-relative folder chat attachments are copied into. */
|
||||
export const WORKSPACE_ATTACHMENTS_DIRECTORY = '.librechat/attachments';
|
||||
|
|
@ -276,6 +277,40 @@ function classifyImportFailure(error: unknown): WorkspaceAttachmentUnavailableRe
|
|||
return 'failed';
|
||||
}
|
||||
|
||||
/**
|
||||
* A worker that cannot create the attachments folder reports it missing, as `NOT_FOUND` or,
|
||||
* through an older Code API, as `INVALID_PATH` with the same message: workers before
|
||||
* LibreChat-AI/code-interpreter#360 never created a parent on a root registered by path alone.
|
||||
*/
|
||||
function classifyIgnoreFailure(error: unknown): WorkspaceAttachmentUnavailableReason {
|
||||
if (error instanceof WorkspaceToolHttpError && isWorkspacePathMissing(error)) {
|
||||
return 'unsupported';
|
||||
}
|
||||
return classifyImportFailure(error);
|
||||
}
|
||||
|
||||
/** What a failed workspace request may log: its outcome and the worker's error code, never a
|
||||
* response body, a host path, or file content. */
|
||||
interface WorkspaceFailureMetadata {
|
||||
type: string;
|
||||
status?: number;
|
||||
reason?: WorkspaceToolHttpError['reason'];
|
||||
upstreamStatus?: number;
|
||||
upstreamCode?: string;
|
||||
}
|
||||
|
||||
function getWorkspaceFailureMetadata(error: unknown): WorkspaceFailureMetadata {
|
||||
if (!(error instanceof WorkspaceToolHttpError)) {
|
||||
return getSafeErrorMetadata(error);
|
||||
}
|
||||
return {
|
||||
type: error.name,
|
||||
reason: error.reason,
|
||||
...(error.upstreamStatus != null ? { upstreamStatus: error.upstreamStatus } : {}),
|
||||
...(error.upstreamCode != null ? { upstreamCode: error.upstreamCode } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Admits at most `limit` tasks at once; a finishing task hands its slot to the next waiter. */
|
||||
function createLimiter(limit: number): <T>(task: () => Promise<T>) => Promise<T> {
|
||||
let active = 0;
|
||||
|
|
@ -519,6 +554,7 @@ async function importOne({
|
|||
const reason = classifyImportFailure(error);
|
||||
logger.warn(
|
||||
`[workspaceAttachments] Import of file ${file.file_id} into workspace ${target.workspaceId} failed: ${reason}`,
|
||||
getWorkspaceFailureMetadata(error),
|
||||
);
|
||||
return { status: 'unavailable', reason };
|
||||
} finally {
|
||||
|
|
@ -672,12 +708,13 @@ async function ensureAttachmentsIgnored({
|
|||
},
|
||||
});
|
||||
} catch (error) {
|
||||
if (classifyImportFailure(error) !== 'conflict') {
|
||||
const reason = classifyIgnoreFailure(error);
|
||||
if (reason !== 'conflict') {
|
||||
logger.warn(
|
||||
'[workspaceAttachments] Could not create the attachments .gitignore',
|
||||
getSafeErrorMetadata(error),
|
||||
`[workspaceAttachments] Could not create ${WORKSPACE_ATTACHMENTS_GITIGNORE} in workspace ${target.workspaceId}: ${reason}`,
|
||||
getWorkspaceFailureMetadata(error),
|
||||
);
|
||||
return classifyImportFailure(error);
|
||||
return reason;
|
||||
}
|
||||
if (target.context.codeWorkspace?.operations.includes('read_file') !== true) {
|
||||
return 'not_ignored';
|
||||
|
|
@ -703,8 +740,8 @@ async function ensureAttachmentsIgnored({
|
|||
}
|
||||
} catch (readError) {
|
||||
logger.warn(
|
||||
'[workspaceAttachments] Could not read the attachments .gitignore',
|
||||
getSafeErrorMetadata(readError),
|
||||
`[workspaceAttachments] Could not read ${WORKSPACE_ATTACHMENTS_GITIGNORE} in workspace ${target.workspaceId}`,
|
||||
getWorkspaceFailureMetadata(readError),
|
||||
);
|
||||
return classifyImportFailure(readError);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -54,6 +54,11 @@ function describeUnusablePath(operation: WorkspacePathOperation, displayPath: st
|
|||
return `The worker could not open ${quoted}. The file may not exist yet (a command may still be writing it), or the path is a directory or a symlink, or passes through one. List its directory to check before retrying.`;
|
||||
}
|
||||
|
||||
/** Whether the worker reported the path absent, in either the current or the legacy shape. */
|
||||
export function isWorkspacePathMissing(error: WorkspaceToolHttpError): boolean {
|
||||
return getWorkspacePathRejection(error) === 'missing';
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends a short explanation to a worker's path rejection so the model can tell a file that
|
||||
* does not exist yet from a malformed path. Other rejections are returned unchanged.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue