* fix: Preserve Draft Identity Across Navigation
* fix: Await Conversation Records With Loaded Assistant Catalogs
* fix: Reconcile Retained Conversation State on Route Remount
* ⚡ perf: Throttle Code Highlighting While a Message Streams
* fix: harden streamed code highlight throttling
* test: cover wall clock changes during highlighting
* style: tidy highlight regression test
* fix: restart highlight work across lifecycle changes
* style: avoid nested highlight timing ternary
* fix: propagate highlight throttle to startup config
* fix: share and validate highlight throttle
* fix: keep streamed code visible during highlighting
* test: stream highlight tool arguments
* fix: preserve highlights when cadence config resolves
* fix: reschedule highlights when cadence changes
* test: preserve default fake tool chunking
* fix: prevent stale streamed highlights
* test: open the tool pane before asserting streamed highlights
Every scenario in this file waited for highlight tokens without opening the
card. Dev's #16143 stopped passing a closed pane any code at all, so the four
runs polled a card that renders raw text and had nothing to find: the failed
traces show the disclosure at aria-expanded="false" for the whole run, with no
click against it and no tokens in the code element.
Highlighting is now asserted through the card's disclosure, which ProgressText
owns and which carries an aria-expanded state only once the card has input to
show, so waiting on it also waits for the first streamed argument chunk. The
open happens inside expectHighlightedCode, so a scenario cannot assert tokens
without it, and it lands while arguments are still streaming, which is the only
window where the throttle is under test at all.
* test: reopen the rebuilt card for the settled highlight
Opening the pane got the streaming assertions passing and the traces show 240
highlight spans mid-stream, so the throttle itself lands. The settled check
still failed because persisting the streamed message rebuilds the card, and a
rebuilt card starts closed while autoExpandTools is off: the disclosure goes
back to aria-expanded="false" and a closed pane renders raw text.
The settled and cancelled states now assert through the same open-then-wait
helper, so each one measures the card the reader would actually be looking at
instead of the tokens the streaming card happened to leave behind.
* test: leave a window to cancel a streaming highlight
With the settled assertions fixed, the cancellation scenario timed out on the
Stop button instead: it waited for a highlight before stopping, and the ~40
argument chunks it streams at 35 ms are gone in under two seconds, so the run
had already finished and there was nothing left to cancel. It failed on all
three attempts.
The card is now opened and the run stopped before any token is awaited, since
tokens after cancellation are what the scenario is about, and the cancel
variant streams its arguments at a wider cadence so the window does not depend
on how loaded the runner is. Only that label changes cadence; every other
scenario keeps the timing it had.
* fix: preserve initial highlights and honor shared-page cadence
---------
Co-authored-by: Lia <lia@librechat.ai>
* fix: preserve tool pane choices through response finalization
* test: read real message context in content part mock
---------
Co-authored-by: Lia <lia@librechat.ai>
* ✒️ fix: Persist a Generated Title Before the Turn Ends
* 🧷 fix: Keep the Early Title Save From Rewriting Message References
* 🩹 fix: Carry the Recovered User Message Reference
* 🧵 fix: Reference Every Recovered Message Row
* 🪢 fix: Reference Paused and Resumed Response Rows
---------
Co-authored-by: Lia <lia@librechat.ai>
* 🌁 fix: Stop Painting the Closed Mobile Drawer
* 🌁 fix: Re-assert the unpainted value when the slide settles
React owns the resting value and writes it when the travel window closes at
TRANSITION_MS; the release ran a buffer later and cleared the property, which
dropped that value while React still believed its unchanged prop was applied.
React never wrote it again, so every animated close left the drawer painted and
the artifact could recur. Re-asserted through one shared constant, the same way
the drawer width already is.
---------
Co-authored-by: Lia <lia@librechat.ai>
* fix(client): map image/svg+xml artifacts to a renderable template (#16087)
* fix: Rebuild the SVG preview shell from edited source
An SVG artifact previews a derived index.html holding a copy of the
source, so replacing only the edited index.svg left the preview on the
original drawing. Expose the derived-file builder as deriveFiles and
rebuild the whole set from the editor text in SandboxArtifactTabs.
* fix: Scope the SVG preview sizing rule to the root viewport
CSS overrides SVG presentation attributes, so the unscoped `svg` rule in the
preview shell stretched every nested `<svg>` viewport to the panel, corrupting
the layout of sprites and inset diagrams. Scope it to `body > svg`.
---------
Co-authored-by: Frank_zhu <58329837+Frank-zhu0404@users.noreply.github.com>
Co-authored-by: Lia <lia@librechat.ai>
* 🖼️ fix: Resolve Pinned Model Icons from Endpoint Config
- pass `endpointsConfig` and `model` to `MinimalIcon` from the pinned favorites row so a custom endpoint's `iconURL` is honored
Fixes#16088
* test: Cover Pinned Model Endpoint Config Propagation
---------
Co-authored-by: Lia <lia@librechat.ai>
`style.css` pinned every `code` and `pre` element to
`Consolas, Söhne Mono, Monaco, Andale Mono, Ubuntu Mono, monospace !important`.
The repository ships none of those faces, so Windows rendered code in Consolas
and macOS in Monaco, which carries neither an italic nor a bold face for the
browser to use. `!important` also outranked the 21 `pre` and `code` elements
that ask for `font-mono` by class, so the self-hosted Roboto Mono the app
already bundles was never used for code anywhere.
Move the stack to `theme.fontFamily.mono`, where `sans` already lives, so
Tailwind's preflight styles the bare elements and the `font-mono` utility
carries the same value. The tail is ordered so the glyphs the bundled latin
subset omits keep Roboto Mono's advance width.
Co-authored-by: Lia <lia@librechat.ai>
* 🫧 fix: Fold a Streaming Thought Into the Live Row Before Its First Tool Call
A thought at the live tail rendered as its own row with a multi-line peek until a tool call arrived, which then snapped it into the one-row fold. With a reasoning model that talks between calls that is a jump up and back down on every step. The span now folds from the thought's first character and previews it one sentence at a time, under a reasoning glyph until a tool gives it icons.
* 🫧 fix: Keep a Live Card's Key When Its First Tool Call Arrives
* 🫧 fix: Stop Unfolding the Whole Live Span for Every Code Call Without a Leading Intent
blocksLiveFold unfolded the entire span while a bash/code call with complete args, no output and no intent was running, so its card could show the sandbox-startup label. When the model writes intent after command, every code call qualifies: a 47-call run opened to its full height and shut again on each call. The row now reads the same sandbox signal for its newest call and the span stays one card. Also keeps tool-anchored card-key aliases across finalization so a reasoning-led card a reader opened stays open when the response settles.
* 🧹 chore: Sort Imports in ActivityPhaseGroup
* 🫧 fix: Preserve Reasoning Disclosures and Isolate Streaming Siblings
* 🧪 test: Keep Real Part Identity in Content Renderer Mocks
* 🫧 fix: Migrate Sandbox Startup Readers and Writer to Jotai
---------
Co-authored-by: Lia <lia@librechat.ai>
`useLazyHighlight` tokenized the same input twice on every mount that could
highlight immediately. The state initializer highlighted during render whenever
the grammars were already loaded, which holds for every card after the first in
a session, and then the effect highlighted the same input again because its
dedupe ref started empty and could not match on a fresh mount. Each card paid
two tokenizations, two hast-to-React conversions and an extra commit.
Card bodies also tokenized while collapsed. Every code, bash, read-file and
file-authoring card highlighted its content on mount, so opening a long agent
conversation highlighted code nobody had asked to see.
The tokens now carry the key they were produced from, so the effect recognizes
what the initializer already did, and each call site passes its content only
while its pane is open. ExecuteCode gains the raw fallback its three siblings
already had: with highlighting deferred to the pane opening, rendering only the
highlighted nodes would leave the pane empty until the grammars load.
* ⚡ perf: Exclude Agent Version History From Default `getAgent` Reads
getAgent now defaults its projection to { versions: 0 }; loadAgent/loadAddedAgent
and canAccessAgentFromBody use getAgentWithVersionCount so the version count stays
exact without transferring the unbounded versions array on every chat request.
Callers that need history (v1 update/revert handlers) request it explicitly.
* fix: tighten agent version projection types
* fix: type projected agent version counts
* fix: type default agent projection
* style: format agent projection overload
* fix: expose projected agent return type
* 🫧 feat: Hold a Live Run's Activity at One Row
Fold the span a run is still writing into a single collapsed row from its first tool call, with a header that bubbles up the newest activity (streamed intent, generic running text, filled batch label, or the thought streaming after them) on a 500ms leading+trailing throttle. The settled rendering is unchanged.
* 🫧 fix: Name Every Live Line and Take the Fold Preference From the Host
Live header resolves failed/cancelled through resolveToolCallPhase, names trailing commentary, and only folds agents-shaped calls it can name. ContentParts takes foldLiveActivity from its host instead of reading Recoil; subagent panels opt out.
* 🫧 fix: Carry Background Stops and Nested Sign-Ins Into the Live Fold
* 🫧 feat: Preview Tail Reasoning One Sentence at a Time in the Live Row
* 🫧 fix: Keep Handoffs, Detached Failures and Status Announcements Out of the Fold's Blind Spots
* 🫧 fix: Keep the Live Line's Shimmer Off the Ticker's Animated Element
Found in Chromium: .shimmer declares animation/position/display, so on the same element it replaced the slide-out and the retired line never left. The sweep now rides an inner span, and the header button is block-level flex so a live row measures the same 28px as the settled row.
* 🧹 chore: Sort Imports in the Live Activity Helper
* 🫧 refactor: Decide a Live Line's Outcome With the Group Header's Resolver
The live header derived pass/fail on its own and re-learned, one review at a time, signals the cards already handle. getToolMeta moves out of ToolCallGroup into Content/outcome.ts and the live line reads it, which covers cancelled status attachments and memory-tool prose failures. A legacy Assistants call now ends a live span like a handoff, and the live disclosure is named by its current line alone (aria-labelledby) so the polite region's previous line stays out of its accessible name.
* 🫧 fix: Make the Live Row Agree With the Cards It Hides
Span-level outcome beside the newest line (an earlier call can fail while a later one runs), announcements with their own identity in one polite region that outlives the live header, the memory-error artifact and step-scoped attachment ownership in the shared resolver, one localized 'Failed: {{0}}' template for the card and the row, and a parity suite that compares the folded row with the REAL cards on unmocked outcome logic.
* 🫧 fix: Keep Live Subagents Unfolded and Give Reused Ids and CJK Sentences Their Own Lines
* 🫧 fix: Hold a Finished CJK Sentence and Honor Open Thinking in Live Folds
* 🫧 fix: Say "Running in Background" as the Card Does and Hold Reasoning Identity Across Whitespace
* fix: Harden live activity folding boundaries and lifecycle
* 🫧 feat: Surface a Span's Own Glyphs on Its Collapsed Header
A header stands for rows it hides, so it carries the most specific glyphs they show. The icon stack swaps the generic search glyph for the sites a web search read (from attachments, or the streamed results while live), and the settled phase header keeps the span's tool, MCP and site icons instead of a bare check; a failed phase keeps its warning glyph. Applied to the live row, the settled phase header and the tool group header. Source helpers move out of WebSearch into Content/sources.ts.
* fix: Preserve owned glyphs and outcomes across collapsed headers
---------
Co-authored-by: Lia <lia@librechat.ai>
* ⚓ fix: Keep a Resumed Compaction Anchored to the Turn It Summarizes
A compaction submits no user turn: its user-message slot names the leaf it
summarizes up to. The resume paths adopted that identity-only projection as a
ROW, rewriting the answer being summarized into an empty, parentless user
message, which buildTree files as a phantom root: the thread folded and the
pane could return on another branch. Treat the slot as an anchor everywhere
rows are written, and let the anchor name the branch to restore.
* Recognize a compaction anchored on a user leaf
Compact runs on whatever leaf the branch ends with and canCompact does not restrict its author, so the anchor is a user message as often as an answer. Detecting it by not-user-created recognized only the assistant-leaf kind: the other was rebuilt as an ordinary turn, so the sync path merged the identity-only projection over the stored row and blanked the prompt still on screen, and a failed abort appended a second row under its id. Judge the anchor by the projection shape instead, and carry the resolved answer on the resumed submission so a flagless re-attach agrees.
---------
Co-authored-by: Lia <lia@librechat.ai>
* 🧹 fix: Build the Legacy Meili Cleanup Index MongoDB Rejected
`meili_excluded_legacy_cleanup_v3` declared `_meiliCleanupVersion: { $exists: false }`
in its `partialFilterExpression`. MongoDB rewrites that to `$not`, which no partial
index accepts, so the build failed on every startup for Message and Conversation and
the index never existed.
The missing-version condition moves into the key, where a missing field indexes as
null and the legacy cleanup query reaches it on the same scan. The filter keeps the
two conditions a partial index can express, and the name moves to `_v4` so no
deployment that somehow holds the old spec hits an options conflict.
* 🎯 fix: Bound the Legacy Cleanup Index to Documents Awaiting Cleanup
The buildable filter admitted every excluded document carrying `_meiliIndex: false`,
which the schema writes on every new subagent message and conversation. Those
documents already carry the current `_meiliCleanupVersion`, so the cleanup query never
selects them and their entries never leave the index.
The unstamped state is now expressed as a null equality, which a partial filter
accepts and which matches an absent or null version. The legacy cleanup branch asks
the same way, so the planner can still reach the index, and a document leaves it as
soon as cleanup stamps the version.
* 🥊 test: Prove MCP Refresh Coordination Across Replica Processes
Fork real replica processes with production Mongo, Redis, encryption and OAuth adapters, and assert one redemption per rotation, peer adoption, and recovery after the authorizing replica is killed. A negative control with coordination disabled observes two redemptions, so a green coordinated run cannot pass on timing alone.
Adds a refreshGate hook to the shared OAuth test provider so concurrent refreshes can be held open. No production code changes.
* test: Establish Replica Overlap Instead of Assuming It
The coordinated assertion counted provider redemptions after a fixed delay, so a peer that arrived once the winner had already persisted would read a fresh credential, never contend, and still leave one redemption: the test would have passed while proving nothing. Both replicas now report entering the refresh path on a credential they observed expired, and getTokens own onRefreshSuccess/onTokensAdopted hooks report which side each took, so the pair (one redeemed, one adopted) is asserted rather than inferred from timing.
A worker that never signalled ready was also left running with live Mongo and Redis connections, which would outlive the suite and disturb the rest of the integration lane; boot failures now reap the child and report the workers own initialization error.
---------
Co-authored-by: Lia <lia@librechat.ai>
* 💵 feat: Show Cost per Record, Step and Response in the Trace Ledger
* 💵 fix: Cost for Whole Responses Only, Hidden Records Included, and Said Aloud
* 💵 fix: Give the Oldest Loaded Response No Cost While Older Records Remain
Classify HTTP 408, 429, and 5xx before legacy body-message classifiers can invalidate client registration or start consent. Preserve typed temporary failures across refresh storage and verify retry with the existing grant against the real SDK test provider. Keep permanent grant errors and existing UI retry behavior intact.
Co-authored-by: Lia <lia@librechat.ai>
* ✂️ fix: Name Tool Rounds From the Trace, and Match a Cut Response From Its End
* 🧵 fix: Join a Cut Model Call's Round Only When One Is Waiting
* 🏷️ fix: Read Labels From the End Only for the Response the Limit Cut
* 🪪 fix: Say a Tool Round Came From the Conversation Only When It Did
* 🧾 fix: Carry Where a Tool Round's Calls Came From
* refactor(redis): import script cache proposal from #16069
Squashed copy of PR #16069 at 7e994194c2, rebased onto current dev without changing the original branch.
Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
* refactor(redis): cache independent claims without queueing streams
---------
Co-authored-by: Lia <lia@librechat.ai>
Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
* fix: give same-batch code calls the files a skill just loaded
A batch that carries a skill call next to execute_code/bash ran both
against the code-session snapshot the graph took when it planned the
batch, so the sandbox had no /mnt/data/skills/<name>/ for that turn.
Code calls in a mixed batch now wait on the skill calls and merge their
uploaded refs into their own context before dispatch.
* test: pin the spec's own file ref kind so CodeEnvFile stays assignable
---------
Co-authored-by: Lia <lia@librechat.ai>
* 🥢 fix: Exclude Prompt Inputs From Terminal Events
Terminal events carried prompt-building inputs into every place a FINAL is
kept: the runtime cache, the durable Redis job hash, Pub/Sub publication and
late/cross-replica replay. Neither terminal producer projected the payload, so
a 706 KiB attachment-heavy FINAL was stored and published at full size.
sanitizeMessageForTransmit removed fileContext and files[].text from
requestMessage at the controller, but never image_urls, and responseMessage
was not sanitized at all.
projectTerminalEvent is one shared, schema-aware projection applied at both
GenerationJobManager.emitDone() and publishTerminalClaim(), and on read where
a stored record may predate it. It excludes fileContext, image_urls and
embedded file bodies from requestMessage, responseMessage and every
runMessages entry, while preserving message content, attachment references and
display metadata, and the terminal/reconciliation protocol fields.
publishTerminalClaim compared publicationEvent !== finalEvent to decide
persistenceFailed. Projection allocates a new object, so that identity check
now compares against the projected intendedEvent; a successfully persisted
FINAL would otherwise have been reported as a persistence failure.
* fix: Preserve Output Attachment Text and Project Live Terminal Frames
Addresses three review findings at 9e5f6f8ce.
Output attachment text was excluded as if it were a prompt input. `files`
carries the user's uploads, whose `text` is the body extracted for the prompt,
but `attachments` holds resolved artifactPromises that BaseClient assigns onto
responseMessage, so its `text` is model-generated output rendered inline by
TextAttachment from `file.text ?? ''`. Excluding it was also unrecoverable:
useAttachmentPreviewSync polls the preview endpoint only while status is
'pending', and an absent status reads as 'ready', so a late or cross-replica
subscriber whose only source is the stored FINAL rendered a blank preview.
Each collection now carries its own exclusion set; storage bookkeeping (_id,
__v) is still excluded from both.
A live Pub/Sub FINAL from an older replica bypassed projection. The store-read
paths were covered, but during a rolling deploy an old generation owner
publishes an unprojected frame that a new subscriber cached on its runtime and
forwarded to the browser. queueDone is the one choke point every terminal
delivery to a subscriber passes through, so the projection now runs there.
The declared return type was the input type T, so the exported projected
contract was never enforced. FinalMessageFields carries an index signature,
which makes Omit alone a no-op, so ProjectedMessageFields now maps the
transient fields to `?: never` and overloads return the projected contract for
a FinalEvent, the exact type for a non-terminal event, and ServerSentEvent for
the union every manager call site passes.
* fix: Spell Out Transient File Fields for isolatedDeclarations
tsdown builds packages/api with --isolatedDeclarations, which rejects a spread
element in an inferred array type (TS9018), so composing TRANSIENT_FILE_FIELDS
from a shared bookkeeping tuple broke Build packages and every lane that
depends on a built package. tsc --noEmit does not use that flag and passed,
which is why this reached CI.
Both tuples are now spelled out, with a comment recording the constraint.
---------
Co-authored-by: Lia <lia@librechat.ai>
* 🥖 fix: Refresh MCP Credentials That Arrive Already Expired
storeTokens replaced a stated access-token lifetime with the 365-day default whenever it had already elapsed, so a credential that arrived expired was recorded as valid for a year. getTokens decides to refresh from that record, so it never did: recovery waited for the resource server to reject a request, and on connection establishment a second rejection of the refreshed tokens starts interactive OAuth instead.
A lifetime stated by the response is now persisted as it stands, including when it has elapsed, so the next read refreshes it silently. A JWT exp keeps its existing leniency because it comes from the provider clock, where skew can make a live credential look expired.
* style: Sort the jsonwebtoken Import in the Expiry Suite
Package imports are ordered by line length, so `keyv` precedes `jsonwebtoken`. Fixes the Static checks import-order gate.
* fix: Renew Expired OAuth Results Before Connection Readiness
Preserve finite zero lifetimes at exchange and storage. Both callback consumers re-read expired flow results through coordinated refresh after crossing and releasing the callback persistence fence. Cover the real SDK callback transaction, concurrent token waiter, zero-expiry updates, retryable failures, bounded recovery, cancellation, and the unchanged fast path.
---------
Co-authored-by: Lia <lia@librechat.ai>
* 🐣 feat: Invoke Newly Authored Skills In the Same Run
* test: Pin the SDK skill tool text the authoring variant rewrites
* fix: Replace a stale skill definition instead of suppressing the duplicate
* fix: Pin Skill Invocation to the Doc Authored In the Run
---------
Co-authored-by: Lia <lia@librechat.ai>
* 🔑 fix: Stringify Ban Cache Keys When Redis Is Off
Keyv/Mongo throws when checkBan passes a raw ObjectId as the cache key
with Redis disabled, which 500s every social OAuth login.
Fixes#16025
Signed-off-by: GokayAI <60583610+gokay-ai@users.noreply.github.com>
* 🔑 fix: Stringify Violation Log Keys and Cover Bans With Real Keyv
logViolation keyed its violation and ban logs by the raw
`req.user.id ?? req.user._id`, the same shape checkBan used, so a lean
user document would hit the same keyv 5.6 `key.startsWith` TypeError on
the namespaced violation stores and record its ban under an ObjectId.
The new spec drives checkBan and logViolation through real namespaced
Keyv instances (Mongo-backed ban store, in-memory violation logs) with
an ObjectId-only OAuth user: an unbanned user passes, and a ban logged
from one address is enforced for the same user from another.
* 🎯 refactor: Stringify Only the ObjectId Fallback for Ban Keys
The id is converted once, where a non-string can enter: the lean
document's `_id` fallback. `req.user.id` is already a string on every
path that sets it (the JWT strategies, Mongoose's `id` virtual, the 2FA
limiter's temp-token id), and the email lookup already stringifies, so
`getBanCacheKey` and that line go back to their dev form.
---------
Signed-off-by: GokayAI <60583610+gokay-ai@users.noreply.github.com>
Co-authored-by: Danny Avila <danny@librechat.ai>
* 🗂️ fix: Keep a Running Attachment Chat in the Sidebar
Since #15694, a turn with model-bound attachments defers its user-message
write until the model admits the payload. That write was also what created
a new conversation's row, so for the whole first model call, which with a
long generated script or extended thinking can run for minutes, the
conversation did not exist. Any conversation-list refetch in that window
(starting another chat, deleting one, reloading) dropped the running chat
from the sidebar until its run finished, and GET /api/convos/:id answered
404 for it.
When attachments are the only reason to defer, the new conversation's row
is now written as the run starts, carrying the same fields the message
write would set but no message. The message itself stays deferred until
admission, and its write waits for a seed still in flight so the two
upserts never race. A content policy still holds back every write, the
row included, as #14425 intended.
The conversation half of saveMessageToDatabase moves into
saveConversationToDatabase so the seed and the message write share one
path.
* 🧱 refactor: Own Turn Conversation Writes in packages/api
The conversation half of a turn's writes (the row a message save
upserts, the retention context it stamps, and the new seed ahead of a
deferred first message) moves into `conversations/save.ts`, which takes
`getConvo`/`saveConvo` from the caller. BaseClient keeps only the
wiring: the retention lookup that must stay synchronous for Stop, the
message save, and the calls into the module.
The seed passes an empty `appendMessageIds`, which tells `saveConvo`
the row holds no messages yet, so it no longer reads the message list
before the upsert. It also resolves the conversation once and leaves it
on the request, so the deferred message save reuses it instead of
looking the conversation up again.
save.spec.ts drives the real data-schemas methods against an in-memory
MongoDB: the seed creates an empty row without reading messages, the
message save appends to it without a second lookup, an existing chat and
a subagent thread are left alone, a temporary chat keeps its retention,
and a failed lookup settles instead of rejecting.
Claude accepts base64 documents only for PDF. Through an OpenAI-compatible
gateway, a textual file was sent as an OpenAI `file` part with its own media
type, which the gateway maps to a base64 document that Claude rejects with a
400 on every later turn. Send it as a text part with the decoded contents,
using the same Claude detection as the document filter.
Fixes#16054
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix: Stop Sealing a Code Environment Decision a Chat Never Made
Switching an existing chat to a coding agent left the composer unable to
send. The chat had no workspace to select, Send stayed disabled, and the
workspace chip was a read-only status with a recovery hint.
Both layers treated "no decision recorded" as "decided to run without an
attached environment". `readPersistedDecision` documented that a stored
conversation always carries a decision and inferred `without_attached`
whenever `codeEnvironmentMode` and `codeWorkspaces` were both absent,
which is the ordinary state of a chat whose turns never involved a
code-capable agent. `resolveConversationCodeEnvironmentDecision` then
sealed that inference, so the first workspace its owner picked came back
as `locked`. The client mirrored the same premise: `locked` was any saved
chat, so `useCodeWorkspace` withheld agent defaults, a remembered
selection, and a sole workspace, and `CodeWorkspaceMenu` rendered its
non-interactive locked branch.
Only a recorded decision is sealed now. A conversation holding neither
field is undecided, so its first coding turn establishes the decision,
and `resolvePersistableCodeEnvironmentDecision` records that decision
with its selections; writing the mode alone would leave `attached`
without the selections the next turn validates. On the client the same
predicate drives `locked`, and the selection defaults that already
applied to a new chat now apply to any chat that has not decided.
An explicit `without_attached` stays sealed, a legacy row still infers
`attached` from the selections it stores, and a sealed decision is still
replaced only by its owner's move.
* fix: Record the first code environment decision on an existing chat
A saved chat that holds no decision may record the one a run establishes,
but every caller persists through `saveConvo`, which carries those fields
only in `$setOnInsert`. On a row that already exists the write was dropped,
so the choice never survived a reload and a later turn could resolve a
different workspace.
`saveConvo` now fills a whole decision onto a row that holds none, by
compare-and-set on that absence: a writer that decided first keeps its
decision, a chat that already holds one is untouched, and bare selections
never seed a row.
* fix: Record the decision a failed turn of a saved chat ran under
`saveErrorTurn` built its conversation fields only when it was seeding a new
row, so an existing chat kept the stored error turn without the decision that
turn ran under: a retry could then pick a different workspace than the failure
already recorded. The validated decision now travels on both branches, where
the conditional write in `saveConvo` keeps it from replacing a stored one.
* refactor: Resolve the error turn's decision fields in `packages/api`
The error-turn save derived its own decision fields, putting persistence
policy in a CJS controller where `/api` is meant to hold wiring only. It now
calls `resolvePersistableCodeEnvironmentDecision`, the resolver the streaming
saves already use, so one rule decides what a turn may record: a chat that
holds a decision keeps it and receives no decision fields at all.
* fix: Keep the legacy code environment lock until the protocol is advertised
The composer unlocked a saved chat that holds no decision without consulting
`codeEnvironmentDecisionVersion`, so during the rollout window it could attach
an agent default and submit it to a replica that still reads a field-less row
as a sealed `without_attached` and rejects the turn as `locked`.
The unlock now waits for the deployment to advertise the protocol, which makes
the hook identical to its previous behavior while the flag is unset. Nothing is
lost by waiting: the unmade decision is only reported once that flag is on.
---------
Co-authored-by: Lia <lia@librechat.ai>