Follow-up to #14316 / #14317. The share dialog deduped picker adds by raw
idOnTheSource, but loaded ACL rows carry the external oid for OpenID/Entra
users while search results carry the local _id (searchPrincipals dropped the
selected idOnTheSource before transforming). Re-adding an already-listed user
therefore appended a duplicate row, and the stable-id de-dup in
computeShareChanges let the appended default-role row silently shadow a
pending role edit (no-op PUT with a success toast).
- Dedupe adds via a new dedupeNewShares helper keyed by principalKey, and
skip marking the dialog dirty when nothing was added
- Propagate idOnTheSource through the user-search transform so picker
results match ACL rows (also fixes excludeIds filtering)
- Add regression tests
Closes#14654
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Danny Avila <danny@librechat.ai>
Expose ADMIN_PANEL_URL through the startup config for users holding the
access:admin capability, and render an Admin section in Settings > General
with an external link to the admin panel. The URL is omitted server-side
for unauthenticated requests and users without admin access.
* 🌊 feat: Wire Adaptive Stream Smoothing Across Google, Bedrock, and Zero-Disable Semantics
With @librechat/agents 3.4.0 smoothing defaults ON (25ms adaptive) for
every provider; this completes the LibreChat side:
- google: fix the unguarded endpoints.all clobber and wire streamRate
into llmConfig._lc_stream_delay — previously read from config and
silently dropped, making google streamRate a no-op end to end
- bedrock: wire streamRate (endpoint + endpoints.all) — previously
absent entirely, so bedrock smoothing was unreachable from config
- anthropic/openai: nullish guards so streamRate: 0 survives as the
explicit smoothing disable; drop the azure 30/17 hardcoded fallback
the SDK default now supersedes
- delete dead createHandleLLMNewToken (no call sites since #6886, and
LangChain backgrounds callbacks so a sleep there never paced anything)
- schema: streamRate gains .min(0) and docs; example docs updated,
including pairing STREAM_DELTA_COALESCE_MS with the smoothing tick
* 🩹 fix: Address Review — Keep Published Shim, Typed Delay Access, Scoped Docs
- restore createHandleLLMNewToken as a @deprecated compatibility shim:
it ships in the public @librechat/api root, so removal is reserved for
a major release
- assign llmConfig._lc_stream_delay via the SDK's typed property (3.4.0
StreamSmoothingOptions) instead of Record<string, unknown> casts at
all five sites
- scope the 25ms-default wording to agents SDK-backed providers (legacy
Assistants/Ollama still per-chunk sleep at DEFAULT_STREAM_RATE=1) and
clarify coalescing guidance when streamRate: 0
* refactor: unify Tailwind color tokens into a single source
Both the client SPA and @librechat/client Tailwind configs now consume one
createTailwindColors() map, eliminating config drift. Fixes the package-side
build along the way: shadcn tokens are wrapped in hsl(), the broken opacity
helper is removed, and text-destructive/border-destructive/switch-unchecked
plus the gray/green palettes are included.
* refactor: replace hardcoded colors in sidebar conversation list with tokens
Migrate the Conversations sidebar section to semantic tokens: focus rings to
ring-text-primary (keeps >=3:1 contrast in both modes; the mid-gray ring would
fail WCAG 1.4.11 on dark), the active-conversation indicator and hover-fade
gradient to surface/text tokens, and the pagination controls. Removes every
dark: color twin; no behavior change.
* feat: add semantic status-color tokens; migrate MCP status badge
Add a status-color layer (status-{success|info|warning|error|neutral} plus
-subtle variants) to style.css and the unified createTailwindColors map, with a
blue palette for the info hue. Migrate MCPStatusBadge (badges + dots) and
MCPCardActions to the new tokens, removing all hardcoded status colors and
dark: twins. Status colors are now themeable like the rest of the system.
* refactor: migrate status badges to semantic status-color tokens
Migrate the genuine status badges to the status-* tokens: MCPConfigDialog
connection pills (info/warning/neutral/error/success + dot), MemoryUsageBadge
usage levels, and DialogImage quality badge (also gains dark-mode support it
previously lacked). Removes hardcoded colors and dark: twins.
* feat: add Alert component and migrate alert banners to it
Add a reusable Alert component (@librechat/client) with error/success/warning/
info/neutral variants backed by the status-color tokens, default per-variant
icons, and role=alert. Migrate the duplicated colored-div banners to it:
Auth ErrorMessage, RequestPasswordReset success, and the identical error boxes
in ToolSelectDialog, AssistantToolsDialog, and MCPToolSelectDialog.
* refactor: migrate remaining alert banners and error states to tokens
Migrate the last banners to the Alert component: ResetPassword success,
MessageContent connection error, and MemoryInfo storage-full errors. Tokenize
the Agents ErrorDisplay error state in place (icon badge, headings, message,
retry button) since it's a full error state, not a compact callout. Also
tokenize ResetPassword field-validation errors to text-text-destructive
(fixes the low-contrast dark:text-red-900).
* refactor: tokenize SidePanel Memories/Parameters/Bookmarks colors
Delete-confirm buttons to surface-destructive tokens (MemoryCardActions,
BookmarkCardActions), drop redundant text-white on submit Buttons (the variant
already sets it), legacy preset button green hover/focus to submit tokens, and
slider hover borders to border-light. Leaves DynamicCheckbox dark overrides for
a separate pass against the Checkbox component.
* refactor: tokenize Settings danger/destructive buttons
Map the DangerButton, the Data tab destructive actions (RevokeKeys, ClearChats,
DeleteCache), and the DeleteAccount button from bg-red-*/bg-destructive to the
surface-destructive tokens.
* refactor: tokenize Chat file-upload table and upload status colors
Tokenize TemplateTable th/td/border classes (surface-primary, border-light,
text-primary/secondary) and FileUpload status colors (text-text-secondary,
text-text-destructive, text-status-success) plus the import button hover.
* fix: explicit type annotations on Alert for isolatedDeclarations
@librechat/client builds with tsdown --isolatedDeclarations, which requires
exported consts to have explicit type annotations (TS9010). Annotate
alertVariants and Alert to match the Button.tsx pattern.
* refactor: add soft status-border token layer for Alert and lighten dark status foregrounds
* refactor: tokenize Chat menus, popovers, and message surfaces
* refactor: tokenize Chat message content, tool output, and file UI colors
* refactor: add semantic link color token and migrate hyperlinks to it
* refactor: tokenize Files and Auth surfaces, text, borders, and CTAs
* refactor: add accent-primary brand token; tokenize Nav/Input/Prompts/Endpoints colors
* refactor: tokenize Auth brand-green accents, Skills, Sharing, Plugins, MCP colors
* refactor: tokenize OAuth, Share, ui, Bookmarks, Tools, Messages, Web, SharePoint colors
* refactor: final solid-color cleanup (brand-green accents, neutral grays, error text)
* refactor: migrate status callout banners to status-subtle/border tokens
* refactor: tokenize token-usage gauge, mic, and oauth countdown status colors
* refactor: replace shadcn color vocabulary with semantic tokens
Remove the shadcn/ui color tokens (background, foreground, card, popover,
muted, accent, secondary, destructive, input) and migrate every usage to
LibreChat semantic surface/text/border tokens.
Add surface-inverted/text-inverted for the neutral inverted CTA and
surface-fixed/text-fixed for controls that must not flip with the theme
(favicon chips, QR container, carousel arrows). New tokens are defined once
in style.css (light + dark), createTailwindColors, the theme types,
applyTheme and the default/dark theme objects so they stay overridable at
runtime.
Collapse paired dark: color variants into the dark-aware tokens and tokenize
the remaining raw palette and white/black utilities, mapping status colors to
the status-* tokens and legacy ring-black/ring-white focus rings to
ring-text-primary.
Retain the background, primary and ring tokens, which are still referenced by
the SidePanel/Agents and SidePanel/Builder panels (excluded from this pass).
* refactor: tokenize remaining status, neutral and message-text colors
Map the leftover semantic colors to tokens: skill error/dirty states and the
selected-version/selected-skill highlights move to status-warning/status-success,
the global indicator to status-success, and the markdown message text to
text-text-primary. Drop the redundant dark: overrides on the dynamic checkbox,
which the Checkbox primitive already handles.
What remains is intentional and stays raw: categorical color sets (category
icons, principal avatars, per-tool toggle accents), brand marks, the
WCAG-tuned toast severities, code/diagram surfaces, scrims, and text-white on
submit/destructive action surfaces.
* refactor: remove unused CSS rules, dead comments, and duplicate keyframes
Drop ~829 lines of dead styles across style.css (2992->2355) and
mobile.css (323->131): unreferenced classes (legacy token utilities,
orphaned animations, form/prose/scrollbar leftovers), commented-out
blocks, and duplicate/orphaned keyframes. Library-injected (hljs, sandpack,
codemirror, markdown language) and dynamically-applied (scroll-animation,
icon sizes) classes were retained.
* fix: resolve ESLint and frontend test failures
- Format with prettier (Alert, MCPStatusBadge, ApiKeys, Memory, etc.) after
--no-verify commits skipped the hook
- Localize the 'Or' auth divider (com_auth_or) instead of a bare literal
- Drop dead InvocationModePicker imports in Skill forms; fix VerifyEmail
unused arg + useEffect deps
- Revert out-of-scope color edits in legacy Files/VectorStore views that
carried pre-existing untranslated-string lint debt
- Update Memory tests to assert status-* tokens (text-status-error,
bg-status-error-subtle) instead of the old hardcoded red classes
* refactor: migrate theme tokens to RGB channels for opacity support
Convert semantic + palette CSS variable values in style.css from hex to bare
'R G B' channel triplets, and emit Tailwind colors as
rgb(var(--token) / <alpha-value>) via createTailwindColors. This makes opacity
modifiers (bg-surface-primary/50, bg-border-medium/60, etc.) resolve correctly
and remain dark-aware, fixing ~26 existing usages that previously fell back to a
hardcoded light hex.
- Wrap direct var(--token) color usages in CSS rules as rgb(var(--token))
(style.css, Dropdown.css, Tooltip.css) and two inline component styles
- applyTheme writes bare triplets to match the new wrapping
- shadcn tokens (HSL) and the JS palette (hex) are unchanged
* fix: prettier formatting after dev rebase
* refactor(client): migrate low-risk primitives to @librechat/client
Swap raw <label>, <textarea>, and native title= tooltips for the
@librechat/client Label, Textarea, and TooltipAnchor components across
Agents, Endpoints settings, Export modal, Prompts, Sharing, and Memory
dialogs. Add localization keys (scroll, sibling navigation, none
selected, select var) for the remaining swap waves.
* refactor(client): migrate buttons, inputs and labels to @librechat/client
Swap raw <button>, <input> and <label> elements for the @librechat/client
Button, Input and Label components across Auth, Chat, Conversations,
Endpoints, Nav, Prompts, Skills, Tools and Web. Preserve bespoke geometry
and behavior via cn className merging, keep data-testid/aria wiring, and
localize previously hardcoded aria-labels. Skip swaps that would break
floating-label animations, tiny bespoke controls or inline-text links.
Add com_ui_reload_page key.
* refactor(client): migrate dialogs, toggles and remaining controls to @librechat/client
Swap behavioral controls for @librechat/client equivalents: HeadlessUI
and legacy dialogs to OGDialog, native checkbox/switch to Checkbox/Switch
(onCheckedChange), and remaining buttons/inputs across Chat, Skills,
Tools, Sharing, Memories and Settings. Convert applicable native title=
tooltips to TooltipAnchor and localize close/scroll aria-labels. Skip
swaps that would break floating-label animations or bespoke select
behavior. Update co-located test mocks to provide the newly-used Button
and cn dependencies.
* style(client): soften dropdown and settings search inputs
Remove the heavy focus ring on the settings search and the searchable
Dropdown's search input, replacing it with a subtle border-light. Make
the search field background inherit the dropdown surface so it matches in
both light and dark mode, and reduce the Dropdown trigger border from
medium to light.
* refactor(client): migrate Agent Builder and Tool Library to @librechat/client
Swap raw buttons, inputs, labels, textareas and native title tooltips for
the @librechat/client Button/Input/Label/Textarea/TooltipAnchor components
across the Agent Builder panel (SidePanel/Agents) and the Tools
marketplace. Remove heavy input focus rings in favor of subtle borders,
soften dropdown trigger borders, and convert stray shadcn/raw colors in
touched lines to semantic tokens. Localize the tool delete aria-label and
toast messages. Update co-located test mocks to provide the newly-used
Button component.
* fix(client): keep Input border static on pointer focus
The pointer-focus override in Field.css used border-color: var(--border-light),
which became an invalid value after the theme moved to RGB channel tokens and
was silently dropped, letting the border fall back to currentColor (text-primary)
on mouse focus. Wrap it in rgb() so mouse focus produces no border, ring, or
outline change; keyboard focus keeps its ring for accessibility.
* refactor(client): remove residual shadcn color tokens
The background/primary/primary-foreground/ring and unused chart-* tokens were
retained only for the then-unmigrated Agent Builder. With that panel migrated,
replace the last usages with LibreChat semantic tokens (ring-primary/ring-ring
-> ring-text-primary; bg-primary/text-primary-foreground -> bg-surface-inverted
/text-text-inverted; text-primary -> text-text-primary; bg-background ->
bg-surface-primary) and drop the token definitions from createTailwindColors,
applyTheme, the theme objects, types, and style.css.
* fix(client): address semantic theme review feedback
* fix(client): use boolean Monaco hover option
* fix(client): resolve CI validation failures
* test(client): update shared component mocks
* fix(client): expose status tokens to runtime themes and document channel format
Add the status, text-destructive and border-destructive families to IThemeRGB,
IThemeVariables, IThemeColors, mapTheme and the bundled light/dark themes so
ThemeProvider consumers can theme Alert and the status badges instead of falling
back to the stylesheet palette.
Update the theme README to document the channel-triplet contract that the RGB
migration introduced, since the previous examples used complete CSS colors that
now produce invalid declarations.
* test(e2e): use accessible message action locators
* fix(client): address theme env, dialog padding and locked button review feedback
Expose every IThemeRGB token through REACT_APP_THEME_* instead of the
hand-maintained subset that omitted the status, destructive, inverted and
fixed families.
Drop the padding OGDialogContent contributes to the Tool Library so the
header divider spans the panel again, and stop disabled:opacity-100 from
overriding the locked delete-account button's dimmed state.
* fix(client): read theme environment variables from the build-time env
getThemeFromEnv read process.env, which vite-plugin-node-polyfills replaces
with an empty shim in the browser, so every REACT_APP_THEME_* value was
dropped and the loader always returned undefined.
Read import.meta.env instead and register the REACT_APP_THEME_ prefix with
Vite so the values are inlined at build time. The env source is now a
parameter, which lets the tests cover the mapping without mutating globals.
* fix(client): replace Tailwind classes that no longer resolve
Several class names in the client and shared component package emit no CSS
rule at all: legacy token- names with no definition, Tailwind v1/v4 names,
and plain typos. They fail silently past typecheck and tests.
- text-md -> text-base (Tailwind has no md font size)
- text-grey-100, text-tertiary -> text-text-tertiary
- text-token-secondary -> text-text-secondary
- bg-token-surface-primary/tertiary, bg-token-main-surface-secondary and
border-token-border-hover -> their semantic tokens
- bg-surface, bg-surface-50 -> bg-surface-primary
- bg-surface-primary-hover -> bg-surface-hover
- outline-hidden -> outline-none where focus styling already exists
- drop focus:shadow-outline, border-d-0 and the malformed
ring-offset-ring-offset, which have no meaningful replacement
MemoryArtifacts keeps its default outline instead of gaining outline-none,
since that button has no other focus indicator. MentionItem drops its dead
background rather than adopting one, which would have matched its hover
colour and erased the hover affordance.
Localize the two literal strings the pre-commit lint flagged in the touched
files, reusing the existing com_ui_upload_image and com_ui_more_count keys.
---------
Co-authored-by: Danny Avila <danny@librechat.ai>
* fix: SSRF-guard speech (STT/TTS) and OCR outbound requests at connect time
Speech (STT/TTS) and OCR issued outbound HTTP to operator-provided target URLs
with only proxy config attached, so a target that resolves to a private, loopback,
link-local, or cloud-metadata address was reachable by the server. This is the same
class already guarded for the custom models fetch, Actions, avatar, MCP, and the
OpenAI/Anthropic endpoint clients.
Add one helper applySSRFSafeAgentIfDirect(config, url, allowedAddresses) that rejects
non-http(s) or unparseable target URLs, sets maxRedirects to 0 so a redirect cannot
bypass the connect-time check, and attaches createSSRFSafeAgents when no proxy or agent
is already set (proxy precedence preserved). Wire it into the six speech/OCR call sites
and thread each section's allowedAddresses exemption from pr-01.
Scope is private/internal SSRF only. It does not restrict forwarding a credential to a
public host, which is a separate egress-allowlist concern. Absent an allowedAddresses
entry, private targets now fail closed, matching endpoints, actions, and MCP. Document
the new fields in librechat.example.yaml with the operator warning that allowedAddresses
hostnames are trusted before the private-IP check.
* fix: block literal private-IP hosts and thread STT exemptions through generic uploads
applySSRFSafeAgentIfDirect only attached the DNS-lookup agents, but Node
skips the custom lookup for IP-literal hosts, so a literal private IP such
as http://127.0.0.1 connected unchecked. Reject literal private IPs
synchronously in the helper, reusing the same allowedAddresses exemption
logic as the lookup path.
The generic audio-upload path did not forward the section-level
allowedAddresses to sttRequest, so a private STT endpoint permitted via
speech.stt.allowedAddresses failed with ESSRF outside the speech route.
Thread the exemption through files/audio.ts and widen the STTService type.
* fix: derive effective SSRF port for literal IPs and validate OCR target before opening its stream
The literal-IP precheck normalized an empty URL.port to '', so
allowedAddresses exemptions on a default port (127.0.0.1:80, [::1]:443)
never matched. Derive 80/443 from the scheme when the port is omitted.
uploadDocumentToMistral opened the upload file stream before the SSRF
check, so a blocked or malformed target threw with the descriptor still
open. Run the proxy/SSRF setup before fs.createReadStream.
Reword the librechat.example.yaml allowedAddresses guidance to prefer a
private IP literal over a hostname, and reconcile the speech/OCR SSRF
specs to assert the synchronous literal-IP block instead of driving the
connect-time lookup that Node skips for IP literals.
* fix: block literal private IPs before the proxy return, destroy OCR stream on failure, canonicalize IPv6 exemptions
Move the literal-IP check above the proxy/agent early return so a literal
private IP is rejected even when a proxy is configured; document that a
forward proxy must be SSRF-enforcing.
Wrap the Mistral upload post in try/finally and destroy the file stream,
so an async connect-time block does not leak the descriptor.
Canonicalize IP literals in normalizeAddressCandidate through the same URL
serialization targets use, so IPv4-mapped and expanded IPv6 exemptions match.
* ⏱️ fix: Compile admin file-config MIME patterns on a linear-time engine
convertStringsToRegex compiled admin-configured supportedMimeTypes with the native RegExp engine, and checkType runs those patterns against an uploaded file's Content-Type on the server event loop, so a catastrophic-backtracking pattern in fileConfig could ReDoS the whole process on upload.
The MIME-pattern compiler is now swappable. It defaults to native RegExp, which browser builds keep so no engine is added to the client bundle, and the server injects a linear-time engine (RE2JS) at startup. Only test is ever called on these matchers, so the shared type widens to a structural RegexLike with no behavior change for valid patterns. The browser stays on native because a client-side stall would only affect that one tab.
* ⏱️ fix: Wire the linear MIME compiler in the experimental entry point
api/server/experimental.js mounts the same upload routes and calls mergeFileConfig but never set the linear-time compiler, so admin MIME patterns still compiled with native RegExp there. Mirror the setup, and widen the client-side supportedMimeTypes type to the shared RegexLike so the browser typechecks against the same structural matcher.
* 🧹 refactor: Configure the file-config linear engine from a shared helper
Move the RE2 wiring out of both JS server entry points into a single
configureFileConfigRegexEngine helper exported from @librechat/api, so /api stays a thin
caller and the setup no longer has to be kept in sync across index.js and experimental.js.
Also warn loudly when compiling an endpoint's supportedMimeTypes drops every pattern (an
empty allowlist would reject all uploads), and correct the isMimeTypeSupported docstring to
say RegexLike rather than RegExp.
* fix: fail closed when every MIME pattern fails to compile
convertStringsToRegex returned [] when all configured patterns failed to
compile, and filter.ts reads an empty allowlist as no restriction, so a
restrictive config whose patterns all fail allowed every attachment.
Return a single reject-all matcher instead so every consumer fails closed.
* test: cover streamed subagent results end to end
* test: assert real e2e conversation id
* test: harden streamed subagent e2e
* test: stop incompatible subagent fixtures
* chore: update @librechat/agents to version 3.4.0 in package.json and package-lock.json
* 🌊 fix: Preserve Custom Endpoint `streamRate` When `endpoints.all` Is Defined
`buildCustomOptions` assigned `allConfig.streamRate` unconditionally whenever
an `endpoints.all` block existed, overwriting the per-endpoint `streamRate`
with `undefined` for any `all` block that did not define one of its own.
The value is read back later to set `_lc_stream_delay` on the llmConfig, so
stream smoothing was silently disabled for every custom endpoint whenever
`endpoints.all` was present for unrelated reasons (e.g. `activityLabel`).
Guard on `allConfig?.streamRate`, matching the existing OpenAI path.
* 🌊 fix: Preserve Explicit `streamRate: 0` Through the Custom Endpoint Chain
Codex review: truthy guards dropped zero-valued streamRate at both the
endpoints.all override and the llmConfig assignment. With agents 3.4.0
defaulting stream smoothing ON, 0 becomes the explicit disable, so both
sites now use nullish guards; endpoints.all.streamRate: 0 overrides an
endpoint-level rate and an endpoint-level 0 reaches _lc_stream_delay.
Spec extended with both zero cases.
* fix(langfuse): disable central fanout media uploads
* test(langfuse): cover fanout media policy in run config
* chore(deps): bump agents for Langfuse media policy
* chore(deps): bump agents to 3.3.13
* fix(langfuse): gate central fanout media uploads
* feat: add allowedAddresses exemption to speech (STT/TTS) and OCR config schemas
Add the existing allowedAddressesSchema as an optional field on sttSchema,
ttsSchema, and ocrSchema, reusing the schema already attached to endpoints,
mcpSettings, and actions so port scoping and normalization stay identical.
STT and TTS resolve a single provider by counting non-empty section keys, so
exclude the allowedAddresses key from that scan. Without the exclusion a
configured exemption list would be counted as a second provider and trip the
"Multiple providers are set" guard. The field is inert on its own: nothing
reads it for SSRF yet, and provider detection now ignores it.
* fix: preserve allowedAddresses through the OCR config loaders
loadOCRConfig rebuilt the ocr config with only apiKey, baseURL,
mistralModel, and strategy, dropping allowedAddresses before it reached
req.config.ocr. Pass it through in both the AppService loader
(packages/data-schemas/src/app/ocr.ts) and the duplicate at
packages/api/src/files/ocr.ts so the exemption survives config load.
* 🛡️ fix: Run message-filter PII patterns on a linear-time regex engine
The messageFilter.pii middleware compiled admin-configured customPatterns with the native RegExp engine and ran them synchronously against every message on the shared event loop, so a catastrophic-backtracking pattern such as (a+)+$ could stall the entire process (native RegExp takes tens of seconds at roughly 32 characters) and take the instance down for every user.
Compile these patterns with RE2JS, a linear-time RE2 port with no native addon, so catastrophic backtracking is impossible regardless of the pattern rather than something the code tries to detect. Patterns using features RE2 does not support, such as backreferences, fail to compile and are dropped and logged exactly as an invalid pattern already is. The filter only tests for a match, so this is a drop-in engine swap with no behavior change for valid patterns.
* 🛡️ fix: Reject RE2-incompatible messageFilter patterns at config load
The customPatterns regex was validated with native RegExp at config load, but the runtime now compiles it with a linear-time engine (RE2) that does not support backreferences or lookaround. Such a pattern passed validation, then failed to compile and was silently dropped at request time, quietly removing PII protection after upgrade.
Reject backreferences and lookaround during config validation with an explicit message, and document RE2 syntax in the example config instead of "JavaScript-flavor". The runtime engine remains the authoritative boundary and still drops-and-logs anything this load-time check misses.
* 🧹 test: Use direct MessageFilterPiiConfig annotations in the PII specs
The added ReDoS cases satisfy the exported MessageFilterPiiConfig type directly, so the `as unknown as` assertions were unnecessary. Annotate the config objects directly, matching the repo's type-safety guidance.
* 🧹 fix: Reject named backreferences in messageFilter patterns at config load
Extend the config-load check to also reject named backreferences (\k<name>), which are valid JavaScript regex but unsupported by the linear-time runtime engine, so they surface at load rather than being dropped at request time. Together with the existing numeric-backreference and lookaround checks this covers the RE2-incompatible construct set; the runtime engine remains authoritative.
* 🛡️ fix: Preserve Unicode whitespace matching in messageFilter starter patterns
RE2's \s is ASCII-only, so after the engine swap the built-in api-key and Bearer starters no
longer matched a secret separated by non-ASCII whitespace (e.g. a non-breaking space), which
native RegExp did match. Broaden the whitespace classes to [\s\p{Zs}] so those patterns keep
their original coverage, and add a regression test for a non-breaking-space separator.
* 🛡️ fix: Validate messageFilter patterns with the RE2 engine at config load
Replace the syntax blacklist (numeric/named backreferences, lookaround) with authoritative
validation: config load now compiles each custom pattern with the same linear-time engine the
runtime uses, so any RE2-incompatible construct (including control escapes like \cA) is rejected
at load with a clear error instead of being silently dropped at request time.
The validator is swappable and defaults to native RegExp so browser builds add no engine; the
server wires the RE2-backed check at startup via configureMessageFilterRegexValidator in both
entry points.
* 🛡️ fix: Match the full whitespace set in messageFilter starter patterns
RE2's `\s` omits the vertical tab and `\p{Zs}` omits U+2028, U+2029, and
U+FEFF, so a separator built from one of those characters slipped past the
`api-key` and `Bearer` starter patterns and reached the model. Broaden the
starter whitespace class to the full JavaScript whitespace set so those
separators are covered again.
* fix: fail closed when messageFilter.pii compiles to zero patterns
DB and admin config overrides bypass the RE2 schema validation (it only
runs at YAML load), so an override whose only pattern is RE2-incompatible
was dropped at compile time, left zero patterns, and let the request
through. compile() now returns a failClosed flag when a config declared
patterns but every one failed to compile; the middleware returns 400 and
findPiiMatchInMessages returns a distinct misconfigured match that the
OpenAI and Responses controllers surface with an admin-facing message.
* 🛡️ fix: Fail closed when any messageFilter.pii custom pattern drops
compile() previously set failClosed only when every pattern dropped (patterns.length === 0 && dropped > 0). With the default starters present, a single RE2-incompatible custom override incremented dropped but left patterns.length > 0, so the filter silently enforced only the surviving subset and text matching only the dropped rule passed.
failClosed now keys off dropped > 0, so any dropped custom pattern blocks with the misconfigured 400. YAML patterns are RE2-validated at load, so dropped stays 0 for valid configs and only unvalidated DB or admin overrides can trip it. Reframed the two keeps-others-active specs to assert fail-closed and added a default-starters partial-drop regression.
* 🧹 fix: Correct the misconfigured JSDoc and drop redundant casts in the PII specs
The misconfigured flag now means any configured custom pattern failed to compile, not that every pattern failed, so its JSDoc on PiiMatch is updated to match. The partial-drop regressions now use direct MessageFilterPiiConfig annotations instead of as-unknown-as casts, keeping the specs type-checked, consistent with the rest of the suite.
* ⚡ feat: Coalesce Redis Streaming Delta Publications into Windowed Batches
Every streamed delta currently costs two Redis EVALs (durable append + sequence-allocating publish), and the publish round trip is awaited inside the provider-stream consumption loop. Behind STREAM_DELTA_COALESCE_MS (default off), message/reasoning/run-step deltas now buffer for a small window and flush as one CHUNK_BATCH frame: a single INCRBY reserves consecutive per-event sequences and one EVAL publishes the batch, while a matching batched XADD keeps the durable chunk log on the same cadence so the resume frontier's log-vs-counter timing assumptions hold. Subscribers unpack batch frames at ingress into individually sequenced chunks, so the reorder buffer, duplicate drop, and force-flush behavior are unchanged. Durable, steer-receipt, created, and terminal emissions stay on the awaited per-event path and act as ordering barriers that flush any pending window first; terminal claims flush both sides before the status CAS so a warm tail cannot fence against its own completion.
Benchmarked on local Redis (per-scenario RESETSTAT, INFO cpu/commandstats): at 100-200 ev/s a 25ms window cuts EVAL calls 67-82% and Redis engine CPU 52-70%; at the incident's 40 ev/s it halves EVALs while a 20ms window batches nothing (avg 1.0/frame). Producer await stall drops from ~0.9ms/delta to ~0.05ms/delta, matching the previously measured 16-18% USE_REDIS_STREAMS wall-time overhead. Delivery p95 stays under one window (27-28ms at 25ms).
* 📝 docs: Document STREAM_DELTA_COALESCE_MS in .env.example
* 🚧 fix: Drain Coalesced Windows Before Abort and Shutdown Terminal CAS
abortJob and the graceful-shutdown finalizer claim terminal state through their own CAS calls rather than claimTerminalJob, so the pre-CAS coalescer flush did not cover them: a window tail buffered at abort time flushed against the already-aborted status, fenced (-1), and the false receipts retired the healthy runtime and error-closed subscribers before the abort FINAL frame. Extract the flush into flushCoalescedStreamBuffers and call it from all three terminal paths that can interrupt a live emitter (claim, abort, shutdown); the abort call sits ahead of the content snapshot so a chunk-log reconstruction also observes the flushed tail. Regression test aborts mid-window and asserts the tail is delivered with no subscriber error (fails without the fix). Paused-state terminals (approval expiry, pause-persistence timeout) need no flush: the pause's durable barrier already drained the window and nothing streams while paused.
* 🛡️ fix: Keep Fence Retire a Lost-Signal Backstop on Aborted Runtimes
A cross-replica abort claims its terminal CAS on the aborting replica, so the owner cannot drain its coalesced window pre-CAS; the window flush then fences against the aborted status. When the flush timer lands in the CAS-to-FINAL gap, the false receipts retired the owner runtime and detached its SSE handlers, so the abort FINAL published moments later was dropped and attached clients hung until client-side reconnect. The stop signal reaching the owner (~1ms pub/sub) is proof the abort/replacement flow owns terminal delivery and cleanup, so retireRuntimeAfterDurableFence now returns early for runtimes whose abort signal already landed. The forced teardown remains exactly for its original purpose: a fence observed by a NOT-yet-aborted owner, which is the lost-signal case. Regression test pins the race deterministically via the abort beforePublish hook (which runs between the CAS and the FINAL), forcing the owner flush there: without the guard the FINAL is dropped and the subscriber never completes; with it the FINAL delivers cleanly.
* 🧰 fix: Gate, Isolate, and Bound the Coalesced Delta Path
Three hardening fixes for the coalescing prototype. The manager now enables the fire-and-forget delta path only when the configured services actually batch — presence of flushPendingChunks/flushPendingAppends is the advertisement — so a custom transport that only implements emitChunk keeps the awaited per-event ordering contract even with STREAM_DELTA_COALESCE_MS set, and a batching transport is never paired with a per-event store (which would let the durable log trail the sequence counter by a full window). Batch unpack isolates each event: a throwing subscriber callback now degrades exactly like a lost individual frame (that sequence stalls until the reorder force-flush) instead of discarding the batch tail whose sequences were already reserved. And the emitter tracks outstanding coalesced receipts per stream, awaiting one once 256 accumulate: healthy settlement is a window plus a round trip so the count sits in single digits and the await never runs, while a stalled Redis now paces the producer exactly like the flag-off awaited path instead of accumulating batches, resolver closures, and queued commands without bound.
Unit tests cover the capability gate (hint shape and await behavior for capable, incapable, and window-off configurations) and the backpressure threshold; an integration test pins the unpack isolation (fails without it: the batch tail vanishes instead of recovering via force-flush). Benchmark re-run confirms the counter and gate cost nothing measurable: identical EVAL counts and the serial drain still enqueue-bound.
* 🎛️ fix: Make STREAM_DELTA_COALESCE_MS the Single Coalescing Switch
The per-instance coalesceWindowMs constructor overrides could disagree with the environment the manager reads: overrides without the env silently did nothing, and an enabled env with an override of 0 selected the un-awaited manager path while both services published and appended per-event. Nothing in the repo passed these options, so remove them — the transport, the job store, and the manager now read STREAM_DELTA_COALESCE_MS through one resolver, making a half-enabled process unrepresentable rather than documented against. The capability-presence gate remains for services that do not implement batching at all.
* 🧪 fix: Observe Abort Tail Delivery Before Terminal Teardown in Test
The same-replica abort test waited for the coalesced tail only after abortJob returned, but abortJob's finally-block cleanup tears down local subscription state and publish receipts acknowledge Redis execution, not subscriber delivery. Single-node pub/sub delivers sub-millisecond so the frames always won locally; under the CI Redis Cluster they cross the cluster bus and lost the race, timing out the assertion. Await delivery concurrently with the abort instead — the pre-CAS flush publishes the tail several round trips before the teardown, so observing during the call is deterministic in both topologies. Test-only change.
* fix: improve accessibility with semantic HTML and keyboard support
* fix: preserve focus on attachments and stop CSS leaking into label text
Passing `Wrapper` to FileRow as an inline arrow made it a new component type on
every render, so React remounted the whole file row. A keyboard user who tabbed
to an attachment thumbnail lost focus to <body> the moment the upload settled.
Hoist the wrappers to module scope so their identity is stable.
BlinkAnimation rendered a <style> tag into the DOM; stylesheet text becomes part
of the ancestor's textContent and leaks raw CSS into label readouts. Move the
keyframes into the tailwind config, named logo-blink to avoid colliding with the
existing `blink` keyframes in style.css, and honour prefers-reduced-motion.
* fix: make preset row actions reachable by keyboard
The pin, edit and delete buttons on a preset row were hidden with `invisible`,
which sets visibility: hidden and removes them from the tab order entirely. The
`group-focus-within` variant meant to reveal them never fired, because nothing
inside the row ever receives DOM focus during keyboard navigation. Verified in a
browser: arrowing and tabbing through the presets menu skipped the row and the
buttons reported focusable: false, while hovering made them focusable.
Hide them with opacity instead, which keeps them in the tab order, and reveal on
focus as well as hover. At rest they still compute to opacity 0, so there is no
visual change.
* fix: harden a11y heading, Space activation, and preset hit targets
Gate the page heading on a title that matches the routed conversation so
stale Recoil state is not announced during navigation. Ignore key-repeat
on role=button TooltipAnchor activation while still blocking Space scroll.
Disable pointer events on transparent preset actions until hover or focus.
* fix: address a11y review follow-ups and eslint formatting
Use the shared layout test harness for ChatView heading tests, default
role=button TooltipAnchors into the tab order, ship spinner keyframes in
package CSS, and let native preset buttons handle activation once.
* 🚦 feat: Configurable Circuit Breakers for Runaway Streamed Tool Args
* docs: forewarn create_file about the streamed tool-argument limit
The breaker failing a near-limit write should not be the model's first
exposure to the bound. Both create_file variants now state the default
64 KB per-call limit and the incremental pattern (create the first
section, extend with edit_file) in the tool description and the content
parameter description.
* fix: keep skill create_file description under the provider advisory cap
The limit-guidance paragraph pushed the skill-aware description to 1169
chars, past the 1024-char advisory bound where providers may truncate.
The skill variant now carries the guidance only in its content parameter
description, which sits closest to the generated payload and is not at
truncation risk; the shorter code-sandbox variant keeps the full
paragraph.
* 🚦 feat: per-tool streamed-arg limits with a create_file default
Thirty days of production data show create_file is the only tool class
with legitimate near-limit arguments (p99 80.6 KiB; every other tool
p99 under 10 KiB). Rather than loosening the global 64 KiB cap for all
tools, the yaml gains maxToolCallArgBytesByTool (per-tool overrides,
keyed by model-facing tool name, 0 disables that tool's guard) and
LibreChat ships { create_file: 131072 } by default; yaml entries merge
over and can replace it. Pairs with maxToolCallArgBytesByTool support
in the agents SDK and stays inert until the dependency bump.
* test: pass per-tool spec configs as plain Partial literals
The as-TAgentsEndpoint casts fail TS2352 for object-valued fields:
comparability does not grant nested literals the implicit index
signature that plain assignability does, so casts carrying
maxToolCallArgBytesByTool never sufficiently overlap. The mapper
already accepts Partial<TAgentsEndpoint>, so the new cases pass
uncast literals instead.
* chore(deps): bump @librechat/agents to 3.3.12
* 📉 perf: Bound Early Event Buffering for Detached Generations
A generation streaming with no attached subscriber re-entered buffering
mode on every disconnect and retained each emitted event in
earlyEventBuffer for its remaining duration. A single 26-minute detached
run (~58,800 tool-argument deltas) grew the heap past 2 GiB with GC cost
climbing alongside it, while client reconnects always resume from
durable state and discard that local buffer anyway.
- Close the early buffer after the first attachment drains it in Redis
mode; the durable chunk log and pub/sub own recovery from then on,
matching how cross-replica subscribers already attach.
- Enforce hard bounds (5,000 events / 8 MB estimated) in both modes; on
overflow the buffer is discarded and closed, with recovery falling back
to the durable chunk log (Redis) or resume snapshot (in-memory).
- Add a generation_stream_early_buffer_overflows_total counter and
earlyBufferedEvents/Bytes gauges on getRuntimeStats() for visibility.
- Add incident-shaped regression tests and update specs that pinned the
old post-disconnect re-buffering contract.
* fix: redirect post-overflow first attachments to resume recovery
A buffer discarded by the overflow guard left the initial non-resume
SSE attachment with nothing to replay, silently omitting pre-attach
output until the final event. Track the overflow on the runtime and
close such attachments with the existing reconnect signal instead: the
client already re-attaches with resume=true on transport failure and
its sync frame reconstructs the discarded output from durable/snapshot
state. Adds no per-event work; the check is one boolean per attachment.
* fix: enforce buffer bounds when restoring canceled resume captures
Captured emissions restored by a resume canceled before activation
bypassed the early-buffer hard cap, so one oversized restoration could
persist past the limits with no later emission to trip the guard.
Restoration now applies the same overflow-and-close behavior through a
shared helper, and the restore-cap spec fails before this change
(5 events / ~10MB retained) and passes after.
* chore: add Redis management scripts and update package.json for Redis commands
Skill priming fanned out one unbounded batch upload per cold skill,
bursting through codeapi's per-user upload limiter (30 per 5 min).
Failures degraded silently: nothing persisted, every turn re-burned
budget, and handle_skill reported success with no files mounted.
- Bound batch uploads to 3 process-wide slots across both prime paths
- Single-flight primeSkillFiles per (skill id, version)
- Retry a 429 once per Retry-After, capped at 15s, fresh streams
- handle_skill now tells the model when bundled files are unavailable
- Warn on fulfilled-null primes in primeInvokedSkills
* 🪺 fix: Keep Preempt-Abandoned Siblings Nested, Make Message Tree Order-Robust
* 🔗 fix: Sever Cycle Back-Edges So the Returned Message Tree Is Acyclic
* 🧪 fix: Satisfy TFile in buildTree Spec fileMap Fixture
* 🌲 fix: Assert Repaired Trees in convoStructure Specs, Uncharge Self-Parent Edges
* 📌 feat: Identity-Stable Sibling Selection Across Background Tree Churn
* 🎭 test: E2E Coverage for Thread Fold and Sibling Selection Invariants
* 🔑 fix: Treat Newest-Sibling Re-Key as Hydration, Not a New Branch
* 🧭 fix: Rebind Sibling Selection Per Parent, Detect Appends by Membership
Atomic file claiming (#11675) added a unique partial index on
(filename, conversationId, context, tenantId) for execute_code outputs.
Records written before it inserted a new document per regeneration, so
any deployment that re-ran a cell producing the same filename carries
duplicates the index cannot span: Mongo aborts the build with E11000 and
the constraint is silently absent — the claim path still works, but
without its database-level guard against concurrent inserts.
Adds config/migrate-code-file-duplicates.js to normalize that legacy
data, following the existing migration conventions (dry-run default,
--batch-size, runAsSystem for cross-tenant scans).
Renames rather than deletes: each duplicate is a distinct stored object,
typically still referenced by a message attachment, so removing one
would strip a real artifact from a user's history. The newest record
keeps the canonical name — matching the claim path's latest-write-wins
behavior — and older copies gain a ' (n)' suffix that skips names
already taken in the conversation. Attachments embed their own filename,
so rendered history is unchanged.
After a successful apply the script builds the index directly (targeted
createIndex, not syncIndexes) so the operator learns immediately whether
the constraint is now in place.
* 🔒 fix: Single-Flight MCP OAuth Token Refresh per User/Server
Concurrent refresh-token redemptions (tool-call 401, ping, reconnect
retries, expired-token reads) each replayed the same stored refresh
token at the OAuth token endpoint. RFC 9700 reuse detection treats the
replay as theft and revokes the entire grant family, forcing manual
re-consent every access-token expiry.
MCPTokenStorage.forceRefreshTokens is the choke point every refresh
path converges on; it now single-flights redemptions per
(tenantId, userId, serverName) so concurrent callers share one wire
call and receive the same rotated result. The refresh token is re-read
from storage inside the locked execution — never from a caller
snapshot — so a redemption starting after another refresh completed
uses the rotated token instead of replaying the consumed one.
Fixes#14583
* 🧪 test: Isolate Single-Flight Keys per Test via Unique Server Names
* 🔒 fix: Evict Stalled Refresh Slots, Decouple Waiter Aborts from Shared Redemption
Codex review round 1:
- A redemption that never settles no longer wedges the single-flight
slot until process restart: a stale-entry timer evicts the map entry
so later refreshes start fresh, while existing waiters keep their
promise.
- Caller AbortSignals no longer thread into the shared redemption. An
impatient waiter (silent refresh's short timeout) resolves its own
wait with null via a per-waiter race; the shared wire call proceeds
for everyone else, bounded by transport timeouts plus eviction.
* 🔒 fix: Abort Stalled Refreshes Before Slot Release, Hook Cache Invalidation to Redemption
Codex review round 2:
- The stale timer now aborts the wedged execution instead of deleting
its slot; the slot frees only once the execution has settled, and an
abort guard before the token-endpoint call stops a woken pre-wire
stall from replaying a refresh token a successor already rotated.
- New onRefreshSuccess hook runs inside the shared redemption after
rotated tokens persist, so the silent-refresh path's mcp_get_tokens
cache invalidation fires even when the initiating waiter timed out
before the redemption completed.
* 📝 docs: Record Post-Dispatch Abort Recovery Rationale on Stale-Refresh Valve
Unresolved {{LIBRECHAT_USER_*}} header templates leaked literally to
upstream providers when user context was missing at resolution time
(e.g. async title generation racing client disposal), letting a gateway
trust LibreChat's own template syntax as an account identity.
resolveHeaders now takes an opt-in stripUnresolved flag that blanks any
resolvable-but-unresolved LIBRECHAT_USER/BODY/OPENID placeholder, enabled
at every final resolution boundary (resolveConfigHeaders, model fetches,
Google init, summarization overrides, azureAssistants init). Staged
passes that resolve again later with more context are left untouched, as
is the async-resolved {{LIBRECHAT_GRAPH_ACCESS_TOKEN}} and unknown names.
titleConvo now resolves headers from the req captured at entry instead of
re-reading this.options.req, which disposeClient nulls concurrently.
Fixes#14580
The lazy BookmarkNav's Suspense resolution commits during waitFor's
polling, outside any act scope, so its follow-up render work lands in
React's real scheduler as a macrotask. The single empty async act added
in #14071 only drains microtasks and the act queue, so on slow Windows
shards that work can still be pending when baselines are captured. The
next act flushes pending root work wholesale, so the first stream tick
carries the leftover pass and inflates the tag counter (Expected: 1,
Received: 2). Flush full event-loop turns inside act until two
consecutive turns add no renders, then capture baselines.
* 💬 feat: Interim Progress Card for Streaming ask_user_question Calls
* 🔍 fix: Match Progress Card Against Every Live Ask Pause, Not Newest Only
* ⏳ feat: Hold Streaming Cursor Under Answered Question While Resume Is In Flight
* 📦 chore: Upgrade react-router-dom to v7.18.2 (security)
Fixes GHSA-wrjc-x8rr-h8h6 (open redirect via backslash in Link/useNavigate,
CVE-2025-68470 bypass) and GHSA-337j-9hxr-rhxg (deserializeErrors constructor
injection). Neither has a 6.x patch; v7's react-router-dom is a shim
re-exporting react-router, so all existing imports work unchanged.
- vite manualChunks: match react-router so the routing chunk still captures
the router (v7 moves all code out of the react-router-dom package)
- jest: add test/polyfills.js (TextEncoder/TextDecoder + minimal Request);
v7's CJS bundle constructs TextEncoder at module scope and builds a Request
per navigation, neither exists in jsdom
- auth specs: v7 types drop the synthetic default export; use a namespace
import and mark the mock factory __esModule so the useOutletContext spy
patches the object components actually read
- isSafeRedirect: reject backslashes as defense in depth for the same
open-redirect class the router patch addresses
* 📦 chore: Regenerate stale bun.lock
bun.lock predated months of package.json drift and still pinned
react-router 6.30.3. Regenerated with bun install --lockfile-only so bun
installs match current manifests, including react-router 7.18.2.
* 🗂️ fix: Commit project-chip URL updates synchronously under router v7
v7 wraps router state updates in React.startTransition unconditionally, so
the chip's paired updates tear: the conversation draft (Recoil) commits
synchronously while the ?projectId removal defers. ChatRoute's
draftProjectMismatch re-init sees draft != URL in that window and restores
the removed project. The flushSync navigate option commits both in one pass,
matching v6 ordering. Caught by the projects e2e specs.
* 🧹 chore: Drop unused banner-query spy variable in Registration spec
Pre-existing warning, but the changed-files eslint gate runs with
--max-warnings=0 so it blocks this PR. The spy call stays; only the
never-read variable goes.
* 🔗 fix: Normalize MCP Tool Keys at Every Producer, Resolve Raw Names via Aliases
Tool keys had two spellings that could diverge for any server whose name
contains characters outside [a-zA-Z0-9_.-]: the tool cache (and registry
inspector) built keys with the RAW server name, while runtime instances
are named with normalizeServerName(serverName). Three code comments
already asserted "tool keys embed the normalized server name" - no
producer honored it. For a special-character server that meant:
- definitions-only mode shipped raw def names the model echoed back,
but the executor's tool map held the normalized instance name, so
every call failed with "Tool not found";
- per-tool tool_options (defer_loading / allowed_callers /
run_in_background / describe_intent) were persisted under raw keys
that never matched the definition names the option passes resolve
against, so builder settings were silently inert;
- tool-key parsing against normalized candidate lists silently fell
back to last-delimiter splitting, which mis-parses delimiter-bearing
tool names.
The reconciliation is one contract enforced in three moves:
1. PRODUCERS NORMALIZE. The tool cache (packages/api/src/mcp/tools.ts)
and the registry inspector build keys with the normalized server
name, matching the instance names MCP.js has always assigned. The
builder's tool ids, agent.tools entries, tool_options keys, and
definition names all flow from these keys, so every model-facing
name now agrees. The cache STORE stays keyed by the raw config name.
2. CONFIG LOOKUPS RESOLVE ALIASES. New shared helpers in data-provider
(buildServerNameAliases, normalizeMCPToolKey) map a parsed
normalized name back to the raw config name that the registry,
config maps, tool cache, and plugin-auth rows are keyed by. Applied
in the definitions loader closure, handleTools grouping,
createMCPTool's parsing fallback, getUserMCPAuthMap, and the MCP
tools endpoint - matching both spellings so legacy raw keys keep
resolving.
3. LEGACY DATA HEALS AT ONE BOUNDARY. initializeAgent rewrites
raw-keyed agent.tools entries and tool_options keys to the
normalized form (normalizeAgentToolKeys) before anything consumes
them, so agents persisted under the old convention load their tools
AND have all four per-tool options honored. Placeholder and
server-pin tokens stay raw - they are config-identity references,
not model-facing names.
Servers whose names are already in the safe character set (the common
case) produce byte-identical keys before and after; the fast path
allocates nothing. Stale Redis-cached raw keys self-heal via the
existing reconnect-on-missing path within one cache cycle.
* 🧯 fix: Deterministic Alias Collisions + Raw Names in Definition Metadata
Two review findings on the normalization contract:
- Two configured server names that normalize to the same segment (e.g.
'Sales Force' and 'Sales:Force' -> 'Sales_Force') produce inherently
ambiguous tool keys; the alias map silently resolved last-wins, so a
tool selected from one server could execute against the other's
config. buildServerNameAliases now resolves collisions to the FIRST
configured name deterministically, and resolveMCPServerContext warns
once per colliding pair per process so the operator can rename one
server. A collision-resistant identifier would change every existing
tool key, so detection + stable routing is the right treatment here;
startup-time config validation can follow separately.
- The definitions loader resolved parsed (normalized) server names to
raw only inside the ToolService closure, while the definition
metadata (serverName -> mcpRawServerName) kept the normalized value.
Server instructions are keyed by raw config names, so a
special-character server's instructions were silently omitted in
definitions-only mode. loadToolDefinitions now takes rawServerNames,
resolves the boundary against both spellings, and stores the RAW
name in definition metadata - consistent with the instance path.
* 🧯 fix: Heal Stale Caches, Skill Allowed-Tools, and Builder Selectors
Three review findings on the normalization rollout, all in the
transition class:
- Stale cache entries (P1): the definitions-only loader treats the
per-server tool map as authoritative and never reconnects on a
per-key miss, so a pre-change raw-keyed Redis entry would make a
special-character server's tools vanish for up to the cache TTL.
getMCPServerTools now heals legacy raw-keyed entries to the
normalized format at read time (keys and function names), covering
every consumer with no coordinated invalidation; safe names return
the map untouched.
- Skill allowed-tools: a skill declaring a raw MCP key in
allowed-tools bypassed the initialize-boundary heal (the union runs
after it) and would neither dedupe against healed agent tools nor
match the normalized tool map. The primes' allowedTools now pass
through the same normalizeAgentToolKeys heal before unioning.
- Builder selectors: matchesMcpServer and useVisibleTools parsed tool
ids against raw server names only, so an attached special-character
server rendered as an unselected orphan card. Both now accept the
normalized spelling and resolve it back to the raw map key, keeping
legacy raw ids working.
* 🧯 fix: Fail Closed on Normalized Server-Name Collisions
Escalation of the collision finding: a deterministic first-wins alias
plus a warning still let the tools listing publish BOTH colliding
servers, so a tool selected under the shadowed second server would
silently execute against the first server's configuration (their
model-facing keys are identical, so routing cannot ever distinguish
them).
- findShadowedServerNames identifies later-configured names whose
normalized form an earlier different name claimed.
- getMCPTools excludes shadowed servers from the published listing
entirely (with a warn naming the collision), so their tools are
never selectable - nothing ambiguous can be picked.
- Server creation reserves both spellings: a generated slug may not
collide with a raw config name OR the normalized form its tool keys
would carry.
Collision-resistant model-facing IDs remain out of scope: changing
normalizeServerName's output would rewrite every existing tool key
(agent documents, caches, instance names) for ALL servers to handle a
misconfiguration that is now blocked from exposure instead.
* ✅ fix: Dedupe Reserved Server-Name Spellings at Creation
The reservation list appended normalized forms unconditionally, which
duplicated every safe name (raw === normalized) and broke the
route-level contract test pinning the exact list. Dedupe via a Set so
safe names contribute one entry, while special-character names still
reserve both spellings; adds the special-character reservation case.
* 🧯 fix: Never Heal a Shadowed Server's Keys; Align Authorization Tie-Break
Persisted references were the remaining collision vector: an agent or
skill saved with the shadowed later server's raw key was HEALED into
the shared normalized key, authorized through a last-wins map, and
routed first-wins - authorized as one server, executed as another.
- normalizeAgentToolKeys now refuses to rewrite keys of shadowed
servers (findShadowedServerNames): rewriting would produce exactly
the first server's key. Left raw, the key cannot match the
normalized-keyed tool map and the tool fails visibly - broken beats
misrouted. Covers agent.tools, tool_options, and skill
allowed-tools through the shared heal.
- filterAuthorizedTools (agents/v1.js) builds its normalized-to-raw
map via the shared buildServerNameAliases instead of a last-wins
Map constructor, so authorization resolves a colliding key to the
SAME first server execution routes to.
* 🧯 fix: Direct Identity Wins Over Aliases; Heal Client Forms and Degraded Contexts
Four review findings on the normalization edges:
- Alias hijack (P1): a user-DB server named exactly like an operator
server's normalized form ('foo' vs YAML 'foo!') had its tools
rerouted to the operator server by unconditional alias resolution.
Resolution is now DIRECT-FIRST everywhere: the parsed name is tried
as-is, and only when nothing resolves is it treated as a normalized
spelling (definitions loader, handleTools grouping, createMCPTool
fallback). buildServerNameAliases seats identity entries before
derived ones so a literal name owns its slot regardless of config
order, findShadowedServerNames and the collision warning derive from
the same construction, and getUserMCPAuthMap fetches auth under both
spellings so either owner finds its rows.
- Builder double-match: a normalized name containing the delimiter
('foo mcp bar' -> 'foo_mcp_bar') also suffix-matched a server named
'bar', selecting both cards and making removal strip the wrong tool.
matchesMcpServer now resolves the token ONCE against the full
configured list (longest boundary, both spellings) when the caller
supplies it; selection and removal share the resolution.
- Builder legacy ids: an agent saved with raw-keyed ids showed its
tools unchecked while the runtime heal kept them active, and
selection updates never replaced the legacy entries. McpSection maps
legacy raw ids to their current normalized ids when deriving and
rewriting this server's selection.
- Degraded context: a transient ensureConfigServers failure returned
an entirely empty context, leaving normalized keys unresolvable for
the request. resolveMCPServerContext now keeps the name lists (they
derive from the config snapshot alone) and degrades only the
lazy-init configs.
* 🧯 fix: Collision Detection Sees Accessible Servers; Shadowed Refs Fail Closed End to End
Round follow-ups on the collision design, all in the
DB-server-visibility class:
- The legacy-key heal detected collisions against operator-config
names only, so healing could still produce a key that direct-first
resolution routes to an invisible user-DB server. initializeAgent
gains an optional getAccessibleMcpServerNames dep (wired through
ToolService for controllers that mock it, directly elsewhere),
consulted ONLY when a configured name needs normalization - zero
cost for safe-name deployments. The heal then sees the full
accessible set and skips shadowed servers' keys.
- Wildcard and legacy raw tokens bypassed catalog filtering, letting a
shadowed server's instances join a run under the same normalized
names as the winner's. filterAuthorizedTools rejects tools of
shadowed servers at authorization (its merged map sees DB + config),
and handleTools skips them at execution.
- The builder migrated only tool selection, not tool_options: legacy
raw option keys showed disabled while the runtime honored them, and
toggles could not clear them. McpSection now migrates option keys to
the current normalized ids (existing normalized entries win).
- A transient ensureConfigServers failure degraded to an EMPTY server
context, leaving normalized keys unresolvable for the request.
resolveMCPServerContext keeps the name lists (derived from the
config snapshot alone) and degrades only the lazy-init configs.
* 🧯 fix: Complete the Collision Audit at Every Gate; Safer Heal Semantics
Round follow-ups hardening the collision audit:
- Execution guards now consult the FULL accessible set: the caller's
heal threads its already-fetched names through loadTools, and
handleTools fetches them itself when a configured name needs
normalization (never for safe-name deployments) - so a cross-tier
collision (user-DB 'foo' vs operator 'foo!') fails closed at eager
execution instead of joining the run under one normalized name.
- Healing is SKIPPED when the collision audit cannot complete
(transient lookup failure, or no dep): un-healed raw keys still
resolve through the direct-first candidates, so skipping is safe
while rewriting against an incomplete audit is not.
- The audit lookup is gated on the agent actually carrying
delimiter-bearing keys (tools, tool_options, or skill
allowed-tools), so non-MCP agents never pay a registry round-trip
even on specially named deployments.
- normalizeAgentToolKeys gives the CURRENT (normalized) entry
precedence when both spellings carry options, matching the builder's
migration semantics instead of letting insertion order decide.
- The builder's toCurrentToolId resolves entries boundary-exactly
against every configured server (longest match, both spellings), so
a raw suffix shared with a LONGER server name can no longer reassign
that server's selection or options while another dialog is open.
* 🧯 fix: Shared Collision Audit for Definitions Loading; Fail Closed on Audit Failure
Round follow-ups closing the remaining audit gaps:
- The definitions-only loader now consumes the same collision audit as
eager loading: shadowed servers' entries (wildcards included) are
dropped before definitions are emitted, so the default execution
path can never resolve a shadowed server's normalized function name
to another server. The audit names thread from initializeAgent's
heal; the loader self-fetches only when a configured name needs
normalization.
- resolveCollisionAuditNames centralizes the audit-resolution policy
(threaded set > self-fetch when needed > incomplete on failure), and
BOTH loaders now fail closed under an incomplete audit: any
normalization-sensitive reference (its own name needs normalizing,
or it equals the normalized form of a configured special-character
name) is skipped with a warning instead of being audited against
operator names alone. isNormalizationSensitiveName lives in
packages/api as a pure helper so test mocks use the real predicate.
- normalizeAgentToolKeys collapses duplicate ids after healing
(order-preserving): a document carrying both spellings converges on
one key, never two instances with the same function name.
* 🧯 fix: Thread the Audit Everywhere; Identity-Aware Alias Fallback
Round follow-ups on audit plumbing:
- The OpenAI-compatible and Responses tool loaders now forward the
already-resolved accessibleMcpServerNames instead of discarding it,
so the definitions loader neither repeats the registry lookup nor
fails closed on a transient second lookup after the first succeeded.
- The skill-only path threads its audit: when the baseline agent has
no MCP keys but a primed skill's allowed-tools fetched the complete
set, that set (not the operator-only list) reaches the loader, so
the collision remains visible and the shadowed reference stays
rejected end to end.
- OAuth discovery iterates the collision-FILTERED tool list, so a
request can no longer emit an OAuth prompt, wait out the connection
timeout, and reconnect a server whose definitions were deliberately
rejected.
- The definitions loader's alias fallback is identity-aware: when the
parsed name IS a known accessible server, a null tool fetch means
temporarily unavailable (OAuth pending, missing user variables,
disconnected) and no longer reroutes to the raw alias - previously
the aliased operator server's definitions could be emitted under the
unavailable DB server's names.
* 🧯 fix: Legacy-Key Definition Lookup; Retain Audit for Deferred Execution
- createMCPTool resolves tool definitions by BOTH spellings: the key as
persisted plus the canonical normalized key built from the resolved
server name. Assistants and direct tool calls persisted before the
rollout bypass the agent-boundary heal and arrive with raw keys, while
availableTools is now indexed canonically - previously every such call
missed the index, burned a reconnect, and returned the unavailable
stub permanently via the negative cache.
- The initialized agent retains accessibleMcpServerNames (the COMPLETE
collision audit this initialization resolved), buildAgentToolContext
copies it into every per-agent tool context, and loadToolsForExecution
threads it into the eager loader as bare options. Deferred/event-driven
execution therefore reuses the snapshot instead of repeating the merged
registry read - a transient failure there could fail-closed a tool the
same turn already advertised from the successful first audit.
- MCP.spec.js keeps @librechat/api pure helpers REAL (requireActual
spread) so normalization paths are exercised rather than mirrored.
* 🧯 fix: Parse Legacy Keys Against Both Server-Name Spellings
createMCPTool's boundary candidates were normalized-only, so a legacy
raw key whose server name contains the delimiter (foo_mcp_bar!) missed
the suffix match and fell to the generic last-delimiter split - the
canonical rebuild then produced a key that could never hit the index
and the persisted call stubbed out. The candidate list now carries the
RAW resolved name (and raw config names on the parse-only path) next
to the normalized spellings.
* 🧯 fix: Honest Audit Completeness; Shadowed-Server Form-Key Guard
- resolveAllMcpConfigs tolerates ensureConfigServers failures, so the
merged registry read can silently omit config-only servers while the
audit still reported complete: true - a foo/foo! collision would go
unseen and a persisted key could route to the wrong server. Both
audit consumers now union the snapshot-derived raw config names back
in (resolveCollisionAuditNames unions the caller's rawServerNames;
the initializeAgent heal unions configRawServerNames), keeping the
completeness label honest without an extra read: operator names come
from the registry-independent config snapshot, user-DB names from the
merged read that fails loudly into the existing incomplete path.
- The client tool_options migration now mirrors the runtime heal's
fail-closed rule for SHADOWED servers: when the dialog's server has
lost its normalized slot to another catalog name, legacy raw keys
stay raw instead of being rewritten onto the winning server's key,
where a later save would apply the wrong server's per-tool settings.
The dialog's own server joins the alias construction so a stale
catalog map can't misread as a collision.
* 🧯 fix: Heal Legacy Assistant MCP Tool Names on Save
The assistants create/update controllers look tools up in the cached
definitions by exact key, and the cache is now normalized-keyed - an
assistant saved before the convention resubmits its raw-suffixed MCP
name on every edit, so any save silently removed the tool.
healMcpToolNames pre-heals the payload's tool list: a delimiter-bearing
string that misses the cache resolves through the configured raw names
(longest-suffix, boundary-exact) and rewrites to the normalized key
only when that key actually exists in the cache. SHADOWED raw names
stay raw and fail closed, mirroring the runtime heal; the config read
happens only when a delimiter-bearing name actually misses, and read
failures propagate (write path) rather than silently dropping tools.
v2's update loop also stops re-reading the tool cache per iteration.
* 🧯 fix: Full-Audit Shadow Set + Dedupe in the Assistant Key Heal
- The assistant-save heal built its shadow set from operator config
names alone, so a cross-tier collision (user-DB `foo` owning the
normalized slot of operator `foo!`) looked unshadowed and the legacy
key healed into the shared normalized name - which direct-first
execution then binds to the DB server. The shadow set now comes from
resolveCollisionAuditNames' full accessible audit, and an incomplete
audit skips healing outright (every rewrite candidate is
normalization-sensitive by construction, so raw-and-fail-closed is
the only safe answer).
- Healed string entries dedupe order-preserving: a payload carrying
both spellings of the same tool collapses to one entry instead of
expanding into duplicate function definitions the provider rejects.